DSCResources/DSC_CertReq/DSC_CertReq.psm1

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
#Requires -Version 4.0

$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'

# Import the Certificate PDT Helper Module
Import-Module -Name (Join-Path -Path $modulePath `
        -ChildPath (Join-Path -Path 'CertificateDsc.PDT' `
            -ChildPath 'CertificateDsc.PDT.psm1'))

# Import the Certificate Resource Common Module.
Import-Module -Name (Join-Path -Path $modulePath `
        -ChildPath (Join-Path -Path 'CertificateDsc.Common' `
            -ChildPath 'CertificateDsc.Common.psm1'))

Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common')

# Import Localization Strings.
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'

<#
    .SYNOPSIS
        Returns the current state of the certificate that may need to be requested.
 
    .PARAMETER Subject
        Provide the text string to use as the subject of the certificate.
 
    .PARAMETER CAServerFQDN
        The FQDN of the Active Directory Certificate Authority on the local area network.
 
    .PARAMETER CARootName
        The name of the certificate authority, by default this will be in format domain-servername-ca.
 
    .PARAMETER KeyLength
        The bit length of the encryption key to be used.
 
    .PARAMETER Exportable
        The option to allow the certificate to be exportable, by default it will be true.
 
    .PARAMETER ProviderName
        The selection of provider for the type of encryption to be used.
 
    .PARAMETER OID
        The Object Identifier that is used to name the object.
 
    .PARAMETER KeyUsage
        The Keyusage is a restriction method that determines what a certificate can be used for.
 
    .PARAMETER CertificateTemplate
        The template used for the definiton of the certificate.
 
    .PARAMETER SubjectAltName
        The subject alternative name used to creat ethe certificate.
 
    .PARAMETER Credential
        The `PSCredential` object containing the credentials that will be used to access the template in the Certificate Authority.
 
    .PARAMETER AutoRenew
        Determines if the resource will also renew a certificate within 7 days of expiration.
 
    .PARAMETER CAType
        The type of CA in use, Standalone/Enterprise.
 
    .PARAMETER CepURL
        The URL to the Certification Enrollment Policy Service.
 
    .PARAMETER CesURL
        The URL to the Certification Enrollment Service.
 
    .PARAMETER UseMachineContext
        Determines if the machine should be impersonated for a request. Used for templates like Domain Controller Authentication
 
    .PARAMETER FriendlyName
        Specifies a friendly name for the certificate.
 
    .PARAMETER KeyType
        Specifies if the key type should be RSA or ECDH, defaults to RSA.
 
    .PARAMETER RequestType
        Specified if the request type should be CMC or PKCS10, deafults to CMC.
