技術文章 · 監控與資訊安全

用 NXLog 收集與解析 Windows 事件,轉送到 ArcSight 或 Elastic SIEM

用 NXLog 收集 Windows 安全性事件,解析登入、程序建立、帳號鎖定及 Kerberos。用五筆合成事件練習 CEF、Logstash ECS、雙向 TLS 與 SIEM 欄位驗收。

作者 廷皓科技編輯部 · 發布  · 更新  · 約 27 分鐘閱讀

監控與資訊安全 — 廷皓技術專欄插圖

演練值如何代入。以 LAB_ 開頭的代號代表合成測試值。命令或設定中的代號,請先一致代換成隔離測試環境的值。前綴代號依欄位規格填入前綴長度,需要位址型別的欄位請填入合法的合成位址。代換後再驗證設定語法與預期結果。

LAB_BIND_ALL_V4 代表所有 IPv4 介面。若設定會監聽網路,驗收時要核對預期的介面與可達範圍。

完成事件收集後,可用ArcSight 與 Elastic 進階獵捕比對 AD、4688 與 SQL Audit,再確認規則、權限和資料保留。

轉送架構、軟體版本與憑證

在 Windows 上,NXLog 透過 im_msvistalog 讀取事件,依 XML 欄位名稱取值。若使用 ArcSight,NXLog 會把欄位轉成 CEF,再經 rsyslog 和 SmartConnector 送到 ESM。若使用 Elastic(ELK),NXLog 會逐行送出 JSON,由 Logstash 對應 Elastic Common Schema(ECS)欄位後寫入 Elasticsearch。

LAB_DNS_NAME_5   Windows Security / 4624、4625、4688
LAB_DNS_NAME_6    Windows Security / 4740、4769
  └─ NXLog im_msvistalog → 事件欄位白名單
       ├─ A  CEF / RFC 5424 / mTLS 6514 → rsyslog
       │                                  → Syslog File SmartConnector → ArcSight ESM
       └─ B  JSON / LF / mTLS 5444      → Logstash → HTTPS 9200 → Elasticsearch → Kibana

本文的 NXLog 設定適用於 Agent 6.16,使用 xm_rewrite、xm_cef、xm_json 和 om_ssl。ArcSight 採用 SmartConnectors 25.1 的 Syslog File 流程,Linux 中繼需安裝 rsyslog 8 和 GnuTLS 驅動。Elastic 的範例版本為 8.19.25。

使用 NXLog Community Edition 3.2 時,請按該版手冊改用 Query 和 xm_json。該手冊未列出本文使用的 xm_rewrite 和 xm_cef。接到受控轉換器前,先確認 Agent 送出哪些欄位、時間是否附上時區,以及能否驗證接收端憑證。

每台 Agent 各用一張用戶端憑證。接收端憑證的 SAN 必須包含 Agent 在 Host 中設定的 DNS 名稱。Agent 信任接收端的 CA,rsyslog 和 Logstash 則信任簽發 Agent 憑證的專用 CA。伺服器與用戶端憑證分別使用 serverAuth 和 clientAuth,並提供完整的中繼 CA 憑證鏈。限制私鑰的讀取權限,讓執行服務的帳號可以讀取。本文的主機名稱及 IP 位址採用文件專用的保留網域與網段。

啟用 Windows 稽核並找出原始事件

在電腦群組原則(GPO)中開啟 Windows 設定 → 安全性設定 → 進階稽核原則設定 → 系統稽核原則,依主機角色啟用下表的稽核子類別。以 auditpol 確認實際生效的設定。若同時使用舊的「本機原則 → 稽核原則」,請檢查是否啟用以子類別設定覆寫類別設定的原則。先在試點主機和網域控制站(DC)量測事件量,確認安全性記錄的保留空間足夠。

事件查詢位置進階稽核子類別優先核對的欄位
4624 登入成功接受登入的主機,例如 RDP 連線的目的主機Audit Logon(Success)TargetUserName、TargetLogonId、LogonType、IpAddress
4625 登入失敗發生登入失敗的主機Audit Logon(Failure)TargetUserName、Status、SubStatus、LogonType
4688 建立程序建立該程序的端點或伺服器Audit Process Creation(Success)SubjectLogonId、NewProcessName、NewProcessId、ProcessId。事件版本 2 可再查 ParentProcessName。
4740 帳號鎖定網域帳號查 DC。本機帳號查該帳號所在的主機。Audit User Account Management(Success)TargetUserName,以及事件檢視器中顯示的 Caller Computer Name。
4769 Kerberos 服務票證請求處理 Kerberos 服務票證請求的 DCAudit Kerberos Service Ticket Operations(Success、Failure)TargetUserName、ServiceName、Status、IpAddress

在 事件檢視器 → Windows 記錄 → 安全性 開啟事件,切到 詳細資料 → XML 檢視。先確認來源主機 System/Computer、事件時間 TimeCreated/@SystemTime、提供者 Provider/@Name、版本 Version 和記錄編號 EventRecordID,再依 <Data Name="…"> 取值。

Windows 版本與更新可能改變事件欄位,例如 4769。Microsoft 的 4740 XML 範例以 TargetDomainName 記錄介面上標為 Caller Computer Name 的值。做欄位對應前,先核對本機的原始 XML 和事件版本,確認這個值代表哪個欄位。

auditpol.exe /get /category:*
wevtutil.exe gl Security
Get-CimInstance Win32_Service -Filter "Name='nxlog'" |
  Select-Object Name, State, StartName, PathName

Get-WinEvent -FilterHashtable @{
  LogName = 'Security'
  ProviderName = 'Microsoft-Windows-Security-Auditing'
  Id = 4624,4625,4688,4740,4769
  StartTime = (Get-Date).AddMinutes(-15)
} -MaxEvents 20 | Select-Object TimeCreated, MachineName, Id, Version, RecordId

在受控主機上執行以下 PowerShell 指令,讀取最近一筆 4688 的 XML,再用 Name 屬性擷取程序欄位。輸出的主機名稱和程序路徑可能含有內部資訊,請在本機核對。

