-
Notifications
You must be signed in to change notification settings - Fork 0
/
certdog-cert.ps1
1195 lines (1053 loc) · 35.8 KB
/
certdog-cert.ps1
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ------------------------------------------------------------------------------------------------
# Krestfield Certdog Certificate Management Script
# ------------------------------------------------------------------------------------------------
#
# Copyright (c) 2021, Krestfield Limited
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this list of conditions
# and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
# and the following disclaimer in the documentation and/or other materials provided with the distribution.
# * Neither the name of Krestfield Limited nor the names of its contributors may be used to endorse or
# promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ------------------------------------------------------------------------------------------------
#
# For an official supported, signed version of this script contact support@krestfield.com
#
# For more details on this script go here
# https://krestfield.github.io/docs/certdog/cert_powershell.html
#
# This script requires the certdog application to issue certificates
# More information: https://krestfield.github.io/docs/certdog/get_certdog.html
#
# Simple run options:
#
# .\certdog-cert.ps1 -new
#
# This will prompt for all information including the certdog login as well as
# the dn, sans and whether to create a sheduled task etc.
# To provide the certdog login details without being prompted, run:
#
# .\certdog-cert.ps1 -new -username [certdoguser] -password [certdogpassword]
#
# To run without any prompting:
#
# .\certdog-cert.ps1 -new -username [certdoguser] -password [certdogpassword] -dn [Required DN]
# -sans [SAN List] -saveCreds y
# -createTask y -taskUsername [taskUsername] -taskPassword [taskPassword]
#
# Once the above has been performed the script saves the required information. Running:
#
# .\certdog-cert.ps1 -renew
#
# Will check and process any renewals required when the -new switch was used
#
# If credentials are not saved, this can be run with the username and password options:
#
# .\certdog-cert.ps1 -renew -username [certdoguser] -password [certdogpassword]
#
#
# To list what certificates are being monitored:
#
# .\certdog-cert.ps1 -list
#
#
# To create a scheduled task that runs the .\certdog-cert.ps1 -renew script daily, run
#
# .\certdog-cert.ps1 -taskonly
#
#
# To override the certdog URL as specified in the settings.json file, use -certdogUrl e.g.
#
# .\certdog-cert.ps1 -new -certdogUrl https://certdog.org.com/certdog/api
#
#
# To ignore any SSL errors (if the certdog URL is not protected with a trusted cert),
# use -ignoreSslErrors e.g.
#
# .\certdog-cert.ps1 -new -ignoreSslErrors
#
# ------------------------------------------------------------------------------------------------
Param (
[switch]
$new,
[switch]
$renew,
[switch]
$list,
[switch]
$taskonly,
[switch]
$setcreds,
[switch]
$ignoreSslErrors,
[Parameter(Mandatory=$false)]
$username,
[Parameter(Mandatory=$false)]
$password,
[Parameter(Mandatory=$false)]
$certdogUrl,
[Parameter(Mandatory=$false)]
$dn,
[Parameter(Mandatory=$false)]
$sans,
[Parameter(Mandatory=$false)]
$saveCreds,
[Parameter(Mandatory=$false)]
$createTask,
[Parameter(Mandatory=$false)]
$taskUsername,
[Parameter(Mandatory=$false)]
$taskPassword
)
$script:scriptName = "certdog-cert.ps1"
$script:managedCertsFilename = "managedcerts.json"
# By default we do not ignore SSL errors
$script:IgnoreTlsErrors = $false
# The list of managed certs, if any, that may be saved
$script:managedCerts = @()
$script:CertdogSecureUsername=$null
$script:CertdogSecurePassword=$null
$CREDS_REGISTRY_PATH = "HKLM:\Software\Krestfield\Certdog"
$script:loggedIn = $false
# -----------------------------------------------------------------------------
# When -ignoreSslErrors is called, this is set which ignores https TLS errors
# due to untrusted certificates etc.
# -----------------------------------------------------------------------------
Function IgnoreSSLErrors
{
$script:IgnoreTlsErrors = $true
if ("TrustAllCertsPolicy" -as [type]) {}
else
{
# NOTE: This skips the SSL certificate check
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}
}
# -----------------------------------------------------------------------------
# Logs in the user and retains the authorization token for use by other
# functions
# -----------------------------------------------------------------------------
Function login
{
Param(
[Parameter(Mandatory=$true)]
$username,
[Parameter(Mandatory=$true)]
$password
)
$initialHeaders = @{
'Content-Type' = 'application/json'
}
$body = [Ordered]@{
'username' = "$username"
'password' = "$password"
} | ConvertTo-Json -Compress
try
{
$response = Invoke-RestMethod "$certdogUrl/login" -Method "POST" -Headers $initialHeaders -Body $body
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$authToken = $response.token
$headers.Add("Authorization", "Bearer $authToken")
Set-Variable -Name "HEADERS" -Force -Value $headers -Visibility Private -Scope Global
$script:loggedIn = $true
}
catch
{
$script:loggedIn = $false
Throw "Authentication to certdog at $certdogUrl failed`nError: $_"
}
}
# -----------------------------------------------------------------------------
# Logs out a user from this IP
#
# -----------------------------------------------------------------------------
Function Logout
{
$body = [Ordered]@{}
Run-Rest-Command -endPoint "logouthere" -method "GET" -body $body -methodName "Logout-Here"
}
# -----------------------------------------------------------------------------
# Makes a generic REST call requiring the end point, body, method etc.
# Returns the response
# -----------------------------------------------------------------------------
Function Run-Rest-Command
{
Param(
[Parameter(Mandatory=$true)]
$endPoint,
[Parameter(Mandatory=$true)]
$method,
[Parameter(Mandatory=$true)]
$body,
[Parameter(Mandatory=$true)]
$methodName
)
try {
$headers = Get-Variable -Name "HEADERS" -ValueOnly -ErrorAction SilentlyContinue
if (!$headers)
{
Write-Host "Please authenticate with Login -username [username] -password [password] (or just type Login to be prompted)"
Return
}
$response = Invoke-RestMethod "$certdogUrl/$endPoint" -Headers $headers -Method $method -Body $body
return $response
}
catch
{
Write-Host "$methodName failed: $_"
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$responseBody = $reader.ReadToEnd();
#Write-Host responseBody = $responseBody
$output = $responseBody | ConvertFrom-Json
$output | Format-List
throw $output
}
}
# -----------------------------------------------------------------------------
# Requests a cert with a CSR
#
# -----------------------------------------------------------------------------
Function Request-CertP10
{
[alias("request-csr")]
Param(
[Parameter(Mandatory=$true)]
$caName,
[Parameter(Mandatory=$false)]
$csr,
[Parameter(Mandatory=$false)]
$teamName,
[Parameter(Mandatory=$false)]
$extraInfo,
[Parameter(Mandatory=$false)]
[string[]]$extraEmails
)
if ($script:loggedIn -eq $false)
{
Throw "Not logged in. Unable to request certificate from certdog"
}
if (!$csr)
{
Throw "Unable to request a certificate from certdog as no CSR data was provided"
}
try
{
$body = [Ordered]@{
'caName' = "$caName"
'csr' = "$csr"
'teamName' = "$teamName"
'extraInfo' = "$extraInfo"
'extraEmails' = @($extraEmails)
} | ConvertTo-Json -Compress
$response = Run-Rest-Command -endPoint "certs/requestp10" -method "POST" -body $body -methodName "Request-CertP10"
return $response
}
catch
{
Throw "Unable to obtain certificate from certdog. Error: $_"
}
}
# ------------------------------------------------------------------------------------------------
# Generates a certificate request in the local machine store
#
#
# ------------------------------------------------------------------------------------------------
Function Generate-Csr
{
Param(
[Parameter(Mandatory=$true)]
[string]
$dn,
[Parameter(Mandatory=$false)]
$sans
)
try
{
# Temp filename for CSR and INF file
$UID = [guid]::NewGuid()
$settingsInfFile = "$($env:TEMP)\$($UID)-settings.inf";
$csrFile = "$($env:TEMP)\$($UID)-csr.req"
# Create the settings.inf
$keySize = $global:Settings.csrKeyLength
$hash = $global:Settings.csrHash
$provider = $global:Settings.csrProvider
$providerType = $global:Settings.csrProviderType
$exportable = $global:Settings.exportable
$settingsInf = "
[Version]
Signature=`"`$Windows NT`$
[NewRequest]
KeyLength = $keySize
Exportable = $exportable
MachineKeySet = TRUE
SMIME = FALSE
RequestType = PKCS10
ProviderName = `"$provider`"
ProviderType = $providerType
HashAlgorithm = $hash
;Variables
Subject = `"$dn`"
[Extensions]
"
# Add the SANs
if ($sans -and $sans.count -gt 0) {
$settingsInf += "2.5.29.17 = `"{text}`"
"
foreach ($sanItem In $sans)
{
$settingsInf += "_continue_ = `"$sanItem`&`"
" }
}
# Save settings to file in temp
Set-Content -Path $settingsInfFile -Value $settingsInf
$resp = certreq -q -new $settingsInfFile $csrFile
if ($LASTEXITCODE -ne 0)
{
Throw $resp
}
$csr = Get-Content $csrFile
Remove-Item $csrFile -ErrorAction SilentlyContinue
Remove-Item $settingsInfFile -ErrorAction SilentlyContinue
return $csr
}
catch
{
Throw "There was an error whilst creating the CSR for the requested DN of $dn. Error: $_"
}
}
# ------------------------------------------------------------------------------------------------
# Requests a certificate from certdog
#
# ------------------------------------------------------------------------------------------------
Function Request-Cert
{
Param(
[Parameter(Mandatory=$true)]
[string]
$username,
[Parameter(Mandatory=$true)]
[string]
$password,
[Parameter(Mandatory=$true)]
[string]
$caName,
[Parameter(Mandatory=$true)]
[string]
$csr,
[Parameter(Mandatory=$true)]
[string]
$teamName
)
if ($script:loggedIn -eq $false)
{
login -username $username -password $password
$script:loggedIn = $true
}
$cert = Request-CertP10 -caName $caName -csr $csr -teamName $teamName
#Logout
return $cert.pemCert
}
# ------------------------------------------------------------------------------------------------
# Imports a certificate into the local machine store
#
# ------------------------------------------------------------------------------------------------
Function Import-Cert
{
Param(
[Parameter(Mandatory=$true)]
[string]
$certData
)
$tmpId = [guid]::NewGuid()
$tmpFilename = "$($env:TEMP)\$($UID).cer";
Set-Content -Path $tmpFilename -Value $certData
try
{
if (Test-Path $tmpFilename)
{
Get-ChildItem -Path $tmpFilename | Import-Certificate -CertStoreLocation cert:\LocalMachine\My > $null
# Get Thumbprint
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($tmpFilename)
# Store the Thumbprint in a global ready for use by any subsequent script
$global:thumbprint = $cert.Thumbprint
Remove-Item $tmpFilename -ErrorAction SilentlyContinue
return $cert
}
else
{
Throw "Could not install certificate into local store, the certificate file at $tmpFilename could not be found."
}
}
catch
{
Throw "Importing of the certdog issued certificate failed. Error: $_"
}
}
# ------------------------------------------------------------------------------------------------
# Given the DN returns the common name
#
# e.g.
# Given: CN=test,O=Org,C=GB
# will return: test
#
# ------------------------------------------------------------------------------------------------
Function Get-CommonNameFromDn
{
Param(
[Parameter(Mandatory=$true)]
[string]
$dn
)
$cn = $dn -replace "(CN=)(.*?),.*",'$2'
$cn = $cn -replace "CN=",""
return $cn
}
# ------------------------------------------------------------------------------------------------
# Gather any additional SANs
#
# Note that the common name is added automatically
#
# ------------------------------------------------------------------------------------------------
Function Get-Sans
{
if ($sans)
{
$sanArray = $sans -split (',');
return $sanArray
}
else
{
$addMoreSans = Read-Host "`nDo you wish to add any subject alternative names to this certificate? (y/n)"
if ($addMoreSans -eq "y")
{
$sansOk = $false
do
{
Write-Host "`nEnter additional names in the form [Name Type]=[Name], seperated with a comma"
Write-Host "Name Type can be: DNS, IPAddress or EMAIL"
$addSans = Read-Host "e.g. DNS=test1.com,DNS=test2.com,EMAIL=user@home.com"
$sanArray = @()
Write-Host "`nAdditional Names:"
Foreach ($sanItem In $addSans -split ",")
{
Write-Host " " $sanItem -ForegroundColor Yellow
$sanArray = $sanArray + "$sanItem"
}
$allOk = Read-Host "`nAll ok? (y/n)"
if ($allOk -eq "y")
{
$sansOk = $true
}
}
while ($sansOk -ne $true)
}
else
{
$sanArray = @()
}
return $sanArray
}
}
# ------------------------------------------------------------------------------------------------
# If the .\config dir is not present, creates it
# ------------------------------------------------------------------------------------------------
Function Check-ConfigDir
{
$dirLoc = "$PSScriptRoot\config"
if (!(Test-Path $dirLoc))
{
New-Item -ItemType directory -Path $dirLoc -Force > $null
}
}
# ------------------------------------------------------------------------------------------------
# Saves the certs to be managed
#
# ------------------------------------------------------------------------------------------------
Function Save-ManagedCerts
{
Check-ConfigDir
# Save the cert details
$script:managedCerts | ConvertTo-Json -depth 100 | Out-File "$PSScriptRoot\config\$managedCertsFilename"
}
# ------------------------------------------------------------------------------------------------
# Loads the managed certs
#
# ------------------------------------------------------------------------------------------------
Function Load-ManagedCerts
{
$managedCertsFilename = "$PSScriptRoot\config\$managedCertsFilename"
if (Test-Path $managedCertsFilename)
{
[string[]]$script:managedCerts = Get-Content -Path $managedCertsFilename | ConvertFrom-Json
}
}
# ------------------------------------------------------------------------------------------------
# Saves the user credentials which means the renew option can be run
# without requiring the credentials to be passed
#
# ------------------------------------------------------------------------------------------------
Function Save-Credentials
{
# If option not provided, prompt
if (!$saveCreds)
{
$saveCreds = Read-Host "Do you wish to save your credentials so they are not required when 'renew' is run? (y/n)"
}
if ($saveCreds -like "y")
{
if (!$script:CertdogSecureUsername)
{
$user = Get-Username
$pass = Get-Password
}
# Save the certdog credentials to the registry
$secureUsername = $script:CertdogSecureUsername | ConvertFrom-SecureString
$securePassword = $script:CertdogSecurePassword | ConvertFrom-SecureString
if (!(Test-Path $CREDS_REGISTRY_PATH))
{
New-Item -Path $CREDS_REGISTRY_PATH -Force | Out-Null
}
New-ItemProperty -Path $CREDS_REGISTRY_PATH -Name "SecureUsername" -Value $secureUsername -PropertyType String -Force | Out-Null
New-ItemProperty -Path $CREDS_REGISTRY_PATH -Name "SecurePassword" -Value $securePassword -PropertyType String -Force | Out-Null
Write-Host "Credentials saved OK. They can only be accessed by the account running this script. Run '$script:scriptName -setcreds' to update"
}
}
# ------------------------------------------------------------------------------------------------
# Loads the certdog secure credentials from the registry
#
# ------------------------------------------------------------------------------------------------
Function Load-Credentials
{
# If username and password passed in, use those, otherwise get from the registry
if ($username -and $password)
{
$script:CertdogSecureUsername = ConvertTo-SecureString -String $username -AsPlainText -Force
$script:CertdogSecurePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
}
else
{
# Load the certdog credentials from the registry
try
{
if (Test-Path $CREDS_REGISTRY_PATH)
{
Get-ItemProperty -Path $CREDS_REGISTRY_PATH | Select-Object -ExpandProperty "SecureUsername" -ErrorAction Stop | Out-Null
$secureUsername = (Get-ItemProperty -Path $CREDS_REGISTRY_PATH -Name "SecureUsername").SecureUsername
$script:CertdogSecureUsername = $secureUsername | ConvertTo-SecureString
if (!$script:CertdogSecureUsername)
{
Throw "Unable to obtain credentials from the store"
}
Get-ItemProperty -Path $CREDS_REGISTRY_PATH | Select-Object -ExpandProperty "SecurePassword" -ErrorAction Stop | Out-Null
$SecurePassword = (Get-ItemProperty -Path $CREDS_REGISTRY_PATH -Name "SecurePassword").SecurePassword
$script:CertdogSecurePassword = $securePassword | ConvertTo-SecureString
if (!$script:CertdogSecurePassword)
{
Throw "Unable to obtain credentials from the store"
}
}
else
{
Throw "No credentials could be found in the registry. Either run .\$script:scriptName -new to have them stored on this machine or provide to this script"
}
}
catch
{
Throw "Failed to load username or password from registry. $_"
}
}
}
# ------------------------------------------------------------------------------------------------
# Writes the message to a log file and optionally the event log
#
# ------------------------------------------------------------------------------------------------
Function Write-Event
{
Param(
[Parameter(Mandatory=$true)]
$message,
[Switch]
$toEventLog,
[Switch]
$isError
)
$EventLogSource="certdog"
$EventLogID=$global:Settings.eventLogId
Add-Content $global:RenewLogFile "$message"
if ($toEventLog)
{
if (![System.Diagnostics.EventLog]::SourceExists($EventLogSource))
{
New-EventLog –LogName Application –Source $EventLogSource
}
$entryType = "Information"
if ($isError)
{
$entryType = "Error"
$EventLogID=$global:Settings.errorLogId
}
Write-EventLog –LogName Application –Source $EventLogSource –EntryType $entryType –EventID $EventLogID –Message $message -Category 0
}
#Write-Host $message
}
# ------------------------------------------------------------------------------------------------
# Creates a scheduled task which will call this script with the -renew switch
# Task will run once a day between 1 and 3am
#
# ------------------------------------------------------------------------------------------------
Function Create-Task()
{
try
{
# If option not provided, prompt
if (!$createTask)
{
$createTask = Read-Host "`nDo you want to create a task to automatically renew certificates? (y/n)"
}
if ($createTask -like "y")
{
if (!$taskUsername)
{
Write-Host "`nThe script will use saved credentials to authenticate to certdog"
Write-Host "Only the account that saved those credentials will have access to them"
Write-Host "The task must run under this same account"
$username = Read-Host "`nEnter the username of this account"
$securePassword = Read-Host -assecurestring "Enter the password"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword))
}
else
{
$username = $taskUsername
$password = $taskPassword
}
$description = "Checks for expiry of Certdog certificates"
$taskName = "Certdog Cert Expiry Check"
$scriptLoc = "$PSScriptRoot\$script:scriptName"
$arg = "-Command `"& '$scriptLoc' -renew`""
if ($script:IgnoreTlsErrors)
{
$arg = "-Command `"& '$scriptLoc' -renew -ignoreSslErrors`""
}
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $arg -WorkingDirectory $PSScriptRoot
# Run every day a random time between 1am and 3am
$trigger = New-ScheduledTaskTrigger -Daily -DaysInterval 1 -At 1am -RandomDelay (New-TimeSpan -minutes 120)
# Create the task (if not already present)
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName}
if($taskExists)
{
Write-Host "`nDid not create a new task as a task already exists to monitor TLS certificates called $taskName"
}
else
{
$newTask = Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -User $username -Password $password -Description $description -ErrorAction Stop | Out-Null
Write-Host "`nTask: '"$taskName"' created OK"
}
Write-Host "If required, you can manually edit the timings of this task from the Task Scheduler"
Write-Host "`nBye`n"
}
else
{
Write-Host "`nThis certificate will not auto-renew"
Write-Host "`nYou can manually renew this certificate (and any others that are being monitored) by running"
Write-Host " $script:scriptName -renew" -ForegroundColor Gray
Write-Host "`nSee: https://krestfield.github.io/docs/certdog/cert_powershell.html for more information"
Write-Host "`nBye`n"
}
}
catch
{
Throw "Unable to create scheduled task. Error: $_"
}
}
# ------------------------------------------------------------------------------------------------
# If a username has not been passed in, prompt for it
# Store this username in the CertdogSecureUsername secure string
#
# ------------------------------------------------------------------------------------------------
Function Get-Username()
{
# If not passed in, prompt the operator
if (!$username)
{
$username = Read-Host "`nEnter your certdog username"
}
# Store as a secure string
$script:CertdogSecureUsername = ConvertTo-SecureString -String $username -AsPlainText -Force
return $username
}
# ------------------------------------------------------------------------------------------------
# If a password has not been passed in, prompt for it
# Store this password in the CertdogSecurePassword secure string
#
# ------------------------------------------------------------------------------------------------
Function Get-Password()
{
if (!$password)
{
$script:CertdogSecurePassword = Read-Host -assecurestring "Enter your certdog password"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($script:CertdogSecurePassword))
return $password
}
else
{
$script:CertdogSecurePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
return $password
}
}
# ------------------------------------------------------------------------------------------------
# Extracts the SANS from a certificate and returns an array
#
# ------------------------------------------------------------------------------------------------
Function getSansFromCert
{
Param(
[Parameter(Mandatory=$true)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]
$cert
)
try
{
# Get all SAN extensions
$sanExt = $cert.Extensions | Where-Object {$_.Oid.FriendlyName -eq "subject alternative name"}
if ($sanExt)
{
$sanString = $sanExt.Format(1) -replace "DNS Name", "DNS"
$sanString = $sanString -replace "IP Address", "IPAddress"
$sanString = $sanString -replace "RFC822 Name", "EMAIL"
$sanString = $sanString -replace "`r`n", ";"
$sanArray = $sanString.split(";")
return $sanArray
}
}
catch
{
Throw "There was an error obtaining the SANs from certificate cert.SubjectDN Error: $_"
}
}
# ------------------------------------------------------------------------------------------------
# Obtain the certs from managedcerts.json and check if it is expiring in $settings.renewalDays
# If so, renew the cert
#
# ------------------------------------------------------------------------------------------------
Function CheckFor-ExpiringCerts
{
if ($script:managedCerts)
{
$newCertThumbprints = @()
foreach($certThumbprint in $script:managedCerts)
{
$currentCertificate = Get-ChildItem -Path CERT:LocalMachine/My | Where-Object -Property Thumbprint -EQ -Value $certThumbprint
if (!$currentCertificate)
{
Write-Event -message "`nCould not find a certificate with thumbprint: $certThumbprint"
}
else
{
$certSubject = $currentCertificate.Subject
$certThumbprint = $currentCertificate.Thumbprint
$expiring = $currentCertificate.NotAfter
Write-Event -message "`nCurrent Certificate - $certSubject Thumbprint: $certThumbprint Expiring $expiring"
$renewalDays = $global:Settings.renewalDays
if ($currentCertificate.NotAfter -le (get-date).AddDays($renewalDays))
{
Write-Event -message "Is expiring in less than $renewalDays days. Renewing now..."
# Get certificate dn and common name
$certDn = $currentCertificate.Subject
$certSans = getSansFromCert $currentCertificate
$csr = Generate-Csr -dn $certDn -sans $certSans
# Need to convert from secure
$username = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($script:CertdogSecureUsername))
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($script:CertdogSecurePassword))
$cert = Request-Cert -username $username -password $password -caName $global:Settings.certIssuerName -csr "$csr" -teamName $global:Settings.teamName
Write-Event -message "Obtained new certificate from certdog OK"
# Import the certificate
$newCert = Import-Cert $cert
$newCertThumbprint = $newCert.Thumbprint
$newCertExpiry = $newCert.NotAfter
Write-Event -message "New Certificate - Thumbprint: $newCertThumbprint Expiring: $newCertExpiry"
# Store the new thumbprint to monitor
$newCertThumbprints += $newCertThumbprint
}
else
{
Write-Event -message "Is not expiring (in the next $renewalDays days)"
# No change so we store the same thumbprint as before
$newCertThumbprints += $certThumbprint
}
}
}
# Save the new thumbprints
$script:managedCerts = $newCertThumbprints
Save-ManagedCerts
}
else
{
Write-Event -message "No certificates to monitor`n"
}
}
# ------------------------------------------------------------------------------------------------
# Displays the startup header
#
# ------------------------------------------------------------------------------------------------
Function Show-Heading
{
Write-Host "`n`nCertdog Certificate Manager Script" -ForegroundColor Gray
Write-Host "----------------------------------`n" -ForegroundColor Green
}
# ------------------------------------------------------------------------------------------------
# Updates the Get New Certificate
#
# Prompts for input regarding DN, username and password then requests the cert
# and installs to the machine store.
#
# ------------------------------------------------------------------------------------------------
Function Get-NewCert
{
Show-Heading
if (!$dn)
{
$dn = Read-Host "Enter the DN (e.g. CN=name,O=org,C=GB)"
if (!$dn)
{
Throw "A subject DN is required"
}
Write-Host "`nCertificate DN will be: " -NoNewline
Write-Host $dn -ForegroundColor Yellow
$continue = Read-Host "`nContinue? (y/n)"
}
else {
$continue = "y"
}
if ($continue -eq "y")
{
Load-ManagedCerts
$sans = Get-Sans
$username = Get-Username
$password = Get-Password
$caName = $global:Settings.certIssuerName
# Generate the CSR
Write-Host "`nGenerating certificate request..."
$csr = Generate-Csr -dn $dn -sans $sans
Write-Host "Request created OK"
# Request and obtain the certificate
Write-Host "`nRequesting certificate..."
$cert = Request-Cert -username $username -password $password -caName $caName -csr "$csr" -teamName $global:Settings.teamName
Write-Host "Obtained certificate OK"
# Import the certificate
Write-Host "`nImporting certificate..."
$newCert = Import-Cert $cert
# Add this to the list of managed certs
$script:managedCerts += $newCert.Thumbprint
Write-Host "`nCertificate has been issued and imported OK`n"
Save-Credentials
Save-ManagedCerts
# Create scheduled task
Create-Task
}
}
# ------------------------------------------------------------------------------------------------
# Gets the renew log filename - creates the log directory if doesn't already exist
#
# ------------------------------------------------------------------------------------------------
Function Get-RenewLogFile
{
$dateStamp = get-date -Format yyyyMMddTHHmmss