Coder Social home page Coder Social logo

jxy-s / herpaderping Goto Github PK

View Code? Open in Web Editor NEW
1.1K 31.0 210.0 23.34 MB

Process Herpaderping proof of concept, tool, and technical deep dive. Process Herpaderping bypasses security products by obscuring the intentions of a process.

License: MIT License

C++ 97.37% C 2.63%
exploit windows security process-herpaderping vulnerability security-vulnerability exploitation exploits exploit-development exploit-framework

herpaderping's Introduction

Process Herpaderping

Process Herpaderping is a method of obscuring the intentions of a process by modifying the content on disk after the image has been mapped. This results in curious behavior by security products and the OS itself.

Summary

Generally, a security product takes action on process creation by registering a callback in the Windows Kernel (PsSetCreateProcessNotifyRoutineEx). At this point, a security product may inspect the file that was used to map the executable and determine if this process should be allowed to execute. This kernel callback is invoked when the initial thread is inserted, not when the process object is created.

Because of this, an actor can create and map a process, modify the content of the file, then create the initial thread. A product that does inspection at the creation callback would see the modified content. Additionally, some products use an on-write scanning approach which consists of monitoring for file writes. A familiar optimization here is recording the file has been written to and defer the actual inspection until IRP_MJ_CLEANUP occurs (e.g. the file handle is closed). Thus, an actor using a write -> map -> modify -> execute -> close workflow will subvert on-write scanning that solely relies on inspection at IRP_MJ_CLEANUP.

To abuse this convention, we first write a binary to a target file on disk. Then, we map an image of the target file and provide it to the OS to use for process creation. The OS kindly maps the original binary for us. Using the existing file handle, and before creating the initial thread, we modify the target file content to obscure or fake the file backing the image. Some time later, we create the initial thread to begin execution of the original binary. Finally, we will close the target file handle. Let's walk through this step-by-step:

  1. Write target binary to disk, keeping the handle open. This is what will execute in memory.
  2. Map the file as an image section (NtCreateSection, SEC_IMAGE).
  3. Create the process object using the section handle (NtCreateProcessEx).
  4. Using the same target file handle, obscure the file on disk.
  5. Create the initial thread in the process (NtCreateThreadEx).
    • At this point the process creation callback in the kernel will fire. The contents on disk do not match what was mapped. Inspection of the file at this point will result in incorrect attribution.
  6. Close the handle. IRP_MJ_CLEANUP will occur here.
    • Since we've hidden the contents of what is executing, inspection at this point will result in incorrect attribution.

plantuml

@startuml
hide empty description

[*] --> CreateFile
CreateFile --> FileHandle
FileHandle --> Write
FileHandle --> NtCreateSection
Write -[hidden]-> NtCreateSection
NtCreateSection --> SectionHandle
SectionHandle --> NtCreateProcessEx
FileHandle --> Modify
NtCreateProcessEx -[hidden]-> Modify
NtCreateProcessEx --> NtCreateThreadEx
Modify -[hidden]-> NtCreateThreadEx
NtCreateThreadEx --> [*]
FileHandle --> CloseFile
NtCreateThreadEx -[hidden]-> CloseFile
NtCreateThreadEx --> PspCallProcessNotifyRoutines
PspCallProcessNotifyRoutines -[hidden]-> [*]
CloseFile --> IRP_MJ_CLEANUP
IRP_MJ_CLEANUP -[hidden]-> [*]
PspCallProcessNotifyRoutines --> Inspect
PspCallProcessNotifyRoutines -[hidden]-> CloseFile 
IRP_MJ_CLEANUP --> Inspect
Inspect -[hidden]-> [*]

CreateFile : Create target file, keep handle open.
Write : Write source payload into target file.
Modify : Obscure the file on disk.
NtCreateSection : Create section using file handle.
NtCreateProcessEx : Image section for process is mapped and cached in file object.
NtCreateThreadEx : The cached section is used.
NtCreateThreadEx : Process notify routines fire in kernel.
Inspect : The contents on disk do not match what was executed. 
Inspect : Inspection of the file at this point will result in incorrect attribution.
@enduml

Behavior

You'll see in the demo below, CMD.exe is used as the execution target. The first run overwrites the bytes on disk with a pattern. The second run overwrites CMD.exe with ProcessHacker.exe. The Herpaderping tool fixes up the binary to look as close to ProcessHacker.exe as possible, even retaining the original signature. Note the multiple executions of the same binary and how the process looks to the user compared to what is in the file on disk.

Diving Deeper

We've observed the behavior and some of this may be surprising. Let's try to explain this behavior.

Technical Deep Dive

Background and Motivation