$entry = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} -MaxEvents 1
[xml]$xml = $entry.ToXml()
$fields = @{}
foreach ($item in $xml.Event.EventData.Data) {
  $fields[$item.GetAttribute('Name')] = $item.InnerText
}
[pscustomobject]@{
  Hostname = $xml.Event.System.Computer
  RecordId = $xml.Event.System.EventRecordID
  SubjectLogonId = $fields['SubjectLogonId']
  NewProcessName = $fields['NewProcessName']
  ParentProcessName = $fields['ParentProcessName']
}

用 NXLog 服務實際使用的帳號,驗證它能讀取 Security 通道。使用專用服務帳號時,依 GPO 與通道的存取控制清單核對唯讀權限。可以把下一節的 QueryList 貼到事件檢視器的 XML 自訂檢視,讓 Windows 和 SIEM 用相同條件比對。

4688 的命令列須另啟用。GPO「系統 → 稽核程序建立 → 在程序建立事件中包含命令列」可能以明文記下認證資訊、權杖或密碼參數。本文擷取程序和父程序的路徑。若要保留命令列,先確認用途,再訂定遮罩方式、索引權限和保留期限。加入 Sysmon、PowerShell Operational 或 System 記錄時,依各自的 Provider、Channel 和 Version 設定解析規則。

升級 Windows 或調整 parser 時,至少保留一筆合成對照資料驗收缺欄處理。4688 第 2 版才有建立者程序名稱,舊版仍可保留 PID 和新程序路徑供查詢。跨 DC 收到不同版本的 4769 時,按來源版本逐一比對欄位與最近更新。解析後缺少的值應留空,讓告警與資料品質查詢能各自處理。

設定 NXLog 的事件篩選與欄位解析

把下方片段和所選路線的輸出設定一起加入 nxlog.conf,沿用已安裝的模組目錄、資料目錄和日誌位置。先在隔離環境測試。如果現有路由也在讀取 Security 通道,先比對收集的來源和事件類型,以免同一事件重複入庫。

<Extension keep_windows>
    Module xm_rewrite
    Keep EventTime, EventReceivedTime, Hostname, Channel, SourceName, EventID, RecordNumber, Version, TargetUserName, TargetDomainName, TargetUserSid, SubjectUserName, SubjectDomainName, SubjectUserSid, TargetLogonId, SubjectLogonId, LogonType, IpAddress, IpPort, Status, SubStatus, ServiceName, LogonGuid, NewProcessName, NewProcessId, ParentProcessName, ProcessId, CallerComputerName
</Extension>

<Input windows_security>
    Module im_msvistalog
    ReadFromLast TRUE
    SavePos TRUE
    TolerateQueryErrors FALSE
    CaptureMessage FALSE
    CaptureEventXML FALSE
    AddPrefix FALSE
    <QueryXML>
        <QueryList>
            <Query Id="0" Path="Security">
                <Select Path="Security">
                    *[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and (EventID=4624 or EventID=4625 or EventID=4688 or EventID=4740 or EventID=4769)]]
                </Select>
            </Query>
        </QueryList>
    </QueryXML>
    Exec keep_windows->process();
</Input>
$agent = Join-Path $env:ProgramFiles 'nxlog\nxlog.exe'
$conf  = Join-Path $env:ProgramFiles 'nxlog\conf\nxlog.conf'
& $agent -c $conf -v
# 語法驗證成功後,在已核准的試點套用變更
Restart-Service -Name nxlog
Get-Service -Name nxlog
Get-Content (Join-Path $env:ProgramFiles 'nxlog\data\nxlog.log') -Tail 40

CaptureMessage FALSE 讓 NXLog 略過依介面語言產生的訊息文字。AddPrefix FALSE 保留 EventData 中的原始欄位名稱。用一條 Keep 列出所有要保留的欄位。若在同一處加寫第二條 Keep,它會再篩選前一條留下的欄位。

首次訂閱時,ReadFromLast TRUE 只讀取訂閱後的新事件。若已儲存讀取位置,SavePos TRUE 會讓 Agent 從該位置接續讀取。補收歷史事件前,先為補收作業設定獨立的輸入與目的地,並訂定時間範圍和去除重複事件的規則。

路線 A · 以 CEF 轉送事件到 ArcSight

在 NXLog 指定 CEF 欄位

xm_cef 預設將 Windows Event ID 放在 externalId。如果同時保留 EventTime 和 EventReceivedTime,輸出會出現兩個 rt。本文先把兩個時間分別寫入 end 和 rt,單位都是 Unix epoch 毫秒。接著用第二組欄位白名單移除已轉換的 Windows 欄位,以 xm_cef 產生 CEF 並處理字元跳脫,最後加上 RFC 5424 標頭。

CEF 欄位ArcSight 中的意義
事件類別 IDDevice Event Class ID 使用 Provider:EventID,例如 Microsoft-Windows-Security-Auditing:4688。
dvchost、deviceFacility、cn2分別記錄事件來源主機、Windows 安全性通道和原始記錄編號。cn2Label 固定為 WindowsRecordID。
end、rtEnd Time 是事件發生時間,Device Receipt Time 是 Agent 收件時間。Manager Receipt Time 可另查 ESM 的收件時間。
duser、suser分別記錄目標帳號與執行動作的帳號。4688 的程序建立者看 suser。若版本 2 的事件也有 Target Subject,可在 duser 查目標帳號。
src、cs6src 用於有效的 IPv4 位址,也接受從 IPv4-mapped IPv6 轉回的 IPv4。其他含冒號的來源值保留在 cs6。若要在 ESM 用 IPv6 位址做條件查詢,先核對 Connector 和 ESM 支援哪些 IPv6 欄位。
cn1、cs1 至 cs5依序是登入類型、程序路徑、父程序路徑、登入 ID、狀態碼及子狀態碼。cs3 在 4624 代表目標帳號的登入 ID,在 4688 則代表程序建立者的登入 ID。
展開 NXLog 的 CEF 與 TLS 輸出設定
<Extension cef>
    Module xm_cef
    IncludeHiddenFields FALSE
</Extension>
<Extension syslog>
    Module xm_syslog
</Extension>
<Extension keep_cef>
    Module xm_rewrite
    Keep _win_time, CEFVersion, CEFDeviceVendor, CEFDeviceProduct, CEFDeviceVersion, CEFSignatureID, CEFName, CEFSeverity, dvchost, deviceFacility, end, rt, outcome, duser, suser, src, shost, destinationServiceName, cn1, cn1Label, cn2, cn2Label, cs1, cs1Label, cs2, cs2Label, cs3, cs3Label, cs4, cs4Label, cs5, cs5Label, cs6, cs6Label
