Skip to content

Chapter 9: The Service Module

Introduction

Windows services are the foundation of the operating system's functionality. They start before users log in, run in the background without requiring interactive sessions, and handle everything from network configuration to security monitoring. For an attacker, services represent both an obstacle and an opportunity: security services stand guard against malicious activity, but the service architecture itself provides one of the most reliable persistence mechanisms available.

The Service Module in Mimikatz addresses both sides of this equation. It provides commands to manipulate existing services—starting, stopping, suspending, and removing them—and offers a turnkey method to install Mimikatz itself as a persistent service that survives system reboots. From an operational perspective, the ability to stop security services before performing noisy operations and then establish persistence through the same mechanism makes this module a cornerstone of post-exploitation tradecraft.

In my experience, service manipulation is one of the first things I consider after gaining administrative access. The immediate question is: what security services are running, and can I blind them? The secondary question is: how do I maintain access if I lose my current foothold? The Service Module answers both.

This chapter covers the architecture of Windows services and the Service Control Manager, the full command set for service manipulation, operational techniques for both offense and defense, detection strategies based on specific Event IDs, and best practices for maintaining operational security when using these capabilities.

Technical Foundation

Windows Service Architecture

Windows services are executable programs that perform specific functions and can be configured to start automatically without user interaction. The service architecture provides isolation, privilege management, and lifecycle control through a centralized management system.

The Service Control Manager (SCM)

The Service Control Manager (services.exe) is the Windows component responsible for:

  1. Starting and stopping services according to their configuration
  2. Maintaining service state and handling state transitions
  3. Processing control requests from administrators and applications
  4. Managing service dependencies to ensure proper startup order
  5. Communicating with services through a defined protocol

The SCM acts as the gateway for all service operations. Any program that wants to control a service must communicate through the SCM.

Service Registry Configuration

Service definitions are stored in the registry at:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<ServiceName>

Each service key contains values that define its behavior:

ValueDescriptionExample
ImagePathPath to the service executableC:\Windows\System32\svchost.exe -k netsvcs
StartStartup type0=Boot, 1=System, 2=Automatic, 3=Manual, 4=Disabled
TypeService type0x10=Own Process, 0x20=Share Process
ObjectNameAccount the service runs asLocalSystem, NT AUTHORITY\LocalService
DisplayNameHuman-readable nameWindows Update
DescriptionService descriptionEnables the detection, download...
DependOnServiceRequired servicesRPCSS, Tcpip

Service Execution Contexts

Services run under specific security contexts that determine their capabilities:

ContextAccess LevelNetwork CredentialsUse Case
LocalSystem (SYSTEM)Full local accessComputer account on networkHigh-privilege services
LocalServiceLimited local accessAnonymous on networkLow-privilege services
NetworkServiceLimited local accessComputer account on networkNetwork-aware services
Domain/Local UserUser's permissionsUser's credentialsApplication services

SYSTEM is the most powerful context—services running as SYSTEM have unrestricted access to the local system. This is why security services like Windows Defender run as SYSTEM, and why establishing persistence as a SYSTEM service is so valuable.

Service Control Protocol

Services communicate with the SCM through a defined protocol:

  1. SCM starts the service process
  2. Service calls StartServiceCtrlDispatcher to connect to SCM
  3. Service registers a handler for control requests
  4. Service reports status (STARTING, RUNNING, STOPPING, etc.)
  5. SCM sends control requests (stop, pause, etc.) to the handler

The service::me command in Mimikatz handles step 4—reporting successful startup to the SCM so it doesn't think the service failed.

Command Reference

service::start - Starting Services

Starts a service that is currently stopped or in a disabled state (if startup type allows).

Syntax

mimikatz # service::start <servicename>

Example

mimikatz # service::start EventLog
Service 'EventLog' started.

Technical Details

The command uses the StartService() Windows API, which requires:

  • SC_MANAGER_CONNECT right on the SCM
  • SERVICE_START right on the target service

service::stop - Stopping Services

