Get-ADUserCertificate.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
#
# Created by: lucas.cueff[at]lucas-cueff.com.com
#
# Released on: 11/2017
#
#'(c) 2017 - Distributed under Artistic Licence 2.0 (https://opensource.org/licenses/artistic-license-2.0).'
#
<#
    .SYNOPSIS
    simple module to get single or all user/contact certificate from an AD
    look for a certificate in usercert, usercertificate, usersmimecertificate attributes for contact and user object
    2 functions available : Get-ADUserCertificate and Get-AllADUserCertificates
    the function are standalone and the code could be used outside the module easily. the only prerequisite is RSAT with AD cmdlets.
 
    .DESCRIPTION
    Require RSAT if used on non Domain Controller environment.
    Do not manage manual authentication to directory (to be managed in a future version)
 
    .EXAMPLE
    C:\PS> import-module Get-ADUserCertificate.psm1
    C:\PS> Remove-Module Get-ADUserCertificate
#>


Function Get-ADUserCertificate { 
<#
    .SYNOPSIS
    get user certificate(s) from contact or user object from an AD
    look for a certificate in usercert, usercertificate, usersmimecertificate attributes for object contact and user
 
    .DESCRIPTION
    Require RSAT if used on non Domain Controller environment.
    You can use several search type entry : distinguishedName or SamAccountName/CN or Mail
    you can search in another forest/domain using parameter "server" (by default take the current domain for logged on user)
    you can export the certificates found in file using "exportcert" parameter (require a file with full path)
 
    .EXAMPLE
    Get-ADUserCertificate -searchtype distinguishedName -searchentry "CN=account,OU=testou1,OU=testou,DC=ad,DC=ad,DC=com" -exportcert "C:\test\test\test.cer"
    Get-ADUserCertificate -searchtype Mail -searchentry "user.account@test.com"
    Get-ADUserCertificate -searchtype SamAccountNameOrCN -searchentry "UserAccount1" -server anotherad.ad.com
     
#>

    [CmdletBinding()] 
    Param( 
          [parameter(Mandatory=$True)] 
          [ValidateSet('Mail','SamAccountNameOrCN','distinguishedName')]
          [String]$searchtype,
          [parameter(Mandatory=$True)] 
          [String]$searchentry,
          [parameter(Mandatory=$false)] 
          [ValidatePattern('^[a-zA-Z]:\\(((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$')]
          [String]$exportcert,
          [parameter(Mandatory=$false)] 
          [ValidatePattern('^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}$')]
          [String]$server
    ) 
    # import AD Module
    try {
        import-module ActiveDirectory
    } catch {
        write-warning "Not able to load active directory module"
        write-warning "Please check if RSAT is installed"
        write-error "Error Type: $($_.Exception.GetType().FullName)"
        write-error "Error Message: $($_.Exception.Message)"
        return 
    }
    # get current domain if necessary
    if (-not $server) {
        $server = (get-addomain -current loggedonuser).dnsroot
        $pdc = (get-addomain -current loggedonuser).PDCEmulator
    } Else {
        $pdc = (get-addomain -server $server).PDCEmulator
    }
    # prepare exportcert content
    if ($exportcert) {
        if ($exportcert -like "*.cer") {
            $exportpath = split-path -path $exportcert
            $exportfilebase = split-path -Leaf $exportcert
        } Else {
            write-warning "the file name and path provided are not containing a valid CER file with full path entry. ex : c:\temp 2\temp\test.cer"
            return
        }
    }
    # retrieve AD object based on distinguishedName, SamAccountName Or CN or mail
    switch ($searchtype) {
        "distinguishedName" {
            If ($searchentry -like "CN=*") {
                try {
                    $searchpattern = get-adobject -Filter { ((objectclass -eq "user") -or (objectclass -eq "contact")) -and (distinguishedName -eq $searchentry)} -server $server -Properties objectClass,distinguishedname,displayName,mail,UserCertificate,UserSMIMECertificate,UserCert,sn,givenname
                } catch {
                    write-error "Error Type: $($_.Exception.GetType().FullName)"
                    write-error "Error Message: $($_.Exception.Message)"
                    return 
                }
            }
        }
        "Mail" {
            IF ($searchentry -match "^[a-zA-Z0-9.!£#$%&'^_`{}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$") {
                try {
                    $searchpattern = get-adobject -Filter { ((objectclass -eq "user") -or (objectclass -eq "contact")) -and (mail -eq $searchentry)} -server $server -Properties objectClass,distinguishedname,displayName,mail,UserCertificate,UserSMIMECertificate,UserCert,sn,givenname
                } catch {
                    write-error "Error Type: $($_.Exception.GetType().FullName)"
                    write-error "Error Message: $($_.Exception.Message)"
                    return 
                }
            } 
        }
        "SamAccountNameOrCN" {
            If ($searchtype -eq "SamAccountNameOrCN") {
                try {
                    $searchpattern = get-adobject -Filter { ((objectclass -eq "user") -or (objectclass -eq "contact")) -and ((sAMAccountName -eq $searchentry) -or (CN -eq $searchentry))} -server $server -Properties objectClass,distinguishedname,displayName,mail,UserCertificate,UserSMIMECertificate,UserCert,sn,givenname
                } catch {
                    write-error "Error Type: $($_.Exception.GetType().FullName)"
                    write-error "Error Message: $($_.Exception.Message)"
                    return
                }
            }
        }
        #default {}
    }
    If ($searchpattern) {
        # Preparing new object
        $global:UserTemplateObject = New-Object psobject
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name ObjectClass -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name distinguishedname -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name displayName -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificate -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificate -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCert -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name mail -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name givenname -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name sn -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificateLastOriginatingChangeTime -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificateLastOriginatingDeleteTime -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificateLastOriginatingChangeTime -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificateLastOriginatingDeleteTime -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertLastOriginatingChangeTime -Value $null
        $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertLastOriginatingDeleteTime -Value $null
        # check the certificate presence
        If ($searchpattern.UserSMIMECertificate) {
            $cer1 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $searchpattern.UserSMIMECertificate
            $cer1metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usersmimecertificate -Server $pdc
        } Else {
            write-warning "no certificate in UserSMIMECertificate attribute for object $($searchpattern.distinguishedname)"
        }
        If ($searchpattern.UserCertificate) {    
            $cer2 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $searchpattern.UserCertificate
            $cer2metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usercertificate -Server $pdc
        } Else {
            write-warning "no certificate in UserCertificate attribute for object $($searchpattern.distinguishedname)"
        }
        If ($searchpattern.UserCert) {    
            $cer3 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $searchpattern.UserCert
            $cer3metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usercert -Server $pdc
        } Else {
            write-warning "no certificate in UserCert attribute for object $($searchpattern.distinguishedname)"
        }
        #building new object with content
        $ObjCertUser = $UserTemplateObject | Select-Object *
        $ObjCertUser.ObjectClass = $searchpattern.ObjectClass
        $ObjCertUser.distinguishedname = $searchpattern.distinguishedname
        $ObjCertUser.displayName = $searchpattern.displayName
        if($cer1) {
            $ObjCertUser.UserSMIMECertificate = $cer1
            $ObjCertUser.UserSMIMECertificateLastOriginatingChangeTime = $cer1metadata.LastOriginatingChangeTime
            $ObjCertUser.UserSMIMECertificateLastOriginatingDeleteTime = $cer1metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile1 = $exportfilebase -replace ".cer","_$($searchentry)_USMcrt.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile1)
                if (-not (test-path $exportcertfn)) {
                    $cer1.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        if ($cer2) {
            $ObjCertUser.UserCertificate = $cer2
            $ObjCertUser.UserCertificateLastOriginatingChangeTime = $cer2metadata.LastOriginatingChangeTime
            $ObjCertUser.UserCertificateLastOriginatingDeleteTime = $cer2metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile2 = $exportfilebase -replace ".cer","_$($searchentry)_Ucrtf.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile2)
                if (-not (test-path $exportcertfn)) {
                    $cer2.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        if ($cer3) {
            $ObjCertUser.UserCert = $cer3
            $ObjCertUser.UserCertLastOriginatingChangeTime = $cer3metadata.LastOriginatingChangeTime
            $ObjCertUser.UserCertLastOriginatingDeleteTime = $cer3metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile2 = $exportfilebase -replace ".cer","_$($searchentry)_Ucrt.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile2)
                if (-not (test-path $exportcertfn)) {
                    $cer2.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        $ObjCertUser.mail = $searchpattern.mail
        $ObjCertUser.givenname = $searchpattern.givenname
        $ObjCertUser.sn = $searchpattern.sn
        #send back the new object as output
        return $ObjCertUser
    } Else {
        write-warning "no user or contact AD object found with your criteria : $($searchentry)"
        return 
    }
}

Function Get-AllADUserCertificates { 
<#
    .SYNOPSIS
    get all user certificate(s) from all contact or user objects from an AD
    look for a certificate in usercert, usercertificate, usersmimecertificate attributes for all contact and user objects
 
    .DESCRIPTION
    Require RSAT if used on non Domain Controller environment.
    you can search in another forest/domain using parameter "server" (by default take the current domain for logged on user)
    you can export the certificates found in file using "exportcert" parameter (require a file with full path)
    you can skip warning message with user input using "skipconfirm" parameter
 
    .EXAMPLE
    Get-ADUserCertificate -exportcert "C:\test\test2"
    Get-ADUserCertificate -skipconfirm $true
    Get-ADUserCertificate -server anotherad.ad.com
     
#>

    [CmdletBinding()] 
    Param( 
          [parameter(Mandatory=$false)] 
          [ValidatePattern('^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}$')]
          [String]$server,
          [parameter(Mandatory=$false)] 
          [ValidatePattern('^[a-zA-Z]:\\(((?![<>:"/\\|?*]).)+((?<![ .])\\)?)*$')]
          [String]$exportcert,
          [parameter(Mandatory=$false)]
          [bool]$skipconfirm
    ) 
    # warning message if parameter "skipconfirm" is not used
    if ($skipconfirm -eq $false) {
        write-warning "this cmdlet will get all certificates from your AD for user and contact objects. It may overload your directory, please use it carefully !"
        Write-Host "Press any key to continue ..." -foreground "green"
        $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | out-null
    }
    # import AD Module
    try {
        import-module ActiveDirectory
    } catch {
        write-warning "Not able to load active directory module"
        write-warning "Please check if RSAT is installed"
        write-error "Error Type: $($_.Exception.GetType().FullName)"
        write-error "Error Message: $($_.Exception.Message)"
        return 
    }
    # get current domain if necessary
    if (-not $server) {
        $server = (get-addomain -current loggedonuser).dnsroot
        $pdc = (get-addomain -current loggedonuser).PDCEmulator
    } Else {
        $pdc = (get-addomain -server $server).PDCEmulator
    }
    # prepare exportcert content
    if ($exportcert) {
        $exportpath = split-path -path $exportcert
    }
    #get info from AD
    try {
        $searchresult = @(get-adobject -Filter { ((objectclass -eq "user") -or (objectclass -eq "contact")) -and ((UserCertificate -like "*") -or (UserCert -like "*") -or (UserSMIMECertificate -like "*"))} -server $server -Properties objectClass,distinguishedname,displayName,mail,UserCertificate,UserSMIMECertificate,UserCert,sn,givenname)
    } catch {
        write-error "Error Type: $($_.Exception.GetType().FullName)"
        write-error "Error Message: $($_.Exception.Message)"
        return 
    }
    # Preparing new object
    $FinalObjCertUser = @()
    $global:UserTemplateObject = New-Object psobject
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name ObjectClass -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name distinguishedname -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name displayName -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificate -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificate -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCert -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name mail -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name givenname -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name sn -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificateLastOriginatingChangeTime -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserSMIMECertificateLastOriginatingDeleteTime -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificateLastOriginatingChangeTime -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertificateLastOriginatingDeleteTime -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertLastOriginatingChangeTime -Value $null
    $UserTemplateObject | Add-Member -MemberType NoteProperty -Name UserCertLastOriginatingDeleteTime -Value $null
    # doing the main stuff
    write-host "$($search.count) certificates found." -foreground "green"
    foreach ($result in $searchresult) {
        # check the certificate presence
        If ($result.UserSMIMECertificate) {
            $cer1 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $result.UserSMIMECertificate
            $cer1metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usersmimecertificate -Server $pdc
        } Else {
            write-warning "no certificate in UserSMIMECertificate attribute for object $($result.distinguishedname)"
        }
        If ($result.UserCertificate) {    
            $cer2 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $result.UserCertificate
            $cer2metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usercertificate -Server $pdc
        } Else {
            write-warning "no certificate in UserCertificate attribute for object $($result.distinguishedname)"
        }
        If ($result.UserCert) {    
            $cer3 = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $result.UserCert
            $cer3metadata = Get-ADReplicationAttributeMetadata $searchpattern.distinguishedName -properties usercert -Server $pdc
        } Else {
            write-warning "no certificate in UserCert attribute for object $($result.distinguishedname)"
        }
        #building new object with content
        $ObjCertUser = $UserTemplateObject | Select-Object *
        $ObjCertUser.ObjectClass = $result.ObjectClass
        $ObjCertUser.distinguishedname = $result.distinguishedname
        $ObjCertUser.displayName = $result.displayName
        if($cer1) {
            $ObjCertUser.UserSMIMECertificate = $cer1
            $ObjCertUser.UserSMIMECertificateLastOriginatingChangeTime = $cer1metadata.LastOriginatingChangeTime
            $ObjCertUser.UserSMIMECertificateLastOriginatingDeleteTime = $cer1metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile1 = $exportfilebase -replace ".cer","_$($result.distinguishedname)_USMcrt.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile1)
                if (-not (test-path $exportcertfn)) {
                    $cer1.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        if ($cer2) {
            $ObjCertUser.UserCertificate = $cer2
            $ObjCertUser.UserCertificateLastOriginatingChangeTime = $cer2metadata.LastOriginatingChangeTime
            $ObjCertUser.UserCertificateLastOriginatingDeleteTime = $cer2metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile2 = $exportfilebase -replace ".cer","_$($result.distinguishedname)_Ucrtf.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile2)
                if (-not (test-path $exportcertfn)) {
                    $cer2.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        if ($cer3) {
            $ObjCertUser.UserCert = $cer3
            $ObjCertUser.UserCertLastOriginatingChangeTime = $cer3metadata.LastOriginatingChangeTime
            $ObjCertUser.UserCertLastOriginatingDeleteTime = $cer3metadata.LastOriginatingDeleteTime
            if ($exportcert) {
                $exportfile2 = $exportfilebase -replace ".cer","_$($result.distinguishedname)_Ucrt.cer"
                $exportcertfn = join-path ($exportpath) ($exportfile2)
                if (-not (test-path $exportcertfn)) {
                    $cer2.rawdata | set-content "$($exportcertfn)" -Encoding Byte
                } Else {
                    write-warning "cannot create $($exportcertfn) - file already exists"
                }
            }
        }
        $ObjCertUser.mail = $searchpattern.mail
        $ObjCertUser.givenname = $searchpattern.givenname
        $ObjCertUser.sn = $searchpattern.sn
        $FinalObjCertUser += $ObjCertUser
    }
    return $FinalObjCertUser
}

Export-ModuleMember -Function Get-ADUserCertificate, Get-AllADUserCertificates