</Extension>

<Output arcsight_cef>
    Module om_ssl
    Host LAB_DNS_NAME_7:6514
    CAFile "C:/ProgramData/nxlog/pki/receiver-ca.pem"
    CertFile "C:/ProgramData/nxlog/pki/agent.pem"
    CertKeyFile "C:/ProgramData/nxlog/pki/agent-key.pem"
    RequireCert TRUE
    AllowUntrusted FALSE
    AllowHostnameValidation TRUE
    OutputType Syslog_TLS
    <Exec>
        $_win_time = $EventTime;
        $CEFVersion = 0;
        $CEFDeviceVendor = 'NXLog';
        $CEFDeviceProduct = 'NXLog Windows Event';
        $CEFDeviceVersion = nxlog_version();
        $CEFSignatureID = $SourceName + ':' + string($EventID);
        $CEFName = 'Windows Security Event ' + string($EventID);
        $CEFSeverity = 3;
        $dvchost = $Hostname;
        $deviceFacility = $Channel;
        $end = integer($EventTime) / 1000;
        if defined($EventReceivedTime) $rt = integer($EventReceivedTime) / 1000;
        $cn2 = integer($RecordNumber);
        $cn2Label = 'WindowsRecordID';

        if defined($TargetUserName) and $TargetUserName != '-' and $TargetUserName != '' $duser = $TargetUserName;
        if defined($SubjectUserName) and $SubjectUserName != '-' and $SubjectUserName != '' $suser = $SubjectUserName;
        if ($EventID == 4624 or $EventID == 4625) and defined($LogonType) and string($LogonType) =~ /^[0-9]+$/ {
            $cn1 = integer($LogonType);
            $cn1Label = 'WindowsLogonType';
        }
        if $EventID == 4624 {
            $outcome = 'success';
            if defined($TargetLogonId) and string($TargetLogonId) =~ /^0x[0-9a-f]+$/i {
                $cs3 = lc(string($TargetLogonId));
                $cs3Label = 'WindowsLogonId';
            }
        } else if $EventID == 4625 {
            $outcome = 'failure';
            $CEFSeverity = 5;
        } else if $EventID == 4688 {
            if defined($NewProcessName) and $NewProcessName != '' {
                $cs1 = $NewProcessName;
                $cs1Label = 'WindowsProcessPath';
            }
            if defined($ParentProcessName) and $ParentProcessName != '' {
                $cs2 = $ParentProcessName;
                $cs2Label = 'WindowsParentPath';
            }
            if defined($SubjectLogonId) and string($SubjectLogonId) =~ /^0x[0-9a-f]+$/i {
                $cs3 = lc(string($SubjectLogonId));
                $cs3Label = 'WindowsLogonId';
            }
        } else if $EventID == 4769 {
            if defined($ServiceName) $destinationServiceName = $ServiceName;
            if defined($Status) and string($Status) =~ /^0x[0-9a-f]+$/i {
                if string($Status) =~ /^0x0+$/i $outcome = 'success';
                else $outcome = 'failure';
            }
        } else if $EventID == 4740 and defined($CallerComputerName) and $CallerComputerName != '-' {
            $shost = $CallerComputerName;
        }
        if defined($Status) and string($Status) =~ /^0x[0-9a-f]+$/i {
            $cs4 = string($Status);
            $cs4Label = 'WindowsStatus';
        }
        if defined($SubStatus) and string($SubStatus) =~ /^0x[0-9a-f]+$/i {
            $cs5 = string($SubStatus);
            $cs5Label = 'WindowsSubStatus';
        }
        if ($EventID == 4624 or $EventID == 4625 or $EventID == 4769) and defined($IpAddress) {
            if string($IpAddress) =~ /^(?:::ffff:)?((?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9]))$/i {
                if $1 != 'LAB_BIND_ALL_V4' $src = $1;
            } else if string($IpAddress) =~ /:/ and string($IpAddress) != '::' {
                $cs6 = string($IpAddress);
                $cs6Label = 'WindowsSourceAddressRaw';
            }
        }
        keep_cef->process();
        $Message = to_cef();
        $EventTime = $_win_time;
        $Hostname = $dvchost;
        $SourceName = 'nxlog';
        $SyslogFacilityValue = 16;
        $SyslogSeverityValue = 6;
        to_syslog_ietf();
    </Exec>
</Output>
<Route to_arcsight>
    Path windows_security => arcsight_cef
</Route>

以下是 4688 的 CEF 內容。只要欄位和值正確,排列順序可以不同。Device Product 是 NXLog Windows Event。本文以 CEF Severity 3 和 5 區分事件優先度,分析登入失敗仍需看來源、帳號及後續活動。

CEF:0|NXLog|NXLog Windows Event|6.16|Microsoft-Windows-Security-Auditing:4688|Windows Security Event 4688|3|dvchost=LAB_DNS_NAME_5 deviceFacility=Security end=1794625208000 rt=1794625209000 cn2=81003 cn2Label=WindowsRecordID suser=lab-user cs1=C:\\Windows\\System32\\notepad.exe cs1Label=WindowsProcessPath cs2=C:\\Windows\\explorer.exe cs2Label=WindowsParentPath cs3=0x4a01 cs3Label=WindowsLogonId

設定 Linux 中繼與 SmartConnector

在專用的 Linux 中繼載入 GnuTLS 驅動。若已有 global 或 imtcp 設定,請併入既有設定,或依版本在 input 區塊設定。Agent 以 Syslog_TLS 在每筆訊息前加上位元組數,rsyslog 依該長度讀取完整訊息。請核對兩端的訊息大小限制。rsyslog 解開 TLS 後,將 CEF 逐行寫入本機的 Syslog 檔,供 SmartConnector 讀取。

展開 rsyslog 的雙向 TLS 設定
global(
    maxMessageSize="32k"
    defaultNetstreamDriverCAFile="/etc/rsyslog/nxlog-tls/agent-ca.pem"
    defaultNetstreamDriverCertFile="/etc/rsyslog/nxlog-tls/relay.pem"
    defaultNetstreamDriverKeyFile="/etc/rsyslog/nxlog-tls/relay-key.pem"
)

module(load="imtcp" StreamDriver.Name="gtls" StreamDriver.Mode="1"
       StreamDriver.AuthMode="x509/name")

