DSCResources/MSFT_xCertReq/MSFT_xCertReq.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
#Requires -Version 4.0

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

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

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

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

# Import Localization Strings
$localizedData = Get-LocalizedData `
    -ResourceName 'MSFT_xCertReq' `
    -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)

<#
    .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 createthe certificate.
 
    .PARAMETER Credential
    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.
#>

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("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()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName
    )

    # 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): "
            $($LocalizedData.GettingCertReqStatusMessage -f $Subject, $CA)
        ) -join '' )

    $cert = Get-Childitem -Path Cert:\LocalMachine\My |
        Where-Object -FilterScript {
        $_.Subject -eq "CN=$Subject" -and `
            $_.Issuer.split(',')[0] -eq "CN=$CARootName"
    }

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

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

        $returnValue = @{
            Subject             = $Cert.Subject.split(',')[0].replace('CN=', '')
            CAServerFQDN        = $caObject.CAServerFQDN
            CARootName          = $Cert.Issuer.split(',')[0].replace('CN=', '')
            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-CertificateSan -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 createthe certificate.
 
    .PARAMETER Credential
    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.
#>

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

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

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

        [Parameter()]
        [ValidateSet("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()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName
    )

    # 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): "
            $($LocalizedData.StartingCertReqMessage -f $Subject, $ca)
        ) -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 `
                $_.Issuer.split(',')[0] -eq "CN=$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 = "`"$Subject`""
    $keySpec = '1'
    $machineKeySet = 'TRUE'
    $smime = 'FALSE'
    $privateKeyArchive = 'FALSE'
    $userProtected = 'FALSE'
    $useExistingKeySet = 'FALSE'
    $providerType = '12'
    $requestType = 'CMC'

    # 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 "xCertReq-$guid"
    $infPath = [System.IO.Path]::ChangeExtension($workingPath, '.inf')
    $reqPath = [System.IO.Path]::ChangeExtension($workingPath, '.req')
    $cerPath = [System.IO.Path]::ChangeExtension($workingPath, '.cer')
    $rspPath = [System.IO.Path]::ChangeExtension($workingPath, '.rsp')

    # 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"
"@

    }
    $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`"
"@

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

    }
    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): "
            $($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): "
            $($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): "
                $($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): "
                        $($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 ($LocalizedData.CertReqOutNotFoundError -f $certReqOutPath)
                } # if
            } # if
        }
        else
        {
            $submitRequest = & certreq.exe @('-submit', '-q', '-config', $CA, $ReqPath, $CerPath)
        } # if

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

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

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

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

    Write-Verbose -Message ( @(
            "$($MyInvocation.MyCommand): "
            $($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 createthe certificate.
 
    .PARAMETER Credential
    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.
#>

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("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()]
        [ValidateNotNullOrEmpty()]
        [System.String]
        $FriendlyName
    )

    # 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): "
            $($LocalizedData.TestingCertReqStatusMessage -f $Subject, $ca)
        ) -join '' )

    # Exception for standard template DomainControllerAuthentication
    $cert = Get-Childitem -Path Cert:\LocalMachine\My |
        Where-Object -FilterScript {
        $_.Subject -eq $Subject -and `
            $_.Issuer.split(',')[0] -eq "CN=$CARootName"
    }

    if ($CertificateTemplate -eq 'DomainControllerAuthentication')
    {
        $cert = Get-Childitem -Path Cert:\LocalMachine\My |
            Where-Object -FilterScript {
            (Get-CertificateTemplateName -Certificate $PSItem) -eq $CertificateTemplate -and `
                $_.Issuer.split(',')[0] -eq "CN=$CARootName"
        }
    }

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

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

        if ($AutoRenew)
        {
            if ($Cert.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): "
                        $($LocalizedData.ExpiringCertificateMessage -f $Subject, $ca, $cert.Thumbprint)
                    ) -join '' )
                return $false
            } # if
        }
        else
        {
            if ($cert.NotAfter -le (Get-Date))
            {
                # The certificate has expired
                Write-Verbose -Message ( @(
                        "$($MyInvocation.MyCommand): "
                        $($LocalizedData.ExpiredCertificateMessage -f $Subject, $ca, $cert.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
            if ($cert.Extensions.Count -gt 0)
            {
                $currentSanList = ($cert.Extensions | Where-Object {$_.oid.FriendlyName -match 'Subject Alternative Name'}).Format(1).split("`n").TrimEnd()
                $currentDNS = @()
                foreach ($san in $currentSanList)
                {
                    if ($san -like 'dns*')
                    {
                        # This SAN is a DNS name
                        $currentDNS += $san.split('=')[1]
                    }
                }

                # Do the cert's DNS SANs and the desired DNS SANs match?
                if (@(Compare-Object -ReferenceObject $currentDNS -DifferenceObject $correctDNS).Count -gt 0)
                {
                    return $false
                }
            }
            else
            {
                # There are no SANs and there should be
                return $false
            }
        }

        if ($CertificateTemplate -ne (Get-CertificateTemplateName -Certificate $cert))
        {
            Write-Verbose -Message ( @(
                    "$($MyInvocation.MyCommand): "
                    $($LocalizedData.CertTemplateMismatch -f $Subject, $ca, $cert.Thumbprint, (Get-CertificateTemplateName -Certificate $cert))
                ) -join '' )
            return $false
        } # if

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

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

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