-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript.ps1
More file actions
463 lines (399 loc) · 17.1 KB
/
Script.ps1
File metadata and controls
463 lines (399 loc) · 17.1 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#Windows CA Monitor v1.0
#In my test environment, I use three different URLs for the CA, you can change it all to one single URL if you only use one of them.
#You should use pkiview.msc to find the URLs
#All the URLs were divided into two parts: HostName & Base URL, if you don't use the default URL settings, please change the BaseUrl below, don't use the default settings!
#Host IPs can be regarded as Domain Names if you are using DNS to access hosts, instead of using IPs
#Default Path are like: http://host.example.com/CertEnroll/.... & http://host.example.com/ocsp
#You can change APIs, but don't forget to change the request header and body!
# Enforce TLS 1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
# Configuration Parameters - Please modify according to your actual environment
$APIKey = "your_api_key_here"
$APIUrl = "https://your-status-page.example.com"
$HostDNSName = "ca-server.example.com"
$HostIP1 = "IP_Addr1"
$HostIP2 = "IP_Addr2"
$CRLBaseUrl = "/CertEnroll/Your_CA_Name.crl"
$DeltaCRLBaseUrl = "/CertEnroll/Your_CA_Name+.crl"
$AIABaseUrl = "/CertEnroll/Your_CA_Name.crt"
$TempDir = "C:\Kener-CAMonitor\Temp"
$OCSPRequestFile = "C:\Kener-CAMonitor\OCSP.req"
$LocalCACertPath = "C:\Kener-CAMonitor\CA.cer"
$RemoteAIAUrls = @(
"http://${HostDNSName}${AIABaseUrl}",
"http://${HostIP1}${AIABaseUrl}",
"http://${HostIP2}${AIABaseUrl}"
)
# Ensure the temp directory exists
if (-not (Test-Path $TempDir)) {
New-Item -ItemType Directory -Path $TempDir -Force | Out-Null
}
# Get current UTC timestamp (in seconds)
function Get-UnixTimestamp {
[System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
}
# Send status to Kener API
function Send-Status {
param(
[String]$Status
)
$headers = @{
"Authorization" = "Bearer $APIKey"
"Content-Type" = "application/json"
}
$body = @{
status = $Status
latency = 500
timestampInSeconds = Get-UnixTimestamp
tag = "CA"
} | ConvertTo-Json
try {
$response = Invoke-RestMethod -Uri "$APIUrl/api/status" -Method Post -Headers $headers -Body $body
Write-Host "Status updated successfully: $Status" -ForegroundColor Green
return $response
}
catch {
Write-Host "Failed to update status: $($_.Exception.Message)" -ForegroundColor Red
return $null
}
}
# Download CRL files
function Download-CRL {
try {
# Download Base CRL
Invoke-WebRequest -Uri "http://${HostDNSName}${CRLBaseUrl}" -OutFile "${TempDir}\CRL1.crl" -ErrorAction Stop
Invoke-WebRequest -Uri "http://${HostIP1}${CRLBaseUrl}" -OutFile "${TempDir}\CRL2.crl" -ErrorAction Stop
Invoke-WebRequest -Uri "http://${HostIP2}${CRLBaseUrl}" -OutFile "${TempDir}\CRL3.crl" -ErrorAction Stop
# Download Delta CRL
Invoke-WebRequest -Uri "http://${HostDNSName}${DeltaCRLBaseUrl}" -OutFile "${TempDir}\DeltaCRL1.crl" -ErrorAction Stop
Invoke-WebRequest -Uri "http://${HostIP1}${DeltaCRLBaseUrl}" -OutFile "${TempDir}\DeltaCRL2.crl" -ErrorAction Stop
Invoke-WebRequest -Uri "http://${HostIP2}${DeltaCRLBaseUrl}" -OutFile "${TempDir}\DeltaCRL3.crl" -ErrorAction Stop
return $true
}
catch {
Write-Host "Failed to download CRL: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# Test URL availability
function Test-Url {
try {
$downloadSuccess = Download-CRL
if (-not $downloadSuccess) {
return $false
}
# Check if all files were downloaded successfully
$files = @(
"${TempDir}\CRL1.crl",
"${TempDir}\CRL2.crl",
"${TempDir}\CRL3.crl",
"${TempDir}\DeltaCRL1.crl",
"${TempDir}\DeltaCRL2.crl",
"${TempDir}\DeltaCRL3.crl"
)
foreach ($file in $files) {
if (-not (Test-Path -Path $file -PathType Leaf)) {
Write-Host "File not found: $file" -ForegroundColor Red
return $false
}
}
return $true
}
catch {
Write-Host "URL test failed: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# Get CRL expiration period
function Get-ExpirePeriod {
param(
[String]$CRLFile
)
try {
$File = Get-Item $CRLFile -ErrorAction Stop
# Use a more reliable method to parse the CRL file
$CertutilOutput = certutil -v $CRLFile | Out-String
# Debug: Output full certutil result (optional)
# Write-Host "certutil output: $CertutilOutput" -ForegroundColor Cyan
# Find the "Next Update:" line and extract the date
$NextUpdateDate = $null
# Directly search for the line containing "Next Update:"
$Lines = $CertutilOutput -split "`r?`n"
foreach ($Line in $Lines) {
if ($Line -match "Next Update:\s*(\d{4}/\d{1,2}/\d{1,2}\s+\d{1,2}:\d{2})") {
$DateString = $Matches[1]
# Try to parse the date format
if ($DateString -match "(\d{4})/(\d{1,2})/(\d{1,2})\s+(\d{1,2}):(\d{2})") {
$year = [int]$Matches[1]
$month = [int]$Matches[2]
$day = [int]$Matches[3]
$hour = [int]$Matches[4]
$minute = [int]$Matches[5]
$NextUpdateDate = Get-Date -Year $year -Month $month -Day $day -Hour $hour -Minute $minute -Second 0
break
}
}
}
if (-not $NextUpdateDate) {
Write-Host "Could not find 'Next Update:' information in CRL file: $CRLFile" -ForegroundColor Yellow
return [TimeSpan]::Zero
}
$CurrentDate = Get-Date
$timeLeft = $NextUpdateDate - $CurrentDate
Write-Host "CRL File: $CRLFile" -ForegroundColor DarkGray
Write-Host " Next Update: $($NextUpdateDate.ToString('yyyy-MM-dd HH:mm'))" -ForegroundColor DarkGray
Write-Host " Current Time: $($CurrentDate.ToString('yyyy-MM-dd HH:mm'))" -ForegroundColor DarkGray
Write-Host " Time Remaining: $([math]::Round($timeLeft.TotalHours, 2)) hours" -ForegroundColor DarkGray
# If the time has passed, return 0
if ($timeLeft.TotalSeconds -lt 0) {
return [TimeSpan]::Zero
}
return $timeLeft
}
catch {
Write-Host "Failed to parse CRL ($CRLFile): $($_.Exception.Message)" -ForegroundColor Red
return [TimeSpan]::Zero
}
}
# Test CRL status
function Test-CRL {
try {
# Get the minimum validity period among all CRLs
$CRLFiles = @(
"${TempDir}\CRL1.crl",
"${TempDir}\CRL2.crl",
"${TempDir}\CRL3.crl"
)
$DeltaCRLFiles = @(
"${TempDir}\DeltaCRL1.crl",
"${TempDir}\DeltaCRL2.crl",
"${TempDir}\DeltaCRL3.crl"
)
# Find the time closest to expiration among all CRLs
$CRLMinTimeLeft = $CRLFiles | ForEach-Object {
$timeLeft = Get-ExpirePeriod -CRLFile $_
if ($timeLeft -gt [TimeSpan]::Zero) {
$timeLeft
}
} | Sort-Object | Select-Object -First 1
if (-not $CRLMinTimeLeft) {
Write-Host "All base CRL files have expired" -ForegroundColor Red
return "DOWN"
}
# Find the time closest to expiration among all Delta CRLs
$DeltaCRLMinTimeLeft = $DeltaCRLFiles | ForEach-Object {
$timeLeft = Get-ExpirePeriod -CRLFile $_
if ($timeLeft -gt [TimeSpan]::Zero) {
$timeLeft
}
} | Sort-Object | Select-Object -First 1
if (-not $DeltaCRLMinTimeLeft) {
Write-Host "All delta CRL files have expired" -ForegroundColor Red
return "DOWN"
}
Write-Host "Base CRL Min Time Remaining: $([math]::Round($CRLMinTimeLeft.TotalHours, 2)) hours" -ForegroundColor Cyan
Write-Host "Delta CRL Min Time Remaining: $([math]::Round($DeltaCRLMinTimeLeft.TotalHours, 2)) hours" -ForegroundColor Cyan
# Set thresholds
$CRLWarnThreshold = [TimeSpan]::FromDays(2) # 2 days
$CRLDownThreshold = [TimeSpan]::FromHours(12) # 12 hours
$DeltaCRLWarnThreshold = [TimeSpan]::FromHours(4) # 4 hours
$DeltaCRLDownThreshold = [TimeSpan]::FromHours(2) # 2 hours
# Determine status
if ($CRLMinTimeLeft -ge $CRLWarnThreshold -and $DeltaCRLMinTimeLeft -ge $DeltaCRLWarnThreshold) {
return "UP"
}
elseif (($CRLMinTimeLeft -ge $CRLDegradedThreshold -and $CRLMinTimeLeft -lt $CRLWarnThreshold) -or
($DeltaCRLMinTimeLeft -ge $DeltaCRLDegradedThreshold -and $DeltaCRLMinTimeLeft -lt $DeltaCRLWarnThreshold)) {
return "DEGRADED"
}
else {
return "DOWN"
}
}
catch {
Write-Host "CRL test failed: $($_.Exception.Message)" -ForegroundColor Red
return "DOWN"
}
}
# Test OCSP response
function Test-OCSP {
try {
# Ensure the OCSP request file exists
if (-not (Test-Path $OCSPRequestFile -PathType Leaf)) {
Write-Host "OCSP request file does not exist: $OCSPRequestFile" -ForegroundColor Red
return $false
}
# Test OCSP response for all endpoints
$Urls = @(
"http://${HostDNSName}/ocsp",
"http://${HostIP1}/ocsp",
"http://${HostIP2}/ocsp"
)
foreach ($Url in $Urls) {
try {
$response = Invoke-WebRequest -Uri $Url -Method Post -ContentType "application/ocsp-request" -InFile $OCSPRequestFile -ErrorAction Stop
if ($response.StatusCode -ne 200) {
Write-Host "OCSP response status code error ($Url): $($response.StatusCode)" -ForegroundColor Yellow
return $false
}
}
catch {
Write-Host "OCSP request failed ($Url): $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
return $true
}
catch {
Write-Host "OCSP test failed: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# Check local CA certificate
function Test-LocalCACertificate {
try {
# Check if the certificate file exists
if (-not (Test-Path $LocalCACertPath -PathType Leaf)) {
Write-Host "Local CA certificate not found: $LocalCACertPath" -ForegroundColor Red
return "DOWN"
}
# Load the certificate
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$Cert.Import($LocalCACertPath)
# Check certificate validity period
$CurrentDate = Get-Date
$DaysToExpire = ($Cert.NotAfter - $CurrentDate).Days
Write-Host "Local CA Certificate Check:" -ForegroundColor DarkCyan
Write-Host " Subject: $($Cert.Subject)" -ForegroundColor DarkGray
Write-Host " Issuer: $($Cert.Issuer)" -ForegroundColor DarkGray
Write-Host " Valid From: $($Cert.NotBefore.ToString('yyyy-MM-dd'))" -ForegroundColor DarkGray
Write-Host " Expires On: $($Cert.NotAfter.ToString('yyyy-MM-dd'))" -ForegroundColor DarkGray
Write-Host " Days Remaining: $DaysToExpire days" -ForegroundColor DarkGray
# Set thresholds
$CriticalThreshold = 14 # 14 days
$WarningThreshold = 30 # 30 days
# Determine status
if ($DaysToExpire -le 0) {
Write-Host "Local CA certificate has expired!" -ForegroundColor Red
return "DOWN"
}
elseif ($DaysToExpire -le $CriticalThreshold) {
Write-Host "Local CA certificate is about to expire (remaining $DaysToExpire days)" -ForegroundColor Red
return "DEGRADED"
}
elseif ($DaysToExpire -le $WarningThreshold) {
Write-Host "Local CA certificate will expire in $DaysToExpire days" -ForegroundColor Yellow
return "UP" # Warning but does not affect overall status
}
return "UP"
}
catch {
Write-Host "Local CA certificate check failed: $($_.Exception.Message)" -ForegroundColor Red
return "DOWN"
}
}
# Check remote AIA certificates
function Test-RemoteAIACertificates {
try {
$OverallStatus = "UP"
$CertCounter = 0
Write-Host "Remote AIA Certificate Check:" -ForegroundColor DarkCyan
foreach ($Url in $RemoteAIAUrls) {
$CertCounter++
$CertPath = "$TempDir\AIA_$CertCounter.crt"
try {
# Download certificate
Invoke-WebRequest -Uri $Url -OutFile $CertPath -ErrorAction Stop
# Check if the certificate file exists
if (-not (Test-Path $CertPath -PathType Leaf)) {
Write-Host " AIA certificate download failed: $Url" -ForegroundColor Red
$OverallStatus = "DOWN"
continue
}
# Load the certificate
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$Cert.Import($CertPath)
# Check certificate validity period
$CurrentDate = Get-Date
$DaysToExpire = ($Cert.NotAfter - $CurrentDate).Days
Write-Host " Certificate #$CertCounter ($Url):" -ForegroundColor DarkGray
Write-Host " Subject: $($Cert.Subject)" -ForegroundColor DarkGray
Write-Host " Issuer: $($Cert.Issuer)" -ForegroundColor DarkGray
Write-Host " Expires On: $($Cert.NotAfter.ToString('yyyy-MM-dd'))" -ForegroundColor DarkGray
Write-Host " Days Remaining: $DaysToExpire days" -ForegroundColor DarkGray
# Set thresholds
$CriticalThreshold = 30 # 30 days
$WarningThreshold = 90 # 90 days
# Determine status
if ($DaysToExpire -le 0) {
Write-Host " AIA certificate has expired!" -ForegroundColor Red
$OverallStatus = "DOWN"
}
elseif ($DaysToExpire -le $CriticalThreshold) {
Write-Host " AIA certificate is about to expire (remaining $DaysToExpire days)" -ForegroundColor Red
if ($OverallStatus -ne "DOWN") {
$OverallStatus = "DEGRADED"
}
}
elseif ($DaysToExpire -le $WarningThreshold) {
Write-Host " AIA certificate will expire in $DaysToExpire days" -ForegroundColor Yellow
# Warning but does not affect overall status
}
}
catch {
Write-Host " AIA certificate check failed ($Url): $($_.Exception.Message)" -ForegroundColor Red
$OverallStatus = "DOWN"
}
}
return $OverallStatus
}
catch {
Write-Host "Remote AIA certificate check failed: $($_.Exception.Message)" -ForegroundColor Red
return "DOWN"
}
}
# Main program
try {
# Test URL and OCSP
$UrlTest = Test-Url
$ocspTest = Test-OCSP
if ($UrlTest -and $OCSPTest) {
$CRLResult = Test-CRL
$CACertResult = Test-LocalCACertificate
$AIAResult = Test-RemoteAIACertificates
# Comprehensive status assessment
Write-Host "`nComprehensive Status Assessment:" -ForegroundColor Magenta
Write-Host " CRL Status: $CRLResult" -ForegroundColor Cyan
Write-Host " CA Certificate Status: $CACertResult" -ForegroundColor Cyan
Write-Host " AIA Certificate Status: $AIAResult" -ForegroundColor Cyan
# Determine final status (take the most severe status)
$FinalStatus = "UP"
if ($CRLResult -eq "DOWN" -or $CACertResult -eq "DOWN" -or $AIAResult -eq "DOWN") {
$FinalStatus = "DOWN"
}
elseif ($CRLResult -eq "DEGRADED" -or $CACertResult -eq "DEGRADED" -or $AIAResult -eq "DEGRADED") {
$FinalStatus = "DEGRADED"
}
# Send final status
Send-Status -Status $FinalStatus
Write-Host "`nFinal Status: $FinalStatus" -ForegroundColor Green
}
else {
Send-Status -Status "DOWN"
Write-Host "URL or OCSP test failed, status set to DOWN" -ForegroundColor Red
}
}
catch {
Write-Host "Main program error: $($_.Exception.Message)" -ForegroundColor Red
Send-Status -Status "DOWN"
}
finally {
# Clean up temporary files
try {
Remove-Item "${TempDir}\*.crl" -Force -ErrorAction SilentlyContinue
Remove-Item "${TempDir}\AIA_*.crt" -Force -ErrorAction SilentlyContinue
}
catch {
Write-Host "Failed to clean up temporary files: $($_.Exception.Message)" -ForegroundColor Yellow
}
}