#>

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Subject,

        [Parameter()]
        [System.String]
        $CAServerFQDN,

        [Parameter()]
        [System.String]
        $CARootName,

        [Parameter()]
        [ValidateSet('192', '224', '256', '384', '521', '1024', '2048', '4096', '8192')]
        [System.String]
        $KeyLength = '2048',

        [Parameter()]
        [System.Boolean]
        $Exportable = $true,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $ProviderName = 'Microsoft RSA SChannel Cryptographic Provider',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $OID = '1.3.6.1.5.5.7.3.1',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $KeyUsage = '0xa0',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CertificateTemplate = 'WebServer',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $SubjectAltName,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $Credential,

        [Parameter()]
        [System.Boolean]
        $AutoRenew,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CAType = 'Enterprise',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CepURL,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CesURL,

        [Parameter()]
        [System.Boolean]
        $UseMachineContext,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName,

        [Parameter()]
        [ValidateSet('RSA', 'ECDH')]
        [System.String]
        $KeyType = 'RSA',

        [Parameter()]
        [ValidateSet('CMC', 'PKCS10')]
        [System.String]
        $RequestType = 'CMC'
    )

    Assert-ResourceProperty -KeyLength $KeyLength -KeyType $KeyType

    # The certificate authority, accessible on the local area network
    if ([string]::IsNullOrWhiteSpace($CAServerFQDN) -or [string]::IsNullOrWhiteSpace($CARootName))
    {
        $caObject = Find-CertificateAuthority
        $CARootName = $caObject.CARootName
        $CAServerFQDN = $caObject.CAServerFQDN
    }

    $ca = "$CAServerFQDN\$CARootName"

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.GettingCertReqStatusMessage -f $Subject, $CA, $FriendlyName, $CertificateTemplate)
        ) -join '' )

    # If the Subject does not contain a full X500 path, construct just the CN
    if (($Subject.split('=').Count) -eq 1)
    {
        $Subject = "CN=$Subject"
    } # if

    $cert = Get-ChildItem -Path Cert:\LocalMachine\My |
        Where-Object -FilterScript {
            (Compare-CertificateSubject -ReferenceSubject $_.Subject -DifferenceSubject $Subject) -and `
            (Compare-CertificateIssuer -Issuer $_.Issuer -CARootName $CARootName) -and `
            (Get-CertificateTemplateName -Certificate $PSItem) -eq $CertificateTemplate -and `
            $_.FriendlyName -eq $FriendlyName
        }

    # If multiple certs have the same subject, issuer, friendly name and template, return the newest
    $cert = $cert |
        Sort-Object -Property NotBefore -Descending |
            Select-Object -First 1

    if ($cert)
    {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.CertificateExistsMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate, $certificate.Thumbprint)
            ) -join '' )

        $returnValue = @{
            Subject             = Get-CertificateCommonName -DistinguishedName $Cert.Subject
            CAServerFQDN        = $caObject.CAServerFQDN
            CARootName          = Get-CertificateCommonName -DistinguishedName $Cert.Issuer
            KeyLength           = $Cert.Publickey.Key.KeySize
            Exportable          = $Cert.PrivateKey.CspKeyContainerInfo.Exportable
            ProviderName        = $Cert.PrivateKey.CspKeyContainerInfo.ProviderName
            OID                 = $null # This value can't be determined from the cert
            KeyUsage            = $null # This value can't be determined from the cert
            CertificateTemplate = Get-CertificateTemplateName -Certificate $Cert
            SubjectAltName      = Get-CertificateSubjectAlternativeName -Certificate $Cert
            FriendlyName        = $Cert.FriendlyName
        }
    }
    else
    {
        $returnValue = @{ }
    }

    $returnValue
} # end function Get-TargetResource

<#
    .SYNOPSIS
        Requests a new certificate based on the parameters provided.
 
    .PARAMETER Subject
        Provide the text string to use as the subject of the certificate.
 
    .PARAMETER CAServerFQDN
        The FQDN of the Active Directory Certificate Authority on the local area network.
 
    .PARAMETER CARootName
        The name of the certificate authority, by default this will be in format domain-servername-ca.
 
    .PARAMETER KeyLength
        The bit length of the encryption key to be used.
 
    .PARAMETER Exportable
        The option to allow the certificate to be exportable, by default it will be true.
 
    .PARAMETER ProviderName
        The selection of provider for the type of encryption to be used.
 
    .PARAMETER OID
        The Object Identifier that is used to name the object.
 
    .PARAMETER KeyUsage
        The Keyusage is a restriction method that determines what a certificate can be used for.
 
    .PARAMETER CertificateTemplate
        The template used for the definiton of the certificate.
 
    .PARAMETER SubjectAltName
        The subject alternative name used to creat ethe certificate.
 
    .PARAMETER Credential
        The `PSCredential` object containing the credentials that will be used to access the template in the Certificate Authority.
 
    .PARAMETER AutoRenew
        Determines if the resource will also renew a certificate within 7 days of expiration.
 
    .PARAMETER CAType
        The type of CA in use, Standalone/Enterprise.
 
    .PARAMETER CepURL
        The URL to the Certification Enrollment Policy Service.
 
    .PARAMETER CesURL
        The URL to the Certification Enrollment Service.
 
    .PARAMETER UseMachineContext
        Determines if the machine should be impersonated for a request. Used for templates like Domain Controller Authentication
 
    .PARAMETER FriendlyName
        Specifies a friendly name for the certificate.
 
    .PARAMETER KeyType
        Specifies if the key type should be RSA or ECDH, defaults to RSA.
 
    .PARAMETER RequestType
        Specified if the request type should be CMC or PKCS10, deafults to CMC.
#>

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Subject,

        [Parameter()]
        [System.String]
        $CAServerFQDN,

        [Parameter()]
        [System.String]
        $CARootName,

        [Parameter()]
        [ValidateSet('192', '224', '256', '384', '521', '1024', '2048', '4096', '8192')]
        [System.String]
        $KeyLength = '2048',

        [Parameter()]
        [System.Boolean]
        $Exportable = $true,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $ProviderName = 'Microsoft RSA SChannel Cryptographic Provider',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $OID = '1.3.6.1.5.5.7.3.1',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $KeyUsage = '0xa0',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CertificateTemplate = 'WebServer',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $SubjectAltName,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $Credential,

        [Parameter()]
        [System.Boolean]
        $AutoRenew,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CAType = 'Enterprise',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CepURL,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CesURL,

        [Parameter()]
        [System.Boolean]
        $UseMachineContext,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName,

        [Parameter()]
        [ValidateSet('RSA', 'ECDH')]
        [System.String]
        $KeyType = 'RSA',

        [Parameter()]
        [ValidateSet('CMC', 'PKCS10')]
        [System.String]
        $RequestType = 'CMC'
    )

    Assert-ResourceProperty -KeyLength $KeyLength -KeyType $KeyType

    # The certificate authority, accessible on the local area network
    if ([string]::IsNullOrWhiteSpace($CAServerFQDN) -or [string]::IsNullOrWhiteSpace($CARootName))
    {
        $caObject = Find-CertificateAuthority
        $CARootName = $caObject.CARootName
        $CAServerFQDN = $caObject.CAServerFQDN
    }

    $ca = "$CAServerFQDN\$CARootName"

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.StartingCertReqMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate)
        ) -join '' )

    # If the Subject does not contain a full X500 path, construct just the CN
    if (($Subject.split('=').Count) -eq 1)
    {
        $Subject = "CN=$Subject"
    } # if

    # If we should look for renewals, check for existing certs
    if ($AutoRenew)
    {
        $certs = Get-ChildItem -Path Cert:\LocalMachine\My |
            Where-Object -FilterScript {
                $_.Subject -eq $Subject -and `
                (Compare-CertificateIssuer -Issuer $_.Issuer -CARootName $CARootName) -and `
                    $_.NotAfter -lt (Get-Date).AddDays(30)
            }

        # If multiple certs have the same subject and were issued by the CA and are 30 days from expiration, return the newest
        $firstCert = $certs |
            Sort-Object -Property NotBefore -Descending |
                Select-Object -First 1
        $thumbprint = $firstCert |
            ForEach-Object -Process { $_.Thumbprint }
    } # if

    <#
        Information that will be used in the INF file to generate the certificate request
        In future versions, select variables from the list below could be moved to parameters!
    #>

    $Subject = ConvertTo-StringEnclosedInDoubleQuotes -Value $Subject
    $ProviderName = ConvertTo-StringEnclosedInDoubleQuotes -Value $ProviderName
    $keySpec = '1'
    $machineKeySet = 'TRUE'
    $smime = 'FALSE'
    $privateKeyArchive = 'FALSE'
    $userProtected = 'FALSE'
    $useExistingKeySet = 'FALSE'
    $providerType = '12'

    # A unique identifier for temporary files that will be used when interacting with the command line utility
    $guid = [system.guid]::NewGuid().guid
    $workingPath = Join-Path -Path $env:Temp -ChildPath "CertReq-$guid"
    $infPath = [System.IO.Path]::ChangeExtension($workingPath, '.inf')
    $reqPath = [System.IO.Path]::ChangeExtension($workingPath, '.req')
    $cerPath = [System.IO.Path]::ChangeExtension($workingPath, '.cer')

    # Create INF file
    $requestDetails = @"
[NewRequest]
Subject = $Subject
KeySpec = $keySpec
KeyLength = $KeyLength
Exportable = $($Exportable.ToString().ToUpper())
MachineKeySet = $MachineKeySet
SMIME = $smime
PrivateKeyArchive = $privateKeyArchive
UserProtected = $userProtected
UseExistingKeySet = $useExistingKeySet
ProviderName = $ProviderName
ProviderType = $providerType
RequestType = $RequestType
KeyUsage = $KeyUsage
"@

    if ($FriendlyName)
    {
        $requestDetails += @"
 
FriendlyName = "$FriendlyName"
"@

    }

    if ($thumbprint)
    {
        $requestDetails += @"
 
RenewalCert = $Thumbprint
"@

    }

    $requestDetails += @"
 
[RequestAttributes]
CertificateTemplate = "$CertificateTemplate"
[EnhancedKeyUsageExtension]
OID = $OID
"@

    # If a standalone CA is used certificate templates are not used.
    if ($CAType -ne 'Enterprise')
    {
        $requestDetails = $requestDetails.Replace(@"
[RequestAttributes]
CertificateTemplate = "$CertificateTemplate"
[EnhancedKeyUsageExtension]
"@
, '[EnhancedKeyUsageExtension]')
    }

    if ($PSBoundParameters.ContainsKey('SubjectAltName'))
    {
        # If a Subject Alt Name was specified, add it.
        $requestDetails += @"
 
[Extensions]
2.5.29.17 = "{text}$SubjectAltName"
"@

    }

    Set-Content -Path $infPath -Value $requestDetails

    <#
        Certreq.exe is used to handle the request of the new certificate
        because of the lack of native PowerShell Certificate cmdlets.
        Syntax: https://technet.microsoft.com/en-us/library/cc736326.aspx
        Reference: https://support2.microsoft.com/default.aspx?scid=kb;EN-US;321051
    #>


    # NEW: Create a new request as directed by PolicyFileIn
    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.CreateRequestCertificateMessage -f $infPath, $reqPath)
        ) -join '' )

    <#
        If enrollment server is specified the request will be towards
        the specified URLs instead, using credentials for authentication.
    #>

    if ($Credential -and $CepURL -and $CesURL)
    {
        $credPW = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
        $createRequest = & certreq.exe @(
            '-new', '-q',
            '-username', $Credential.UserName,
            '-p', [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($credPW),
            '-PolicyServer', $CepURL,
            '-config', $CesURL,
            $infPath,
            $reqPath
        )
    }
    else
    {
        $createRequest = & certreq.exe @('-new', '-q', $infPath, $reqPath)
    } # if

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.CreateRequestResultCertificateMessage -f ($createRequest | Out-String))
        ) -join '' )

    <#
        SUBMIT: Submit a request to a Certification Authority.
        DSC runs in the context of LocalSystem, which uses the Computer account in Active Directory
        to authenticate to network resources
        The Credential paramter with PDT is used to impersonate a user making the request
    #>

    if (Test-Path -Path $reqPath)
    {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.SubmittingRequestCertificateMessage -f $reqPath, $cerPath, $ca)
            ) -join '' )

        if ($Credential)
        {
            <#
                If enrollment server is specified the request will be towards
                the specified URLs instead, using credentials for authentication.
            #>

            if ($CepURL -and $CesURL)
            {
                $credPW = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
                $submitRequest = & certreq.exe @(
                    '-submit', '-q',
                    '-username', $Credential.UserName,
                    '-p', [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($credPW),
                    '-PolicyServer', $CepURL,
                    '-config', $CesURL,
                    $reqPath,
                    $cerPath
                )
            }
            else
            {
                <#
                    Assemble the command and arguments to pass to the powershell process that
                    will request the certificate
                #>

                $certReqOutPath = [System.IO.Path]::ChangeExtension($workingPath, '.out')
                $command = "$PSHOME\PowerShell.exe"

                if ($UseMachineContext)
                {
                    $arguments = "-Command ""& $env:SystemRoot\system32\certreq.exe" + `
                        " @('-submit','-q','-adminforcemachine','-config','$ca','$reqPath','$cerPath')" + `
                        " | Set-Content -Path '$certReqOutPath'"""
                }
                else
                {
                    $arguments = "-Command ""& $env:SystemRoot\system32\certreq.exe" + `
                        " @('-submit','-q','-config','$ca','$reqPath','$cerPath')" + `
                        " | Set-Content -Path '$certReqOutPath'"""
                }

                <#
                    This may output a win32-process object, but it often does not because of
                    a timing issue in PDT (the process has often completed before the
                    process can be read in).
                #>

                $null = Start-Win32Process `
                    -Path $command `
                    -Arguments $arguments `
                    -Credential $Credential

                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($script:localizedData.SubmittingRequestProcessCertificateMessage)
                    ) -join '' )

                $null = Wait-Win32ProcessStop `
                    -Path $command `
                    -Arguments $arguments `
                    -Credential $Credential

                if (Test-Path -Path $certReqOutPath)
                {
                    $submitRequest = Get-Content -Path $certReqOutPath
                    Remove-Item -Path $certReqOutPath -Force
                }
                else
                {
                    New-InvalidOperationException `
                        -Message ($script:localizedData.CertReqOutNotFoundError -f $certReqOutPath)
                } # if
            } # if
        }
        else
        {
            $submitRequest = & certreq.exe @('-submit', '-q', '-config', $CA, $reqPath, $cerPath)
        } # if

        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.SubmittingRequestResultCertificateMessage -f ($submitRequest | Out-String))
            ) -join '' )
    }
    else
    {
        New-InvalidOperationException `
            -Message ($script:localizedData.CertificateReqNotFoundError -f $reqPath)
    } # if

    # ACCEPT: Accept the request
    if (Test-Path -Path $cerPath)
    {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.AcceptingRequestCertificateMessage -f $cerPath, $ca)
            ) -join '' )

        $acceptRequest = & certreq.exe @('-accept', '-machine', '-q', $cerPath)

        if ($acceptRequest -match '0x')
        {
            New-InvalidOperationException -Message ($script:localizedData.GenericError -f ($acceptRequest | Out-String))
        }
        else
        {
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.AcceptingRequestResultCertificateMessage -f ($acceptRequest | Out-String))
                ) -join '' )
        }
    }
    else
    {
        New-InvalidOperationException `
            -Message ($script:localizedData.CertificateCerNotFoundError -f $cerPath)
    } # if

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.CleaningUpRequestFilesMessage -f "$($workingPath).*")
        ) -join '' )
    Remove-Item -Path "$($workingPath).*" -Force
} # end function Set-TargetResource

