PowerShell 技能连载 - Azure AD安全审计自动化

在云身份管理日益重要的今天,定期安全审计成为保障企业数字资产的关键。本文演示如何通过PowerShell自动执行Azure AD安全配置检测,实现实时安全态势监控。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function Invoke-AzureADSecurityAudit {
param(
[string]$TenantId,
[switch]$ExportReport
)

try {
# 连接Azure AD
Connect-AzureAD -TenantId $TenantId | Out-Null

# 安全基线检测
$results = @(
[PSCustomObject]@{
CheckItem = '多重认证状态'
Result = (Get-AzureADMSAuthorizationPolicy).DefaultUserRolePermissions.AllowedToCreateApps
},
[PSCustomObject]@{
CheckItem = '旧协议支持状态'
Result = (Get-AzureADDirectorySetting | Where-Object {$_.DisplayName -eq 'OrganizationProperties'}).Values
}
)

# 生成报告
if ($ExportReport) {
$results | Export-Csv -Path "./SecurityAudit_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
}

return $results
}
catch {
Write-Error "审计失败:$_"
}
finally {
Disconnect-AzureAD
}
}

实现原理分析:

  1. 通过AzureAD模块实现与云身份服务的认证连接
  2. 检测关键安全配置项包括MFA实施状态和旧版协议支持情况
  3. 支持CSV报告导出功能便于存档分析
  4. 自动清理会话确保操作安全性
  5. 结构化返回结果便于后续处理

该脚本将原本需要人工操作的审计流程自动化,特别适合需要持续合规监控的金融和医疗行业应用场景。

PowerShell 技能连载 - 供应链安全漏洞扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function Invoke-SupplyChainScan {
param(
[Parameter(Mandatory=$true)]
[string]$ImageName,
[string]$OutputFormat = 'table',
[string]$SeverityLevel = 'HIGH,CRITICAL'
)

# 安装Trivy漏洞扫描器
if (-not (Get-Command trivy -ErrorAction SilentlyContinue)) {
winget install aquasecurity.trivy
}

try {
# 执行容器镜像扫描
$result = trivy image --format $OutputFormat --severity $SeverityLevel $ImageName

# 生成HTML报告
$htmlReport = "$env:TEMP\scan_report_$(Get-Date -Format yyyyMMddHHmmss).html"
trivy image --format template --template "@contrib/html.tpl" -o $htmlReport $ImageName

[PSCustomObject]@{
ScanTarget = $ImageName
VulnerabilitiesFound = $result.Count
CriticalCount = ($result | Where-Object { $_ -match 'CRITICAL' }).Count
HighCount = ($result | Where-Object { $_ -match 'HIGH' }).Count
HTMLReportPath = $htmlReport
}
}
catch {
Write-Error "漏洞扫描失败:$_"
}
}

核心功能:

  1. 集成Trivy进行容器镜像漏洞扫描
  2. 支持多种输出格式(table/json/html)
  3. 自动生成带严重等级分类的报告
  4. 包含依赖组件版本检查

应用场景:

  • CI/CD流水线安全门禁
  • 第三方组件入仓检查
  • 生产环境镜像定期审计

PowerShell 技能连载 - 零信任架构下的设备健康检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function Invoke-DeviceHealthCheck {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$DeviceName
)

$healthReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Device = $DeviceName
TPMEnabled = $false
SecureBoot = $false
AntivirusStatus = 'Unknown'
ComplianceScore = 0
}

try {
# 检查TPM状态
$tpm = Get-Tpm -ErrorAction Stop
$healthReport.TPMEnabled = $tpm.TpmPresent

# 验证安全启动状态
$healthReport.SecureBoot = Confirm-SecureBootUEFI

# 获取反病毒状态
$avStatus = Get-MpComputerStatus
$healthReport.AntivirusStatus = $avStatus.AMServiceEnabled ? 'Active' : 'Inactive'

# 计算合规分数
$compliance = 0
if($healthReport.TPMEnabled) { $compliance += 30 }
if($healthReport.SecureBoot) { $compliance += 30 }
if($healthReport.AntivirusStatus -eq 'Active') { $compliance += 40 }
$healthReport.ComplianceScore = $compliance
}
catch {
Write-Warning "设备健康检查失败: $_"
}

$healthReport | Export-Clixml -Path "$env:TEMP/DeviceHealth_$DeviceName.xml"
return $healthReport
}