ruleset(name="nxlog_cef") {
    if $msg startswith "CEF:0|" or $msg startswith " CEF:0|" then {
        action(type="omfile" file="/var/log/nxlog-cef/windows.log"
               template="RSYSLOG_TraditionalFileFormat"
               fileGroup="siem-readers" fileCreateMode="0640")
    }
}

input(type="imtcp" Address="LAB_IP_4" port="6514" ruleset="nxlog_cef"
      SupportOctetCountedFraming="on"
      PermittedPeer=["LAB_DNS_NAME_5", "LAB_DNS_NAME_6"])
sudo rsyslogd -N1
sudo ss -ltn '( sport = :6514 )'
sudo -u arcsight test -r /var/log/nxlog-cef/windows.log
  1. 在中繼建立日誌目錄並設定輪替。讓 rsyslog 可寫入,SmartConnector 服務帳號能讀取。先用核准的 Agent 送一筆新事件,確認日誌檔出現完整的一行 CEF。
  2. 在 SmartConnector Setup Wizard 選 Syslog File,填入 /var/log/nxlog-cef/windows.log,選擇讀取後保留檔案,並確認 ArcSight Common Event Format Syslog 解析器能辨識該行。目的地選 ArcSight Manager (encrypted),填入 ESM Manager 名稱、連接埠和註冊帳號,並核對憑證。
  3. 在 ESM Console 開啟 Active Channel。將 Manager Receipt Time 設為涵蓋重播收件的時段,再以 Device Vendor NXLog 和 Device Product NXLog Windows Event 篩選。逐筆核對 Device Event Class ID、Device Host Name、End Time、Device Receipt Time、Device Custom Number 2 和 Device Custom String 3。
  4. 依 End Time 排序,將五筆事件與下方時間線比對。再以 Device Host Name LAB_DNS_NAME_5、Device Custom String 3 0x4a01 和兩個類別 ID Microsoft-Windows-Security-Auditing:4624、Microsoft-Windows-Security-Auditing:4688 篩選,預期有 2 筆。驗收期間請停用這組事件的 Connector 彙整,並比對 Event Count 與事件明細。

路線 B · 用 Logstash 解析 JSON 並寫入 Elasticsearch

1. 啟用 JSON 轉送與雙向 TLS

將 NXLog 的輸出片段接在共用設定後。NXLog 把每筆事件轉成一行 UTF-8 JSON,Logstash 以換行字元(LF)分隔事件。欄位內的換行會依 JSON 規則跳脫。

讓 Logstash 的 tcp 輸入監聽受控的內網介面,並使用 PEM PKCS#8 格式的伺服器私鑰。ssl_client_authentication 會驗證用戶端憑證的信任鏈。若要限制個別 Agent,請使用專用 CA、限制來源網段,並另外比對憑證的 CN 或 SAN 與事件來源主機。

<Extension json_fields>
    Module xm_json
    DetectNestedJSON FALSE
</Extension>

<Output elastic_json>
    Module om_ssl
    Host LAB_DNS_NAME_8:5444
    CAFile "C:/ProgramData/nxlog/pki/receiver-ca.pem"
    CertFile "C:/ProgramData/nxlog/pki/agent.pem"
    CertKeyFile "C:/ProgramData/nxlog/pki/agent-key.pem"
    RequireCert TRUE
    AllowUntrusted FALSE
    AllowHostnameValidation TRUE
    OutputType LineBased_LF
    Exec to_json();
</Output>
<Route to_elastic>
    Path windows_security => elastic_json
</Route>
input {
  tcp {
    id => "nxlog_windows_tls"
    host => "LAB_IP_5"
    port => 5444
    codec => line { charset => "UTF-8" }
    ecs_compatibility => "v8"
    dns_reverse_lookup_enabled => false
    ssl_enabled => true
    ssl_certificate => "/etc/logstash/nxlog-tls/logstash.pem"
    ssl_key => "/etc/logstash/nxlog-tls/logstash.pk8.pem"
    ssl_certificate_authorities => ["/etc/logstash/nxlog-tls/agent-ca.pem"]
    ssl_client_authentication => "required"
  }
}

2. 依事件提供者、通道與 Event ID 解析欄位

將 input、filter 和 output 放在同一條 Logstash 管線。範例用 Ruby 解析 JSON,只抽取所需的欄位。預設的 JSON filter 可能在解析失敗時把原文寫入日誌。此處只保留錯誤標記,最後也會移除 Logstash 的 ECS codec 可能留下的 event.original。

遇到格式不正確的 JSON、不支援的事件或無法解析的事件時間,Logstash 會加上對應標記並將資料寫入隔離檔。可索引的事件會把白名單內的原始值保存在 winlog.event_data,並依下表建立可查詢的欄位。

