[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
相关推荐
微盛企微增长小知识38 分钟前
2025企业微信私有化部署服务商:微盛AI·企微管家的安全与效率实践
人工智能·安全·企业微信
wanhengidc1 小时前
云手机 云计算中的安全机制
安全·智能手机·云计算
cike_y2 小时前
Servlet原理&Mapping问题&ServletContext对象
java·安全·javaweb
汽车仪器仪表相关领域11 小时前
LambdaCAN:重构专业空燃比测量的数字化范式
大数据·人工智能·功能测试·安全·重构·汽车·压力测试
白帽黑客-晨哥11 小时前
OWASP Top 10 2024 深度解析:Web安全新威胁与防御策略
安全·web安全·网络安全·漏洞挖掘·副业
独行soc11 小时前
2025年渗透测试面试题总结-275(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
是一个Bug13 小时前
ConcurrentHashMap的安全机制详解
java·jvm·安全
测试人社区-千羽14 小时前
边缘计算场景下的智能测试挑战
人工智能·python·安全·开源·智能合约·边缘计算·分布式账本
网安小白的进阶之路15 小时前
B模块 安全通信网络 第二门课 核心网路由技术-1-OSPF之特殊区域
网络·安全