Stops a running service by sending the SERVICE_CONTROL_STOP signal.

Syntax

mimikatz # service::stop <servicename>

Service control

Common Targets for Security Evasion

Service NameDisplay NamePurpose
WinDefendWindows Defender Antivirus ServiceReal-time AV scanning
SenseWindows Defender Advanced Threat ProtectionEDR telemetry
MpsSvcWindows FirewallNetwork filtering
EventLogWindows Event LogSecurity logging
wscsvcSecurity CenterSecurity status monitoring
DiagTrackConnected User ExperiencesTelemetry

Operational Reality

Modern security services implement self-protection mechanisms:

  1. Tamper Protection: Windows Defender can't be stopped when enabled
  2. PPL Protection: Services marked as Protected Process Light reject stop requests
  3. EDR Watchdogs: Many EDRs monitor for service manipulation and auto-restart
  4. Kernel Callbacks: Some EDRs register kernel callbacks that survive service stops

Attempting to stop a protected service often fails with Access Denied even with SYSTEM privileges.

service::suspend and service::resume - Stealth Control

Suspending a service freezes its threads without terminating the process, potentially evading "service stopped" alerts.

Syntax

mimikatz # service::suspend <servicename>
mimikatz # service::resume <servicename>

Why Suspension Can Be Stealthier

AspectStopSuspend
Process stateTerminatedFrozen
Event ID 7036"Stopped"Usually not generated
Registry changeNoneNone
Memory presenceUnloadedRetained
Auto-restartMay triggerUsually doesn't

A suspended security service can't scan files or process events, but its process still exists, which may avoid detection rules that look for missing processes.

service::preshutdown and service::shutdown

These commands send specific control signals to services:

Syntax

mimikatz # service::preshutdown <servicename>
mimikatz # service::shutdown <servicename>

SERVICE_CONTROL_PRESHUTDOWN gives services time to save state before shutdown. SERVICE_CONTROL_SHUTDOWN is the final shutdown signal.

These are less commonly used in offensive scenarios but can be useful for specific service manipulation.

service::remove - Service Deletion

Stops a service and deletes its registry configuration, permanently removing it from the system.

Syntax

mimikatz # service::remove <servicename>

Warning: Removing critical services can render the system unbootable. This command is typically used for cleanup rather than evasion.

service::+ - Mimikatz Service Installation

This is the persistence command. It installs Mimikatz as a service named mimikatzsvc that automatically starts on boot.

Syntax

mimikatz # service::+
Service 'mimikatzsvc' installed.

Service install

What Gets Created

When you run service::+, Mimikatz creates a service with these properties:

PropertyValue
Service Namemimikatzsvc
Display Namemimikatzsvc
Binary Path<current_path>\mimikatz.exe rpc::server service::me exit
Start TypeAutomatic (2)
AccountLocalSystem
TypeOwn Process (0x10)

How It Works

The installed service runs this command sequence:

  1. rpc::server: Starts the RPC server (Chapter 8), listening for remote connections
  2. service::me: Sends SERVICE_RUNNING status to the SCM
  3. exit: Keeps the process running until terminated

The result is a persistent, SYSTEM-level RPC server that survives reboots and awaits your remote connection.

Service installation details

service::- - Service Uninstallation

Removes the mimikatzsvc service—essential for cleanup.

Syntax

mimikatz # service::-
Service 'mimikatzsvc' removed.

Service uninstall

service::me - SCM Communication

This internal command is used by the Mimikatz service to communicate with the SCM.

Syntax

mimikatz # service::me

It sends SERVICE_RUNNING status to the SCM, preventing the SCM from thinking the service failed to start. You typically don't use this command directly—it's part of the service's startup command line.

Attack Scenarios

Scenario 1: Blinding Security Services Before Credential Theft

Context: You need to extract credentials but Windows Defender is active.

Attack Flow:

  1. Check Defender status: sc query WinDefend
  2. Attempt to stop: service::stop WinDefend
  3. If stopped, proceed with sekurlsa::logonpasswords
  4. Restart Defender: service::start WinDefend

