# Windows 새 서비스 등록 이벤트 7045와 WMI 이벤트 구독을 점검 스크립트로 찾고 지우기

> Windows 11에서 시스템 권한으로 도는 서비스와 WMI 이벤트 구독은 재부팅 뒤에도 남는 은밀한 자동 실행 방법입니다. 무해한 시험 서비스와 구독을 직접 등록하고, 이벤트 7045와 5861과 점검 스크립트로 찾은 뒤 지워 처음 상태로 돌아온 것까지 확인합니다.

- 주소: https://copyandrun.com/blog/windows-service-7045-wmi-subscription-persistence/
- 분야: Windows 보안
- 발행일: 2026-10-28
- 태그: Windows, 지속성, 서비스, WMI, 이벤트 7045

[Run 키 글](/blog/windows-run-key-startup-folder-persistence/)의 자동 실행은 사용자가 로그온해야 동작합니다. 서비스와 WMI 이벤트 구독은 다릅니다. 서비스는 부팅하면 로그온 없이 시작되고 기본 계정이 `LocalSystem`입니다. WMI 이벤트 구독은 파일이 아니라 WMI 저장소에 들어가서, 시작 프로그램 목록이나 파일 검색에는 나타나지 않습니다. 그래서 공격자가 즐겨 쓰는 곳이고, 점검에서 놓치기 쉬운 곳입니다.

이 글에서는 두 곳을 읽는 스크립트를 만들고, 무해한 시험 서비스와 시험 구독을 등록했다가 지웁니다. 서비스는 시작하지 않았고(`Manual`로 만들고 `Stopped`인 채 지웠습니다), 구독은 실제로는 일어나지 않는 이벤트를 기다리도록 만들었습니다.

## 준비물

| 항목 | 확인한 값 |
|---|---|
| 운영체제 | Windows 11 (빌드 26200), 표시 언어 영어 |
| PowerShell | 관리자 PowerShell (Windows PowerShell 5.1). 서비스 등록과 WMI 저장소 쓰기에 필요합니다 |
| 시험 서비스 | `CrLabSvc`, 수동 시작, 실행 파일 `cmd.exe /c echo crlab` |
| 시험 구독 | 필터 `CrLabFilter`, 소비자 `CrLabConsumer` |

## 1. 두 곳에서 볼 것

| 위치 | 남는 기록 | 읽는 법 |
|---|---|---|
| 새 서비스 | 시스템 로그의 이벤트 7045 (`Service Control Manager`) | `ImagePath`가 `C:\Windows`나 `Program Files` 밖이거나 명령 인터프리터(`cmd.exe`, `powershell.exe`)이면 의심합니다 |
| WMI 구독 | `Microsoft-Windows-WMI-Activity/Operational`의 이벤트 5861, `root\subscription` 안의 개체 | 소비자가 `CommandLineEventConsumer`나 `ActiveScriptEventConsumer`이면 실행 내용을 읽습니다 |

WMI 구독은 세 개체가 한 묶음으로 움직입니다. 무엇을 기다릴지 정하는 필터, 기다리던 일이 일어나면 할 일을 정하는 소비자, 둘을 잇는 바인딩입니다.

## 2. 점검 스크립트

`Get-ServiceAndWmiPersistence.ps1`은 아무것도 바꾸지 않고 세 구역을 읽습니다. 최근 몇 시간 안에 등록된 서비스(7045), Windows와 Program Files 밖의 서비스 목록, `root\subscription`의 필터, 소비자, 바인딩 개수와 내용입니다. `-Match`로 이름이나 명령에 들어 있는 글자를 걸러 볼 수 있습니다.

