[powershell 入门]第9天:PowerShell 安全、代码签名与企业部署 作业及深度解析

第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

✅ 若 StatusValidStatusMessage 为 "签名有效",则成功。


✅ 习题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:在事件查看器中查找日志
  1. 打开 事件查看器eventvwr.msc

  2. 导航至:

    复制代码
    cs 复制代码
    应用程序和服务日志 → Microsoft → Windows → PowerShell → Operational
  3. 查找 事件 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

🔍 示例输出片段:

复制代码
cs 复制代码
Message : 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 日志留存要求

⚠️ 重要安全提醒

  1. 自签名证书 ≠ 生产方案:企业应使用 PKI(如 AD CS)颁发代码签名证书
  2. SecretStore 仅限本地开发 :生产环境应使用 Azure Key VaultHashiCorp Vault
  3. Script Block Logging 需配合 SIEM:单独日志难分析,建议接入 Splunk/ELK

🚀 延伸挑战

  • 将 SecretManagement 与 Azure Key Vault 集成
  • 编写 GPO 脚本批量部署 AllSigned 策略
  • 使用 Get-WinEvent + 正则自动检测可疑脚本(如 IEX
相关推荐
小Ti客栈1 天前
安全之加密算法
安全
wadesir1 天前
掌握Rust并发数据结构(从零开始构建线程安全的多线程应用)
数据结构·安全·rust
携欢1 天前
POrtSwigger靶场之Exploiting XXE using external entities to retrieve files通关秘籍
网络·安全·github
菩提小狗1 天前
小迪安全笔记_第4天|扩展&整理|30+种加密编码进制全解析:特点、用处与实战识别指南|小迪安全笔记|网络安全|
笔记·安全·web安全
Irene19911 天前
Bash、PowerShell 常见操作总结
bash·powershell
94620164zwb51 天前
数据备份模块 Cordova 与 OpenHarmony 混合开发实战
安全
秋4271 天前
防火墙基本介绍与使用
linux·网络协议·安全·网络安全·架构·系统安全
sweet丶1 天前
扩展了解DNS放大攻击:原理、影响与防御
网络协议·安全
acrelgxy1 天前
看不见≠不存在,更不等于安全!故障电弧探测器,让隐形危险现出原形。
安全·电力监控系统·智能电力仪表
老赵聊算法、大模型备案1 天前
新规解读:2025 年修正版《中华人民共和国网络安全法》核心变化解读
安全·web安全