核心功能

  1. TPM芯片状态验证
  2. 安全启动模式检测
  3. 反病毒服务状态监控
  4. 自动化合规评分

应用场景

  • 零信任架构准入控制
  • 远程办公设备安全审计
  • 合规性基线验证
  • 安全事件响应前置检查

PowerShell 技能连载 - 基于Azure Functions的无服务器安全检测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function Invoke-SecurityScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,

[ValidateSet('Critical','High','Medium')]
[string]$SeverityLevel = 'High'
)

$securityReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ScannedResources = @()
SecurityFindings = @()
}

# 获取Azure安全中心警报
$alerts = Get-AzSecurityAlert -ResourceGroupName $ResourceGroup |
Where-Object { $_.Severity -eq $SeverityLevel }

# 自动化响应流程
$alerts | ForEach-Object {
$securityReport.ScannedResources += [PSCustomObject]@{
ResourceID = $_.ResourceId
AlertType = $_.AlertType
CompromiseEntity = $_.CompromisedEntity
}

# 触发自动化修复动作
if($_.AlertType -eq 'UnusualResourceDeployment') {
Start-AzResourceDelete -ResourceId $_.ResourceId -Force
$securityReport.SecurityFindings += [PSCustomObject]@{
Action = 'DeletedSuspiciousResource'
ResourceID = $_.ResourceId
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
}
}
}

# 生成安全态势报告
$securityReport | ConvertTo-Json -Depth 3 |
Out-File -FilePath "$env:TEMP/AzureSecReport_$(Get-Date -Format yyyyMMdd).json"
return $securityReport
}

核心功能

  1. 实时获取Azure安全中心高等级警报
  2. 异常资源部署自动隔离机制
  3. JSON格式安全态势报告生成
  4. 多严重级别安全事件过滤

典型应用场景

  • 云环境异常操作实时响应
  • 自动化安全基线维护
  • 多云订阅安全状态聚合
  • 合规审计日志自动生成

PowerShell 技能连载 - 供应链安全漏洞扫描工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Invoke-SupplyChainScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$ScanPath,

[ValidateSet('Critical','High','Medium','Low')]
[string]$SeverityLevel = 'Critical'
)

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
ScannedComponents = @()
SecurityFindings = @()
}

# 组件哈希校验
Get-ChildItem $ScanPath -Recurse -Include *.dll,*.exe,*.psm1 | ForEach-Object {
$fileHash = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
$signature = Get-AuthenticodeSignature $_.FullName

$component = [PSCustomObject]@{
FileName = $_.Name
FilePath = $_.FullName
SHA256 = $fileHash
IsSigned = $signature.Status -eq 'Valid'
Publisher = $signature.SignerCertificate.Subject
}
$report.ScannedComponents += $component

if (-not $component.IsSigned) {
$report.SecurityFindings += [PSCustomObject]@{
Severity = 'High'
Description = "未签名的组件: $($_.Name)"
Recommendation = "要求供应商提供数字签名版本或验证组件来源"
}
}
}

# 依赖包漏洞扫描
$nugetPackages = Get-ChildItem $ScanPath -Recurse -Include packages.config
$nugetPackages | ForEach-Object {
[xml]$config = Get-Content $_.FullName
$config.packages.package | ForEach-Object {
$cveData = Invoke-RestMethod "https://api.cvecheck.org/v1/search?id=$($_.id)"
if ($cveData.vulnerabilities | Where-Object { $_.severity -ge $SeverityLevel }) {
$report.SecurityFindings += [PSCustomObject]@{
Severity = $SeverityLevel
Description = "存在漏洞的依赖包: $($_.id) v$($_.version)"
Recommendation = "升级到最新安全版本 $($cveData.latestVersion)"
}
}
}
}

$report | Export-Csv -Path "$ScanPath\SupplyChainReport_$(Get-Date -Format yyyyMMdd).csv" -NoTypeInformation
return $report
}

核心功能

  1. 软件组件供应链安全扫描
  2. 依赖包漏洞自动化检测
  3. 数字签名验证机制
  4. CVE漏洞数据库集成

典型应用场景

  • 开发环境第三方组件安全检查
  • 软件构建流水线安全审计
  • 供应商交付物合规验证
  • 企业软件资产安全基线报告生成