```powershell
# Read-only check of two persistence places: new services (event 7045) and WMI event subscriptions.
# It changes nothing.
# Usage (elevated PowerShell):
#   powershell -NoProfile -ExecutionPolicy Bypass -File .\Get-ServiceAndWmiPersistence.ps1 -Hours 24 [-Match crlab]
param([int]$Hours = 24, [string]$Match = "")

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

$start = (Get-Date).AddHours(-$Hours)

Write-Output "== New services (System log, event 7045, last $Hours h)"
$new = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager'; Id = 7045; StartTime = $start } -ErrorAction SilentlyContinue)
$shown = 0
foreach ($e in ($new | Sort-Object TimeCreated)) {
    $d = @{}
    ([xml]$e.ToXml()).Event.EventData.Data | ForEach-Object { $d[$_.Name] = $_.'#text' }
    if ($Match -and ($d.ServiceName -notlike "*$Match*") -and ($d.ImagePath -notlike "*$Match*")) { continue }
    $shown++
    Write-Output ("  {0}  {1}" -f $e.TimeCreated.ToString('MM-dd HH:mm:ss'), $d.ServiceName)
    Write-Output ("      image: {0}" -f $d.ImagePath)
    Write-Output ("      type: {0}, start: {1}, account: {2}" -f $d.ServiceType, $d.StartType, $d.AccountName)
}
if ($shown -eq 0) { Write-Output "  none" }

Write-Output "== Services running from outside Windows and Program Files"
$odd = @(Get-CimInstance Win32_Service | Where-Object {
    $_.PathName -and ($_.PathName -notlike '*\Windows\*') -and ($_.PathName -notlike '*Program Files*') -and ($_.PathName -notlike '*ProgramData\Microsoft*')
})
if ($Match) { $odd = @($odd | Where-Object { $_.Name -like "*$Match*" -or $_.PathName -like "*$Match*" }) }
if ($odd.Count -eq 0) { Write-Output "  none" } else { foreach ($s in $odd) { Write-Output ("  {0} [{1}/{2}]  {3}" -f $s.Name, $s.StartMode, $s.State, $s.PathName) } }

Write-Output "== WMI event subscriptions (root\subscription)"
$ns = 'root\subscription'
$filters   = @(Get-CimInstance -Namespace $ns -ClassName __EventFilter -ErrorAction SilentlyContinue)
$consumers = @(Get-CimInstance -Namespace $ns -ClassName __EventConsumer -ErrorAction SilentlyContinue)
$bindings  = @(Get-CimInstance -Namespace $ns -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue)
if ($Match) {
    $filters   = @($filters   | Where-Object { $_.Name -like "*$Match*" -or $_.Query -like "*$Match*" })
    $consumers = @($consumers | Where-Object { $_.Name -like "*$Match*" -or ($_.PSObject.Properties['CommandLineTemplate'] -and $_.CommandLineTemplate -like "*$Match*") })
    $bindings  = @($bindings  | Where-Object { "$($_.Filter)" -like "*$Match*" -or "$($_.Consumer)" -like "*$Match*" })
}
Write-Output ("  filters: {0}, consumers: {1}, bindings: {2}" -f $filters.Count, $consumers.Count, $bindings.Count)
foreach ($f in $filters)   { Write-Output ("  filter   {0}: {1}" -f $f.Name, $f.Query) }
foreach ($c in $consumers) {
    $detail = if ($c.PSObject.Properties['CommandLineTemplate']) { $c.CommandLineTemplate } elseif ($c.PSObject.Properties['ScriptText']) { 'script text' } else { '' }
    Write-Output ("  consumer {0} [{1}] {2}" -f $c.Name, $c.CimClass.CimClassName, $detail)
}
```

## 3. 발견: 처음 상태

아무것도 등록하기 전에 읽었습니다. 서비스 쪽은 이 PC에 설치된 소프트웨어 이름이 나와 싣지 않고, WMI 쪽만 옮깁니다.

```text
== New services (System log, event 7045, last 1 h)
  none
== WMI event subscriptions (root\subscription)
  filters: 1, consumers: 1, bindings: 1
  filter   SCM Event Log Filter: select * from MSFT_SCMEventLogEvent
  consumer SCM Event Log Consumer [NTEventLogEventConsumer]
```

WMI 구독은 필터, 소비자, 바인딩이 하나씩 있습니다. 이 한 쌍(`SCM Event Log Filter`와 `SCM Event Log Consumer`)은 Windows가 기본으로 두는 항목입니다. 점검 때는 이 기본 항목을 기준선으로 삼고, 그 밖에 늘어난 것을 봅니다.

## 4. 재현: 시험 서비스와 시험 구독 등록

```powershell
$ns = 'root\subscription'

# 서비스: 수동 시작이라 시작하지 않으면 실행되지 않습니다
New-Service -Name 'CrLabSvc' -BinaryPathName 'C:\Windows\System32\cmd.exe /c echo crlab' `
    -DisplayName 'CrLab Test Service' -StartupType Manual | Out-Null

# WMI 구독: 이름이 crlab-never.exe인 프로세스가 생길 때만 동작하도록 만든 필터
$filter = New-CimInstance -Namespace $ns -ClassName __EventFilter -Property @{
    Name = 'CrLabFilter'; EventNamespace = 'root\cimv2'; QueryLanguage = 'WQL'
    Query = "SELECT * FROM __InstanceCreationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'crlab-never.exe'" }
$consumer = New-CimInstance -Namespace $ns -ClassName CommandLineEventConsumer -Property @{
    Name = 'CrLabConsumer'; CommandLineTemplate = 'cmd.exe /c echo crlab' }