When designing products for securing Windows platforms, many engineers in this field (myself included) have fallen on preconceived notions with respect to how the OS will handle data. In this scenario, some might expect the file on disk to remain "locked" when the process is created. You can't delete the file. You can't write to it. But you can rename it. Seen here, under the right conditions, you can in fact write to it. Remain vigilant on your assumptions, always question them, and do your research.

The motivation for this research came about when discovering how to do analysis when a file is written. With prior background researching process Hollowing and Doppelganging, I had theorized this might be possible. The goal is to provide better security. You cannot create a better lock without first understanding how to break the old one.

Similar Techniques

Herpaderping is similar to Hollowing and Doppelganging however there are some key differences:

Process Hollowing

Process Hollowing involves modifying the mapped section before execution begins, which abstractly this looks like: map -> modify section -> execute. This workflow results in the intended execution flow of the Hollowed process diverging into unintended code. Doppelganging might be considered a form of Hollowing. However, Hollowing, in my opinion, is closer to injection in that Hollowing usually involves an explicit write to the already mapped code. This differs from Herpaderping where there are no modified sections.

Process Doppelganging

Process Doppelganging is closer to Herpaderping. Doppelganging abuses transacted file operations and generally involves these steps: transact -> write -> map -> rollback -> execute. In this workflow, the OS will create the image section and account for transactions, so the cached image section ends up being what you wrote to the transaction. The OS has patched this technique. Well, they patched the crash it caused. Maybe they consider this a "legal" use of a transaction. Thankfully, Windows Defender does catch the Doppelganging technique. Doppelganging differs from Herpaderping in that Herpaderping does not rely on transacted file operations. And Defender doesn't catch Herpaderping.

Comparison

For reference, the generalized techniques:

Type Technique
Hollowing map -> modify section -> execute
Doppelganging transact -> write -> map -> rollback -> execute
Herpaderping write -> map -> modify -> execute -> close

We can see the differences laid out here. While Herpaderping is arguably noisier than Doppelganging, in that the malicious bits do hit the disk, we've seen that security products are still incapable of detecting Herpaderping.

Possible Solution

There is not a clear fix here. It seems reasonable that preventing an image section from being mapped/cached when there is write access to the file should close the hole. However, that may or may not be a practical solution.

Another option might be to flush the changes to the file through to the cached image section if it hasn't yet been mapped into a process. However, since the map into the new process occurs at NtCreateProcess that is probably not a viable solution.

From a detection standpoint, there is not a great way to identify the actual bits that got mapped, inspection at IRP_MJ_CLEANUP or a callback registered at PsSetCreateProcessNotifyRoutineEx results in incorrect attribution since the bits on disk have been changed, you would have to rebuild the file from the section that got created. It's worth pointing out here there is a new callback in Windows 10 you may register for PsSetCreateProcessNotifyRoutineEx2 however this suffers from the same problem as the previous callback, it's called out when the initial thread is executed, not when the process object is created. Microsoft did add PsSetCreateThreadNotifyRoutineEx which is called out when the initial thread is inserted if registered with PsCreateThreadNotifyNonSystem, opposed to when it is about to begin execution (as the old callback did). Extending PSCREATEPROCESSNOTIFYTYPE to be called out when the process object is created won't help either, we've seen in the Diving Deeper section that the image section object is cached on the NtCreateSection call not NtCreateProcess.

We can't easily identify what got executed. We're left with trying to detect the exploitive behavior by the actor, I'll leave discovery of the behavior indicators as an exercise for the reader.

Known Affected Platforms

Below is a list of products and Windows OSes that have been tested as of (8/31/2020). Tests were carried out with a known malicious binary.

Operating System Version Vulnerable
Windows 7 Enterprise x86 6.1.7601 Yes
Windows 10 Pro x64 10.0.18363.900 Yes
Windows 10 Pro Insider Preview x64 10.0.20170.1000 Yes
Windows 10 Pro Insider Preview x64 10.0.20201.1000 Yes
Security Product Version Vulnerable
Windows Defender AntiMalware Client 4.18.2006.10 Yes
Windows Defender Engine 1.1.17200.2 Yes
Windows Defender Antivirus 1.319.1127.0 Yes
Windows Defender Antispyware 1.319.1127.0 Yes
Windows Defender AntiMalware Client 4.18.2007.6 Yes
Windows Defender Engine 1.1.17300.2 Yes
Windows Defender Antivirus 1.319.1676.0 Yes
Windows Defender Antispyware 1.319.1676.0 Yes
Windows Defender AntiMalware Client 4.18.2007.8 Yes
Windows Defender Engine 1.1.17400.5 Yes
Windows Defender Antivirus 1.323.267.0 Yes
Windows Defender Antispyware 1.323.267.0 Yes

Responsible Disclosure