欄位型別取值方式
@timestamp、event.createddate前者是 Windows 事件的發生時間,後者是 Agent 收件時間。時間字串須帶 UTC 標記或時區偏移。若要記錄 Elasticsearch 寫入時間,可在 ingest pipeline 設定 event.ingested 並更新欄位映射。
host.name、winlog.computer_namekeyword填入產生事件的 Windows 主機名稱。轉送端的 TCP 位址請另外從連線資訊查詢。
event.code、winlog.record_id、event.idkeyword分別記錄事件類型、通道內的記錄編號,以及同一索引內用來識別重送事件的 ID。
source.ipip填入正規化後的 IPv4 或 IPv6 位址。空值和 - 跳過。位址格式錯誤時,事件會帶有 nxlog_invalid_ip 標記。
process.pid、process.parent.pidlong將 4688 的 NewProcessId 和 ProcessId 轉成整數,分別對應新程序和建立者的 PID。程序路徑沿用 XML 中的值。
winlog.event_dataflattened將選定的原始值保存為字串。可直接查 TargetLogonId 或 SubjectLogonId。需要做數值分析時,另設明確型別的欄位。
展開 Logstash 的事件解析設定
filter {
  ruby {
    id => "normalize_windows_event"
    init => 'require "ipaddr"; require "digest"; require "json"'
    code => '
      begin
        raw = JSON.parse(event.get("message"))
      rescue JSON::ParserError
        event.tag("nxlog_bad_json")
        next
      end
      if !raw.is_a?(Hash)
        event.tag("nxlog_bad_schema")
        next
      end
      host = raw["Hostname"].to_s.strip.downcase
      provider = raw["SourceName"].to_s
      channel = raw["Channel"].to_s
      code = raw["EventID"].to_s
      record = raw["RecordNumber"].to_s
      clock = raw["EventTime"].to_s
      if host.empty? || provider != "Microsoft-Windows-Security-Auditing" ||
         channel != "Security" || !%w[4624 4625 4688 4740 4769].include?(code) ||
         record !~ /\A[0-9]+\z/ || clock !~ /(?:Z|[+-][0-9]{2}:[0-9]{2})\z/
        event.tag("nxlog_bad_schema")
        next
      end

      event.set("[event][kind]", "event")
      event.set("[event][dataset]", "nxlog.windows")
      event.set("[event][provider]", provider)
      event.set("[event][code]", code)
      event.set("[host][name]", host)
      event.set("[winlog][computer_name]", host)
      event.set("[winlog][channel]", channel)
      event.set("[winlog][provider_name]", provider)
      event.set("[winlog][event_id]", code)
      event.set("[winlog][record_id]", record)
      event.set("[@metadata][nxlog][EventTime]", clock)
      received = raw["EventReceivedTime"].to_s
      if received =~ /(?:Z|[+-][0-9]{2}:[0-9]{2})\z/
        event.set("[@metadata][nxlog][EventReceivedTime]", received)
      elsif !received.empty?
        event.tag("nxlog_bad_receive_time")
      end
      if raw["Version"].to_s =~ /\A[0-9]+\z/
        event.set("[winlog][version]", raw["Version"].to_i)
      end

      value = lambda do |field|
        item = raw[field]
        text = item.to_s.strip
        if (item.is_a?(String) || item.is_a?(Integer)) && !["", "-", "N/A"].include?(text)
          text
        end
      end
      details = %w[IpAddress IpPort TargetUserName TargetDomainName TargetUserSid
                   SubjectUserName SubjectDomainName SubjectUserSid SubjectLogonId
                   TargetLogonId LogonType Status SubStatus ServiceName LogonGuid
                   NewProcessName NewProcessId ParentProcessName ProcessId CallerComputerName]
      details.each do |field|
        item = value.call(field)
        event.set("[winlog][event_data][#{field}]", item) if item
      end

      case code
      when "4624", "4625", "4769"
        event.set("[event][category]", ["authentication"])
        event.set("[event][type]", ["start"]) if code == "4624"
        outcome = {"4624" => "success", "4625" => "failure"}[code]
        status = value.call("Status")
        if code == "4769" && status && status =~ /\A0x[0-9a-f]+\z/i
          outcome = status.to_i(16).zero? ? "success" : "failure"
        end
        event.set("[event][outcome]", outcome) if outcome
      when "4688"
        event.set("[event][category]", ["process"])
        event.set("[event][type]", ["start"])
      when "4740"
        event.set("[event][category]", ["iam"])
        event.set("[event][type]", ["user", "change"])
      end

      user = value.call(code == "4688" ? "SubjectUserName" : "TargetUserName")
      event.set("[user][name]", user) if user
      if %w[4624 4625 4688].include?(code)
        domain = value.call(code == "4688" ? "SubjectDomainName" : "TargetDomainName")
        event.set("[user][domain]", domain) if domain
      end
      if code == "4769" && (service = value.call("ServiceName"))
        event.set("[service][name]", service)
      end

      if %w[4624 4625 4769].include?(code) && (address = value.call("IpAddress"))
        begin
          raise ArgumentError if address.include?("/") || address.include?("%")
          ip = IPAddr.new(address)
          ip = ip.native if ip.ipv4_mapped?
          event.set("[source][ip]", ip.to_s) unless ip.to_i.zero?
        rescue ArgumentError
          event.tag("nxlog_invalid_ip")
        end
      end
      if code == "4688"
        {"NewProcessName" => "[process]", "ParentProcessName" => "[process][parent]"}.each do |field, target|
          path = value.call(field)
          if path
            event.set("#{target}[executable]", path)
            event.set("#{target}[name]", path.tr(92.chr, "/").split("/").last)
          end
        end
        {"NewProcessId" => "[process][pid]", "ProcessId" => "[process][parent][pid]"}.each do |field, target|
          pid = value.call(field)
          if pid && pid =~ /\A(?:0x[0-9a-f]{1,8}|[0-9]{1,10})\z/i
            parsed = pid[0, 2].downcase == "0x" ? pid.to_i(16) : pid.to_i(10)
            event.set(target, parsed) if parsed <= 4_294_967_295
          end
        end
      end
    '
    tag_on_exception => "nxlog_parser_error"
  }
  if [event][code] and "nxlog_parser_error" not in [tags] {
    date {
      match => ["[@metadata][nxlog][EventTime]", "ISO8601"]
      target => "@timestamp"
      tag_on_failure => ["nxlog_bad_event_time"]
    }
    if [@metadata][nxlog][EventReceivedTime] {
      date {
        match => ["[@metadata][nxlog][EventReceivedTime]", "ISO8601"]
        target => "[event][created]"
        tag_on_failure => ["nxlog_bad_receive_time"]
      }
    }
    if "nxlog_bad_event_time" not in [tags] {
      ruby {
        id => "set_windows_event_id"
        code => '
          key = ["[host][name]", "[winlog][channel]", "[event][provider]",
                 "[winlog][record_id]", "@timestamp"].map { |field| event.get(field).to_s }
          event.set("[event][id]", Digest::SHA256.hexdigest(JSON.generate(key)))
        '
        tag_on_exception => "nxlog_parser_error"
      }
    }
  }
  mutate { remove_field => ["message", "@version", "[host][ip]", "[event][original]"] }
}

若已使用 Elastic Agent 或 Winlogbeat,請在要套用的偵測規則中加入本文的索引,逐條核對 event.dataset、Provider 條件和必要欄位。如果兩套工具都收集同一個通道,請指定主要來源或訂定去除重複事件的規則。

3. 建立索引並設定寫入與隔離路徑

用有建立索引權限的帳號在 Dev Tools 執行下方指令。範例使用 nxlog-windows-lab-*,以免套用 Elasticsearch 8.19 內建的 logs-*-* 資料串流範本。索引設為 dynamic: strict,寫入新欄位前須先定義它的型別。