New-CimInstance -Namespace $ns -ClassName __FilterToConsumerBinding -Property @{ Filter = [ref]$filter; Consumer = [ref]$consumer } | Out-Null
```

## 5. 확인: 두 곳이 모두 잡힙니다

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\Get-ServiceAndWmiPersistence.ps1 -Hours 1 -Match crlab
```

```text
== New services (System log, event 7045, last 1 h)
  10-28 17:17:57  CrLab Test Service
      image: C:\Windows\System32\cmd.exe /c echo crlab
      type: user mode service, start: demand start, account: LocalSystem
== Services running from outside Windows and Program Files
  none
== WMI event subscriptions (root\subscription)
  filters: 1, consumers: 1, bindings: 1
  filter   CrLabFilter: SELECT * FROM __InstanceCreationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'crlab-never.exe'
  consumer CrLabConsumer [CommandLineEventConsumer] cmd.exe /c echo crlab
```

같은 시험을 별도의 시험용 PC에서 다시 하고 화면을 찍었습니다. 서비스는 만든 시각(14:59:50)과 `LocalSystem` 계정이 보이고, 구독은 필터, 소비자, 바인딩이 한 개씩 잡혔습니다.

![Get-ServiceAndWmiPersistence.ps1를 -Match crlab으로 실행한 결과에서 CrLab Test Service가 LocalSystem 계정의 수동 시작 서비스로 나오고, WMI 구독의 필터와 소비자와 바인딩이 한 개씩 잡히는 것을 확인합니다.](https://copyandrun.com/img/windows-service-7045-wmi-subscription-persistence/01-서비스-WMI-점검.png)

같은 두 기록은 이벤트 뷰어에서도 볼 수 있습니다. 사용자 지정 보기에 시스템 로그의 7045와 WMI-Activity 로그의 5861을 함께 걸면 아래처럼 한 목록에 모입니다. 5861을 선택하면 필터 이름 `CrLabFilter`와 소비자 `CrLabConsumer`가 본문에 그대로 보입니다. 목록의 10월 27일 7045는 이 시험용 PC에 이전에 설치된 서비스의 기록입니다.

![이벤트 뷰어의 사용자 지정 보기에 이벤트 5861 한 건과 7045 여섯 건이 모이고, 5861을 선택한 아래 창에 필터 CrLabFilter와 소비자 CommandLineEventConsumer CrLabConsumer가 보이는 것을 확인합니다.](https://copyandrun.com/img/windows-service-7045-wmi-subscription-persistence/02-이벤트-뷰어-7045-5861.png)

읽을 것은 네 가지입니다.

- **계정이 `LocalSystem`입니다.** 계정을 지정하지 않고 만든 서비스는 가장 강한 계정으로 동작합니다. 새 서비스가 보이면 이 줄부터 봅니다.
- **7045는 시스템 로그에 남습니다.** 보안 로그의 4697(서비스 설치)은 이 PC에서 0건이었습니다. 해당 감사가 꺼져 있었기 때문이며, 7045는 별도 설정 없이 남았습니다.
- **`Services running from outside` 구역이 `none`입니다.** 시험 서비스의 실행 파일이 `C:\Windows\System32` 안이어서 이 기준에는 걸리지 않았습니다. 공격자가 시스템 폴더의 정상 도구를 인자와 함께 부르면 위치 기준만으로는 놓칩니다. 7045의 `ImagePath` 전체를 읽는 이유입니다.
- **WMI 구독은 개체 안에 명령이 그대로 들어 있습니다.** 파일을 찾을 필요 없이 소비자의 `CommandLineTemplate`을 읽으면 됩니다.

WMI 구독을 만든 순간은 `Microsoft-Windows-WMI-Activity/Operational`의 이벤트 5861로도 남았습니다. 본문 첫 줄은 다음과 같았습니다.

```text
Namespace = //./root/subscription; Eventfilter = CrLabFilter (refer to its activate eventid:5859); Consumer = CommandLineEventConsumer="CrLabConsumer"; PossibleCause = Binding EventFilter: ...
```

## 6. 되돌리기

WMI는 바인딩, 소비자, 필터 순서로, 서비스는 `sc.exe delete`로 지웁니다.

```powershell
$ns = 'root\subscription'
Get-CimInstance -Namespace $ns -ClassName __FilterToConsumerBinding | Where-Object { $_.Filter.Name -eq 'CrLabFilter' } | Remove-CimInstance
Get-CimInstance -Namespace $ns -ClassName CommandLineEventConsumer | Where-Object Name -eq 'CrLabConsumer' | Remove-CimInstance
Get-CimInstance -Namespace $ns -ClassName __EventFilter | Where-Object Name -eq 'CrLabFilter' | Remove-CimInstance
sc.exe delete CrLabSvc
```

![지운 뒤 같은 스크립트를 다시 실행한 결과에서 필터와 소비자와 바인딩이 모두 0개이고 Get-Service CrLabSvc가 False이지만, 7045 줄은 서비스를 지운 뒤에도 그대로 남아 있는 것을 확인합니다.](https://copyandrun.com/img/windows-service-7045-wmi-subscription-persistence/03-되돌린-뒤.png)

지운 뒤 같은 스크립트를 `-Match crlab`으로 다시 실행하면 필터, 소비자, 바인딩이 모두 0개이고, 서비스는 `Get-Service`로 찾을 수 없었습니다. 기본 항목(`SCM Event Log ...`)은 그대로였습니다. 다만 이벤트 7045는 서비스를 지운 뒤에도 시스템 로그에 남아 있습니다. 기록은 지워지지 않으므로, 나중에 조사할 때 이 이벤트가 증거가 됩니다.

## 7. 읽는 기준

- **WMI 구독이 기본 한 쌍 밖에 있으면** 소비자의 종류와 명령을 읽습니다. 정상 소프트웨어가 만드는 경우도 있지만, 수가 많지 않아 하나씩 확인할 수 있습니다.
- **7045 직후 같은 이름의 서비스가 시작되었다면** 같은 시각대의 프로세스 기록과 맞춰 봅니다. [프로세스 만들기 글](/blog/windows-event-4688-process-creation-audit/)의 4688이 이어서 볼 자료입니다.
- **서비스 이름과 표시 이름이 정상 이름을 흉내 내는지** 봅니다. 이 글의 `CrLab Test Service`처럼 알아볼 수 있는 이름은 시험용일 뿐이고, 실제 사고에서는 정상 이름과 비슷하게 짓습니다.
- **계정이 `LocalSystem`인 새 서비스는 이유를 확인합니다.** 일반 사용자 계정으로 도는 서비스가 훨씬 안전합니다.

## 자주 막히는 곳

| 증상 | 원인과 해결 |
|---|---|
| `New-Service`나 `New-CimInstance`가 접근 거부로 실패합니다 | 관리자 PowerShell이 아닙니다 |
| `sc delete`가 `marked for deletion`이라고 합니다 | 서비스 관리 창이 열려 있거나 서비스가 사용 중입니다. 창을 닫으면 지워집니다. 이 글의 시험에서는 나타나지 않았습니다 |
| 7045가 `none`입니다 | `-Hours` 범위 안에 새 서비스가 없거나 시스템 로그가 밀려났습니다 |
| WMI 개수가 0이 나옵니다 | 이 스크립트는 기본 항목도 세므로 정상 PC에서는 1이 나옵니다. 0이면 권한이나 WMI 상태를 확인합니다 |

## 이어서 해 볼 것

- 예약 작업으로 만드는 자동 실행은 [예약 작업 글](/blog/windows-scheduled-task-persistence-4698/)에서 4698로 찾습니다.
- 새 서비스를 만든 프로세스까지 거슬러 올라가려면 [Sysmon 글](/blog/windows-sysmon-install-process-create-event-1/)의 프로세스 기록을 씁니다.

## 확인 범위

- **해 본 것:** 2026-10-28, Windows 11(빌드 26200) 관리자 PowerShell 5.1에서 위 명령을 실행했습니다. 시험 서비스와 시험 WMI 구독을 등록해 7045, 5861, 스크립트로 찾았고, 지운 뒤 개체가 모두 사라진 것과 기본 WMI 항목이 그대로인 것을 확인했습니다. 서비스는 한 번도 시작하지 않았습니다.
- **화면 확인:** 2026-10-29, 시험용 PC(Windows 11 평가판, 한국어 표시)에서 같은 시험을 다시 해 스크립트 결과와 이벤트 뷰어 화면을 찍었고, 지운 뒤 서비스와 구독이 없는 것을 확인했습니다. 이 시험용 PC에서도 보안 로그의 4697은 0건이었습니다.
- **해 보지 않은 것:** 서비스를 시작했을 때의 동작, 구독 조건이 실제로 맞았을 때 소비자가 실행되는 동작, `ActiveScriptEventConsumer`, 영구 구독을 재부팅 뒤에 확인하는 것, 도메인 환경.
- **읽을 때 주의:** 서비스 목록과 WMI 기준선은 이 PC의 값입니다. 처음 상태의 서비스 목록은 이 PC에 설치된 소프트웨어 이름이 있어 싣지 않았습니다.