PowerShell 技能连载 - 零信任架构下的设备健康检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function Invoke-DeviceHealthCheck {
param(
[string[]]$ComputerNames = $env:COMPUTERNAME
)

$securityBaseline = @{
SecureBootEnabled = $true
TPMPresent = $true
BitLockerStatus = 'FullyEncrypted'
AntivirusStatus = 'Enabled'
FirewallProfile = 'Domain'
}

$results = @()

foreach ($computer in $ComputerNames) {
try {
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer
$tpm = Get-CimInstance -ClassName Win32_Tpm -ComputerName $computer -ErrorAction Stop
$bitlocker = Get-BitLockerVolume -MountPoint $osInfo.SystemDrive -ErrorAction Stop

$healthStatus = [PSCustomObject]@{
ComputerName = $computer
LastBootTime = $osInfo.LastBootUpTime
SecureBoot = [bool](Confirm-SecureBootUEFI)
TPMVersion = $tpm.SpecVersion
BitLockerProtection = $bitlocker.ProtectionStatus
DefenderStatus = (Get-MpComputerStatus).AntivirusEnabled
FirewallStatus = (Get-NetFirewallProfile -Name Domain).Enabled
ComplianceScore = 0
}

# 计算合规分数
$healthStatus.ComplianceScore = [math]::Round((
($healthStatus.SecureBoot -eq $securityBaseline.SecureBootEnabled) +
($healthStatus.TPMVersion -match '2.0') +
($healthStatus.BitLockerProtection -eq 'On') +
($healthStatus.DefenderStatus -eq $true) +
($healthStatus.FirewallStatus -eq $true)
) / 5 * 100, 2)

$results += $healthStatus
}
catch {
Write-Warning "$computer 健康检查失败: $_"
}
}

$results | Format-Table -AutoSize
}

核心功能:

  1. 自动化验证设备安全基线配置
  2. 检测TPM 2.0和SecureBoot状态
  3. 评估BitLocker加密状态
  4. 生成设备合规性评分

应用场景:

  • 零信任网络接入前检查
  • 远程办公设备安全审计
  • 合规性自动化报告生成

PowerShell JEA安全架构解析

JEA端点配置

1
2
3
4
5
6
7
8
# 创建会话配置文件
$sessionParams = @{
Path = '.JEAConfig.pssc'
SessionType = 'RestrictedRemoteServer'
RunAsVirtualAccount = $true
RoleDefinitions = @{ 'CONTOSO\SQLUsers' = @{ RoleCapabilities = 'SqlReadOnly' } }
}
New-PSSessionConfigurationFile @sessionParams

角色能力定义

1
2
3
4
5
6
7
8
9
# 创建角色能力文件
$roleCapability = @{
Path = 'Roles\SqlReadOnly.psrc'
VisibleCmdlets = 'Get-Sql*'
VisibleFunctions = 'ConvertTo-Query'
VisibleProviders = 'FileSystem'
ScriptsToProcess = 'Initialize-SqlEnv.ps1'
}
New-PSRoleCapabilityFile @roleCapability

会话沙箱验证

1
2
3
4
5
6
# 连接JEA端点并验证权限
$session = New-PSSession -ConfigurationName JEAConfig
Invoke-Command -Session $session {
Get-Command -Name * # 仅显示白名单命令
Get-ChildItem C:\ # 触发权限拒绝
}

典型应用场景

  1. 数据库只读访问控制
  2. 第三方供应商操作审计
  3. 生产环境故障诊断隔离
  4. 跨域资源受限访问

安全加固要点

  • 虚拟账户生命周期控制
  • 转录日志完整性校验
  • 模块白名单签名验证
  • 会话超时熔断机制

PowerShell 技能连载 - 基于ATT&CK框架的进程行为分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function Invoke-ProcessBehaviorAnalysis {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]$ComputerName = $env:COMPUTERNAME
)

$techniques = Invoke-RestMethod -Uri 'https://attack.mitre.org/api/techniques/'
$processes = Get-CimInstance -ClassName Win32_Process -ComputerName $ComputerName

$report = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
SuspiciousProcesses = @()
MITRETechniques = @()
}