Logstash 透過 HTTPS 搭配專用 API key 寫入 nxlog-windows-lab-000001。該金鑰只需要叢集的 monitor 權限和此索引的 index 權限。Kibana 的查詢帳號則另授 read 和 view_index_metadata。

展開 Elasticsearch 的索引與欄位映射
PUT /nxlog-windows-lab-000001
{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "@timestamp": {"type": "date"},
      "tags": {"type": "keyword"},
      "event": {"properties": {
        "created": {"type": "date"}, "id": {"type": "keyword"},
        "kind": {"type": "keyword"}, "code": {"type": "keyword"},
        "dataset": {"type": "keyword"}, "provider": {"type": "keyword"},
        "category": {"type": "keyword"}, "type": {"type": "keyword"},
        "outcome": {"type": "keyword"}
      }},
      "host": {"properties": {"name": {"type": "keyword"}}},
      "source": {"properties": {"ip": {"type": "ip"}}},
      "user": {"properties": {
        "name": {"type": "keyword"}, "domain": {"type": "keyword"}
      }},
      "service": {"properties": {"name": {"type": "keyword"}}},
      "process": {"properties": {
        "pid": {"type": "long"}, "name": {"type": "keyword"},
        "executable": {"type": "wildcard"},
        "parent": {"properties": {
          "pid": {"type": "long"}, "name": {"type": "keyword"},
          "executable": {"type": "wildcard"}
        }}
      }},
      "winlog": {"properties": {
        "computer_name": {"type": "keyword"}, "channel": {"type": "keyword"},
        "event_id": {"type": "keyword"}, "record_id": {"type": "keyword"},
        "provider_name": {"type": "keyword"}, "version": {"type": "long"},
        "event_data": {"type": "flattened"}
      }}
    }
  }
}
展開 Dev Tools 的 API key 建立指令
POST /_security/api_key
{
  "name": "nxlog-lab-writer",
  "expiration": "24h",
  "role_descriptors": {
    "nxlog_writer": {
      "cluster": ["monitor"],
      "indices": [{"names": ["nxlog-windows-lab-000001"], "privileges": ["index"]}]
    }
  }
}
展開 Logstash 的寫入與隔離設定
output {
  if [event][id] and "nxlog_parser_error" not in [tags] {
    elasticsearch {
      hosts => ["https://LAB_DNS_NAME_9:9200"]
      api_key => "${NXLOG_ES_API_KEY}"
      ssl_enabled => true
      ssl_certificate_authorities => ["/etc/logstash/nxlog-tls/elasticsearch-ca.pem"]
      ssl_verification_mode => "full"
      manage_template => false
      ilm_enabled => false
      data_stream => false
      index => "nxlog-windows-lab-000001"
      action => "index"
      document_id => "%{[event][id]}"
    }
  } else {
    file {
      id => "nxlog_quarantine_metadata"
      path => "/var/lib/logstash/nxlog-quarantine/rejected.ndjson"
      file_mode => 0600
      codec => json_lines
    }
  }
}
sudo install -d -o logstash -g logstash -m 0700 /var/lib/logstash/nxlog-quarantine
sudo -u logstash /usr/share/logstash/bin/logstash-keystore --path.settings /etc/logstash add NXLOG_ES_API_KEY
sudo -u logstash /usr/share/logstash/bin/logstash --path.settings /etc/logstash           --config.test_and_exit -f /etc/logstash/conf.d/nxlog-windows.conf

先確認 Logstash 服務可以讀取 keystore。將 API 回應中的 id 和 api_key 組成 id:api_key,存入 NXLOG_ES_API_KEY。隔離檔只保留允許的欄位和錯誤類型,需限制誰能讀取以及保留多久。

event.id 由來源主機、通道、提供者、記錄編號與 UTC 事件時間產生。在同一個索引內,index 動作會覆寫同 ID 的文件。正式環境若有多租戶、索引輪替或跨索引重播,還要考慮租戶識別、主機的固定識別碼,以及重播時應寫回哪個索引。

重播五筆合成事件並核對時間線

將下方五筆 JSON 複製到實驗環境的 nxlog-lab.ndjson,以 UTF-8 儲存。將 IpAddress 的 LAB_IP_* 換成隔離環境的合成 IPv4,保留原有的 mapped IPv6 前綴。LAB_V6_* 請換為合法的合成 IPv6。設定中的收集器名稱要與憑證相符。重播時維持雙向 TLS 驗證,將查詢時區設為 UTC。

展開五筆合成 NXLog 事件
{"EventTime":"2026-11-14T11:00:00.000+08:00","EventReceivedTime":"2026-11-14T11:00:01.000+08:00","Hostname":"LAB_DNS_NAME_5","Channel":"Security","SourceName":"Microsoft-Windows-Security-Auditing","Version":0,"EventID":4625,"RecordNumber":81001,"TargetUserName":"lab-user","TargetDomainName":"LAB","LogonType":"10","IpAddress":"::ffff:LAB_IP_1","Status":"0xC000006D","SubStatus":"0xC000006A"}
{"EventTime":"2026-11-14T03:00:03.000Z","EventReceivedTime":"2026-11-14T03:00:04.000Z","Hostname":"LAB_DNS_NAME_6","Channel":"Security","SourceName":"Microsoft-Windows-Security-Auditing","Version":2,"EventID":4769,"RecordNumber":91001,"TargetUserName":"lab-user@LAB_DNS_NAME_10","ServiceName":"WIN-APP$","IpAddress":"LAB_V6_1","Status":"0x0"}
{"EventTime":"2026-11-14T03:00:05.000Z","EventReceivedTime":"2026-11-14T03:00:06.000Z","Hostname":"LAB_DNS_NAME_5","Channel":"Security","SourceName":"Microsoft-Windows-Security-Auditing","Version":2,"EventID":4624,"RecordNumber":81002,"TargetUserName":"lab-user","TargetDomainName":"LAB","TargetLogonId":"0x4a01","LogonType":"10","IpAddress":"LAB_IP_1"}
{"EventTime":"2026-11-14T03:00:08.000Z","EventReceivedTime":"2026-11-14T03:00:09.000Z","Hostname":"LAB_DNS_NAME_5","Channel":"Security","SourceName":"Microsoft-Windows-Security-Auditing","Version":2,"EventID":4688,"RecordNumber":81003,"SubjectUserName":"lab-user","SubjectDomainName":"LAB","SubjectLogonId":"0x4a01","NewProcessName":"C:\\Windows\\System32\\notepad.exe","NewProcessId":"0x1180","ParentProcessName":"C:\\Windows\\explorer.exe","ProcessId":"0x960"}
{"EventTime":"2026-11-14T03:00:15.000Z","EventReceivedTime":"2026-11-14T03:00:16.000Z","Hostname":"LAB_DNS_NAME_6","Channel":"Security","SourceName":"Microsoft-Windows-Security-Auditing","Version":0,"EventID":4740,"RecordNumber":91002,"TargetUserName":"svc-lab-backup","TargetDomainName":"WIN-BACKUP"}
展開 Elastic 的雙向 TLS 重播範例
from pathlib import Path
import socket
import ssl
import time