<#
    .SYNOPSIS
        Tests if a new certificate should be requested.
 
    .PARAMETER Subject
        Provide the text string to use as the subject of the certificate.
 
    .PARAMETER CAServerFQDN
        The FQDN of the Active Directory Certificate Authority on the local area network.
 
    .PARAMETER CARootName
        The name of the certificate authority, by default this will be in format domain-servername-ca.
 
    .PARAMETER KeyLength
        The bit length of the encryption key to be used.
 
    .PARAMETER Exportable
        The option to allow the certificate to be exportable, by default it will be true.
 
    .PARAMETER ProviderName
        The selection of provider for the type of encryption to be used.
 
    .PARAMETER OID
        The Object Identifier that is used to name the object.
 
    .PARAMETER KeyUsage
        The Keyusage is a restriction method that determines what a certificate can be used for.
 
    .PARAMETER CertificateTemplate
        The template used for the definiton of the certificate.
 
    .PARAMETER SubjectAltName
        The subject alternative name used to creat ethe certificate.
 
    .PARAMETER Credential
        The `PSCredential` object containing the credentials that will be used to access the template in the Certificate Authority.
 
    .PARAMETER AutoRenew
        Determines if the resource will also renew a certificate within 7 days of expiration.
 
    .PARAMETER CAType
        The type of CA in use, Standalone/Enterprise.
 
    .PARAMETER CepURL
        The URL to the Certification Enrollment Policy Service.
 
    .PARAMETER CesURL
        The URL to the Certification Enrollment Service.
 
    .PARAMETER UseMachineContext
        Determines if the machine should be impersonated for a request. Used for templates like Domain Controller Authentication
 
    .PARAMETER FriendlyName
        Specifies a friendly name for the certificate.
 
    .PARAMETER KeyType
        Specifies if the key type should be RSA or ECDH, defaults to RSA.
 
    .PARAMETER RequestType
        Specified if the request type should be CMC or PKCS10, deafults to CMC.