$processes | ForEach-Object {
$behaviorScore = 0
$matchedTechs = @()

# 检测隐藏进程
if ($_.ParentProcessId -ne 1 -and -not (Get-Process -Id $_.ParentProcessId -ErrorAction SilentlyContinue)) {
$behaviorScore += 20
$matchedTechs += 'T1055' # Process Injection
}

# 检测异常内存操作
if ($_.WorkingSetSize -gt 1GB) {
$behaviorScore += 15
$matchedTechs += 'T1056' # Memory Allocation
}

if ($behaviorScore -gt 25) {
$report.SuspiciousProcesses += [PSCustomObject]@{
ProcessName = $_.Name
ProcessId = $_.ProcessId
Score = $behaviorScore
CommandLine = $_.CommandLine
}
$report.MITRETechniques += $matchedTechs | Select-Object @{n='TechniqueID';e={$_}}, @{n='Description';e={$techniques.techniques.Where{$_.id -eq $_}.name}}
}
}

$report | ConvertTo-Json -Depth 3 | Out-File "$env:TEMP/ProcessAnalysis_$(Get-Date -Format yyyyMMdd).json"
return $report
}

核心功能

  1. ATT&CK技术特征匹配
  2. 进程行为异常评分
  3. 自动化威胁检测
  4. JSON报告生成

典型应用场景

  • 企业终端安全监控
  • 红队攻击痕迹分析
  • 蓝队防御策略验证
  • 安全事件快速响应

PowerShell 技能连载 - 安全策略配置指南

PowerShell执行策略是脚本安全的第一道防线,通过灵活配置平衡功能与安全。

1
2
3
4
5
# 查看当前执行策略
Get-ExecutionPolicy -List

# 设置远程签名策略
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

脚本签名验证

  1. 创建代码签名证书:

    1
    2
    3
    4
    5
    6
    7
    $certParams = @{
    Subject = 'CN=PowerShell Scripts'
    Type = 'CodeSigning'
    KeyUsage = 'DigitalSignature'
    KeyLength = 2048
    }
    $cert = New-SelfSignedCertificate @certParams
  2. 签名脚本文件:

    1
    2
    3
    4
    5
    6
    $signParams = @{
    Certificate = $cert
    FilePath = 'script.ps1'
    TimestampServer = 'http://timestamp.digicert.com'
    }
    Set-AuthenticodeSignature @signParams

安全日志分析

1
2
3
4
5
6
7
# 查询脚本块日志
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-PowerShell/Operational'
Id = 4104
} | Where-Object {
$_.Message -match '可疑命令'
}

最佳实践:

  • 使用AllSigned策略生产环境
  • 定期轮换签名证书
  • 启用脚本块日志记录
  • 结合AppLocker增强控制

PowerShell 技能连载 - 红队渗透测试自动化框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function Invoke-RedTeamScan {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$TargetRange,

[ValidateSet('Basic','Advanced')]
[string]$ScanMode = 'Basic'
)

$threatReport = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
VulnerableSystems = @()
AttackPaths = @()
RiskScore = 0
}

try {
# 检测本地权限提升漏洞
$localVulns = Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall |
Where-Object { $_.GetValue('DisplayName') -match '脆弱服务' }
if ($localVulns) {
$threatReport.VulnerableSystems += [PSCustomObject]@{
SystemName = $env:COMPUTERNAME
Vulnerability = '本地权限提升'
CVE = 'CVE-2024-XXXX'
}
}

# 高级模式横向移动检测
if ($ScanMode -eq 'Advanced') {
$networkSystems = Test-NetConnection -ComputerName $TargetRange -Port 445 |
Where-Object TcpTestSucceeded

$networkSystems | ForEach-Object {
$shares = Get-SmbShare -ComputerName $_.RemoteAddress -ErrorAction SilentlyContinue
if ($shares) {
$threatReport.AttackPaths += [PSCustomObject]@{
Source = $env:COMPUTERNAME
Target = $_.RemoteAddress
AttackVector = 'SMB共享漏洞'
}
}
}
}

# 计算风险评分
$threatReport.RiskScore = [math]::Min(100, ($threatReport.VulnerableSystems.Count * 30) + ($threatReport.AttackPaths.Count * 20))
}
catch {
Write-Error "渗透测试失败: $_"
}

# 生成红队行动报告
$threatReport | ConvertTo-Json | Out-File -Path "$env:TEMP/RedTeamReport_$(Get-Date -Format yyyyMMdd).json"
return $threatReport
}

核心功能

  1. 本地权限提升漏洞检测
  2. 网络横向移动路径分析
  3. SMB共享漏洞自动化扫描
  4. 动态风险评分系统

应用场景

  • 红队渗透测试演练
  • 企业网络安全评估
  • 攻击路径可视化
  • 安全防御策略验证