server = "LAB_DNS_NAME_8"
tls = ssl.create_default_context(cafile="receiver-ca.pem")
tls.load_cert_chain("agent.pem", "agent-key.pem")
records = Path("nxlog-lab.ndjson").read_bytes().splitlines()

with socket.create_connection((server, 5444), timeout=10) as tcp:
    with tls.wrap_socket(tcp, server_hostname=server) as stream:
        stream.sendall(b"\n".join(records) + b"\n")
        time.sleep(2)

重播用來驗證接收端。若也要驗證 NXLog 的收集流程,請在受控的 Windows 試點登入並開啟記事本,再依序比對事件檢視器的原始事件、NXLog 產生的 CEF 或 JSON,以及 SIEM 的查詢結果。

展開 ArcSight 的五筆 CEF 重播範例

在隔離環境使用 Python 3.11 或更新版本,以及同一份 nxlog-lab.ndjson。先用 LAB_DNS_NAME_5 的用戶端憑證重播 3 筆,再將 agent_host 和憑證切換為 LAB_DNS_NAME_6 重播另外 2 筆。完成後到 Active Channel 核對五筆事件。

from datetime import datetime
import json
from pathlib import Path
import socket
import ssl
import time


def fixture_rows():
    names = {4624: "success", 4625: "failure", 4769: "success"}
    for line in Path("nxlog-lab.ndjson").read_text(encoding="utf-8").splitlines():
        ev = json.loads(line)
        event_id = ev["EventID"]
        at = datetime.fromisoformat(ev["EventTime"])
        received = datetime.fromisoformat(ev["EventReceivedTime"])
        ext = {"dvchost": ev["Hostname"], "deviceFacility": ev["Channel"],
               "end": int(at.timestamp() * 1000), "rt": int(received.timestamp() * 1000),
               "cn2": ev["RecordNumber"], "cn2Label": "WindowsRecordID"}
        for src, dst, label in [("TargetUserName", "duser", None), ("SubjectUserName", "suser", None),
                                ("ServiceName", "destinationServiceName", None), ("LogonType", "cn1", "WindowsLogonType"),
                                ("NewProcessName", "cs1", "WindowsProcessPath"), ("ParentProcessName", "cs2", "WindowsParentPath"),
                                ("TargetLogonId", "cs3", "WindowsLogonId"), ("SubjectLogonId", "cs3", "WindowsLogonId"),
                                ("Status", "cs4", "WindowsStatus"), ("SubStatus", "cs5", "WindowsSubStatus")]:
            if src in ev:
                ext[dst] = ev[src]
                if label:
                    ext[dst + "Label"] = label
        if event_id in names:
            ext["outcome"] = names[event_id]
        ip = ev.get("IpAddress", "").removeprefix("::ffff:")
        if ":" in ip:
            ext["cs6"] = ip
            ext["cs6Label"] = "WindowsSourceAddressRaw"
        elif ip:
            ext["src"] = ip
        sev = 5 if event_id == 4625 else 3
        ce = f'CEF:0|NXLog|NXLog Windows Event|6.16|{ev["SourceName"]}:{event_id}|Windows Security Event {event_id}|{sev}|'
        # 這裡僅組裝本頁五筆合成事件,正式 Windows 輸出使用 xm_cef。
        escape = lambda value: str(value).replace("\\", "\\\\").replace("=", "\\=").replace("\r", "\\r").replace("\n", "\\n")
        ce += " ".join(f"{key}={escape(value)}" for key, value in ext.items())
        yield f'<134>1 {at.isoformat()} {ev["Hostname"]} nxlog - - - {ce}'


def main():
    server = "LAB_DNS_NAME_7"
    tls = ssl.create_default_context(cafile="receiver-ca.pem")
    tls.load_cert_chain("agent.pem", "agent-key.pem")
    # 使用中繼受信任的 Win-APP/Win-DC 試驗憑證逐台驗證來源。
    agent_host = "LAB_DNS_NAME_5"
    with socket.create_connection((server, 6514), timeout=10) as tcp:
        with tls.wrap_socket(tcp, server_hostname=server) as stream:
            for row in fixture_rows():
                if row.split(" ", 4)[2] != agent_host:
                    continue
                data = row.encode("utf-8")
                stream.sendall(f"{len(data)} ".encode("ascii") + data)
            time.sleep(2)


if __name__ == "__main__":
    main()

在 Kibana 的 Discover → Create a data view 建立 nxlog-windows-lab-*,將 @timestamp 選為時間欄位。把範圍設為 2026-11-14 02:59:50–03:00:20 UTC(臺灣時間 10:59:50–11:00:20),依 @timestamp 由舊到新排序。加入 host.name、event.code、winlog.record_id、user.name 和 source.ip 欄位,再執行下方 KQL。

event.dataset: "nxlog.windows" and
event.code: ("4625" or "4769" or "4624" or "4688" or "4740")
事件時間(UTC)來源主機Event ID/記錄編號驗收重點
03:00:00LAB_DNS_NAME_54625/81001原始時間換算成 UTC 後為 03:00:00。來源 IP 為 LAB_IP_1,event.outcome=failure。
03:00:03LAB_DNS_NAME_64769/91001來源 IP 為 LAB_V6_1,Status=0x0。在 CEF 的 cs6 可查到原始 IPv6。
03:00:05LAB_DNS_NAME_54624/81002目標登入 ID 為 0x4a01,LogonType=10。
03:00:08LAB_DNS_NAME_54688/81003建立者的登入 ID 為 0x4a01。新程序 PID 為 4480,父程序 PID 為 2400。
03:00:15LAB_DNS_NAME_64740/91002被鎖定的帳號是 svc-lab-backup。這筆事件沒有來源 IP。
展開解答 · 找出同一主機上的登入與程序事件

