第9天重点回顾
✅ 执行策略(Execution Policy) :AllSigned 要求所有脚本必须由受信任发布者签名
✅ 代码签名 :使用 Set-AuthenticodeSignature + 有效证书
✅ SecretManagement 模块 :统一管理凭据/密钥(支持 Azure Key Vault、Windows DPAPI 等)
✅ Script Block Logging :通过组策略或注册表启用,记录所有 PowerShell 脚本内容到 Windows 事件日志
习题1:创建自签名证书并签署脚本,在 AllSigned 策略下运行
步骤 1:以管理员身份打开 PowerShell(需写入本地计算机证书存储)
cs
# 创建自签名证书(仅用于测试!有效期1年)
$cert = New-SelfSignedCertificate `
-Subject "CN=PowerShell Test Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Type CodeSigningCert `
-CertStoreLocation "Cert:\CurrentUser\My" `
-NotAfter (Get-Date).AddYears(1)
Write-Host "✅ 证书已创建,Thumbprint: $($cert.Thumbprint)" -ForegroundColor Green
💡 说明:
- 使用
CurrentUser\My避免需要管理员权限(若用LocalMachine则需提权)-Type CodeSigningCert是关键,否则无法用于签名
步骤 2:创建一个测试脚本 hello.ps1
cs
'Write-Host "Hello from signed script!" -ForegroundColor Cyan' | Out-File .\hello.ps1 -Encoding UTF8
步骤 3:用证书签署脚本
cs
Set-AuthenticodeSignature -FilePath .\hello.ps1 -Certificate $cert
✅ 成功输出示例:
cs
Directory: C:\test
SignerCertificate Status Path
----------------- ------ ----
[Subject] Valid hello.ps1
CN=PowerShell Test Signing
...
步骤 4:设置执行策略为 AllSigned 并运行
cs
# 设置当前用户策略为 AllSigned
Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope CurrentUser -Force
# 首次运行会弹出安全警告 → 选择"运行一次"或"始终运行"
.\hello.ps1
⚠️ 关键提示:
- 首次运行时,PowerShell 会弹出 "发布者不受信任" 对话框
- 点击 "更多选项" → "始终运行" ,系统会将该证书添加到 "受信任的发布者" 存储(
Cert:\CurrentUser\TrustedPublisher)- 之后即可无提示运行
🔍 验证证书是否被信任
cs
# 查看受信任的发布者
Get-ChildItem Cert:\CurrentUser\TrustedPublisher
# 查看脚本签名状态
Get-AuthenticodeSignature .\hello.ps1
✅ 若
Status为Valid且StatusMessage为 "签名有效",则成功。
✅ 习题2:使用 SecretManagement 存储数据库连接字符串
目标:安全存储敏感字符串(如
"Server=db;Database=prod;User=sa;Password=Secret123!"),避免明文写入脚本。
步骤 1:安装必要模块(首次使用)
cs
Install-Module Microsoft.PowerShell.SecretManagement -Force -AllowClobber
Install-Module Microsoft.PowerShell.SecretStore -Force # 本地存储后端
💡
SecretStore是微软官方提供的本地加密存储(基于 DPAPI)
步骤 2:注册 SecretStore 保险库(Vault)
cs
Register-SecretVault -Name LocalSecretStore -ModuleName Microsoft.PowerShell.SecretStore
首次注册会提示设置 密码(用于解锁本地保险库)
步骤 3:将连接字符串存为 SecureString 并保存
cs
# 构造连接字符串(实际中可能来自用户输入或配置)
$plainText = "Server=db.example.com;Database=SalesDB;User=admin;Password=P@ssw0rd!"
# 转为 SecureString
$secureString = ConvertTo-SecureString $plainText -AsPlainText -Force
# 存入保险库(SecretManagement 自动处理 SecureString)
Set-Secret -Name "DB_ConnectionString" -Secret $secureString -Vault LocalSecretStore
✅ 输出:无错误即成功
步骤 4:在脚本中安全读取
cs
# 从保险库获取(返回 SecureString)
$secureConn = Get-Secret -Name "DB_ConnectionString" -Vault LocalSecretStore
# 转回明文(仅在需要时,如传给 SqlConnection)
$marshal = [System.Runtime.InteropServices.Marshal]
$ptr = $marshal::SecureStringToBSTR($secureConn)
$connectionString = $marshal::PtrToStringBSTR($ptr)
$marshal::FreeBSTR($ptr)
Write-Host "连接字符串已加载(长度: $($connectionString.Length) 字符)" -ForegroundColor Green
# 实际使用:[System.Data.SqlClient.SqlConnection]::new($connectionString)
🔒 安全优势:
- 脚本中不出现明文密码
SecureString在内存中加密- 保险库受操作系统保护(DPAPI)
✅ 习题3:启用 Script Block Logging 并验证日志
目标:记录所有执行的 PowerShell 脚本内容到 Windows 事件日志(用于审计/取证)
步骤 1:启用 Script Block Logging(通过注册表)
cs
# 创建注册表项(需管理员权限)
$regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"
if (-not (Test-Path $regPath)) {
New-Item $regPath -Force | Out-Null
}
Set-ItemProperty -Path $regPath -Name "EnableScriptBlockLogging" -Value 1
Set-ItemProperty -Path $regPath -Name "EnableScriptBlockInvocationLogging" -Value 1 # 可选:记录调用上下文
Write-Host "✅ Script Block Logging 已启用。请重启 PowerShell 生效。" -ForegroundColor Yellow
cs计算机配置 → 管理模板 → Windows 组件 → PowerShell → ✔ 启用 PowerShell Script Block 日志记录
步骤 2:重启 PowerShell,运行测试脚本
cs
# 任意脚本(会被完整记录)
Get-Process | Where-Object CPU -gt 100
步骤 3:在事件查看器中查找日志
-
打开 事件查看器 (
eventvwr.msc) -
导航至:
cs应用程序和服务日志 → Microsoft → Windows → PowerShell → Operational -
查找 事件 ID 4104(Script Block Logging 的标准 ID)
✅ 日志内容包含:
- 完整的脚本文本(
<ScriptBlockText>)- 执行用户
- 进程 ID
- 是否被混淆(Obfuscated)
或通过 PowerShell 查询:
cs
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" |
Where-Object Id -eq 4104 |
Select-Object TimeCreated, Message |
Format-List
🔍 示例输出片段:
csMessage : Creating Scriptblock text (1 of 1): Get-Process | Where-Object CPU -gt 100 ...
🧠 第9天安全能力总结
| 技术 | 用途 | 企业价值 |
|---|---|---|
| 代码签名 + AllSigned | 防止未授权脚本执行 | 满足合规要求(如 PCI DSS、ISO 27001) |
| SecretManagement | 安全存储密钥/密码 | 消除脚本硬编码凭据风险 |
| Script Block Logging | 审计所有 PowerShell 活动 | 满足 SOC2、GDPR 日志留存要求 |
⚠️ 重要安全提醒
- 自签名证书 ≠ 生产方案:企业应使用 PKI(如 AD CS)颁发代码签名证书
- SecretStore 仅限本地开发 :生产环境应使用 Azure Key Vault 或 HashiCorp Vault
- Script Block Logging 需配合 SIEM:单独日志难分析,建议接入 Splunk/ELK
🚀 延伸挑战
- 将 SecretManagement 与 Azure Key Vault 集成
- 编写 GPO 脚本批量部署
AllSigned策略 - 使用
Get-WinEvent+ 正则自动检测可疑脚本(如IEX)