Reality Check: With Tamper Protection enabled, this will fail. You'll need to use kernel techniques (Chapter 13) or work around Defender rather than disabling it.

Scenario 2: Persistence Installation

Context: You have SYSTEM access and want to maintain it across reboots.

Attack Flow:

  1. Copy Mimikatz to a persistent location: C:\Windows\System32\drivers\msupdate.exe
  2. Rename the binary to something innocuous
  3. If using custom build: modify service name before compilation
  4. Run service::+
  5. Verify installation: sc query mimikatzsvc
  6. Test persistence by rebooting (in lab)

After Reboot:

  1. Connect via RPC from another system
  2. Verify the service is running
  3. Perform operations
  4. Clean up before leaving: service::-

Scenario 3: Stealth Service Suspension

Context: You want to disable security monitoring without triggering "service stopped" alerts.

Attack Flow:

  1. Identify security services: sc query state= all | findstr /i "defend sense"
  2. Suspend rather than stop: service::suspend Sense
  3. Verify suspension (process exists but threads frozen)
  4. Perform operations
  5. Resume before leaving: service::resume Sense

Limitation: Not all services handle suspension gracefully. Some may crash or become unstable.

Scenario 4: Service Configuration for Lateral Movement

Context: You want to establish persistence on a remote system.

Attack Flow (requires administrative access to remote system):

  1. Copy Mimikatz to remote system via SMB
  2. Use sc.exe to create service remotely:
    sc \\target create svcname binPath= "C:\path\mimikatz.exe rpc::server service::me exit"
    sc \\target start svcname
  3. Connect via Mimikatz RPC from your system
  4. Perform operations remotely

Detection and Indicators of Compromise

Event ID 7045 - Service Installation

The primary detection point for service-based persistence. Every new service installation generates Event ID 7045 in the System log.

Event ID 7045

Event Structure

xml
<Event xmlns="...">
  <System>
    <EventID>7045</EventID>
    <TimeCreated SystemTime="2024-01-15T10:30:00.000Z" />
    ...
  </System>
  <EventData>
    <Data Name="ServiceName">mimikatzsvc</Data>
    <Data Name="ImagePath">C:\temp\mimikatz.exe rpc::server service::me exit</Data>
    <Data Name="ServiceType">user mode service</Data>
    <Data Name="StartType">auto start</Data>
    <Data Name="AccountName">LocalSystem</Data>
  </EventData>
</Event>

Detection Rules

# SIEM pseudo-query for suspicious service installation
index=wineventlog EventCode=7045
| where (
    ImagePath LIKE "%rpc::server%"
    OR ImagePath LIKE "%service::me%"
    OR ImagePath LIKE "%mimikatz%"
    OR ServiceName IN ("mimikatzsvc", suspicious_service_list)
    OR AccountName="LocalSystem" AND StartType="auto start"
)
| table _time, host, ServiceName, ImagePath, AccountName

Event ID 7036 - Service State Changes

Monitors for security services stopping unexpectedly.

Event Structure

xml
<Event xmlns="...">
  <System>
    <EventID>7036</EventID>
    ...
  </System>
  <EventData>
    <Data Name="param1">Windows Defender Antivirus Service</Data>
    <Data Name="param2">stopped</Data>
  </EventData>
</Event>

High-Priority Service Stops

Alert when these services stop outside maintenance windows:

Service Display NamePriority
Windows Defender Antivirus ServiceCritical
Windows Defender Advanced Threat Protection ServiceCritical
Windows FirewallHigh
Windows Event LogCritical
Security CenterHigh

Event ID 4697 - Security Audit

If audit policy is configured, service installation also generates Security Event 4697:

Computer Configuration → Windows Settings → Security Settings →
Advanced Audit Policy → System → Audit Security System Extension

This provides additional context including the process that installed the service.

Sysmon Detection

Sysmon can provide enhanced visibility:

Event IDIndicatorDetection Value
1Process creationMimikatz binary executing
12/13Registry modificationService registry keys created
7Image loadedService executable loaded

Detection Summary

Event SourceEvent IDIndicatorPriority
System7045New service installedHigh
System7036Security service stoppedCritical
Security4697Service install auditHigh
Sysmon1Suspicious service binaryMedium
Sysmon12Services registry writeMedium

Defensive Strategies

1. Monitor for Service Installation Events

Create high-priority alerts for Event ID 7045:

powershell
# PowerShell detection script
$events = Get-WinEvent -FilterHashtable @{
    LogName = 'System'
    ID = 7045
    StartTime = (Get-Date).AddHours(-24)
}

foreach ($event in $events) {
    $xml = [xml]$event.ToXml()
    $serviceName = $xml.Event.EventData.Data |
        Where-Object {$_.Name -eq 'ServiceName'} |
        Select-Object -ExpandProperty '#text'

    if ($serviceName -notin $approvedServices) {
        # Alert on unapproved service
        Write-Warning "Unapproved service installed: $serviceName"
    }
}

2. Enable Tamper Protection

Windows Defender's Tamper Protection prevents stopping Defender services:

powershell
# Check Tamper Protection status
Get-MpPreference | Select-Object DisableTamperProtection

Enable via:

  • Windows Security → Virus & threat protection → Manage settings
  • Microsoft Endpoint Manager (Intune) policy
  • Group Policy (limited scenarios)

3. Implement Application Whitelisting

Block unauthorized service installations through:

SolutionApproach
Windows Defender Application ControlCode integrity policies
AppLockerPublisher/hash rules
Third-party EDRBehavioral blocking

4. Audit Service Account Permissions

Review which accounts can install services:

powershell
# Check service security
sc sdshow scmanager

The default allows Administrators to install services. Consider whether this is appropriate for your environment.

5. Deploy Service Integrity Monitoring

Baseline your environment's services and alert on changes:

powershell
# Baseline services
Get-Service | Select-Object Name, DisplayName, Status, StartType |
    Export-Csv C:\Baseline\services.csv

# Compare current to baseline
$current = Get-Service
$baseline = Import-Csv C:\Baseline\services.csv
Compare-Object $baseline $current -Property Name

6. Restrict Remote Service Installation

Limit remote SCM access:

Computer Configuration → Windows Settings → Security Settings →
Local Policies → User Rights Assignment →
Access this computer from the network

7. Monitor Security Service Health

Implement watchdog monitoring for critical services:

powershell
# Continuous monitoring script
$criticalServices = @('WinDefend', 'Sense', 'EventLog')
while ($true) {
    foreach ($svc in $criticalServices) {
        $status = (Get-Service $svc -ErrorAction SilentlyContinue).Status
        if ($status -ne 'Running') {
            # Alert and attempt restart
            Send-Alert "Critical service $svc is $status"
            Start-Service $svc -ErrorAction SilentlyContinue
        }
    }
    Start-Sleep -Seconds 30
}

Operational Considerations

Service Naming and Evasion

The default mimikatzsvc name is an obvious indicator. For operational use, consider:

  1. Custom Compilation: Modify kuhl_m_service.c to change:

    • SERVICE_NAME
    • SERVICE_DISPLAYNAME
    • Service description
  2. Naming Strategy: Choose names that blend with legitimate services:

    • WindowsUpdateComponentService
    • Microsoft.NET Framework NGEN Service
    • Intel(R) Management Engine
  3. Binary Naming: Rename the Mimikatz binary:

    • svchost.exe (dangerous—may conflict)
    • msdtc.exe (if not used)
    • Custom name matching service name

Service Dependencies

Configure dependencies to ensure your service starts at the right time:

sc config mimikatzsvc depend= "Tcpip/RpcSs"

This ensures network services are available before your RPC server starts.

Cleanup Procedures