在同一台主機、同一次開機的時間範圍內,比對 4624 的 TargetLogonId 和 4688 的 SubjectLogonId。本例兩筆都是 0x4a01,可把登入和程序建立連起來。

4769 由 DC 記錄,來源是 IPv6。若要確認它和應用伺服器上的 IPv4 登入是否有關,還須核對裝置、來源位址及時間。4740 鎖定的是另一個帳號,應另查該帳號的排程和維運記錄。

event.dataset: "nxlog.windows" and host.name: "LAB_DNS_NAME_5" and
((event.code: "4624" and winlog.event_data.TargetLogonId: "0x4a01") or
 (event.code: "4688" and winlog.event_data.SubjectLogonId: "0x4a01"))

合成事件的驗收結果

以 Logstash 8.19 與 TCP 外掛 6.4.17 為參考,在隔離環境送入五筆合成事件。無效 JSON、不支援的事件及無效時間應被標示。用 HTTPS 及限定權限的 API key 寫入後核對欄位映射;重送時 event.id 應一致,索引仍應有 5 筆,兩組 KQL 預期分別查到 5 筆與 2 筆。另驗缺少用戶端憑證、憑證不受信任和伺服器名稱不符三種情境均遭拒絕。

ArcSight 路線依路線 A 端到端驗收。以相同五筆合成 CEF 比對事件類型、時間、登入 ID、記錄編號、程序路徑與來源欄位。CEF 解碼器可以協助檢查格式,正式納管前應在 SmartConnector 與 ESM 再核對這些欄位。

排查收集問題與監測上線狀態

症狀先查什麼如何確認修正生效
查不到 4688 或 DC 的 4769在產生事件的主機核對生效的 GPO、事件 XML、NXLog 服務帳號的讀取權限,以及 Agent 儲存的讀取位置。若只有 4688 的命令列缺漏,再檢查該欄位的稽核原則與轉送白名單。在試點產生新事件,用相同的通道、提供者和記錄編號從來源一路查到 SIEM。
TLS 已連線,卻收不到事件或多筆黏在一起逐段確認如何分隔事件。ArcSight 中繼依長度前綴收件,Logstash 以 LF 分隔。再檢查中繼的收件規則、SmartConnector 的讀取位置、檔案輪替和單筆事件的大小上限。依序送兩筆可辨識的事件,確認接收端分別記錄為兩筆。
Elasticsearch 回傳 400、401 或 403400 先查 Bulk 回應中的單筆錯誤,常見原因是欄位映射或資料串流範本不符。401 查 API key 是否有效,403 查金鑰對目標索引的權限。確認索引存在,再用 _count 核對數量並抽查欄位。用權限不足的金鑰驗證寫入確實遭拒。
主機名稱錯誤或事件時間相差八小時比較原始 XML 的 System/Computer 和 TimeCreated,以及 CEF 的 dvchost、end 和 rt。也檢查介面時區與各主機的 NTP 同步。將同一事件的時間統一換算成 UTC,再分別核對事件發生、Agent 收件及 SIEM 收件時間。
登入失敗增加,或相同事件反覆出現依主機角色比對平日基線,再查是否有核准的維運、密碼輪替或同一記錄重送。若時間線中途有缺口,也要查採集延遲或遺失。從多個來源核對事件。如果涉及高權限帳號、陌生來源、維運時段之外的活動或異常程序,再依證據決定是否升級調查。

若連線卡在 TLS 握手,先核對信任的 CA、憑證有效期、用途(EKU),以及伺服器 DNS 名稱是否符合 SAN。

依主機角色追蹤每日事件數、接收延遲、解析失敗率、隔離筆數及 SIEM 寫入狀態,並監控憑證到期日。以事件量和可容忍的中斷時間估算 Windows 安全性記錄及 Logstash 持久化佇列所需空間。

要確認 SIEM 確實收到資料,請在演練中測試中斷後恢復收件、事件重送,以及日誌輪替,並逐筆核對接收端。Logstash 的死信佇列(DLQ)用於追查 Elasticsearch 無法重試的寫入錯誤。本文的隔離檔則用來追查在解析階段被分流的事件,兩處都要監控。

登入和程序事件要查哪個帳號欄位?

4624 和 4625 的 Target 是嘗試登入的帳號。4688 的 Subject 是建立程序的帳號。比對時以同一主機、開機時段和登入 ID 為範圍。若要用 PID 追蹤程序,也須核對建立時間,避免把重用同一 PID 的程序混在一起。

ArcSight 要在哪裡查 IPv6 來源?

本文的 CEF 設定把 IPv4 寫入 src,IPv6 原始字串則查 Device Custom String 6。Elastic 的 source.ip 可存 IPv4 和 IPv6。若要在 ESM 設定 IPv6 規則,先確認 SmartConnector 和 ESM 支援的對應欄位。

升級後如何確認沒有漏收或漏解析?

依提供者、通道、事件 ID 和事件版本保存合成測試案例,涵蓋不同介面語言、空欄位、時區、IPv6、事件版本與重播。先比對新舊版本的事件數、欄位和值,以及解析錯誤,再逐步擴大部署。

案例:握手成功,但事件主機需要驗證

Logstash 的 TCP 輸入在伺服器模式下驗證用戶端的憑證鏈。插件的 ssl_client_authentication 不比對用戶端的 CN 或 SAN,憑證驗證本身也無法確認事件中的 host.name。正式用法可依受控中繼提供的已驗證身分做設備對照,或把不同權限範圍放入獨立入口與專用 CA。若打算從插件的連線中繼資料核對身分,先確認實際版本提供哪些欄位、保留多久及用途。

在測試環境,用同一張合成 Agent 憑證傳送登記名稱及未配對的合成名稱。兩筆都可能通過 TLS 握手,只有設備歸屬相符的事件才應進入受信索引。另一筆送到品質調查路徑,保留時間與受控的來源代碼。驗收前核對其他服務不共用該簽發 CA。

官方文件

查核資料

  1. Elastic Logstash TCP 與 SSL/TLS 參數

聯絡廷皓討論 看更多文章