#>

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Subject,

        [Parameter()]
        [System.String]
        $CAServerFQDN,

        [Parameter()]
        [System.String]
        $CARootName,

        [Parameter()]
        [ValidateSet('192', '224', '256', '384', '521', '1024', '2048', '4096', '8192')]
        [System.String]
        $KeyLength = '2048',

        [Parameter()]
        [System.Boolean]
        $Exportable = $true,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $ProviderName = 'Microsoft RSA SChannel Cryptographic Provider',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $OID = '1.3.6.1.5.5.7.3.1',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $KeyUsage = '0xa0',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CertificateTemplate = 'WebServer',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $SubjectAltName,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $Credential,

        [Parameter()]
        [System.Boolean]
        $AutoRenew,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CAType = 'Enterprise',

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CepURL,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CesURL,

        [Parameter()]
        [System.Boolean]
        $UseMachineContext,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName,

        [Parameter()]
        [ValidateSet('RSA', 'ECDH')]
        [System.String]
        $KeyType = 'RSA',

        [Parameter()]
        [ValidateSet('CMC', 'PKCS10')]
        [System.String]
        $RequestType = 'CMC'
    )

    Assert-ResourceProperty -KeyLength $KeyLength -KeyType $KeyType

    # The certificate authority, accessible on the local area network
    if ([string]::IsNullOrWhiteSpace($CAServerFQDN) -or [string]::IsNullOrWhiteSpace($CARootName))
    {
        $caObject = Find-CertificateAuthority
        $CARootName = $caObject.CARootName
        $CAServerFQDN = $caObject.CAServerFQDN
    }

    $ca = "$CAServerFQDN\$CARootName"

    # If the Subject does not contain a full X500 path, construct just the CN
    if (($Subject.split('=').count) -eq 1)
    {
        $Subject = "CN=$Subject"
    }

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.TestingCertReqStatusMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate)
        ) -join '' )

    $filterScript = {
        (Compare-CertificateSubject -ReferenceSubject $_.Subject -DifferenceSubject $Subject) -and `
        (Compare-CertificateIssuer -Issuer $_.Issuer -CARootName $CARootName) -and `
        (Get-CertificateTemplateName -Certificate $PSItem) -eq $CertificateTemplate -and `
        $_.FriendlyName -eq $FriendlyName
    }

    # Exception for standard template DomainControllerAuthentication
    if ($CertificateTemplate -eq 'DomainControllerAuthentication')
    {
        $filterScript = {
            (Get-CertificateTemplateName -Certificate $PSItem) -eq $CertificateTemplate -and `
            (Compare-CertificateIssuer -Issuer $_.Issuer -CARootName $CARootName)
        }
    }

    $certificate = Get-ChildItem -Path Cert:\LocalMachine\My |
        Where-Object -FilterScript $filterScript

    # If multiple certs have the same subject and were issued by the CA, return the newest
    $certificate = $certificate |
        Sort-Object -Property NotBefore -Descending |
            Select-Object -First 1

    if ($certificate)
    {
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.CertificateExistsMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate, $certificate.Thumbprint)
            ) -join '' )

        if ($AutoRenew)
        {
            if ($certificate.NotAfter -le (Get-Date).AddDays(30))
            {
                # The certificate was found but it is expiring within 30 days or has expired
                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($script:localizedData.ExpiringCertificateMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate ,$certificate.Thumbprint)
                    ) -join '' )
                return $false
            } # if
        }
        else
        {
            if ($certificate.NotAfter -le (Get-Date))
            {
                # The certificate has expired
                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($script:localizedData.ExpiredCertificateMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate ,$certificate.Thumbprint)
                    ) -join '' )
                return $false
            } # if
        } # if

        if ($PSBoundParameters.ContainsKey('SubjectAltName'))
        {
            # Split the desired SANs into an array
            $sanList = $SubjectAltName.Split('&')
            $correctDns = @()

            foreach ($san in $sanList)
            {
                if ($san -like 'dns*')
                {
                    # This SAN is a DNS name
                    $correctDns += $san.split('=')[1]
                }
            }

            # Find out what SANs are on the current cert
            $currentDns = @()
            if ($certificate.Extensions.Count -gt 0)
            {
                $currentSanList = Get-CertificateSubjectAlternativeNameList -Certificate $certificate

                foreach ($san in $currentSanList)
                {
                    if ($san -like 'dns*')
                    {
                        # This SAN is a DNS name
                        $currentDns += $san.split('=')[1]
                    }
                }
            }

            if ($currentDns.Count -eq 0)
            {
                # There are no current DNS SANs and there should be
                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($script:localizedData.NoExistingSansMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate, ($correctDns -join ',') ,$certificate.Thumbprint)
                    ) -join '' )
                return $false
            }

            if (@(Compare-Object -ReferenceObject $currentDns -DifferenceObject $correctDns).Count -gt 0)
            {
                # Current DNS SANs and the desired DNS SANs do not match
                Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.SansMismatchMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate,($currentDns -join ',') , ($correctDns -join ',') ,$certificate.Thumbprint)
                ) -join '' )
                return $false
            }
        }

        $currentCertificateTemplateName = Get-CertificateTemplateName -Certificate $certificate

        # Check the friendly name of the certificate matches
        if ($FriendlyName -ne $certificate.FriendlyName)
        {
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($script:localizedData.CertFriendlyNameMismatchMessage -f $Subject, $ca, $currentCertificateTemplateName, $certificate.Thumbprint, $certificate.FriendlyName)
                ) -join '' )
            return $false
        } # if

        # The certificate was found and is OK - so no change required.
        Write-Verbose -Message ( @(
                "$($MyInvocation.MyCommand): "
                $($script:localizedData.ValidCertificateExistsMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate, $certificate.Thumbprint)
            ) -join '' )
        return $true
    } # if

    # A valid certificate was not found
    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($script:localizedData.NoValidCertificateMessage -f $Subject, $ca, $FriendlyName, $CertificateTemplate)
        ) -join '' )
    return $false
} # end function Test-TargetResource