Always clean up after operations:

  1. Stop the service: service::-
  2. Verify removal: sc query mimikatzsvc (should return "FAILED 1060")
  3. Delete the binary
  4. Check for residual registry entries
  5. Review event logs for your activity

Privilege Requirements

OperationRequired Privilege
Query servicesNone (most services)
Start/stop servicesSERVICE_START/STOP on specific service
Install servicesSC_MANAGER_CREATE_SERVICE
Remove servicesDELETE on specific service

Administrative privileges generally provide all necessary rights.

Protected Services Handling

When encountering protected services:

  1. Identify protection type: PPL, Tamper Protection, EDR self-defense
  2. Kernel techniques: Use driver loading (Chapter 13) to bypass
  3. Indirect approaches: Work around rather than disable
  4. Accept limitations: Some protections can't be bypassed without detection

Practical Lab Exercises

Exercise 1: SCM Exploration

Objective: Understand service configuration through registry and command-line tools.

  1. List all services:

    cmd
    sc query state= all
  2. Examine a specific service's registry configuration:

    cmd
    reg query HKLM\SYSTEM\CurrentControlSet\Services\EventLog
  3. Check service security descriptor:

    cmd
    sc sdshow EventLog
  4. Document the relationship between registry values and service behavior.

Exercise 2: Service Installation and Verification

Objective: Install and verify the Mimikatz service.

  1. Run Mimikatz with administrative privileges
  2. Install the service: service::+
  3. Verify via services.msc:
    • Find mimikatzsvc
    • Check startup type (should be Automatic)
    • Check account (should be LocalSystem)
  4. Verify via command line:
    cmd
    sc query mimikatzsvc
    sc qc mimikatzsvc
  5. Clean up: service::-

Exercise 3: Event Log Analysis

Objective: Identify the forensic trail left by service installation.

  1. Clear the System event log (lab only)
  2. Install the service: service::+
  3. Open Event Viewer → System log
  4. Find Event ID 7045
  5. Document:
    • ServiceName
    • ImagePath (note the command line arguments)
    • StartType
    • AccountName
  6. Create a detection rule based on your findings

Exercise 4: Service Manipulation Testing

Objective: Test service control capabilities and observe detection events.

  1. Start with Sysmon installed and configured
  2. Stop a test service (not critical): service::stop Themes
  3. Check System log for Event ID 7036
  4. Restart the service: service::start Themes
  5. Attempt to stop Windows Defender: service::stop WinDefend
  6. Observe the error if Tamper Protection is enabled
  7. Document which services can and cannot be stopped

Exercise 5: Persistence Testing

Objective: Validate that service persistence survives reboot.

Warning: Only perform on lab/test systems

  1. Install the service: service::+
  2. Verify service is running: sc query mimikatzsvc
  3. Reboot the system
  4. After reboot, verify:
    • Service is running: sc query mimikatzsvc
    • Mimikatz process exists: tasklist | findstr mimikatz
    • RPC port is listening: netstat -an | findstr LISTENING
  5. Clean up:
    • Connect to service: rpc::connect
    • Remove: service::-
    • Kill process if needed

Summary

The Service Module provides essential capabilities for both offensive operations and security assessment. Understanding how to manipulate services—and how that manipulation can be detected—is fundamental to both attack and defense.

Key Takeaways:

  • service::stop can disable security services but modern protections often prevent this
  • service::suspend may be stealthier than stopping but has compatibility issues
  • service::+ installs persistent, SYSTEM-level access that survives reboot
  • Event ID 7045 is the primary indicator for service installation—monitor it closely
  • Event ID 7036 reveals service state changes including security service stops
  • Tamper Protection and PPL significantly limit service manipulation capabilities
  • Operational security requires changing default service names and cleaning up after operations

Service-based persistence remains one of the most reliable methods because it uses legitimate Windows functionality. The key for attackers is blending in; the key for defenders is knowing what "normal" looks like and alerting on deviations.


Next: Chapter 10: Process ModulePrevious: Chapter 8: RPC Remote Control