This vulnerability was disclosed to the Microsoft Security Response Center (MSRC) on 7/17/2020 and a case was opened by MSRC on 7/22/2020. MSRC concluded their investigation on 8/25/2020 and determined the findings are valid but do not meet their bar for immediate servicing. At this time their case is closed, without resolution, and is marked for future review, with no timeline.

We disagree on the severity of this bug; this was communicated to MSRC on 8/27/2020.

  1. There are similar vulnerabilities in this class (Hollowing and Doppelganging).
  2. The vulnerability is shown to defeat security features inherent to the OS (Windows Defender).
  3. The vulnerability allows an actor to gain execution of arbitrary code.
  4. The user is not notified of the execution of unintended code.
  5. The process information presented to the user does not accurately reflect what is executing.
  6. Facilities to accurately identify the process are not intuitive or incorrect, even from the kernel.

Source

This repo contains a tool for exercising the Herpaderping method of process obfuscation. Usage is as follows:

Process Herpaderping Tool - Copyright (c) Johnny Shaw
ProcessHerpaderping.exe SourceFile TargetFile [ReplacedWith] [Options...]
Usage:
  SourceFile               Source file to execute.
  TargetFile               Target file to execute the source from.
  ReplacedWith             File to replace the target with. Optional,
                           default overwrites the binary with a pattern.
  -h,--help                Prints tool usage.
  -d,--do-not-wait         Does not wait for spawned process to exit,
                           default waits.
  -l,--logging-mask number Specifies the logging mask, defaults to full
                           logging.
                               0x1   Successes
                               0x2   Informational
                               0x4   Warnings
                               0x8   Errors
                               0x10  Contextual
  -q,--quiet               Runs quietly, overrides logging mask, no title.
  -r,--random-obfuscation  Uses random bytes rather than a pattern for
                           file obfuscation.
  -e,--exclusive           Target file is created with exclusive access and
                           the handle is held open as long as possible.
                           Without this option the handle has full share
                           access and is closed as soon as possible.
  -u,--do-not-flush-file   Does not flush file after overwrite.
  -c,--close-file-early    Closes file before thread creation (before the
                           process notify callback fires in the kernel).
                           Not valid with "--exclusive" option.
  -k,--kill                Terminates the spawned process regardless of
                           success or failure, this is useful in some
                           automation environments. Forces "--do-not-wait
                           option.

Cloning and Building

The repo uses submodules, after cloning be sure to init and update the submodules. Projects files are targeted to Visual Studio 2019.

git clone https://github.com/jxy-s/herpaderping.git
cd .\herpaderping\
git submodule update --init --recursive
MSBuild .\herpaderping.sln

Credits

The following are used without modification. Credits to their authors.

  • Windows Implementation Libraries (WIL)
    A header-only C++ library created to make life easier for developers on Windows through readable type-safe C++ interfaces for common Windows coding patterns.
  • Process Hacker Native API Headers
    Collection of Native API header files. Gathered from Microsoft header files and symbol files, as well as a lot of reverse engineering and guessing.

herpaderping's People

Contributors

jxy-s avatar lilhoser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

herpaderping's Issues

unable to build with visual studio 2019

Greetings!

I'm trying to build this project with visual studio 2019.
The build fails with error: "cannot open source file "span"
Any suggestions on where to find this library?

Thanks

Build error

hey when i try to build the solution using visual studio 2019 i get these errors :

Severity Code Description Project File Line Suppression State
Error C1083 Cannot open include file: 'wil/common.h': No such file or directory ProcessHerpaderping C:\Users**\Desktop\jxy-s-herpaderping-3d4c5ff\source\ProcessHerpaderping\pch.hpp 46

Unable to Build on Windows VS Studio 2019

following the instructions in the read me I was unable to build the executable. Am I missing a dependency or a setting change for the solution?
I received the following error

Microsoft (R) Build Engine version 16.4.0+e901037fe for .NET Framework
Copyright (C) Microsoft Corporation. All rights reserved.

Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
Build started 11/10/2020 2:39:13 PM.
Project "C:\Users\Mack\source\repos\herpaderping\herpaderping.sln" on node 1 (default targets).
ValidateSolutionConfiguration:
  Building solution configuration "Debug|x64".
Project "C:\Users\Mack\source\repos\herpaderping\herpaderping.sln" (1) is building "C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHer
paderping.vcxproj" (2) on node 1 (default targets).
PrepareForBuild:
  Creating directory "x64\Debug\".
  Creating directory "C:\Users\Mack\source\repos\herpaderping\build\Debug.x64\".
  Creating directory "x64\Debug\ProcessH.25CB55EF.tlog\".
InitializeBuildStatus:
  Creating "x64\Debug\ProcessH.25CB55EF.tlog\unsuccessfulbuild" because "AlwaysCreate" was specified.