<#
    .SYNOPSIS
        This function will check and ensure the right key length was choosen
        for the key type that was intended to be used.
 
    .PARAMETER KeyLength
        The bit length of the encryption key to be used.
 
    .PARAMETER KeyType
        Specifies if the key type should be RSA or ECDH, defaults to RSA.
#>

function Assert-ResourceProperty
{
    [CmdletBinding()]
    param
    (
        [Parameter()]
        [ValidateSet('192', '224', '256', '384', '521', '1024', '2048', '4096', '8192')]
        [System.String]
        $KeyLength = '2048',

        [Parameter()]
        [ValidateSet('RSA', 'ECDH')]
        [System.String]
        $KeyType = 'RSA'
    )

    if ((($KeyType -eq 'RSA') -and ($KeyLength -notin '1024', '2048', '4096', '8192')) -or `
        (($KeyType -eq 'ECDH') -and ($KeyLength -notin '192', '224', '256', '384', '521')))
    {
        New-InvalidArgumentException -Message (($script:localizedData.InvalidKeySizeError) -f $KeyLength, $KeyType) -ArgumentName 'KeyLength'
    }
}# end function Assert-ResourceProperty

<#
    .SYNOPSIS
        Compares two certificate subjects.
 
    .PARAMETER ReferenceSubject
        The certificate subject to compare. If the ReferenceSubject
        is null the function will return False.
 
    .PARAMETER DifferenceSubject
        The certificate subject to compare with the ReferenceSubject.
#>

function Compare-CertificateSubject
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [System.String]
        $ReferenceSubject,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $DifferenceSubject
    )

    if ([System.String]::IsNullOrEmpty($ReferenceSubject))
    {
        return $false
    }

    $referenceSubjectArray = ($ReferenceSubject -split ',').Trim() | Sort-Object
    $differenceSubjectArray = ($DifferenceSubject -split ',').Trim() | Sort-Object

    $difference = Compare-Object `
        -ReferenceObject $referenceSubjectArray `
        -DifferenceObject $differenceSubjectArray

    return ($difference.Count -eq 0)
}

<#
    .SYNOPSIS
        Checks if the Certificate Issuer matches the CA Root Name.
 
    .PARAMETER Issuer
        The Certificate Issuer.
 
    .PARAMETER CARootName
        The CA Root Name to compare with the Certificate Issuer.
#>

function Compare-CertificateIssuer
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $Issuer,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $CARootName
    )

    return ((Get-CertificateCommonName -DistinguishedName $Issuer) -eq $CARootName)
}

<#
    .SYNOPSIS
        Ensures a string is enclosed in dobule quotes.
 
    .PARAMETER Value
        The string to ensure is enclosed in double quotes.
#>

function ConvertTo-StringEnclosedInDoubleQuotes
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Value
    )

    if ($Value[0] -ne '"')
    {
        $Value = '"{0}' -f $Value
    }
    if ($Value[$Value.Length - 1] -ne '"')
    {
        $Value = '{0}"' -f $Value
    }

    return $Value
}

<#
    .SYNOPSIS
        Finds the Common Name in a X500 Distinguished Name.
 
    .PARAMETER DistinguishedName
        The X500 Distinguished Name.
#>

function Get-CertificateCommonName
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $DistinguishedName
    )

    return ($DistinguishedName.split(',') |
            ForEach-Object -Process { $_.TrimStart(' ') } |
                Where-Object -FilterScript { $_ -match 'CN=' }).replace('CN=', '')
}