This article provides a systematic overview of security hardening and incident response for Windows and Linux hosts. It covers the definition, principles, and baselines of security hardening, along with Windows system architecture, credential protection, account permissions, PowerShell security, event logs, IIS logs, firewall settings, registry, and patch management. For Linux, it addresses accounts, logging, file permissions, services, firewalls, versions, and access control. The incident response section details event classification, handling of typical incidents, the PICERL process, on-site investigation, common tools, traffic and memory analysis, and report writing. The article concludes with checklists, a collection of tools and resources, and lab guides, emphasizing that all operations must be conducted in an authorized environment and that configurations should be tailored to actual needs, with rollback verification performed.
Host Security Hardening and Incident Response Tutorial
This document is written for system administrators, security operations staff, and incident responders. It systematically explains security hardening for Windows and Linux hosts, as well as the detection, handling, and reporting of security incidents. The commands and configurations herein apply only to authorized lab environments or assets you own and manage. Do not use them on systems you are not authorized to access.
The download links and GitHub repositories listed in this document should be based on the pages published by the official or project maintainers. Referenced open-source cases are intended only for detection validation, log analysis, and hardening comparison, and must be used in isolated environments. Addresses, ports, and paths in the configuration examples must be replaced according to your organization's actual setup, validated in a test environment before execution, and accompanied by a rollback plan.
1. Overview of Security Hardening
1.1 Definition and Goals of Security Hardening
1.1.1 Definition
Hardening is a systematic engineering effort that, while preserving business availability, raises the cost of intrusion and reduces the impact of compromise by shrinking the attack surface, enforcing least privilege, and ensuring security events remain observable. It is not a synonym for installing antivirus software, nor is it about shutting down every service. Hardening that can be published and audited should meet three criteria: a clear baseline, verification commands, and records of changes and rollbacks.
Host security also follows the CIA model:
Attribute
English
Host-side meaning
Corresponding hardening measures
Confidentiality
Confidentiality
Unauthorized subjects cannot read credentials or business data
Password and key management, permissions, encryption, mandatory access control
Integrity
Integrity
System files, configurations, and logs cannot be tampered with
Signing, integrity monitoring, auditing, patching
Availability
Availability
Legitimate business remains recoverable after an attack or operational error
Backups, patch windows, firewall anti-scan-exhaustion, incident response procedures
The three properties need to be balanced. For example, mounting /tmp as noexec reduces the chance of malicious programs landing and executing, but it can break installers that rely on running scripts from that directory, so it must first be confirmed in a test environment.
1.1.2 Attack Surface
The attack surface refers to every entry point an external or internal subject could use to get into the system, escalate privileges, or maintain control, including: open ports, listening addresses, accounts and authentication methods, executable paths, scheduled tasks and services, writable directories, remote management protocols, web application upload points, and so on. The direct effect of hardening is to reduce the number of entry points, strengthen the authentication at each one, and ensure every attempt leaves a log.
1.1.3 Four Questions Host Hardening Must Answer
Most compromises in production stem from known issues such as weak passwords, an enabled Guest account, management ports open to untrusted networks, auditing policies not enabled, lagging patches, services listening on all interfaces, and disabled mandatory access control. The primary goal of hardening is to eliminate these predictable risks rather than waiting for unknown vulnerabilities.
1.1.4 Baselines, Exceptions, and Changes
A baseline is a set of checkable configuration states (for example, SSH disallowing password login, or a firewall denying by default). When business genuinely requires deviating from the baseline, the exception should be recorded: the reason, the approver, the expiry date, and compensating controls (for example, only open to the management network segment). "Following the document to the letter" with no exception management leads to firewalls or SELinux being turned off during troubleshooting, rendering the baseline ineffective.
1.2 Fundamental Principles
1.2.1 Defense in Depth
Never rely on a single control. When one layer fails (for example, a password is guessed), later layers should still delay, alert on, or block the attack. Typical layers on the host side are as follows:
The testable standard for defense in depth is: after removing one layer, can the remaining layers still function independently? For example, if firewall rules are flushed, does SSH still prohibit password login; if password login is re-enabled, is the source still restricted by the firewall?
1.2.2 Least Privilege
Grant only the privileges required to complete the intended work, and elevate them only when needed. Use a standard user for day-to-day operations; use a separate privileged account or just-in-time (JIT) elevation for administrative tasks. The broader the privileges, the more credentials can be read, the more configurations can be modified, and the more hosts can be reached laterally after a single point is compromised.
In practice, distinguish the following:
1.2.3 Default Deny
Firewalls, application control, sudo, and mandatory access control should adopt a default-deny, explicit-allow posture. A deny list that only tracks known-malicious objects cannot cover unknown techniques. The proper order for default deny is: first write the allow rule for your current management channel, then change the default action to deny, and finally confirm access is still possible through another already-verified channel. Doing this in reverse will cut off management access.
1.3 Mapping Threat Paths to Controls
Common intrusion paths can be mapped to the controls in this document as follows. This path illustrates that "every link should have a control"; it is not a step-by-step implementation.
Stage
Common conditions
Host-side controls
Covered chapters
Reconnaissance
Port and service exposure
Default deny, reducing listening surface
7, 13, 14
Initial access
Weak passwords, vulnerabilities, web uploads
Passwords and keys, patching, upload validation
3, 6, 9, 10
Execution
Scripts and interpreters
WDAC, CLM, noexec
4, 12
Privilege escalation
Local vulnerabilities, SUID, UAC misuse
Patching, SUID cleanup, standard-user work
2, 3, 12, 15
Credential access
SAM, LSASS, shadow
LAPS, PPL, permissions
2, 3, 10
Lateral movement
Password reuse, open management ports
LAPS, firewall source restriction
3, 7, 14
Persistence
Services, scheduled tasks, cron, Run keys
Auditing, Autoruns, systemd inventory
2, 8, 13
Defense evasion
Clearing logs, disabling protection
Log forwarding, integrity monitoring
5, 11, 21
Objective achieved
Cryptomining, ransomware, exfiltration
Outbound control, traffic analysis, incident response
7, 18, 22
Hardening raises the cost at every stage; incident response completes containment, forensics, eradication, recovery, and improvement after an event occurs.
1.4 Lab Environment and Reference Baselines
1.4.1 Lab Environment Requirements
Prepare isolated virtual machines for the exercises; do not use a production domain controller or production database for your first practice run.
When running commands on the lab machine that may interrupt a remote connection (changing the firewall default policy, changing the SSH port, disabling passwords), open the virtual machine console at the same time so you don't lock yourself out of the system.
1.4.2 Downloadable Baselines and Audit Projects
Project
Purpose
Address
Microsoft Security Compliance Toolkit
Windows security baselines, policy comparison
CISOfy Lynis
Linux/UNIX host auditing and hardening recommendations
https://github.com/CISOfy/lynis
dev-sec linux-baseline
Linux security baseline (InSpec)
https://github.com/dev-sec/linux-baseline
ansible-lockdown
Hardening roles that can be applied through automation
SigmaHQ/sigma
Detection rules (usable for logs and SIEM)
https://github.com/SigmaHQ/sigma
Lynis local run example:
The Suggestions section at the end of the output should be handled by priority; never change dozens of items at once if you would then be unable to roll back. On the Windows side, you can compare the baselines from the Security Compliance Toolkit against the local gpresult /h report.html to confirm whether domain policy or local policy is actually in effect.
1.4.3 Conventions used in this document
II. Windows System Architecture and Credential Protection
The Windows security model rests on three mechanisms: privilege-level isolation (kernel versus user mode), object access control (SIDs and ACLs), and separation of identity from privilege (accounts and access tokens). Understanding where credentials are stored at rest and cached at runtime is the foundation for Chapters 3, 5, 8, and 20.
2.1 User Mode and Kernel Isolation
2.1.1 How It Works
Windows NT uses a hybrid kernel. At runtime it is divided into kernel mode and user mode.
Mode
Privilege level
Typical components
Access scope
Kernel mode
Ring 0
`ntoskrnl.exe` (executive), `hal.dll` (hardware abstraction layer), kernel drivers
Hardware, all physical memory, and system objects
User mode
Ring 3
Ordinary applications, `explorer.exe`, and the user-mode portions of most service processes
The process's own virtual address space
User mode cannot directly access hardware or arbitrary kernel memory. When a kernel service is needed, the process enters the kernel via a system call. The System Service Descriptor Table (SSDT) holds the addresses of system service routines. After a user-mode request crosses into the kernel through a trap gate or similar mechanism, the executive handles object management, process and thread scheduling, I/O, and so on. This boundary is the core security boundary of the operating system: crossing it means being able to modify any process, disable protections, and read all memory.
The Object Manager assigns security descriptors to files, processes, registry keys, tokens, and so on. Access checking compares the subject's SID, group SIDs, and the object's DACL. Even if a process is already running in user mode, it cannot open a protected object without the corresponding ACE. This is why "having a process" and "having SYSTEM" are not the same state.
2.1.2 What Local Privilege Escalation Means
Local Privilege Escalation means: a subject that can already execute code on the machine obtains a higher integrity level or a SYSTEM/administrator token through a vulnerability or misconfiguration. Common technical preconditions include handle leaks in kernel drivers, object reference-count errors, arbitrary address writes, and so on. Hardening cannot eliminate every kernel flaw, but it can reduce loadable unsigned drivers, install kernel updates promptly, and strip business accounts of unnecessary SeDebugPrivilege and SeLoadDriverPrivilege.
View current privileges:
If a standard user has SeDebugPrivilege with a status of Enabled, it should be treated as a misauthorization. This privilege allows opening other processes and reading/writing their memory, which conflicts with the goal of credential protection.
2.1.3 Driver Signing and Verification
64-bit Windows requires kernel driver signing by default. Keep "Force driver signing" enabled. Temporarily disabling it is only appropriate for debugging scenarios explicitly mandated by a vendor, and it must be restored afterward. You can use sigcheck (Sysinternals) to verify the signatures of driver files in the system directory:
Sysinternals Suite: https://learn.microsoft.com/sysinternals/downloads/sysinternals-suite
2.2 SAM and Local Credential Storage
2.2.1 Storage Location and Contents
The Security Account Manager (SAM) holds the local account database.
Item
Location or description
File
`%SystemRoot%\System32\config\SAM`
Registry
`HKLM\SAM` (loaded by the system at runtime; by default the ACL allows only SYSTEM access)
Companion hive
Key material in `SECURITY` and `SYSTEM` participates in protecting the hashes
Domain accounts
Not in SAM, but in the domain controller's `NTDS.dit`
SAM stores password hashes, not plaintext. On modern systems this is primarily the NTLM Hash (MD4 over the UTF-16 encoded password). The early LM Hash is extremely weak and is now disabled by default; it must remain disabled. While running, the SAM file is locked and cannot be copied directly by Explorer; only offline disk mounting, WinRE, or Volume Shadow Copy (VSS) can yield a copy. Access control over backup media and shadow copies is therefore just as important as the SAM file itself.
2.2.2 Pass-the-Hash and Password Reuse
Once a hash is obtained, there are generally two follow-on paths: one is offline password guessing (dictionaries, rainbow tables); the other is Pass-the-Hash: without recovering the plaintext, use the NTLM Hash directly to complete certain network authentication. If multiple hosts share the same local administrator password, the hash from one host can be used to authenticate to the others. This is fully independent of "how complex the password is": even if the password is very long, as long as it is reused, Pass-the-Hash still holds.
2.2.3 Hardening and Verification
List local users:
2.3 LSASS and Logon Sessions
2.3.1 The Logon Flow
A simplified interactive logon proceeds as follows:
LSASS's responsibilities include: loading authentication packages, validating credentials, issuing tokens, maintaining logon sessions, and enforcing password policy. To support single sign-on and certain network protocols, historically it might cache plaintext, NTLM hashes, or Kerberos tickets (TGT) in memory. The target process for in-memory credential theft is therefore often LSASS.
2.3.2 WDigest, PPL, and Credential Guard
WDigest used to keep plaintext passwords in memory. It is off by default on modern systems, but you should still verify:
If this value exists and is 0x1, change it back to 0 and assess whether existing sessions need to be logged off. See the relevant mitigation documentation in the Microsoft security bulletin for the official guidance.
Protected Process Light (PPL) raises the bar for other processes trying to open a handle to LSASS. It can be set as follows:
RunAsPPL set to 1 means enabled (the exact value depends on the documentation for your current system). In enterprise environments, enable Credential Guard on supported Windows versions and use virtualization-based security (VBS) to isolate secrets, so that even if user-mode malicious code gains administrator rights, it is much harder to extract hashes from the isolated area. Credential Guard reference: https://learn.microsoft.com/windows/security/identity-protection/credential-guard/
2.3.3 Detection Points
Abnormal opens of LSASS, module injection into LSASS, and handle requests from processes not signed by Microsoft should be treated as high-priority events. Sysmon can record process access (Event ID 10, which must be enabled in its configuration). See the sysmon-config referenced in Chapter 4 for a configuration example. During analysis, correlate with 4672 (special logon) and 4624 in Chapter 5.
2.4 Services, Scheduled Tasks, and Startup Items
2.4.1 Mechanism Comparison
Mechanism
Manager
Typical privilege
Key locations
Service
Service Control Manager SCM (`services.exe`), usually in session 0
Mostly LocalSystem
`HKLM\SYSTEM\CurrentControlSet\Services`
Scheduled task
Task Scheduler service
Can specify any user, including SYSTEM
`%SystemRoot%\System32\Tasks` and the registry `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule`
Startup item
Winlogon, Explorer, etc.
User or system
Run, RunOnce, Startup folder, IFEO, Winlogon notification packages
Session 0 isolation means services do not run on the user's interactive desktop, reducing the historical problem of service pop-ups being abused for privilege escalation. But services still run with high privileges, so the harm is unchanged if their ImagePath is replaced.
Service start types: Start with a value of 0 boot, 1 system, 2 automatic, 3 manual, 4 disabled. Autostart combined with a writable path is a high-risk combination.
Scheduled task triggers include: time, logon, event, idle, session unlock, and so on. Any task that runs as SYSTEM with an action that launches a program from a user-writable directory should be investigated immediately.
2.4.2 Inspection Commands
PowerShell:
Watch for: paths under Temp, Public, or user directories; paths with spaces but no quotes (possibly exploitable via path parsing); and service names that mimic Windows components but have an unknown publisher.
Autoruns can list most autostart locations in a single pass. Download: https://learn.microsoft.com/sysinternals/downloads/autoruns
We recommend checking Hide Microsoft Entries and Verify Code Signatures, then reviewing the remaining items.
Events: 7045 (System channel, service installation), 4698 and 4702 (Security channel, scheduled task creation and modification). You must enable the corresponding auditing first — see Chapter 5. Related to persistence, .evtxSamples: https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES/tree/master/Persistence
2.4.3 Quoting the ImagePath
If the path is C:\Program Files\Vendor\app.exe without quotes, the system may try to execute C:\Program.exe first. If C:\ is writable, a program with the same name can be placed there. The correct form is "C:\Program Files\Vendor\app.exe". To check for unquoted service paths containing spaces:
3. Windows Accounts and Permission Management
Identities represent subjects, while permissions constrain what those subjects can do. A common compromise path goes like this: take control of a logon-capable account, escalate to administrator, join a privileged group, then use that identity to connect to other hosts.
3.1 Local vs. Domain Account Boundary
3.1.1 Differences
Type
Storage location
Scope
Management
Local account
local SAM on this machine
This machine only
Local security policy, `lusrmgr.msc`
Domain account
Domain controller `NTDS.dit`
Domain or forest
Active Directory and Group Policy
Both are security principals identified by SID. Built-in account SIDs have fixed suffixes — for example, the local Administrators group ends in S-1-5-32-544. You can add a domain user to a machine's local Administrators group to grant that user the highest local privileges on the host, while the identity itself can still be revoked in the domain.
View the SID:
3.1.2 Lateral Movement and LAPS
When local administrator passwords are reused, the hash or password can be reused across multiple machines. Windows LAPS generates a unique local administrator password for each computer, stores it in AD or Entra ID, and rotates it on a schedule. Deployment points:
You should also restrict network logon for local accounts. Example Group Policy path: Computer Configuration → Windows Settings → Security Settings → Local Policies → User Rights Assignment → "Deny access to this computer from the network", and add local accounts. Apply the same restriction for Remote Desktop.
Everyday office accounts must not belong to Domain Admins. The local Administrators group on workstations should be empty, or contain only dedicated admin accounts (for example adm-jsmith). Never use the same personal account you use for email.
For in-domain threats such as Kerberos ticket forgery or abuse of the directory replication protocol to sync hashes, you need tiered administration (Tier 0/1/2) and privileged account protection; local SAM hardening alone cannot address these. See 3.4.
3.2 Least Privilege and User Account Control
3.2.1 Tokens and Integrity Levels
When a user in the Administrators group logs on, the system prepares two tokens:
Integrity levels from low to high are typically Low, Medium, High, System. A lower-integrity process cannot write to a higher-integrity object. Browser sandboxes usually run at Low.
Microsoft has stated that UAC is not a security boundary; it reduces the likelihood of malware silently obtaining a full token without user interaction. Therefore, code already running in the local Administrators group cannot rely on UAC to prevent elevation. The real isolation is to use a standard user for daily work and restrict executables with WDAC or AppLocker.
To view process integrity (the Integrity column in Sysinternals Process Explorer), or:
3.2.2 UAC-Related Policies
Registry:HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Value name
Recommended
Description
EnableLUA
1
Enables Admin Approval Mode
ConsentPromptBehaviorAdmin
2
Prompt for consent on administrative actions (see policy documentation for exact enumeration)
PromptOnSecureDesktop
1
Show the prompt on the secure desktop, reducing the risk of spoofed UAC windows
FilterAdministratorToken
1
The built-in Administrator also uses a filtered token (if that account is still in use)
GUI:UserAccountControlSettings.exe or secpol. Choose "Always notify", never "Never notify". Group Policy: Computer Configuration → Windows Settings → Security Settings → Local Policies → Security Options.
3.2.3 Application Control
AppLocker can restrict exe, scripts, msi, and dll by publisher, path, or hash. WDAC (Windows Defender Application Control) policies are closer to a security boundary and can be enforced together with HVCI. WDAC: https://learn.microsoft.com/windows/security/application-security/application-control/windows-defender-application-control/
Administrative work should be done from a Privileged Access Workstation (PAW): a workstation with no office suite, no email, and no general internet access, used only to connect to servers and domain controllers. Reference: https://learn.microsoft.com/security/privileged-access-workstations/
3.3 Guest Account and Password Policy
3.3.1 Guest Account
Guest is a built-in account, disabled by default. When an installer or a bad policy enables it, the password is often empty. Its privileges are low, but it can still be used to probe shares, verify network connectivity, and break the audit assumption that only real-name accounts can log on.
Confirm that Account active is No. In a domain, use Group Policy: Computer Configuration → Windows Settings → Security Settings → Local Policies → Security Options → "Accounts: Guest account status" set to Disabled.
3.3.2 Password Spraying and Lockout
Online guessing takes two forms: repeated attempts against a single account (which easily triggers lockout), and password spraying — trying a few common passwords against many accounts so each account's failure count stays below the threshold. For this reason, a lockout threshold alone isn't enough; you also need to detect the pattern of "many accounts each failing once or twice," which corresponds to the statistical analysis of 4625 in Chapter 5.
The offline risk is obtaining the SAM or NTDS.dit and cracking the hashes, which has nothing to do with lockout and can only be mitigated through hash algorithms, password length, LAPS, and protecting backups.
3.3.3 Password Policy Recommendations
Item
Recommendation
Notes
Length
At least 14 for regular accounts, 15 for privileged accounts
Length beats forcing various character classes into a complex mix
Reuse
Never the same as external websites
A single leak affects the domain
Periodic forced changes
Should not be the only measure
Frequent changes lead to predictable rewrites; reset immediately after a leak
Multi-factor
Enable for remote access and privileged operations
Smart cards, Windows Hello for Business, FIDO2
Lockout
Set a threshold and monitor
Avoid locking administrators out; console logon can be excluded
Group Policy: Computer Configuration → Windows Settings → Security Settings → Account Policies → Password Policy. In a domain, you can use fine-grained password policies (PSO) for privileged users.
View effective policy:
3.4 Privileged Group Management
3.4.1 Key Groups
Scope
Group
Description
Machine
Administrators
Full control of the machine
Machine
Users / Remote Desktop Users
Regular logon and Remote Desktop
Domain
Domain Admins
Highest privilege in the domain; membership should be minimal
Forest
Enterprise Admins
Forest-wide; should be empty for daily use, reserved for emergencies
Forest
Schema Admins
Can modify the schema; must be empty day-to-day
Domain
Protected Users
Stronger credential protection for members
Service accounts should use Group Managed Service Accounts (gMSA) to avoid long-lived static passwords. IIS application pools should not use Domain Admins.
3.4.2 Protected Users and Tiering
Members of the Protected Users group are forced to use Kerberos AES, cannot use NTLM, and have the types of cacheable credentials restricted, which reduces the impact of pass-the-hash and some ticket theft. Before adding accounts, confirm that applications support Kerberos and AES; older devices may fail to log on. Reference: https://learn.microsoft.com/windows-server/security/credentials-protection-and-management/protected-users-security-group
Tiering model:
Never use a Domain Admins account to log on to workstations. If a workstation is compromised, the account's hash or ticket should never be present in the workstation's memory.
3.4.3 Account Auditing
Enable success and failure auditing for account management, and watch for 4720 (user created), 4728/4732 (added to group), and 4740 (account locked out). A newly created account with a hidden purpose (name containing $, blank description, suddenly added to Administrators) should be treated as an incident.
4. Windows PowerShell Security Controls
PowerShell is the primary interface for management automation, but it is also commonly used to execute code in memory, download scripts, and move laterally via WMI or WinRM. The control objectives are: restrict who can run what language capabilities, and ensure that what runs is recorded and leaves the machine.
4.1 Execution Policy
4.1.1 Scope
Scopes, from highest to lowest precedence, are MachinePolicy, UserPolicy, Process, CurrentUser, and LocalMachine. Common policy values:
Policy
Meaning
Restricted
Scripts cannot run; interactive commands are allowed
RemoteSigned
Local scripts can run; those downloaded from the internet must be signed
AllSigned
All scripts must be signed and trusted
Unrestricted
Unsigned scripts can run after a warning
Bypass
No policy is applied
The design goal is to reduce admins accidentally running scripts of unknown origin — not to block malicious code.
4.1.2 Why It Is Not a Security Boundary
At the process level you can specify -ExecutionPolicy Bypass. You can also use -Command, -EncodedCommand, or Invoke-Expression to execute without a .ps1 file. For this reason, setting the local policy to Restricted is not a valid control against malicious code. To effectively restrict execution, use AppLocker or WDAC to allow scripts by path, publisher, or hash.
It is still recommended to set LocalMachine to RemoteSigned or AllSigned as an operational hygiene measure, combined with a script-signing process.
4.2 Script Block Logging and Module Logging
4.2.1 Events and Policy
Feature
Event ID
Channel
Module logging
4103
Microsoft-Windows-PowerShell/Operational
Script block logging
4104
Same as above
Script block logging records the decrypted script block before execution, so even with Base64 and string-concatenation obfuscation the true intent can still be seen. Deep script block logging records deeper-level calls, produces more data, and should have its volume assessed before forwarding in production.
Group Policy: Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell → Turn on PowerShell Script Block Logging, Turn on Module Logging. Official reference: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_logging
Registry (after the policy takes effect):
Module logging also requires specifying module names; set it to * to record everything (log volume increases significantly).
4.2.2 Collection and Evasion
Evasion tactics include disabling the policies above, interfering with ETW providers, and calling .NET through unmanaged code to reduce script-engine logging. Therefore 4103 and 4104 must be forwarded to a centralized system in real time via WEF or a host agent. Clearing them locally does not affect already-forwarded copies. Separate alerts should fire when: someone changes EnableScriptBlockLogging to 0, the PowerShell Operational log is cleared, or a large burst of 4104 events suddenly stops.
Query recent script blocks:
4.3 Constrained Language Mode
4.3.1 Capability Restrictions
In Constrained Language Mode (CLM), PowerShell cannot use Add-Type to compile code, and cannot arbitrarily create COM objects, call Win32 APIs, or use reflection. Many memory-loading techniques that depend on these capabilities will fail. Check the current session:
FullLanguage indicates full language; ConstrainedLanguage indicates constrained.
4.3.2 Enforcement
CLM is typically triggered by AppLocker script rules or WDAC policy, not merely by setting the environment variable __PSLockDownPolicy. An environment variable alone can be changed back by a process with the necessary privileges. WDAC or AppLocker must be authoritative, and the result should be verified in a standard user session using the command above. If an admin account needs full language, use a separate policy and a separate workstation; avoid opening FullLanguage to all users on business servers.
System updates must be installed promptly; most known CLM bypass conditions are fixed with security updates.
4.4 AMSI and Transcription Logging
4.4.1 AMSI
The Antimalware Scan Interface (AMSI) submits script content to a registered antimalware provider (Windows Defender or a third-party EDR) after de-obfuscation and before execution. PowerShell, VBA, WSH, and others can go through AMSI. AMSI depends on provider updates and process integrity; tampering with the scanning function in memory or causing initialization to fail leads to missed detections. Therefore AMSI cannot be the sole control; it must be combined with CLM/WDAC, script block logging, and EDR behavioral detection (process injection, memory writes to the PowerShell process, ETW unloading).
4.4.2 Transcription
Group Policy: Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell → Turn on PowerShell Transcription. Specify an output directory, for example C:\ProgramData\PSTranscripts; the ACL should allow only Administrators and SYSTEM to write, with Users read-only or without permission to write to others' files. Transcription records input and output for later audit, but it contains sensitive commands, so the directory itself must be included in backup and access auditing.
4.5 Control Comparison and Sysmon
Control
Constitutes a security boundary?
Primary purpose
Execution policy
No
Reduce operator mistakes
Script block and module logging
No (detection)
Traceability and alerting
CLM and WDAC
Close to yes
Restrict language capabilities
AMSI, EDR, and transcription
Detection and content scanning
Behavior discovery and auditing
Sysmon installation (admin):
Download: https://learn.microsoft.com/sysinternals/downloads/sysmon
Sample config: https://github.com/SwiftOnSecurity/sysmon-config
Modular config: https://github.com/olafhartong/sysmon-modular
Before using a community config, tailor it to your environment; otherwise the event volume may exceed storage and analysis capacity. For PowerShell, at minimum record: the command line in ProcessCreate (event 1), powershell.exe network connections (event 3), and abnormal DLLs in image loads (event 7).
5. Windows Event Log Collection and Analysis
The security log is the primary basis for detection and forensics. Without an enabled audit policy, the Security channel cannot provide fields such as logon type or account changes — it is like having no recording at all.
5.1 Log Channels and Capacity
5.1.1 Storage Location
Path: %SystemRoot%\System32\winevt\Logs\, suffix .evtx. The default single-file size is often only a few tens of MB and it wraps around. In production you should:
Pay attention to maxSize and retention. Modification example (adjust to actual capacity):
5.1.2 Channel Responsibilities
Channel
Contents
Security purpose
System
Drivers, service start/stop, system components
7045 new service, driver failure
Application
Application errors
Supplementary clues
Security
Logons, object access, privileges, account changes
Core audit
PowerShell/Operational
Script blocks and modules
4103, 4104
Microsoft-Windows-Sysmon/Operational
Processes, network, registry, etc.
Requires installing Sysmon separately
Microsoft-Windows-Windows Defender/Operational
Threat detection
Complements EDR
5.1.3 Enabling Audit Policies
The traditional nine categories are broken down further under "Advanced Audit Policies." At a minimum, enable the following:
Subcategory
Success
Failure
Purpose
Logon
Yes
Yes
4624, 4625
Account Logon
Yes
Yes
Domain credential validation
Account Management
Yes
Yes
User and group membership
Privilege Use
As needed
As needed
Sensitive privileges
Process Creation
Yes
No
4688, and make sure command-line auditing is also enabled
Object Access
As needed
As needed
Requires setting a SACL on the object
Policy Change
Yes
Yes
Audit policy being disabled
System Integrity
Yes
Yes
1102, etc.
View from the command line:
Enabling process-creation command lines: group policies "Audit Process Creation" and "Include command line in process creation events." Registry:
A 4688 without a command line only shows powershell.exebut not the script contents, so its detection value drops significantly.
Local Security Policy GUI:secpol.msc. In a domain environment you must use GPO, to avoid each machine's manual settings being overwritten by the next gpupdate.
5.2 Key Security Events
5.2.1 Logon-related
Event ID
Meaning
Analysis points
4624
Successful logon
Logon Type, TargetUserName, IpAddress, LogonProcessName
4625
Failed logon
Failure reason, sub-status, source address
4634 / 4647
Logoff
Session ended
4648
Explicit credentials
A process running under another user's identity; common during lateral movement
4672
Special privileges
Often accompanies an administrator logon
4776
NTLM credential validation
Local machine or DC
4768 / 4769
Kerberos TGT / TGS
Domain environment
Logon types:
Type
Name
Typical scenario
2
Interactive
Console
3
Network
SMB, some remote management
4
Batch
Scheduled task
5
Service
Service start
7
Unlock
Unlock
8
NetworkCleartext
Cleartext network (should be avoided)
9
NewCredentials
RunAs /netonly
10
RemoteInteractive
Remote Desktop
11
CachedInteractive
Cached domain logon
For lateral movement within the network, pay special attention to Type 3 and Type 10. A Type 10 outside working hours, or sourced from an unusual country or an unregistered bastion host, should be escalated for investigation.
5.2.2 Accounts, Persistence, and Clearing Logs
Event ID
Channel
Meaning
4720 / 4726
Security
User created / deleted
4728 / 4732
Security
Added to global group / local group
4738
Security
User account changed
4698 / 4702
Security
Scheduled task created / updated
7045
System
Service installed
1102
Security
Security log cleared
4719
Security
System audit policy changed
1102 and 4719 should be treated as high-priority alerts: they may indicate privilege abuse or defense evasion. PowerShell 4104 is covered in Chapter 4. Sysmon: 1 process creation, 3 network, 7 image load, 8 CreateRemoteThread, 10 process access, 11 file creation, 12/13 registry.
Detection practice samples: https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES
Copy the .evtx from the repository to your analysis machine and open them with wevtutil or Get-WinEvent—do not "replay" them into real channels on a production machine. Sigma rules: https://github.com/SigmaHQ/sigma
Sentinel query examples: https://github.com/Azure/Azure-Sentinel
5.3 Extracting with wevtutil
wevtutil Suited to on-site backup; does not depend on PowerShell execution policy.
XPath can combine time and event IDs. The exported .evtx can be copied to an offline analysis machine. If disk space is tight, export Security, System, PowerShell, and Sysmon first.
Clearing a log writes event 1102. The defense is real-time forwarding, plus restricting log-clearing permissions to accounts within the Event Log Readers group only.
5.4 Analyzing with Get-WinEvent
Get-EventLog Covers only traditional channels and performs poorly.Get-WinEvent supports XML and hashtables.
Extract the logon type from 4624:
Correlation method: link 4624 and 4688 by LogonId to get "who logged on and what process they started." A burst of 4625s from the same source IP on host A, followed by a 4624 Type 3 for that IP on host B, forms a lateral movement lead.
Log Parser 2.2 can query .evtx with SQL-like syntax: https://www.microsoft.com/en-us/download/details.aspx?id=24659
WEF (Windows Event Forwarding) sends events from source computers to a collector, which the SIEM then pulls from. This is the official centralized approach when you don't want to install third-party agents. See: https://learn.microsoft.com/windows/security/operating-system-security/windows-security-baselines and the WEF documentation.
6. IIS Access Log Analysis
OS logs reflect host logons and system events; IIS logs reflect every HTTP request to the website. When an attacker breaks in through file upload, SQL injection, or deserialization, traces typically appear in the access log earlier than in the system log.
6.1 Path, Format, and Enabling
6.1.1 Default Location
Directory:C:\inetpub\logs\LogFiles\. Each site has its own subdirectory W3SVCn, where n is the site ID. To find the site ID in IIS Manager: Sites → the site in question → Advanced Settings. The filename u_exYYMMDD.log is the extended format of the UTC date.
It can also be redirected to another disk via configuration. During incident response, search for applicationHost.config in logFile:
6.1.2 W3C Fields
Default W3C extended format. The file starts something like:
IIS Manager: Site → Logging → select W3C → Select Fields. Recommended additions:cs(Referer),cs(Cookie)(keep privacy in mind),cs-bytes,sc-bytes,time-taken. POST bodies are not logged by default, so the function name of a one-liner web shell may appear only in the query string or later GET parameters, with the body invisible.
Configuration guide: https://learn.microsoft.com/iis/manage/provisioning-and-managing-iis/configure-logging-in-iis
Logs must be forwarded to the SIEM. Once an attacker gains privileges on the web server, they often delete LogFiles or disable logging.
6.2 Field Meanings and Analysis
Field
Meaning
Analysis points
date / time
Time
UTC by default; convert to align with the security log's local time
s-ip / s-port
Server address and port
Distinguish between sites with multiple bindings
c-ip
Client
Often the proxy address behind a reverse proxy; needs `X-Forwarded-For` (must be added as a custom field)
cs-method
Method
Uploads and many backdoor admin panels use POST
cs-uri-stem
Path
`.aspx`, `.ashx`, `.php` suddenly appearing in an upload directory
cs-uri-query
Query
`../`, `union`, `cmd=`, template injection signatures
sc-status
Status
See 6.3
cs(User-Agent)
UA
Empty, `sqlmap`, `curl`, `python-requests`
time-taken
Duration in milliseconds
Unusually long requests may indicate data exfiltration
6.3 Status Codes and Behavior Patterns
Status code
Meaning
Common pattern
200
Success
An obscure script repeatedly POSTs by the same IP
301 / 302
Redirect
Brute-forcing a login form
401 / 403
Unauthorized / Forbidden
Probing directories and admin paths
404
Not found
Many different paths from the same IP in a short window
500
Server error
Probing frameworks and leaking paths
Also look at sc-substatus. For example, 404.0 and 403.14 (directory listing disabled) carry different meanings.
Behavior patterns:
6.4 Extraction and Statistics Examples
Field indexes depend on the actual order of #Fields; always read the file header before analyzing and never assume column 9 is c-ip.
Log Parser:
IIS Failed Request Tracing can record detailed error information. The logs are bulky, so it's best to enable it only for a short period against suspicious URLs.
7. Windows host firewall management
The Windows Firewall is built on the Windows Filtering Platform (WFP) and filters traffic in the host's network stack. It can't replace a perimeter firewall, but it can constrain lateral movement after a compromise and provide a last line of filtering when a laptop leaves the office network.
7.1 Inbound and outbound model
The firewall uses stateful inspection: for an allowed inbound connection, the return outbound traffic is usually permitted automatically, so you don't need to write a symmetric rule (the exact behavior depends on the rule direction and the program involved).
High-security servers should evaluate an outbound allowlist: permit only designated programs to reach update servers, domain controllers, and business peers. An outbound allowlist is expensive on desktop environments, so you can fall back to blocking outbound traffic from programs in unknown paths and logging outbound connections (Sysmon event 3).
Common high-risk inbound ports: 3389 (RDP), 445 (SMB), 135/139, 1433 (SQL Server), 5985/5986 (WinRM), 47001. On application servers with no business need, these ports should be closed to non-management network segments.
7.2 Profiles and network locations
Profile
Matching condition
Policy tendency
Domain
NLA confirms the domain controller is reachable
Unified via GPO
Private
Marked private by the user or by policy
Management ports should still be restricted
Public
Unknown network
Strictest
Domain-joined computers should consistently show DomainAuthenticated. Portable devices on hotel networks should use Public. If NLA fails and the machine falls back to Public when it should be using the domain profile, legitimate inbound traffic may be cut off — investigate DNS and domain controller connectivity rather than turning the firewall off.
Group Policy can prevent users from changing the network location. All three profiles must have Enabled set to True. Enabling only Domain and turning off Public leaves a laptop without a host firewall when it's off the corporate network.
7.3 Rule baseline
GPO lockdown: Computer Configuration → Windows Settings → Security Settings → Windows Defender Firewall. Registry:HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy
7.4 Operational commands
Documentation: https://learn.microsoft.com/powershell/module/netsecurity/new-netfirewallrule
Emergency isolation: on a compromised host you can set all profiles to block inbound and outbound by default, then permit only the port toward the forensic collector. Don't make "turn off the firewall" your first troubleshooting step. When an application can't connect, first check the listening address, whether the service is running, security groups, and network ACLs — suspect the host firewall only last.
8. Windows registry security configuration
The registry is the configuration store for the system and for software, and it's also a prime write target for persistence, image hijacking, and disabling protection. The services in Chapter 2, the policies in Chapter 4, and the firewall policy in Chapter 7 are all stored in the registry.
8.1 Autostart-related keys
Common locations (always check the 32-bit WOW6432Node counterpart as well):
Path
Scope
`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run`
All users
`HKCU\Software\Microsoft\Windows\CurrentVersion\Run`
Current user
`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce`
One-time
`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run`
Policy-specified
Startup folder
`%ProgramData%\Microsoft\Windows\Start Menu\Programs\StartUp` and the corresponding per-user directory
When the data points to Temp, AppData\Local\Temp, Public, or an unsigned exe, export the file hash and isolate it. Sysmon events 12 and 13 can record the creation and value writes of these keys. Autoruns' Logon tab aggregates all of the locations above.
8.2 Image hijacking and Winlogon
8.2.1 IFEO
Path: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\<进程名>. Microsoft uses this to attach a debugger to a designated process. If a string named Debugger exists and points to another executable, the Debugger is launched first every time the target process starts. Historically, the accessibility utilities sethc.exe, utilman.exe, osk.exe, and magnify.exe have been replaced or hijacked via IFEO so they trigger at the logon screen. To investigate:
Treat any Debugger value on a non-debugging workstation as high risk. Subkeys such as SilentProcessExit and GFlags can also be abused; Autoruns' Image Hijacks tab lists them.
Samples: https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES/tree/master/Persistence
8.2.2 Winlogon
Path: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Value
Normal example
Anomaly
Shell
`explorer.exe`
Replaced, or another program appended with a comma
Userinit
`C:\Windows\system32\userinit.exe,`
A path appended after the comma
Notify
Legitimate notification packages
Unknown DLL
Once Userinit has an appended program, that extra program launches at every logon with the user's privileges (high if the logon is an administrator).
8.3 Service registry entries
Path: HKLM\SYSTEM\CurrentControlSet\Services\<短名称>
Value
Meaning
ImagePath
Executable, or `svchost.exe -k group`
Type
1 kernel driver, 2 filesystem, 16/32 own process / shared process
Start
2 automatic
ObjectName
Run-as account, e.g. LocalSystem
FailureCommand
Command run on failure; can be stuffed with a malicious command
ServiceDll
DLL of a service hosted by svchost
New services should trigger a 7045 alert: verify hash, signature, path, and account. A name that mimics WindowsUpdate or SysHelper but lives in a user directory should be treated as malware first.
8.4 Auditing and backup
8.4.1 Registry auditing
Enable "Registry" object access in Advanced Audit Policy, and set SACLs on sensitive keys (audit successful writes). Keys include the Run keys above, Winlogon, Services, PowerShell policy, firewall policy, and LSA. To configure: regedit → key → Permissions → Advanced → Auditing. Events appear in the Security channel, such as event ID 4657 (confirm the actual ID on your current system).
8.4.2 Backup
While the system is in a trusted state:
SAM and SECURITY require SYSTEM privileges, typically done offline or using reg save in the SYSTEM context. Store backup files as confidential material. Restoring the wrong hive can render the system unbootable, so verify on a test machine.
9. Windows patch management
Patch management is about the window in which known vulnerabilities get fixed. Public exploits often appear hours to weeks after a patch is released. Managed objects include the operating system, drivers, Office, browsers, runtimes (.NET, VC++), and third-party components such as Java.
9.1 Update sources and responsibilities
Source
Applies to
Notes
Windows Update
Standalone machines
Hard to approve and roll out in batches
WSUS
Intranet
Free, with classification, approval, and reporting
MECM / SCCM
Medium to large
Inventory, phased rollout, compliance dashboard
Windows Update for Business
Cloud-managed clients
Deferral rings, deadlines
Third-party patching
Non-Microsoft software
Separate catalog and testing
Responsibilities: security operations tracks CVEs, CVSS, and the CISA KEV catalog (https://www.cisa.gov/known-exploited-vulnerabilities-catalog), along with whether a flaw is actively exploited; IT operations handles testing and rollout; business units provide maintenance windows. KEV-listed items exposed to untrusted networks should go through the emergency process rather than the monthly patch day.
Microsoft Security Update Guide: https://msrc.microsoft.com/update-guide
9.2 Emergency patch response
Client logs:C:\Windows\Logs\WindowsUpdate\WindowsUpdate.log(after Win10 you need Get-WindowsUpdateLog to merge ETL). In Event Viewer, the Windows Update client source shows installation results.
9.3 Baseline inventory, canary rollout, and rollback
Without an asset inventory you cannot calculate coverage. You need to know: OS build (winver / [System.Environment]::OSVersion), architecture, whether it is a server, its role (DC, IIS, file server), installed KBs, and third-party software versions.
Canary order: test → staging → production non-core → core. Kernel and driver updates usually require a reboot to take effect; a system that is "installed but not rebooted" shows as fixed in the inventory while still running the old kernel in memory. The maintenance window must include the reboot.
Rollback: some cumulative updates can be uninstalled, others cannot. Core systems should have a system image or VM snapshot. Read the KB's known issues before uninstalling. Revert third-party software according to the vendor's documentation.
The Security Compliance Toolkit can be used to check whether security options were reverted by an update or overridden by a business GPO: https://www.microsoft.com/en-us/download/details.aspx?id=55319
10. Linux account management
The principles of Linux account security are: strong authentication, least privilege, and no Shell for accounts that do not require interactive login. The account database is split between passwd and shadow, while privilege escalation is constrained by sudo and PAM.
10.1 passwd and shadow
10.1.1 Field meanings
/etc/passwd should have permission 644, with seven colon-separated fields per line:
The password placeholder must be x, indicating that the real hash lives in shadow. If this field contains a hash or is empty, that is a serious misconfiguration. UID 0 is root. Accounts whose login Shell is /sbin/nologin or /bin/false cannot log in interactively.
/etc/shadow should have permission 000 or 600, readable only by root. Fields include: hash, last password change date, minimum/maximum change interval, warning days, post-expiry grace period, and account expiration date. A hash prefix of $6$ means SHA-512 crypt, while $y$ and similar mean yescrypt (depending on distribution). Once copied, hashes can be cracked offline, so shadow and its backups deserve the same attention to permissions.
Only root should have UID=0. If you find toor,admin or other accounts sharing UID 0, treat it as an incident.
10.1.2 Threat description
Any user can read passwd, which is used to enumerate logon accounts and home directories. If shadow has overly broad permissions, is read by a web application as root, or ends up in a backup package, it can be used for offline cracking. Hardening includes: strict permissions, limiting backup access, using long passwords for logon accounts, or switching directly to key-based login and locking passwords.
10.2 Least-privilege sudo
10.2.1 Editing rules
/etc/sudoers and the files under /etc/sudoers.d/ must be edited with visudo. visudo checks syntax on save, so you never lock everyone out of privilege escalation.
Rule intuition: who, on which host, as which user, running which commands. Example (format only — do not copy ALL verbatim):
10.2.2 Dangerous grants
The following configurations are equivalent to handing out a root Shell; a compromised normal user can escalate immediately:
Check the commands granted to the current user:
In production, grant by group (%wheel or a custom %ops), use absolute paths for commands, and require a password unless NOPASSWD is truly necessary. For passwordless automation accounts, the command set must be extremely narrow and restricted by source host.
10.3 Locking down unused accounts
System accounts (bin,daemon,nobody, etc.) should not have an interactive Shell.
lastlog -b 90 lists accounts that have not logged in for 90 days; lock them in coordination with HR processes. Default accounts created when installing databases or middleware must have their passwords changed or be set to nologin. Debian and RHEL use different system UID ranges; refer to login.defs in UID_MIN for your distribution to distinguish system accounts from normal ones.
10.4 Password quality and failure lockout
10.4.1 pam_pwquality
Configuration usually lives in /etc/security/pwquality.conf. PAM entries: on RHEL systems /etc/pam.d/system-auth and password-auth; on Debian systems /etc/pam.d/common-password.
Example intent (adjust to your organization's policy):
remember is provided by pam_unix or pam_pwhistory, preventing short-term password reuse. /etc/login.defs such as PASS_MAX_DAYS control validity periods. As with Windows, don't treat frequent forced password changes as your only control.
10.4.2 pam_faillock
Locking after repeated failures slows online guessing. You must configure an unlock time and avoid locking a legitimate administrator out of the only remote channel for a long period. RHEL 8+ uses pam_faillock, while older versions may use pam_tally2.
On the SSH side you should still disable password login first. fail2ban as a compensating control is covered in Chapter 11.
11. Linux log security configuration
The goal of log security is: key actions are recorded, local privileges cannot unilaterally destroy all evidence, and storage is not filled with meaningless data. In practice this relies on rsyslog or syslog-ng, journald, logrotate, permissions, and a mandatory remote copy.
11.1 rsyslog and journald
11.1.1 Dual-track approach
Component
Form
Location
Characteristics
rsyslog
Text
`/var/log/messages`, `secure`, etc.
Easy to grep and forward
journald
binary
`/var/log/journal/`
query by unit, PID, and time
/etc/systemd/journald.conf Recommendation:
Storage=volatile, it is lost on restart.persistent requires the directory /var/log/journal to exist.
11.1.2 rsyslog configuration structure
main file /etc/rsyslog.conf, snippets /etc/rsyslog.d/*.conf. Rules consist of a selector plus an action. The auth facility is written to /var/log/secure on RHEL, and to /var/log/auth.log on Debian (auth,authpriv.* in rsyslog).
After making changes:
-N1 check the syntax, to avoid a typo that prevents the service from starting.
11.2 Authentication logs
Typical lines:
Debian replaces secure with auth.log. Field positions vary with the template; before tallying, head to inspect a column, then use awk.
fail2ban: https://github.com/fail2ban/fail2ban
After installing, copy the jail to jail.local, enable [sshd], and set maxretry, bantime, ignoreip (your management subnet). It reads authentication logs and drives the firewall, and is no substitute for key-based authentication.
11.3 Rotation, permissions, and tamper-proofing
/etc/logrotate.conf and /etc/logrotate.d/ control the rotation period, rotate the number of copies, compress, delaycompress, missingok, create 0640 root adm. Authentication logs should be 600 or 640, owned by root, with group adm or systemd-journal (depending on the distribution).
A disk filled with meaningless logs will stop services from writing. Set capacity alerts on /var. An attacker might systemctl stop rsyslog or change rules to /dev/null. Use auditd to monitor writes to /etc/rsyslog.conf and /etc/rsyslog.d, and keep an eye on whether the rsyslog process is alive. chattr +i can lock individual files, but you need an unfreeze SOP, otherwise rotation itself will fail.
11.4 Central forwarding
Local root can delete /var/log. Evidence must therefore leave the host before it's compromised.
rsyslog forwarding example (TCP):
@@ is TCP, @ is UDP. In production use TLS with certificate verification; see the rsyslog imtcp/omfwd and ossl documentation. The Wazuh agent can also handle collection, integrity monitoring, and alerting: https://github.com/wazuh/wazuh docs: https://documentation.wazuh.com/
To verify forwarding: search the collector for this host's recent SSH failures, trigger one failed login on the host, and confirm the latency is acceptable.
12. Linux file-permission management
Permission misconfiguration is a common precondition for local privilege escalation. Discretionary access control (DAC) is made up of owner, group, others, and special bits; Chapter 12 covers DAC and Chapter 16 covers MAC.
12.1 Basic model and common commands
Permission bits: read 4, write 2, execute 1. The execute bit on a directory means you can enter it. Without the directory execute bit, even a 644 file can't be opened.
namei -l shows the permissions at each level of a path; use it to check whether intermediate directories are traversable when a 600 file is somehow still readable by others.
Object
Recommendation
`/etc/passwd`
644 root:root
`/etc/shadow`
000 or 600 root:root
`/etc/sudoers`
440 root:root
SSH host private key
600
User private key
600, with the `.ssh` directory at 700
`authorized_keys`
600 or 640
Application code
750 or 755, owned by the deployment account; the web runtime user should be read-only if possible
Never use 777 on application directories. A web upload directory that must be writable should be kept separate from executable interpreters, and paired with PHP/IIS rules that block script execution in that directory.
ACL: getfacl/setfacl can grant access beyond UGO. To check for unintended ACLs:
12.2 SUID, SGID, Sticky, and capabilities
Bit
Numeric
Effect
SUID
4
runs with the file owner's identity; when the owner is root, it runs with root privileges
SGID
2
runs with the group identity; on a directory, new files inherit the group
Sticky
1
only the file owner (and root) can delete files in the directory
/tmp, /var/tmp should be 1777, i.e. sticky. Without the sticky bit, users can delete each other's temporary files.
SUID binaries shipped by the distribution (such as passwd, sudo) should be kept. find, vim, bash, python, nmap, cpappearing with SUID is anomalous; you must chmod u-s and trace their origin.
Linux capabilities split root's powers into pieces. cap_setuid, cap_sys_admin granted to an interpreter have an effect close to SUID.
12.3 umask and key directory mount options
By default files are created 666 and directories 777, then the umask is subtracted away. umask 022 → 644/755; umask 077 → 600/700. An overly permissive umask (000) makes new files writable by others.
At the start of a script you can explicitly umask 077.
/tmpWhen the business allows, add /etc/fstab to nosuid,nodev,noexec.noexec blocks execution of binaries in that directory, greatly reducing the chance that planted malware can run directly, but it may affect some installers, so it must be tested./dev/shmThe same applies. For the partition containing the web root, you may consider nodev,nosuid.
chattr +i /etc/passwd prevents accidental modification. During troubleshooting you must chattr -i. Use it only for golden files that rarely change, and document it in the runbook.
13. Linux Service Security Configuration
Every service that is listening is part of the attack surface. Principles: minimal installation, minimal listening, strong authentication on remote management channels, and source restriction.
13.1 systemd Units
13.1.1 File Locations and Precedence
systemd runs as PID 1. Unit files:
systemctl cat shows the merged unit. Pay attention to ExecStart, User, Restart=always, WantedBy=multi-user.target. Attackers may drop files with names similar to systemd-networkd-wait.service whose ExecStart points to /tmp or a user home directory.
13.1.2 Hardening Directives
In a drop-in you can add the following for business services:
Whether these can be added depends on whether the service needs to write to /usr or read the home directory. After changing, systemctl daemon-reload && systemctl restart 服务.
New unit files should be 644 root:root. Monitor /etc/systemd/system with FIM or auditd.
13.2 Disabling Unused Services and Restricting Listening
mask symlinks the unit into /dev/null, preventing it from being pulled in by dependencies. If the database, Redis, or message queue is accessed only by local applications, it should bind 127.0.0.1.ss with a value of *:3306 means all interfaces. After changing configuration, confirm that ss has actually changed, rather than having edited the file but not restarted.
13.3 SSH Hardening
Configure /etc/ssh/sshd_config and sshd_config.d/*.conf. After changes:
-t to check syntax. Recommended items (adjust the port and users to your environment):
AllowTcpForwarding no may affect legitimate tunnels, so confirm with the network team. Host keys in ssh_host_*_key should be 600. Users should place only their own public keys in authorized_keys; never distribute the same private key to all servers. OpenSSH manual: https://man.openbsd.org/sshd_config
Verification: logging in with a key from an allowed network should succeed; from other networks or with a password it should fail;sshd -T | grep -i passwordauthentication to confirm the effective value is no. If a cloud provider's second management channel exists (such as a serial console), make sure it works before changing SSH.
14. Linux Firewall Configuration
The firewall determines the set of ports the host exposes to the outside. As with Chapter 7 for Windows: deny by default, allow explicitly, and put precise rules first. Linux implementations have gone through iptables, firewalld, and nftables, all built on Netfilter underneath.
14.1 Implementation Comparison
Solution
Description
Use case
iptables
User-space tool that operates on tables and chains
Legacy scripts, troubleshooting
firewalld
Zones, with runtime and permanent separated; backend can be nft
Default on RHEL 7+
nftables
New framework, sets and maps, `nft` command
Preferred underlying choice for new deployments
Do not mix multiple tools to modify policy at the same time on a single host, or rules will overwrite each other and become impossible to explain. nftables: https://wiki.nftables.org/
14.2 Default Policy and Ordering
A default allow can only block known addresses. A default deny allows only business ports and sources. iptables/nft both match top-down and stop on the first ACCEPT or DROP. Wrong example: unconditionally DROP first, then APPEND an allow for SSH — SSH will never work. Correct: allow SSH and established connections first, DROP last.
Before changing the default policy, you must log in via the virtual machine console, or ensure the current session is established (RELATED,ESTABLISHED still allowed) and the new rules already include SSH.
14.3 firewalld Baseline
A zone represents the trust level for a NIC or source: drop, block, public, internal, trusted, and so on. Rules without the --permanent flag disappear after reload or reboot.
Removing SSH from the public default services and replacing it with a rich rule restricted by source can significantly reduce internet scanning. Manual: https://firewalld.org/documentation/
When troubleshooting, don't systemctl stop firewalld. Instead check --list-all, whether the port is listening, and SELinux AVC.
14.4 iptables and nftables Notes
iptables tables: filter (INPUT/FORWARD/OUTPUT), nat, mangle. For everyday host filtering, look at filter.
nftables commonly uses inet family to cover both IPv4/IPv6. Configure /etc/nftables.conf, which is loaded by nft -f. Integrity monitoring should be applied to this file. When a cloud security group and the host firewall coexist, both must be aligned, otherwise you get "security group allowed but host DROP" or the reverse.
15. Linux Version and Vulnerability Management
Most exploitable conditions come from known, unpatched vulnerabilities. Version management includes: whether the distribution is still supported, whether the kernel has actually been rebooted into effect, whether software sources are trusted, and whether CVEs are prioritized by exposure.
15.1 Distribution Lifecycle
After reaching EOL, the vendor no longer provides security updates. Continuing to run it is effectively publishing a list of known vulnerabilities. Build an asset table: hostname, distribution, end-of-support date, owner, migration window. Alternative paths include a major-version upgrade, switching to a compatible still-supported distribution, or buying extended vendor support.
15.2 Kernel and Package Updates
Kernel vulnerability fixes usually require a new kernel to be running, i.e., a reboot.uname -r differs from the latest kernel package already installed on disk, meaning you haven't rebooted yet. Live patching (Livepatch, kpatch) can avoid an immediate reboot in some scenarios, but you must use vendor commands to confirm the patch is loaded.
Software sources: production should use internal mirrors (Nexus, Artifactory, official mirror sync) and avoid unknown third-party sources directly.yum versionlock or apt-mark hold can pin glibc, openssl, and similar packages to prevent unplanned upgrades. Upgrades must first be performed in a test environment.
Supply-chain risk: a malicious or compromised repository can plant a backdoor under a legitimate package name. Only enable repositories that pass signature verification, and monitor changes to yum.repos.d / sources.list.
15.3 CVE Tracking and Scanning
CVE provides an identifier, CVSS provides a rough score. Prioritization should also consider: whether it is in CISA KEV, whether public exploits exist, whether the package listens on an untrusted network, and whether an official fix package is available.
Compare installed versions against the "affected versions" in advisories. Host scanning: Vuls https://github.com/future-architect/vuls; OpenVAS/GVM https://github.com/greenbone/openvas-scanner. Scan results must be manually checked for false positives (e.g., mitigated but the version number is unchanged). Lynis can also provide configuration-level recommendations: https://github.com/CISOfy/lynis
16. Linux Access Control
DAC lets the file owner decide who can read and write. PAM determines how identity is proven. MAC (SELinux/AppArmor) further restricts a process by policy even after DAC allows it. TCP Wrappers is mentioned only as a historical concept.
16.1 PAM Authentication Stack
16.1.1 Module Types and Control Flags
Applications (sshd, sudo, login) load modules through files named after the service under /etc/pam.d/, without changing the program code.
Type
Purpose
auth
Verify identity
account
Whether the account is expired or allowed to log in
password
Quality checks when changing passwords
session
Session establishment and teardown (limits, environment, logging)
Control flags:required(continue on failure, fail at the end),requisite(fail immediately),sufficient(succeed early if this passes and no earlier required module failed),optional. Getting the order wrong leads to bypasses or a lockout for everyone. Before touching PAM, always keep a console session open and test SSH from a separate terminal.
16.1.2 Hardening and integrity
Use pam_pwquality,pam_faillock. Never allow unknown pam_*.so into the stack. Package verification:
Swapping pam_unix.so to record passwords is a classic backdoor. Run FIM against /lib*/security and /etc/pam.d. Wazuh FIM can monitor these paths.
16.2 TCP Wrappers
/etc/hosts.allow,/etc/hosts.deny are provided by libwrap, with the syntax 服务:客户端. Modern sshd no longer links against libwrap by default. You can use ldd $(which sshd) to check whether it contains libwrap. IP filtering in production should use a firewall. This mechanism exists mainly as a historical artifact worth understanding as a historical way of "allowing by source".
16.3 SELinux and AppArmor
16.3.1 Modes
Mode
Meaning
Enforcing
Denies violations and audits them
Permissive
Audits but does not deny, used for debugging
Disabled
Fully off and the policy is not loaded at next boot
/etc/selinux/config in SELINUX=enforcing. When troubleshooting, use setenforce 0 to tell whether a policy is blocking you, and once verified, be sure to setenforce 1. Changing the config to disabled and rebooting is removing the MAC layer altogether.
SELinux is type enforcement: processes have domains (e.g. httpd_t), and files have types (e.g. httpd_sys_content_t,shadow_t). Even if DAC allows httpd to read shadow, TE can still deny it. This is the key layer that prevents a web process from reading credentials after remote code execution.
To set context on a new directory:
Do not use chcon as a long-term fix; a reboot or restorecon may wipe the fix. Notebook: https://github.com/SELinuxProject/selinux-notebook
AppArmor is path-based and enabled by default on Ubuntu.
16.4 Layered controls
Full order: network firewall (source) → whether the service should exist and its bind address → PAM (identity and lockout) → DAC and sudo (files and privilege escalation) → MAC (still constrained after a process is compromised) → logs shipped off-host. Verification: on a test machine, deliberately remove only one layer and see whether the rest still block or leave evidence.
17. Incident response: forms and severity levels
Hardening lowers the likelihood of an incident but never to zero. Incident response completes after an event: contain the impact, preserve evidence, remove the cause, restore the business, improve controls. This chapter covers how to respond and by what standard to allocate resources.
17.1 Remote vs. on-site response
Method
Means
Pros
Limits
Remote
SSH, RDP, VPN, EPP/EDR console, Wazuh
Fast, can cover many machines at once
Channel may already be controlled; may alert the adversary; bandwidth limits imaging
On-site
Data center, KVM, external acquisition, unplugging the network cable
Can collect memory and disk; does not rely on the host's SSH
Travel and approvals take time
Strategy: remotely cut command-and-control and lateral movement first (firewall, accounts, VLAN isolation), then do full imaging and final verdict on-site. If EDR shows the attacker is using the same bastion host, stop using it and switch to out-of-band (iLO, iDRAC, cloud serial console) or physical access. Every command run remotely may be recorded by the adversary's monitoring, and should also go into your own timeline.
17.2 Priorities by event type
Type
Priority action
Key evidence
Web backdoor
Isolate the site or upload directory, preserve the files
Web logs, file timestamps, w3wp/php-fpm child processes
Ransomware
Isolate the network, assess backups
Encrypted extensions, ransom note, SMB lateral movement
Cryptomining
Cut outbound connections, check persistence
CPU, mining pool domains, cron
Data exfiltration
Cut outbound traffic, determine data scope
Traffic, database audit, archives
Brute-force guessing
Block the source, check whether login already succeeded
4625/Failed password and 4624/Accepted
All four problems can coexist on one host: weak password gets in, drops a miner, then a backdoor. Categorization is about choosing the first cut, not about investigating only one thing.
17.3 Priority levels
Level
Typical scenario
Timeframe and resources
P0
Core transactions down, domain controller compromised, large-scale ransomware, confirmed bulk exfiltration of personal data
Immediate response, management and legal involved, notification assessed per regulations
P1
Non-core compromise but credentials exist for lateral movement, WebShell already executes system commands
Contain within hours
P2
Single-machine mining, trojan on a test box, no domain admin credentials
Same day
P3
Phishing with attachment unopened, unsuccessful scan, false positive
Log and handle in batch
Severity is based on business impact and spread capability, not whether the sample "looks dangerous". At P0 you may sacrifice some forensic completeness for isolation, but you must document it in the report.
17.4 Communication and compliance
Internal: business (can we disconnect the network, recent changes, shared accounts), management (severity, scope, expected recovery), IT (DNS, firewall, backup availability). External: regulatory notification conditions, police report, cloud provider ticket, certificate revocation. Collection must record who, when, which tools, and which hashes to support later audits. Anything involving ransom payment or direct contact with the adversary must go through your organization's legal process; the technical team must not make commitments on its own.
See Chapter 21 for tool selection. For process standards, see NIST SP 800-61: https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final
18. Detection and handling of typical security events
Standard order: isolate and preserve, expand detection scope, eradicate, monitor. Do not delete samples before backing them up.
18.1 Web backdoor
18.1.1 Detection
On Windows, sort the IIS site directory by modification time and cross-reference Chapter 6 POST 200. Content characteristics include very long single lines, user input flowing directly into execution functions, and files that differ from the business repository. Note that timestamps may have been altered, so you must cross-check with web log times.
18.1.2 Handling
18.2 Anomalous outbound connections
Windows:Get-NetTCPConnection -State Established Correlate the PID with the process path. Watch for: non-browser processes connecting to foreign endpoints, regular-interval beacons, overlong DNS subdomains, and connections to mining-pool ports. Response: block the IP/domain at both the host and the perimeter; kill the process and clean cron/services; reset local credentials; check for a second tunnel (ICMP, DNS, HTTPS fragmentation).
18.3 Brute-force guessing
Linux: tally the source IPs and usernames from 4625 events, then check whether a matching 4624 appears.Failed and Accepted the time difference.
If it succeeded: assume the password and the full potential lateral-movement scope are compromised. Block the source, lock the account, reset the password, enable MFA, and restrict 22/3389. Check for post-success sudo usage, file changes, and new keys.
18.4 Data exfiltration
Indicators: outbound traffic climbs sharply relative to baseline, large archives appear in temp directories, a database is dumped with full-table exports, or object storage shows abnormal sync. Immediately restrict egress (tighten first, relax later) to stop further transfer. Assess whether the data type involves personal information or trade secrets for compliance purposes. Preserve PCAP, firewall sessions, and database audit logs. Rotate any keys that may have been taken.
18.5 Cryptomining
On Windows, check Task Manager and Autoruns. Signs: CPU pinned near 100% for extended periods, a process name that mimics a system service but runs from an unusual path, or a command line containing "stratum" and a pool domain. Response: disconnect or block the pool, stop the process, remove persistence (including inside Docker), and fix the initial entry point (unauthenticated Redis, Docker API, weak SSH password). Mining often coexists with a backdoor, so re-scan web and accounts per 18.1.
19. Incident Response Standard Process
PICERL is a closed loop: without preparation, detection is blind; without thorough eradication, the incident recurs after recovery; without a lessons-learned step, the same entry point will be used again.
19.1 Six-step walkthrough
Step
English
Work involved
Common failure
Preparation
Preparation
Runbook, contacts, toolkits, logs shipped off-box, backups verified restorable, asset inventory
Discovering at incident time that logs are only 20 MB
Detection & Analysis
Detection and Analysis
Confirm whether it is a real event, its type, the time anchor, and the list of affected hosts
Mistaking a scan for an intrusion, or an intrusion for a scan
Containment
Containment
Stop spread: block IPs, isolate VLANs, disable accounts, stop services
Cutting power too early and losing memory; isolating too late and letting ransomware spread
Eradication
Eradication
Remove backdoors, apply patches, change passwords, clear persistence
Only killing the process
Recovery
Recovery
Bring systems back from a trusted backup or rebuilt image, with gradual rollout and tighter monitoring
Returning to production before eradication is complete
Lessons Learned
Lessons Learned
Report, adjust baselines and detection rules, run drills
Verbal review only, no ticket
The preparation phase corresponds to Chapters 1–16 of this document. During detection, do not run antivirus or cleanup directly on the original disk. Image it first, or at minimum copy the samples and logs.
19.2 Operational limits of containment and eradication
Network containment: add rules on both the perimeter firewall and the host firewall; isolate switch ports; apply cloud security groups. Account containment: disable, reset, revoke Kerberos tickets, and revoke VPN certificates. Host containment: stop malicious services, disable tasks, and mount read-only when necessary.
When ransomware is moving laterally across file servers, isolation takes priority over memory forensics. For a single-server advanced threat where forensics is needed, first block egress, keep the machine powered on, capture memory, and only then decide whether to shut down. The eradication checklist must include: users, groups, Run/IFEO/service/WMI, cron/systemd, authorized_keys, web directories, and drivers and preload libraries.
19.3 Recovery and lessons learned
Recovery order: patches and passwords → restore from a known-clean backup or reinstall → rejoin an isolated network segment and observe IOC → then return to production. The observation window depends on the threat level; for P0, keep strengthened monitoring in place for at least a week. Lessons learned must produce closable remediation items (with owners and deadlines) and update Sigma/Wazuh rules and firewall object groups. NIST SP 800-61: https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final
20. On-Scene Triage Methods
The wrong order once you reach the host destroys evidence. The principle is volatile data first, and a checklist to ensure nothing is missed.
20.1 Collect evidence before remediation
Volatility from highest to lowest: CPU registers and memory → network connections and login sessions → running processes → disk.
Windows memory: WinPmem https://github.com/Velocidex/WinPmem; for FTK Imager, refer to the current Exterro page. Linux: LiME https://github.com/504ensicsLabs/LiME; Linpmem https://github.com/Velocidex/Linpmem. Hash with SHA-256 immediately after collection and record it in the collection sheet. For disk, use dd or FTK with a write blocker.
Avoid during collection: full-disk antivirus cleanup, rebooting, asking the user to "just try reinstalling," or unpacking malicious samples on the original disk. If the business must recover immediately, copy memory and key logs first, or accept incomplete evidence and state that in the report.
Also record:
Windows:
20.2 Timeline and the evidence triangle
An anchor can be: the SOC alert time, file creation time, the first Accepted/4624, or the firewall's first block. Align Security, Sysmon, IIS, secure, firewall, and DNS logs to UTC. IIS W3C typically uses UTC; Windows events may be local time; Linux syslog depends on NTP. A large NTP offset skews the timeline, so record each source's timezone.
File MAC times can be altered (timestomping), so external logs must be authoritative. Evidence triangle: host (disk, memory, config), network (PCAP, NetFlow, DNS), and identity (AD, bastion host, email). Only draw conclusions when the three points converge.
20.3 Windows checks
20.4 Linux checks
/proc/PID/exe showing (deleted) means the process is still running in memory while the on-disk file is deleted; the sample must be copied from memory or /proc/PID/exe.
21. Common Incident Response Tools
Tools serve PICERL: collect first, then analyze. The addresses below are subject to the maintainers' current pages; verify hashes or signatures after installation.
21.1 Sysinternals
Suite: https://learn.microsoft.com/sysinternals/downloads/sysinternals-suite
File server: https://live.sysinternals.com/Files/
Tool
Purpose
Key operations
Process Explorer
Process tree, signatures, threads, handles, TCP
For unsigned processes or those with unusual paths, inspect Strings and loaded modules
Autoruns
Startup summary
Hide Microsoft Entries, review unsigned items
TCPView / TCPVCon
Connections
Cross-check with netstat
Process Monitor
File/registry/process
Filter by PID; narrow the time window if the exported PML is too large
Sigcheck
Signature and hash
Run recursively against suspicious directories
Sysmon
Continuous telemetry
See chapter four
Linux Procmon preview: https://github.com/microsoft/Procmon-for-Linux
21.2 OSSEC and Wazuh
Host intrusion detection: file integrity, log alerting, rootkit detection, active response. Wazuh adds indexing and a dashboard on top of OSSEC. Once the agent ships its data out, deleting local logs does not affect the server-side copy.
OSSEC: https://github.com/ossec/ossec-hids
Wazuh: https://github.com/wazuh/wazuh
Docs: https://documentation.wazuh.com/
What to check during incident response: FIM alerts (passwd, pam, systemd, web directories), unusual processes, and login failure storms.
21.3 Memory analysis frameworks
Volatility 3: https://github.com/volatilityfoundation/volatility3
Docs: https://volatility3.readthedocs.io/
Volatility 2 is no longer maintained. Plugin names change between versions; the analysis workflow is covered in chapter twenty-three.
21.4 Integrity checking and rootkit detection
AIDE: https://github.com/aide/aide — initialize the database while the system is clean and store the database file offline.
chkrootkit: https://github.com/chkrootkit-org/chkrootkit
rkhunter can be installed from the distribution's repositories.
Kernel hooks will make ps, ls, and ss return incomplete output. Trusted methods: boot a rescue disc, mount the disk, and scan offline, or compare a known-clean /proc against externally collected memory. For Windows tools such as GMER, use the vendor's site as the source of truth.
21.5 Log analysis tools
Windows: wevtutil, Get-WinEvent, Log Parser 2.2 (https://www.microsoft.com/en-us/download/details.aspx?id=24659). Linux: grep, awk, jq, journalctl. At scale: the Elastic stack, Splunk, Wazuh. Detection rules: https://github.com/SigmaHQ/sigma . Hunting examples: https://github.com/Azure/Azure-Sentinel
EVTX practice: https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES
Chapter 22. Network traffic analysis
Host logs can be deleted or forged. Link-layer records captured from a mirrored span are much harder for the endpoint to tamper with. Encrypted traffic can still be analyzed through length, timing, certificates, SNI, and peer reputation.
22.1 Collection points
Location
Visibility
Limitations
Local Wireshark/tcpdump
All traffic in and out of this host, tied to processes
Can be stopped after privilege escalation; own performance impact
Egress firewall/proxy
North-south, exfiltration, and C2
Does not see east-west lateral movement
Core switch SPAN or TAP
East-west
Whether the mirror is sampled or drops packets
Enterprises should have both egress detection and core detection. Endpoint capture is for deep-dive investigation of a single host. tcpdump example:
Avoid capturing your own SSH forensics session in the packets, or use out-of-band access. Wireshark: https://www.wireshark.org/download.html source: https://github.com/wireshark/wireshark
22.2 Filter syntax
Capture filters (BPF) discard packets before capture, reducing loss: host 10.0.0.8, net 10.0.0.0/8, tcp port 445. Display filters filter after opening the file:
Statistics → Conversations to sort by bytes. Statistics → Protocol Hierarchy to see unusual protocol shares. Follow → TCP Stream to reconstruct plaintext sessions. Export objects: File → Export Objects → HTTP.
22.3 Suspicious DNS and anomalous traffic patterns
DNS tunneling: unusually long, high-entropy subdomain labels, high QPS, a large share of TXT types, responses far larger than normal A records, and highly periodic query intervals. C2 heartbeat: stable intervals, near-identical message lengths, long-lived sessions, and a peer ASN unrelated to the business. Scanning: SYN to many ports in a short window, large volumes of RST. Exfiltration: large transfers to a single external IP outside working hours, uniform TLS record sizes.
When cmd.exe, powershell, and /bin/bash interaction characteristics show up in plaintext, combine with Follow Stream. For encrypted traffic, fall back on metadata and threat intelligence rather than trying to "decrypt HTTPS".
22.4 Triage steps and practice material
Material
Description
Address
Wireshark Sample Captures
Protocol examples
Unit 42 Wireshark tutorials
Tutorial pcaps; archive password is in the repo (mostly 'infected')
https://github.com/PaloAltoNetworks/Unit42-Wireshark-tutorials
Malware-Traffic-Analysis.net
Practice exercises
NETRESEC pcap index
Multi-source list
Unpack archives containing malicious traffic only inside an isolated VM. Do not run exported EXEs on office endpoints.
Chapter 23. Memory forensics
Fileless execution, process injection, and cached credentials may leave no complete PE on disk. A memory image preserves kernel objects, process pages, and network structures at the moment of collection.
23.1 Collection principles
Memory before disk, and never reboot before collection. Notify the business of possible brief load. Match the tool to the kernel version and prefer signed collectors. Do not write the target image to the same volume you are collecting from. Hash the result when done and record: hostname, collector, start and end times, tool version, and image size.
Windows: DumpIt (use Magnet Forensics' current release as the source of truth), FTK Imager, WinPmem. Linux: LiME requires compiling a module against the kernel; Linpmem is a standalone tool. For VMs, take a memory snapshot from the hypervisor, noting whether it includes suspend consistency.
23.2 Processes, network, and injection
Analyze on a dedicated host using Volatility 3. First confirm the image is recognized (Windows uses windows.info; Linux needs symbols). Then:
Command forms change between versions; follow the official docs: https://volatility3.readthedocs.io/ repository: https://github.com/volatilityfoundation/volatility3
23.3 Closing the loop with disk
When paths in memory point to C:\Users\Public\ or /tmp/, return to the disk for file forensics and timeline work. If an exported PE matches the on-disk file's hash, that proves it was dropped; present only in memory and absent on disk points to fileless execution or a deleted-but-running binary (compare with /proc/PID/exe (deleted)). Public practice images carry different licenses; read the notes before use, and do not install analysis frameworks on production.
Chapter 24. Writing the incident response report
The report is the formal record of the incident and must satisfy management decision-making, technical reproduction, and compliance auditing at the same time. Inferences without evidence must not be written as conclusions.
24.1 Structure and audience
Section
Audience
Content requirements
Overview
Management
Time, system, severity, current status, a one-line summary, and whether it is still spreading
Response process
Management & audit
How it was discovered, the notification chain, and the timing of each PICERL step
Technical analysis
Security & operations
Entry point, vulnerability or configuration flaw, hashes, commands, persistence, external connections, detection rule IDs
Impact
Management & legal
Downtime duration, data objects, whether personal information is involved, whether it falls within regulatory scope
Root cause
All
Direct, indirect, and underlying — avoid writing only "hacker attack"
Remediation
All
Urgent/medium-term/long-term, verifiable, with an assigned owner
Attachments
Technical & forensic
Log excerpts, hash tables, collection chain, timeline
In the overview, avoid piling up event IDs. In the technical analysis, avoid large blocks of raw logs with no conclusion; put raw material in the attachments.
24.2 Timeline
Time (with timezone)
Type
Source
Target
Action
Evidence ID
2026-09-02 09:15:22 +08
Scan
198.51.100.10
Host A:445
SYN
FW-001
2026-09-02 09:18:37 +08
Authentication failure
198.51.100.10
A\Administrator
Multiple 4625
EVT-4625-01
2026-09-02 09:19:01 +08
Login success
198.51.100.10
A\Administrator
Type 10
EVT-4624-01
2026-09-02 09:19:10 +08
Upload
198.51.100.10
IIS
New script added
IIS-001, FILE-001
2026-09-02 09:20:00 +08
External connection
Host A
203.0.113.50:443
Callback
PCAP-001
Evidence IDs map to attachments. Mark unconfirmed steps as "pending confirmation." Always state the timezone.
24.3 Impact, root cause, and remediation
Quantify impact where possible: minutes, number of hosts, number of records in database tables or files, and whether the incident triggers notification under the Cybersecurity Law, Data Security Law, or Personal Information Protection Law (legal will decide; technical teams provide the facts).
Three layers of root cause:
Sample remediation items (replace with your organization's ticket numbers):
Vague statements (such as "raise security awareness") cannot be the only remediation item unless accompanied by specific training audience, dates, and assessment.
25. Checklists and reference resources
25.1 Windows hardening checklist
25.2 Linux hardening checklist
25.3 Fifteen-minute on-scene actions
25.4 Tool and case summary
Name
Type
URL
Sysinternals Suite
Official toolkit
Sysmon
Host telemetry
sysmon-config
Configuration example
https://github.com/SwiftOnSecurity/sysmon-config
sysmon-modular
Modular configuration
https://github.com/olafhartong/sysmon-modular
Security Compliance Toolkit
Windows baseline
Log Parser 2.2
Log queries
EVTX-ATTACK-SAMPLES
Event samples for detection
https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES
Sigma
Detection rules
https://github.com/SigmaHQ/sigma
Azure-Sentinel
Hunting queries
https://github.com/Azure/Azure-Sentinel
Lynis
Linux auditing
https://github.com/CISOfy/lynis
linux-baseline
Linux baseline
https://github.com/dev-sec/linux-baseline
fail2ban
Bans failed logins
https://github.com/fail2ban/fail2ban
Wazuh
HIDS / SIEM
https://github.com/wazuh/wazuh
AIDE
File integrity
https://github.com/aide/aide
chkrootkit
Rootkit detection
https://github.com/chkrootkit-org/chkrootkit
Vuls
Vulnerability scanning
https://github.com/future-architect/vuls
Wireshark
Traffic analysis
SampleCaptures
Sample packet captures
Unit42-Wireshark-tutorials
Tutorial pcaps
https://github.com/PaloAltoNetworks/Unit42-Wireshark-tutorials
Volatility 3
Memory analysis
https://github.com/volatilityfoundation/volatility3
WinPmem
Windows memory acquisition
https://github.com/Velocidex/WinPmem
LiME
Linux memory acquisition
https://github.com/504ensicsLabs/LiME
CISA KEV
Known exploited vulnerabilities catalog
https://www.cisa.gov/known-exploited-vulnerabilities-catalog
NIST SP 800-61
Incident handling guide
Windows LAPS
Local administrator passwords
WDAC
Application control
Clone the GitHub repository:
Prefer the checksums from Releases. Archives containing malicious traffic or code may only be used in an isolated lab environment.
25.5 Quick reference: critical events and log paths
System
Path or channel
Key fields
Windows Security
`winevt\Logs\Security.evtx`
4624/4625/4672/4720/4732/4688/1102
Windows System
System.evtx
7045
PowerShell
PowerShell/Operational
4103/4104
Sysmon
Microsoft-Windows-Sysmon/Operational
1/3/7/10/11/12/13
IIS
`C:\inetpub\logs\LogFiles\W3SVC*`
POST, status codes, c-ip
Linux auth
`/var/log/secure` or `auth.log`
Failed/Accepted/sudo
Linux journal
`journalctl -u sshd`
Same as above
Firewall
pfirewall.log or firewalld/nft logs
Blocked vs. allowed
25.6 Glossary
Term
Meaning
ACL
Access control list
AMSI
Antimalware Scan Interface
AVC
SELinux access vector cache denial records
C2
Command and control channel
CIA
Confidentiality, integrity, availability
CLM
PowerShell Constrained Language Mode
DAC / MAC
Discretionary access control / Mandatory access control
FIM
File integrity monitoring
IOC
Indicator of compromise
KEV
Known Exploited Vulnerabilities catalog
LAPS
Local Administrator Password Solution
LSASS
Local Security Authority Subsystem
NLA
Network Location Awareness
PAM
Pluggable Authentication Modules
PAW
Privileged Access Workstation
PICERL
six-step incident response model
PPL
Protected Process Light
PTH
Pass the Hash
SAM
Security Account Manager
SIEM
Security Information and Event Management
SSDT
System Service Descriptor Table
VSS
Volume Shadow Copy
WDAC
Windows Defender Application Control
WEF
Windows Event Forwarding
WFP
Windows Filtering Platform
25.7 Windows Lab: Verifying Host Hardening
Perform the following steps on an isolated virtual machine as a local administrator. Record the output of each command as baseline evidence.
25.7.1 Accounts and UAC
Confirm that Guest is disabled, that everyday test accounts are not in Administrators,net accounts and that the minimum password length is set in UserAccountControlSettings.exe matches policy. Open
25.7.2 Audit Policy and Log Size
Confirm that logon success and failure, account management, and process creation are enabled. Set the Security log maximum size to at least 1 GB (adjust to your lab disk size), then deliberately attempt one logon with a wrong password and run:
You should see a failure record. Then log on with the correct account and check the Logon Type of 4624.
25.7.3 PowerShell Logging
After enabling Script Block Logging, run:
the message should contain hardening-test. Then run $ExecutionContext.SessionState.LanguageMode and record the current language mode as well.
25.7.4 Firewall
Confirm all three profiles are Enabled. Delete the lab rules once the experiment is finished.
25.7.5 Startup Items and Services
Download Autoruns: https://learn.microsoft.com/sysinternals/downloads/autoruns
Check Hide Microsoft Entries and Verify Code Signatures, then export a CSV as a clean baseline. Next, inspect services whose paths are unquoted and contain spaces:
25.7.6 Sysmon (optional)
The configuration is available at https://github.com/SwiftOnSecurity/sysmon-config and can be trimmed. After starting Notepad, check whether Sysmon event ID 1 shows notepad.exe. When the experiment is over, you can uninstall it with sysmon64 -u uninstall it.
25.7.7 Offline Analysis of Event Samples
Copy the .evtx from directories such as Persistence to the analysis machine; do not import them into production.
Practice filtering against the event IDs in the repository documentation. Sigma: https://github.com/SigmaHQ/sigma
25.8 Linux Lab: Verifying Host Hardening
Use a regular user with sudo and keep a separate root console so the SSH experiment cannot lock you out.
25.8.1 Accounts and Permissions
Confirm that UID 0 belongs to root only; sudo has no ALL and no vim/python;/tmp is drwxrwxrwt (1777). For abnormal SUID binaries, record their paths first and understand their purpose before deciding whether to remove them.
25.8.2 SSH
A valid configuration should disable root login and disable password authentication (if you have already switched to keys). Test from another terminal: key succeeds, password fails. Then check journalctl -u sshd -n 20 or /var/log/secure.
25.8.3 Firewall
If using nftables: sudo nft list ruleset. Add a permanent rich rule that allows SSH from limited sources,--reload then test from both an allowed and a disallowed network segment, and remove the lab rule when done.
25.8.4 Logs and Lynis
Lynis: https://github.com/CISOfy/lynis
Do not implement all Suggestions at once. Pick items corresponding to Chapters 10 through 16, change and verify them one by one.
25.8.5 SELinux
It should be Enforcing. When business is blocked, grant only the minimal context set; never set SELINUX=disabled.
25.9 Traffic Analysis Lab
25.10 Memory Analysis Lab (optional)
Perform this only on a dedicated analysis virtual machine.
Use a practice image with clear licensing. First run windows.info or the corresponding Linux plugin to confirm it is readable, then list processes. Do not collect memory from production hosts without approval. Documentation: https://volatility3.readthedocs.io/
25.11 Incident Response Tabletop Exercise
Without touching real production systems, complete a closed loop on paper or in a virtual machine:
Write the results as a one-page report following the Chapter 24 structure, and archive it as your organization's template.