ClCompile:
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\CL.exe /c /IC:\Users\Mack\source\repos\herpaderping\ /
  IC:\Users\Mack\source\repos\herpaderping\ext\submodules\ /IC:\Users\Mack\source\repos\herpaderping\ext\submodules\phnt\ /IC:\Users\Mack\source\repos\herpaderpi
  ng\ext\submodules\wil\include\ /ZI /nologo /W4 /WX /diagnostics:column /sdl /Od /D CODE_ANALYSIS /D _DEBUG /D _CONSOLE /D _UNICODE /D UNICODE /Gm- /EHsc /RTC1
  /MTd /GS /fp:precise /permissive- /Zc:wchar_t /Zc:forScope /Zc:inline /std:c++latest /Yc"pch.hpp" /Fp"x64\Debug\ProcessHerpaderping.pch" /Fo"x64\Debug\\" /Fd"x
  64\Debug\vc142.pdb" /doc"x64\Debug\\" /Gd /TP /analyze /analyze:projectdirectory"C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\\" /analyze
  :rulesetdirectory";C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Team Tools\Static Analysis Tools\\Rule Sets;" /analyze:ruleset "C:\Program Fi
  les (x86)\Microsoft Visual Studio\2019\Enterprise\Team Tools\Static Analysis Tools\Rule Sets\NativeRecommendedRules.ruleset" /analyze:quiet /analyze:plugin"C:\
  Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.24.28314\bin\HostX86\x86\EspXEngine.dll" /FC /errorReport:queue herpaderp.cpp main
  .cpp utils.cpp
  herpaderp.cpp
C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directory
 [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]
  main.cpp
C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directory
 [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]
  utils.cpp
C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directory
 [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]
Done Building Project "C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj" (default targets) -- FAILED.

Done Building Project "C:\Users\Mack\source\repos\herpaderping\herpaderping.sln" (default targets) -- FAILED.


Build FAILED.

"C:\Users\Mack\source\repos\herpaderping\herpaderping.sln" (default target) (1) ->
"C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj" (default target) (2) ->
(ClCompile target) ->
  C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directo
ry [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]
  C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directo
ry [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]
  C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\pch.hpp(35,10): fatal error C1083: Cannot open include file: 'span': No such file or directo
ry [C:\Users\Mack\source\repos\herpaderping\source\ProcessHerpaderping\ProcessHerpaderping.vcxproj]

    0 Warning(s)
    3 Error(s)

Time Elapsed 00:00:03.55````

What about PsSetLoadImageNotifyRoutine ?

Hello!
I apologize at once for the perhaps naive questions.

I am studying your project and found several things:

  1. When PLOAD_IMAGE_NOTIFY_ROUTINE is called, I can see that my _FILE_OBJECT parameters are:
  +0x04a ReadAccess : 0x1 ''
   +0x04b WriteAccess : 0x1 '' <----
   +0x04c DeleteAccess : 0 ''
   +0x04d SharedRead : 0x1 ''
   +0x04e SharedWrite : 0x1 ''
   +0x04f SharedDelete : 0x1 ''

You can see that WriteAccess is non-zero. In the examples from your documentation I see that WriteAccess is 0.

My example of running a program:

ProcessHerpaderping.exe X.exe Y.exe Z.exe

Am I doing something wrong?
I looked at your code and I don't think there can be WriteAccess == 0


  1. I also noticed that when reading the PE header at the ImageBase address (I can get this field in the callback)
    I am reading the original PE header (not the replaced file).
    So I can compare what's currently on the disk with what's at the ImageBase address.
    This will be different when I using your current project.

My question is, are these two items proof that something went wrong with the process? (If we assume that "normal" processes for us are read-only processes)

Thank you. โค

Unable to build: cyclic dependency

Hello! I tried to build, but got the following errors:

Build started...
1>------ Build started: Project: ProcessHerpaderping, Configuration: Release x64 ------
1>Scanning sources for module dependencies...
1>C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(486,5): error : Cannot build the following source files because there is a cyclic dependency between them: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.ixx depends on C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.compat.ixx depends on C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.ixx.
1>Compiling...
1>C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(544,5): error : Cannot build the following source files because there is a cyclic dependency between them: C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.ixx depends on C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.compat.ixx depends on C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.36.32532\modules\std.ixx.
1>Done building project "ProcessHerpaderping.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The only thing I changed is retargeted the project's platform toolset from v142 to v143 (MSVS 2022).

Arch limitation

Not issue, just a quick note which worth noting:

You can only apply this if you're building & running on the same arch as your OS, which means you can't just start a 32bit target on your 64bit host. Neither whether your compiled herpaderper is 32 or 64bit. At least according to my observation.

As far as I yet researched the target process is created with a 64bit image type by default. You would have to somehow specify at the process creation to make it a wow64 process. I've got no idea how by the way ;)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.