This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
wat.ps1
1295 lines (1141 loc) · 64.1 KB
/
wat.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
<#
.SYNOPSIS
WAT - Windows ACME Tool
.DESCRIPTION
This is a client for signing certificates with an ACME-server implemented as a single powershell script.
This tool has no additional requirements.
This work is inspired by the commonly used linux/unix script dehydrated.
If you are serious about the safty of the crypto stuff, please have a look at the Create-Certificate function.
This work is published under:
MIT License
Copyright (c) 2017 Ludwig Behm
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
.INPUTS
System.String[] $Domains
Specify a list of domain names. The first is used as CommonName of your certificate and the following are used in the SubjectAlternateName attribute
You can query for multible certificates with: (("example.com", "www.example.com"), ("jon.doe.xy")) | .\wat.ps1
.OUTPUTS
System.Security.Cryptography.X509Certificates.X509Certificate2
.EXAMPLE
.\wat.ps1 example.com
Basic usage for issuing a certificate for domain example.com
.EXAMPLE
.\wat.ps1 example.com -ContactEmail [email protected]
Updating the registration with given email address
.EXAMPLE
.\wat.ps1 -Domain "example.com" -WellKnown D:\inetpub\.well-known\acme-challenge
Placing the verification tokens in the specified directory
.EXAMPLE
.\wat.ps1 -Domain ("example.com", "www.example.com") -Staging
Including example.com and www.example.com in the SubjectAlternateName attribute of the certificate
Using the Let'sEncrypt staging environment for testing purpose
.EXAMPLE
$certs = (("example.com", "www.example.com"), ("jon.doe.xy")) | .\wat.ps1
Working a set of 2 certificates.
Certificate 1:
Name: example.com
Domains: example.com, www.example.com
Certificate 2:
Name: jon.doe.xy
Domains: jon.doe.xy
.EXAMPLE
C:\Scripts\wat\wat.ps1 -Domains "example.com" -WellKnown C:\inetpub\well-known\acme-challenge -AcceptTerms -AutoFix -Context LocalMachine
This is my entire config (as scheduled task) to update the SMTP Certificate in one of my ExchangeServers.
After the initial set up and binding of the Certificat to the SMTP service (e.g. in the ECP GUI), I don't have to update any ExchangeServer configuration every time the certificate is renewed.
That's what I call In-Place-Renewal - I didn't find anything on the web to this mechanism.
.NOTES
This script uses only Windows components
For the ACME account a RSACng-Key is used and stored in the system
For the use in certificates, private keys are generated in the Create-Certificate function
#>
Param (
# Specify a list of domain names.
# The first is used as CommonName of your certificate.
# Every domain name is added as SubjectAlternateName (SAN).
# The Domains parameter can also be provided as piped input. Please be sure to define arrays of string arrays in this case.
[Parameter(
Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = "Specify a list of domain names. The first is used as CommonName of your certificate."
)]
[String[]] $Domains,
# E-mail addresses that are linked to the account
[String[]] $Email,
# Discards the ACME account key and performs a complete new account registration
[Switch] $ResetRegistration,
# Force update of the account information (maybe you fiddled with the account.json file)
[Switch] $RenewRegistration,
# Force renew of certificate even if it is longer valid than value in RenewDays
[Switch] $RenewCertificate,
# Create complete new private key and certificate
[Switch] $RecreateCertificate,
# Regenerate private keys instead of just signing new certificates on renewal
[Switch] $RenewPrivateKey,
# Adding CSR feature indicating that OCSP stapling should be mandatory
[Switch] $OcspMustStaple,
# Path to certificate authority (default: https://acme-v01.api.letsencrypt.org/directory)
[uri] $CA,
# Accept CAs terms of service
[Switch] $AcceptTerms,
# Using the staging environment of Let'sEncrypt if -CA isn't specified
[Switch] $Staging,
# Which algorithm should be used?
[ValidateSet("Rsa", "ECDSA_P256", "ECDSA_P384")]
[System.Security.Cryptography.CngAlgorithm] $KeyAlgo = [System.Security.Cryptography.CngAlgorithm]::Rsa,
# Size of rsa keys (default: 4096)
# Possible values are between 2048 and 4096 and a multiple of 64 (e.g. 3072 is possible)
[ValidateScript({ ($_%64) -eq 0 -and $_ -ge 2048 -and $_ -le 4096 })]
[int] $KeySize = 4096,
# Minimum days before expiration to automatically renew certificate (default: 30)
[int] $RenewDays = 30,
# Which challenge should be used? (default: http-01)
[ValidateSet("http-01", "dns-01", "tls-sni-01")]
[String] $ChallengeType = "http-01",
# Currently only acme1-boulder dialect is tested
[ValidateSet("acme1-boulder", "acme2-boulder", "acme1")]
[String] $ACMEVersion = "acme1-boulder",
# Base directory for account config and generated certificates
[System.IO.DirectoryInfo] $BaseDir = (Split-Path -Parent $MyInvocation.MyCommand.Definition),
# Output directory for generated certificates
[System.IO.DirectoryInfo] $CertDir = "$BaseDir\Certs",
# Directory for account config and registration information
[System.IO.DirectoryInfo] $AccountDir = "$BaseDir\Accounts",
# Output directory for challenge-tokens to be served by webserver or deployed in -onChallenge
[System.IO.DirectoryInfo] $WellKnown = "C:\inetpub\wwwroot\.well-known\acme-challenge",
# Lockfile location, to prevent concurrent access
[System.IO.FileInfo] $LockFile = "$BaseDir\lock",
# Don't use lockfile (potentially dangerous!)
[Switch] $NoLock,
# Password to encrypt the exported certificate files (only applies to -ExportPfx and -ExportPkcs12)
[Security.SecureString] $ExportPassword = (new-object System.Security.SecureString),
# Export the certificate in PFX format (please use -ExportPassword)
[Switch] $ExportPfx,
# Export the certificate in Pkcs12 format (please use -ExportPassword)
[Switch] $ExportPkcs12,
# Export the certificate as a .crt public certificate file (Only public certificate without private key)
[Switch] $ExportCert,
# Export the certificate with private key in Base64 encoded PEM format (Warning: private key is NOT encrypted)
[Switch] $ExportPem,
# Export the certificate without private key in Base64 encoded PEM format
[Switch] $ExportPemCert,
# Export the private key in Base64 encoded PEM format (Warning: private key is NOT encrypted)
[Switch] $ExportPemKey,
# Export the certificate of the Issuer (e.g. Let'sEncrypt) in Base64 encoded PEM format
[Switch] $ExportIssuerPem,
[ValidateSet("ASCII", "UTF8", "UTF32", "UTF7", "BigEndianUnicode", "Default", "OEM", "Unicode")]
[string] $ExportPemEncoding = "ASCII",
# Script to be invoked with challenge token receiving the following parameter:
# Domain - The domain name you want to verify
# Token / FQDN - The file name for http-01 or domain name for dns-01 and tls-sni-01 challenges
# KeyAuthorization / Certificate - The value you have to place in the file or dns TXT record or the Certificate for tls-sni-01 challenges
[System.Management.Automation.ScriptBlock] $onChallenge,
# Script to be invoked after completing the challenge receiving the same parameter as -onChallenge with the addition of the response status 'valid' or 'invalid' as 4th parameter
[System.Management.Automation.ScriptBlock] $onChallengeCleanup,
# Don't verify the DNS record after executing onChallenge (applies only to dns-01 challenges)
[switch] $NoDnsTest,
# Internal identifier of the ACME account
[String] $InternalAccountIdentifier = "ACMEDefaultAccount",
# Which algorithm should be used for the ACME account key?
[ValidateSet("Rsa", "ECDSA_P256", "ECDSA_P384")]
[System.Security.Cryptography.CngAlgorithm] $AccountKeyAlgo = [System.Security.Cryptography.CngAlgorithm]::Rsa,
# Try to fix common problems automatically.
# This includes:
# - Creating new account with existing configuration if AccountKey is missing (this overwrites account id/data)
[Switch] $AutoFix,
# The place to save the certificate and keys
[System.Security.Cryptography.X509Certificates.StoreLocation] $Context = [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
)
Begin {
function die {
param(
[System.Management.Automation.ErrorRecord] $Exception,
[string] $Message = "",
[int] $ExitCode = 1,
[int] $EventId = 0,
[string] $LogName = "Windows PowerShell",
[string] $Source = "PowerShell",
[int] $Category = 0,
[System.Diagnostics.EventLogEntryType] $EntryType = [System.Diagnostics.EventLogEntryType]::Error,
[switch] $DontRemoveLock
)
try {
[string] $FullDescription = "[$($AppName)] $($Message)"
if ($Exception -ne $null) {
$FullDescription += "`n$($Exception.FullyQualifiedErrorId)"
$FullDescription += "`nExceptionMessage: $($Exception.Exception.Message)"
if ($Exception.ErrorDetails -ne $null) {
$FullDescription += "`n$($Exception.ErrorDetails.Message)"
}
$FullDescription += "`n$($Exception.InvocationInfo.PositionMessage)"
$FullDescription += "`nCategoryInfo: $($Exception.CategoryInfo.GetMessage())"
if ($Exception.PSObject.Members['ScriptStackTrace'] -ne $null) {
$FullDescription += "`nStackTrace:`n$($Exception.ScriptStackTrace)"
}
$FullDescription += "`n$($Exception.Exception.StackTrace)"
}
Write-Eventlog -EntryType $EntryType -LogName $LogName -Source $Source -Category $Category -EventId $EventId -Message $FullDescription
Write-Host $FullDescription -ForegroundColor Red -BackgroundColor Black
if (-not $DontRemoveLock) { Remove-Lock }
Exit $ExitCode
} catch {
Write-Host " X An unexpected Error occured resulting in another error while handling your first error."
Write-Host $_.FullyQualifiedErrorId
Exit $ExitCode
}
}
trap [Exception] { die -Exception $_ }
Set-PSDebug -Strict
Set-StrictMode -Version 2
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$Error.Clear()
function Create-Lock([System.IO.FileInfo] $Path = $LockFile) {
if ($NoLock) { return }
if ($Path.Exists) {die -Message "Lock file $Path present, aborting." -DontRemoveLock}
try {
[IO.File]::OpenWrite($Path).Close()
$PID | Out-File $Path
} catch {
die -Message "LOCKFILE $Path is not writable, aborting."
}
}
function Remove-Lock([System.IO.FileInfo] $Path = $LockFile) {
if ($NoLock) { return }
Remove-Item $Path -ErrorAction SilentlyContinue
}
function Invoke-SignedWebRequest([uri] $Uri, [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Post, [String] $Resource, [hashtable] $Payload) {
$Payload.resource = $Resource
$body = @{
header = Get-JWKHeader;
protected = Encode-UrlBase64 -Object (Get-JWKHeader -Nonce (Get-ACMENonce));
payload = Encode-UrlBase64 -Object $Payload;
}
$body.signature = Get-JWSignature -Value "$($body.protected).$($body.payload)"
[String] $json = ConvertTo-Json -InputObject $body -Compress
try {
$resp = Invoke-WebRequest -Uri $Uri -Method $Method -Body $json -ContentType 'application/json' -UseBasicParsing -UserAgent $UserAgent
} catch [System.Net.WebException] {
$acmeError = $_.ErrorDetails.Message | ConvertFrom-Json
if ($acmeError -ne $null) {
$errType = $acmeError.type.Split(':')|Select-Object -Last 1
Write-Host " ! Error[$($errType)]: $($acmeError.detail)"
throw $errType
}
die -Exception $_
}
$resp.Content|ConvertFrom-Json
}
function Get-ACMENonce([uri] $Uri = $CA) {
$resp = Invoke-WebRequest -Uri $Uri -Method Head -UseBasicParsing -UserAgent $UserAgent
if (-not $resp.Headers.ContainsKey('Replay-Nonce')) {throw "Can't fetch Nonce"}
$resp.Headers['Replay-Nonce']
}
function Get-JWKHeader([System.Security.Cryptography.AsymmetricAlgorithm] $PrivateKey = $AccountKey, [String] $Nonce) {
$export = $PrivateKey.ExportParameters($false)
$header = @{
alg = "RS256";
jwk = @{
kty = "RSA";
};
}
switch ($PrivateKey.Key.Algorithm.Algorithm) {
"RSA" {
$header.jwk.e = Encode-UrlBase64 -Bytes $export.Exponent
$header.jwk.n = Encode-UrlBase64 -Bytes $export.Modulus
}
"ECDSA_P256" {
$header.alg = "ES256"
$header.jwk.kty = "EC"
$header.jwk.crv = "P-256"
$header.jwk.x = Encode-UrlBase64 -Bytes $export.Q.X
$header.jwk.y = Encode-UrlBase64 -Bytes $export.Q.Y
}
"ECDSA_P384" {
$header.alg = "ES384"
$header.jwk.kty = "EC"
$header.jwk.crv = "P-384"
$header.jwk.x = Encode-UrlBase64 -Bytes $export.Q.X
$header.jwk.y = Encode-UrlBase64 -Bytes $export.Q.Y
}
}
if ($Nonce -ne "") { $header.nonce = $Nonce }
$header
}
function Get-JWSignature([String] $Value, [System.Security.Cryptography.AsymmetricAlgorithm] $PrivateKey = $AccountKey) {
switch ($PrivateKey.Key.Algorithm.Algorithm) {
"RSA" { Encode-UrlBase64 -Bytes ($PrivateKey.SignData([System.Text.Encoding]::UTF8.GetBytes($Value), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)) }
"ECDSA_P256" { Encode-UrlBase64 -Bytes ($PrivateKey.SignData([System.Text.Encoding]::UTF8.GetBytes($Value), [System.Security.Cryptography.HashAlgorithmName]::SHA256)) }
"ECDSA_P384" { Encode-UrlBase64 -Bytes ($PrivateKey.SignData([System.Text.Encoding]::UTF8.GetBytes($Value), [System.Security.Cryptography.HashAlgorithmName]::SHA384)) }
}
}
function Get-ACMEDirectory([uri] $Uri) {
[hashtable] $Directory = @{
"newNonce" = "";
"newAccount" = "";
"newAuthz" = "";
"newOrder" = "";
"keyChange" = "";
"revokeCert" = "";
"termsOfService" = "";
}
$json = (Invoke-WebRequest -Uri $Uri -UseBasicParsing -UserAgent $UserAgent).Content | ConvertFrom-Json
if ($ACMEVersion -eq "acme1-boulder") {
# WAT moment #1:
# They invent acme
# Let'sEncrypt is first in implementation
# Fundamentally changes the very first api call! That single point that configures every client!
# WAT?
$Directory.newAccount = $json.'new-reg'
$Directory.account = $json.'new-reg' -replace 'new-reg', 'reg/'
$Directory.newAuthz = $json.'new-authz'
$Directory.authz = $json.'new-authz' -replace 'new-authz', 'authz/'
$Directory.newOrder = $json.'new-cert'
$Directory.order = $json.'new-cert' -replace 'new-cert', 'cert/'
$Directory.keyChange = $json.'key-change'
$Directory.revokeCert = $json.'revoke-cert'
$Directory.termsOfService = $json.meta.'terms-of-service'
} else {
$json.psobject.properties|% {$Directory[$_.Name] = $_.Value }
}
$Directory
}
function Get-PrivateKey([string] $Name, [int] $Size = 4096, [System.Security.Cryptography.CngAlgorithm] $Algorithm, [System.Security.Cryptography.CngKeyUsages] $KeyUsage = [System.Security.Cryptography.CngKeyUsages]::Signing, [System.Security.Cryptography.CngExportPolicies] $ExportPolicy = [System.Security.Cryptography.CngExportPolicies]::None) {
switch ($Algorithm.Algorithm) {
"RSA" {
[type] $RetType = [System.Security.Cryptography.RSACng]
}
"ECDSA_P256" {
$Size = 256
[type] $RetType = [System.Security.Cryptography.ECDsaCng]
}
"ECDSA_P384" {
$Size = 384
[type] $RetType = [System.Security.Cryptography.ECDsaCng]
}
}
if ($ResetRegistration -and [System.Security.Cryptography.CngKey]::Exists($Name)) {
[System.Security.Cryptography.CngKey]::Open($Name).Delete()
}
if ([System.Security.Cryptography.CngKey]::Exists($Name)) {
New-Object -TypeName $RetType.FullName -ArgumentList ([System.Security.Cryptography.CngKey]::Open($Name))
} else {
[System.Security.Cryptography.CngKeyCreationParameters] $keyCreationParams = New-Object System.Security.Cryptography.CngKeyCreationParameters -Property @{
"ExportPolicy" = $ExportPolicy;
"KeyUsage" = $KeyUsage;
}
$keyCreationParams.Parameters.Add([System.Security.Cryptography.CngProperty](New-Object System.Security.Cryptography.CngProperty "Length", ([BitConverter]::GetBytes($Size)), ([System.Security.Cryptography.CngPropertyOptions]::None)))
New-Object -TypeName $RetType.FullName -ArgumentList ([System.Security.Cryptography.CngKey]::Create($Algorithm, $Name, $keyCreationParams))
}
}
function Get-ACMEPrivateKeyThumbprint {
$export = $AccountKey.ExportParameters($false)
switch ($AccountKey.Key.Algorithm.Algorithm) {
"RSA" { [string] $j = '{"e":"' + (Encode-UrlBase64 -Bytes $export.Exponent) + '","kty":"RSA","n":"' + (Encode-UrlBase64 -Bytes $export.Modulus) + '"}' }
"ECDSA_P256" { [string] $j = '{"crv":"P-256","kty":"EC","x":"' + (Encode-UrlBase64 -Bytes $export.Q.X) + '","y":"' + (Encode-UrlBase64 -Bytes $export.Q.Y) + '"}' }
"ECDSA_P384" { [string] $j = '{"crv":"P-384","kty":"EC","x":"' + (Encode-UrlBase64 -Bytes $export.Q.X) + '","y":"' + (Encode-UrlBase64 -Bytes $export.Q.Y) + '"}' }
}
Encode-UrlBase64 -Bytes (([System.Security.Cryptography.SHA256Cng]::Create()).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($j)))
}
function Get-CngPrivateKeyFromCertificate([Parameter(Mandatory = $true, ValueFromPipeline = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2] $Cert) {
# well, by now it should be obvious whats going on here
# feel free to test it with:
# gci cert:\CurrentUser\my | Get-CngPrivateKeyFromCertificate
Begin {
if (-not ("WINAPI.crypt32" -as [type])) {
Add-Type -Namespace WINAPI -Name crypt32 -MemberDefinition @"
[DllImport("crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptAcquireCertificatePrivateKey(
IntPtr pCert,
uint dwFlags,
IntPtr pvReserved, // must be null
[Out] out Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle phCryptProvOrNCryptKey,
[Out] out int dwKeySpec,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
"@
}
}
Process {
[IntPtr] $handle = $Cert.Handle
[Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle] $key = $null
[int] $keySpec = 0
[bool] $free = $false
[bool] $ret = [WINAPI.crypt32]::CryptAcquireCertificatePrivateKey($handle, 0x00040000 <#CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG#>, 0, [ref]$key, [ref]$keySpec, [ref]$free)
if (-not $ret) { throw "Can't acquire NCRYPT private key" }
[System.Security.Cryptography.CngKey] $cngkey = [System.Security.Cryptography.CngKey]::Open($key, [System.Security.Cryptography.CngKeyHandleOpenOptions]::None)
if ($cngkey -eq $null) { throw "Can't acquire private CngKey" }
$cngkey
}
}
function ConvertTo-PEM([Parameter(Mandatory = $true, ValueFromPipeline = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2] $Cert, [Switch] $Public, [Switch] $Private) {
if ($Public) {
Format-Pem -Bytes ($Cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)) -Header "CERTIFICATE"
}
if ($Private) {
if (-not $Cert.HasPrivateKey) {throw "Can't get private key"}
$key = $Cert.PrivateKey
if ($key -eq $null) {
$key = Get-CngPrivateKeyFromCertificate -Cert $Cert
switch ($key.AlgorithmGroup.AlgorithmGroup) {
RSA { ConvertRSATo-Pem -PrivateKey (New-Object -TypeName System.Security.Cryptography.RSACng -ArgumentList ($key)) }
ECDSA { ConvertECDsaTo-Pem -PrivateKey (New-Object -TypeName System.Security.Cryptography.ECDsaCng -ArgumentList ($key)) }
ECDH { Write-Host " ! Exports of EC Certificates in PEM format isn't supported on your system." }
}
} else { ConvertRSATo-Pem -PrivateKey $key }
}
}
function Format-Pem([byte[]]$Bytes, [string]$Header) {
[string] $out = ""
if ($Header.Length) {
$out += "-----BEGIN $($Header)-----`n"
}
[string] $base64 = [System.Convert]::ToBase64String($Bytes)
for ([int] $i = 0; $i -lt $base64.Length; $i += 64) {
$out += $base64.Substring($i, [System.Math]::Min(64, $base64.Length - $i)) + "`n"
}
if ($Header.Length) {
$out += "-----END $($Header)-----"
}
$out
}
function ConvertRSATo-Pem([System.Security.Cryptography.RSA] $PrivateKey) {
[System.Security.Cryptography.RSAParameters] $params = $PrivateKey.ExportParameters($true)
Format-Pem -Bytes (
(Encode-ASN1Sequence (
(Encode-ASN1Integer 0), # version
(Encode-ASN1Integer $params.Modulus),
(Encode-ASN1Integer $params.Exponent),
(Encode-ASN1Integer $params.D),
(Encode-ASN1Integer $params.P),
(Encode-ASN1Integer $params.Q),
(Encode-ASN1Integer $params.DP),
(Encode-ASN1Integer $params.DQ),
(Encode-ASN1Integer $params.InverseQ)
))) -Header "RSA PRIVATE KEY"
}
function ConvertECDsaTo-Pem([System.Security.Cryptography.ECDsa] $PrivateKey) {
[System.Security.Cryptography.ECParameters] $params = $PrivateKey.ExportParameters($true)
if ($params.D -eq $null) {throw "Can't get private key"}
<#
ECPrivateKey ::= SEQUENCE {
version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
privateKey OCTET STRING, $params.D
parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
publicKey [1] BIT STRING OPTIONAL CompressingOption, $params.Q.X, $params.Q.Y
}
#>
Format-Pem -Bytes (
(Encode-ASN1Sequence (
(Encode-ASN1Integer 1), # version
(Encode-ASN1OctetString $params.D), # privateKey
(Encode-ASN1Choice 0 (
[System.Security.Cryptography.CryptoConfig]::EncodeOID(([System.Security.Cryptography.Oid]($PrivateKey.Key.Algorithm.Algorithm)).Value))), # parameters / curve oid
(Encode-ASN1Choice 1 (
Encode-ASN1BitString (([byte[]]0x04) + $params.Q.X + $params.Q.Y))) # 0x04 uncompressed ECPoint, publicKey
))) -Header "EC PRIVATE KEY"
}
function Encode-ASN1OctetString([byte[]] $Data) {
[byte[]] $ret = (4)
$ret += Encode-ASN1ByteLength $Data.Count
$ret += $Data
$ret
}
function Encode-ASN1Integer([Parameter(Position = 0, ParameterSetName = 'Int')] [int] $Data, [Parameter(Position = 0, ParameterSetName = 'Bytes')] [byte[]] $Bytes) {
if ($PSCmdlet.ParameterSetName -eq 'Int') {
[byte[]] $val = [System.BitConverter]::GetBytes($Data)
if ([System.BitConverter]::IsLittleEndian) {[array]::Reverse($val)}
} else {
[byte[]] $val = $Bytes
}
[int] $leftPadLen = 0
for ([int] $i = 0; $i -lt $val.Count -and $val[$i] -eq 0; $i+=1) { $leftPadLen++ }
[byte[]] $trimed = $val|select -Skip $leftPadLen
[byte[]] $filtered = $val|? { $_ -eq 0}
if ($filtered -ne $null -and $filtered.Count -eq $val.Count) { # $val is array of 0
[byte[]] $sanitized = ([byte]0x0)
} else {
if ($trimed[0] -gt 0x7f) {
[byte[]] $sanitized = ([byte]0x0)
$sanitized += $trimed
} else {
[byte[]] $sanitized = $trimed
}
}
[byte[]] $ret = (2)
$ret += Encode-ASN1ByteLength -Length $sanitized.Count
$ret += $sanitized
$ret
}
function Encode-ASN1Sequence([byte[][]] $Data){
[byte[]] $ret = (0x30)
$ret += Encode-ASN1ByteLength -Length ($Data|ForEach-Object -Begin {$i=0} -Process {$i+=([byte[]]$_).Count} -End {$i})
for ([int] $i = 0; $i -lt $Data.Count; $i++) {
$ret += $Data[$i]
}
$ret
}
function Encode-ASN1BitString([byte[]] $Data){
[byte[]] $ret = (0x03)
$ret += Encode-ASN1ByteLength ($Data.Count + 1)
$ret += 0x00 # number of padded bits (our bytes are always 8-based in length)
$ret += $Data
$ret
}
function Encode-ASN1Choice([int] $Value, [byte[]] $Data){
[byte[]] $ret = ((0xA0 -bor $Value))
$ret += Encode-ASN1ByteLength -Length $Data.Count
$ret += $Data
$ret
}
function Encode-ASN1ByteLength([int] $Length) {
if ($Length -lt 128) {
# Short form
[byte[]] $ret = ([byte] $Length)
} else {
# Long form
[int] $req = 0
[int] $t = $Length
while ($t -gt 0) {
$t = Shift-Right $t 8
$req++
}
[byte[]] $ret = (([byte]$req) -bor 0x80)
for ([int] $i = $req -1; $i -ge 0; $i--) {
$ret += [byte]((Shift-Right $Length (8*$i)) -band 0xff)
}
}
$ret
}
function Shift-Right([int] $Value, [int]$Count = 1) {
[math]::Floor($Value * [math]::Pow(2, $Count * -1))
}
function Get-AccountConfig {
Get-Content -Path $AccountConfig | ConvertFrom-Json | ConvertTo-Hashtable
}
function Verify-ACMELicense {
[String] $License = $Directory.termsOfService
if ($License -eq "") {return}
if ($AccountConfig.Exists) {
$config = Get-AccountConfig
if ($config.agreement -ne $License) {
if ($AcceptTerms) {
$config.agreement = $License
Update-ACMERegistration -Config $config
} else {
die -Message "The terms of service changed.`nTo use this certificate authority you have to agree to their terms of service which you can find here: $License`nTo accept these terms of service use -AcceptTerms."
}
}
} elseif (!$AcceptTerms) {
die -Message "To use this certificate authority you have to agree to their terms of service which you can find here: $License`nTo accept these terms of service use -AcceptTerms."
}
}
function Verify-ACMERegistration {
if (-not $AccountConfig.Exists -or $ResetRegistration) {
return Create-ACMERegistration
}
# check $Email for changes
if ($Email -ne $null) {
$config = Get-AccountConfig
if (-not (Compare-Lists $Email $config.contact)) {
$config.contact = $Email
return Update-ACMERegistration -Config $config
}
}
if ($RenewRegistration) {
return Update-ACMERegistration
}
}
function Create-ACMERegistration([hashtable] $Config) {
try {
$req = @{ agreement = $Directory.termsOfService; }
if ($Config -ne $null -and $Config.contact -ne $null) {
$req.contact = $Config.contact
} elseif ($Email -ne $null) {
$req.contact = $Email
}
$resp = Invoke-SignedWebRequest -Uri $Directory.newAccount -Resource new-reg -Payload $req
} catch {
switch ($_.Exception.Message) {
'invalidEmail' {
if ($AutoFix) {
Write-Host " ! AutoFix: removing Contact from request. You will not receive notifications!"
$Config.contact = $null
Update-ACMERegistration $Config
Write-Host " + AutoFix: successful"
return
}
die -Message "Email domain verification failed! Check your email address!"
}
'malformed' { # AccountKey is assigned to different account; possible reason I can think of: (re)moved/deleted account file/directory => only rescue would be creation of new account
if ($AutoFix) {
Write-Host " ! AutoFix: applying -ResetRegistration and recreating AccountKey"
$AutoFix = $false # disable due to recursive loop
[System.Security.Cryptography.CngKey]::Open($AccHash).Delete()
$AccountKey = Get-RSACng -Name $AccHash
Create-ACMERegistration $Config
$AutoFix = $true
Write-Host " + AutoFix: successful"
return
}
die -Message "Local account data is corrupt. Please recreate account with -ResetRegistration"
}
}
die -Exception $_
}
$resp.agreement = $Directory.termsOfService
$resp | ConvertTo-Json -Compress | Out-File -FilePath $AccountConfig
}
function Update-ACMERegistration($Config = (Get-AccountConfig)) {
try {
$resp = Invoke-SignedWebRequest -Uri ($Directory.account + $Config.id) -Resource reg -Payload $Config
} catch {
switch ($_.Exception.Message) {
'invalidEmail' {
if ($AutoFix) {
Write-Host " ! AutoFix: removing Contact from request. You will not receive notifications!"
$Config.contact = $null
Update-ACMERegistration $Config
Write-Host " + AutoFix: successful"
return
}
die -Message "Email domain verification failed! Check your email address!"
}
'malformed' { # id in url is missing or -lt 0; possible reason I can think of: (re)moved account file => only rescue would be creation of new account
if ($AutoFix) {
Write-Host " ! AutoFix: applying -ResetRegistration and recreating account"
Create-ACMERegistration $Config
Write-Host " + AutoFix: successful"
return
}
die -Message "Local account data is corrupt. Please recreate account with -ResetRegistration"
}
'unauthorized' { # wrong account key; maybe copied account directory to different server or runs in different user context?
if ($AutoFix) {
Write-Host " ! AutoFix: applying -ResetRegistration and recreating account"
Create-ACMERegistration $Config
Write-Host " + AutoFix: successful"
return
}
die -Message "Local account data is corrupt. Please recreate account with -ResetRegistration"
}
}
die -Exception $_
}
$resp | ConvertTo-Json -Compress | Out-File -FilePath $AccountConfig
}
function Encode-UrlBase64 {
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='String')]
[String] $String,
[Parameter(Mandatory=$true, ValueFromPipeline=$false, ParameterSetName='Bytes')]
[byte[]] $Bytes,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Object')]
[hashtable] $Object
)
if ($PSCmdlet.ParameterSetName -eq 'Object') {
[byte[]] $Bytes = [System.Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $Object -Compress))
} elseif ($PSCmdlet.ParameterSetName -eq 'String') {
[byte[]] $Bytes = [System.Text.Encoding]::UTF8.GetBytes($String)
}
[Convert]::ToBase64String($Bytes).TrimEnd("=").Replace('+', '-').Replace('/', '_')
}
function Decode-UrlBase64 {
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='String')]
[String] $Value,
[Switch] $AsString,
[Switch] $AsObject
)
if ($Value.Length % 4 -gt 0) {
$Value = $Value + ('=' * (4 - ($Value.Length % 4)))
}
$Value = $Value.Replace('-', '+').Replace('_', '/')
[byte[]] $Bytes = [Convert]::FromBase64String($Value)
if ($AsString) {
[System.Text.Encoding]::UTF8.GetString($Bytes)
} elseif ($AsObject) {
ConvertFrom-Json -InputObject ([System.Text.Encoding]::UTF8.GetString($Bytes))
} else {
$Bytes
}
}
function ConvertTo-Hashtable([Parameter(Mandatory=$true, ValueFromPipeline=$true)] $Object) {
$Object.psobject.Properties|% -Begin {[hashtable] $h = @{}} -Process { $h[$_.Name] = $_.Value } -End { $h }
}
function Compare-Lists([array] $a = $null, [array] $b = $null) {
if ($a -eq $null -and $b -eq $null) { return $true } # both are $null
if ($a -eq $null -or $b -eq $null) { return $false } # only one of them $null?
$a = $a|% {return $_.ToLower()}
$b = $b|% {return $_.ToLower()}
if ($a.Count -ne $b.Count) { return $false }
for ([int] $i = 0; $i -lt $a.Count; $i++) {
if ($a.IndexOf($b[$i]) -eq -1 -or $b.IndexOf($a[$i]) -eq -1) {
return $false
}
}
$true
}
function Verify-Certificate([String] $Domain, [String[]] $SAN) {
if ($ResetRegistration -or $RenewCertificate -or $RecreateCertificate) { return $false }
[System.Security.Cryptography.X509Certificates.X509Certificate2] $cert = Get-LastCertificate -Domain $Domain -SAN $SAN
if ($cert -eq $null) {
Write-Host " ! Can't find existing certificate. Creating new..."
return $false
}
Write-Host " + Checking expire date of existing cert..."
Write-Host " + Valid till $($cert.NotAfter) " -NoNewline
[System.DateTime] $offDate = (Get-Date).AddDays($RenewDays)
if ($cert.NotAfter -gt $offDate) {
Write-Host "(Longer than $(($cert.NotAfter - $offDate).Days) days)."
} else {
Write-Host "(Less than $(($cert.NotAfter - $offDate).Days) days). Renewing!"
return $false
}
# passed all checks
return $true
}
function Get-CertificateFriendlyName([String] $Domain) { "$($Domain) - $($AccHash)" }
function Get-CertificateAlternateDomainNames([Parameter(Mandatory = $true, ValueFromPipeline = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2] $Cert) {
if (($Cert | Get-Member -Name DnsNameList) -ne $null -and $Cert.DnsNameList -ne $null -and $Cert.DnsNameList.Count -gt 0) {
$Cert.DnsNameList|% {$_.ToString()}
} else { # fallback
$Cert.Extensions["2.5.29.17"].Format($false)|% {$_ -split ', '}|? {($_ -split '=')[0] -like '*DNS*'}|% {($_ -split '=')[1]}
}
}
function Get-LastCertificate([String] $Domain, [string[]] $SAN) {
[string[]] $DnsNameList = ($Domain)
if ($SAN -ne $null) { $DnsNameList += $SAN }
[System.Security.Cryptography.X509Certificates.X509Certificate2](gci "Cert:\$($Context)\My" |? {
$_.FriendlyName -eq (Get-CertificateFriendlyName $Domain) -and # Domain and CA check
(Compare-Lists (Get-CertificateAlternateDomainNames $_) $DnsNameList) -and # SAN/DnsNamesList check
$_.HasPrivateKey -and
($key = $_ | Get-CngPrivateKeyFromCertificate) -ne $null -and # PK check
$key.Algorithm.Algorithm.Replace("ECDH_", "ECDSA_") -eq $KeyAlgo.Algorithm -and # PK ExchAlgo check (global input)
# In Win7/2012R2 ECDSA_* keys will show up as ECDH_* - and also I can't export the private keys in pem format
# I don't know yet if I can fix that
($KeyAlgo -ne [System.Security.Cryptography.CngAlgorithm]::Rsa -or $key.KeySize -eq $KeySize) -and # Rsa PK size check (global input)
($_.Extensions["1.3.6.1.5.5.7.1.24"] -ne $null) -eq $OcspMustStaple # OcspMustStaple
} | Sort-Object -Property NotAfter -Descending | Select-Object -First 1)
}
function Get-CertificateIssuerCertificate([Parameter(Mandatory = $true, ValueFromPipeline = $true)][System.Security.Cryptography.X509Certificates.X509Certificate2] $Cert) {
# $issuerUrl = ($Cert.Extensions|? {$_.Oid.Value -eq "1.3.6.1.5.5.7.1.1"}).RawData|Decode-ASN1Sequence|? {($_|Decode-ASN1Sequence)[0].IsCAIssuer}|% {($_|Decode-ASN1Sequence)[1]|Decode-ASN1String}
[System.Security.Cryptography.X509Certificates.X509Extension] $oid = $Cert.Extensions["1.3.6.1.5.5.7.1.1"]
if ($oid -eq $null) { return }
[string] $CaInfo = $oid.Format($false)
if ($CaInfo.IndexOf("(1.3.6.1.5.5.7.48.2)") -eq -1) { return }
[int] $i = $CaInfo.IndexOf("URL=", $CaInfo.LastIndexOf("(1.3.6.1.5.5.7.48.2)")) +4
[uri] $uri = $CaInfo.Substring($i, [System.Math]::Min($CaInfo.Length, $(if ($CaInfo.IndexOf(",", $i) -ne -1) { $CaInfo.IndexOf(",", $i) } else { $CaInfo.Length })) - $i)
$resp = Invoke-WebRequest -UseBasicParsing -Uri $uri -Method Get
if ($resp.StatusCode -ne 200) { return }
New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList ($resp.Content, "")
}
function Sign-Domain([String] $Domain, [String[]] $SAN) {
Verify-ACMEAuthorization $Domain
if ($SAN -ne $null) { $SAN |% { Verify-ACMEAuthorization $_ } }
[System.Security.Cryptography.X509Certificates.X509Certificate2] $OldCert = Get-LastCertificate -Domain $Domain -SAN $SAN
if ($RecreateCertificate -or $OldCert -eq $null) {
Create-Certificate -Domain $Domain -SAN $SAN
} else {
Renew-Certificate -OldCert $OldCert
}
}
function Verify-ACMEAuthorization([String] $Domain) {
Write-Host " + Requesting challenge for $($Domain)..."
$challenges = (Invoke-SignedWebRequest -Uri $Directory.newAuthz -Resource "new-authz" -Payload @{
"identifier" = @{
"type" = "dns";
"value" = $Domain;
}
}).challenges
if (($challenges|? {$_.status -eq "valid"}) -ne $null) { # any valid challange is ok
Write-Host " + Already validated!"
return
}
$challenge = $challenges|? {$_.type -eq $ChallengeType}
if ($challenge.status -ne "pending") { die -Message "Challenge status is '$($challenge.status)'. Can't continue!" }
[string] $keyAuthorization = "$($challenge.token).$(Get-ACMEPrivateKeyThumbprint)"
switch ($ChallengeType) {
'http-01' { &$onChallenge "$($Domain)" "$($challenge.token)" "$($keyAuthorization)" | Write-Host }
'dns-01' {
[string] $dnsAuthorization = Encode-UrlBase64 -Bytes ([System.Security.Cryptography.SHA256Cng]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($keyAuthorization)))
[string] $dnsChallengeDN = "_acme-challenge.$($Domain)"
&$onChallenge "$($Domain)" "$($dnsChallengeDN)" "$($dnsAuthorization)" | Write-Host
if (-not $NoDnsTest) {
if ((Get-Command -Verb Resolve -Noun DnsName) -ne $null) {
Write-Host "Testing DNS record"
[string[]] $dnsServer = '8.8.8.8', '8.8.4.4' # use public servers
if (($rec = Resolve-DnsName -Name $dnsChallengeDN -Type TXT -Server $dnsServer -NoHostsFile -DnsOnly -ErrorAction SilentlyContinue) -eq $null -and ($Error|Select-Object -First 1).CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::OperationTimeout) {$dnsServer = @()} # can't reach dns server => reset to default
while ((($rec = Resolve-DnsName -Name $dnsChallengeDN -Type TXT -Server $dnsServer -NoHostsFile -DnsOnly -ErrorAction SilentlyContinue) -eq $null -and ($Error|Select-Object -First 1).CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::ResourceUnavailable) -or # NXDOMAIN
($rec -ne $null -and (($rec = $rec|? {$_ -is [Microsoft.DnsClient.Commands.DnsRecord_TXT]}|% {$_.Text}|? {$_ -eq $dnsAuthorization}) -eq $null -or $rec.Length -eq 0))) { # found TXT but not the right one
Write-Host -NoNewline "." # show some progress
Start-Sleep -Seconds 3 # be patient
}
Write-Host " "
}
}
}
'tls-sni-01' {
[string] $sniAuthorization = [System.BitConverter]::ToString([System.Security.Cryptography.SHA256Cng]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($keyAuthorization))).Replace('-','').ToLower()
[string] $sniFqdn = "$($sniAuthorization.Substring(0, 32)).$($sniAuthorization.Substring(32, 32)).acme.invalid"
[System.Security.Cryptography.X509Certificates.X509Certificate2] $sniCert = Create-Certificate -Domain $sniFqdn -SelfSigned
&$onChallenge "$($Domain)" "$sniFqdn" $sniCert | Write-Host
}
}
Write-Host " + Responding to challenge for $($Domain)..."
$resp = Invoke-SignedWebRequest -Uri $challenge.uri -Resource 'challenge' -Payload @{
"keyAuthorization" = $keyAuthorization;
}
while ($resp.status -eq "pending") {
Start-Sleep -Seconds 1
$resp = (Invoke-WebRequest -Uri $challenge.uri -Method Get -UseBasicParsing).Content|ConvertFrom-Json
}
switch ($ChallengeType) {
'http-01' { &$onChallengeCleanup "$($Domain)" "$($challenge.token)" "$($keyAuthorization)" "$($resp.status)" | Write-Host }
'dns-01' { &$onChallengeCleanup "$($Domain)" "_acme-challenge.$($Domain)" "$($dnsAuthorization)" "$($resp.status)" | Write-Host }
'tls-sni-01' { &$onChallengeCleanup "$($Domain)" "$sniFqdn" $sniCert "$($resp.status)" | Write-Host }
}
if ($resp.status -eq "valid") {
Write-Host " + Challenge is valid!"
} elseif ($resp.status -eq "invalid") {
die -Message ("Challenge is invalid`n" + " ! Error[$($resp.error.type.Split(':')|Select-Object -Last 1)]: $($resp.error.detail)")
}
}
function Create-Certificate([String] $Domain, [String[]] $SAN, [Switch] $SelfSigned) {
# setup defaults
[int] $Size = $KeySize
[string] $HashAlgo = "SHA256"
$algoId = New-Object -ComObject X509Enrollment.CObjectId
# set crypto specific settings
switch ($KeyAlgo) {
([System.Security.Cryptography.CngAlgorithm]::Rsa) {
$algoId.InitializeFromAlgorithmName(3 <#XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID#>, 0 <#XCN_CRYPT_OID_INFO_PUBKEY_ANY#>, 0 <#AlgorithmFlagsNone#>, "RSA")
}
([System.Security.Cryptography.CngAlgorithm]::ECDsaP256) {
$algoId.InitializeFromAlgorithmName(3 <#XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID#>, 0 <#XCN_CRYPT_OID_INFO_PUBKEY_ANY#>, 0 <#AlgorithmFlagsNone#>, "ECDSA_P256")
$Size = 256
}
([System.Security.Cryptography.CngAlgorithm]::ECDsaP384) {
$algoId.InitializeFromAlgorithmName(3 <#XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID#>, 0 <#XCN_CRYPT_OID_INFO_PUBKEY_ANY#>, 0 <#AlgorithmFlagsNone#>, "ECDSA_P384")
$Size = 384
$HashAlgo = "SHA384"
}
}
Write-Host " + Creating request: ExchangeAlgorithm: $($KeyAlgo.Algorithm), KeySize: $($Size), HashAlgorithm: $($HashAlgo), OCSP-MustStaple: $(if($OcspMustStaple){"On"}else{"Off"})"
# create Key with CertEnroll API
$pk = New-Object -ComObject X509Enrollment.CX509PrivateKey -Property @{
Length = $Size;
ProviderName = "Microsoft Software Key Storage Provider";
ExportPolicy = ( # request for discussion!
1 -bor # XCN_NCRYPT_ALLOW_EXPORT_FLAG
2 -bor # XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG
4 -bor # XCN_NCRYPT_ALLOW_ARCHIVING_FLAG
8 # XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG
);
KeySpec = 1; # XCN_AT_KEYEXCHANGE
KeyUsage = (
1 -bor # XCN_NCRYPT_ALLOW_DECRYPT_FLAG
2 -bor # XCN_NCRYPT_ALLOW_SIGNING_FLAG
4 # XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG
);
Algorithm = $algoId;
MachineContext = ($Context -eq [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine);
}
$pk.Create()
# create request object
$request = if ($SelfSigned) { New-Object -ComObject X509Enrollment.CX509CertificateRequestCertificate }
else { New-Object -ComObject X509Enrollment.CX509CertificateRequestPkcs10 }
$request.InitializeFromPrivateKey($(
if ($Context -eq [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) {
3 # ContextAdministratorForceMachine
} else {
1 # ContextUser
}
), $pk, "")
$request.SuppressDefaults = $true
# add Subject
$dn = New-Object -ComObject X509Enrollment.CX500DistinguishedName
$dn.Encode("CN=$($Domain)", 0) # XCN_CERT_NAME_STR_NONE = 0
$request.Subject = $dn
# sha256/384 signature
$hashId = New-Object -ComObject X509Enrollment.CObjectId
$hashId.InitializeFromValue(([System.Security.Cryptography.Oid]$HashAlgo).Value)
$request.HashAlgorithm = $hashId
# Key Usage
$extKeyUsage = New-Object -ComObject X509Enrollment.CX509ExtensionKeyUsage
$extKeyUsage.InitializeEncode([int][System.Security.Cryptography.X509Certificates.X509KeyUsageFlags](("DigitalSignature", "KeyEncipherment")))
$extKeyUsage.Critical = $true
$request.X509Extensions.Add($extKeyUsage)
# add extensions
$objectIds = New-Object -ComObject X509Enrollment.CObjectIds
# Serverauthentifizierung, Clientauthentifizierung
# Can't work with common friendly names because they vary based on your systems language.... WAT?
"1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"|% {
$objectId = New-Object -ComObject X509Enrollment.CObjectId
$objectId.InitializeFromValue($_)
$objectIds.Add($objectId)