Обновление сертификатов в профиле пользователя Active Directory (userCertificate) - PullRequest
0 голосов
/ 27 марта 2019

Мне нужно обновить массив сертификатов, хранящихся в учетной записи AD пользователя.

У меня есть это:

$allProfileRawCerts = Get-ADUser -Server example.com -Filter {EmailAddress -eq $Mail} -Property Certificates

Что дает

Certificates      : {System.Security.Cryptography.X509Certificates.X509Certificate, System.Security.Cryptography.X509Certificates.X509Certificate, 
                    System.Security.Cryptography.X509Certificates.X509Certificate}
DistinguishedName : <>
Enabled           : True
GivenName         : <>
Name              : <>
ObjectClass       : user
ObjectGUID        : <>
SamAccountName    : <>
SID               : <>
Surname           : <>
UserPrincipalName : <>

Я нашел Ошибка типа параметра PowerChell Set-ADUser userCertificate , которая обеспечивает операцию «добавления»:

$certUser.Usercertificate | ForEach-Object{
    Set-ADUser "ME" -certificate @{Add=[System.Security.Cryptography.X509Certificates.X509Certificate]$_}
}

Однако мне нужно не добавить , а update - удалить некоторые сертификаты в зависимости от условия, затем добавить новые.

Один из подходов (я думаю) состоит в том, чтобы удалить все сертификаты из профиля пользователя, создать новый массив и обновить - но я действительно,на самом деле не нравится удалять действительные данные в неатомарной операции.

Кроме того, проблема (по крайней мере для меня) состоит в том, что я не могу фильтровать (скорее базовый) сертификат X509, но мне нужно преобразоватьсначала к X509Certificate2:

$allProfileSMIMECerts = $allProfileRawCerts.Certificates |
    foreach {New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $_} |
    Where-Object { $_.EnhancedKeyUsageList.FriendlyName -eq "Secure Email" }

Что мне нужно:

  1. Получить список всех сертификатов.
  2. Удалить все, для которых $_.EnhancedKeyUsageList.FriendlyName -eq "Secure Email" истинно.
  3. Добавить новый сертификат.

Как это сделать хорошим способом?

1 Ответ

0 голосов
/ 03 апреля 2019

Решено с использованием следующего кода:

try {
    $allProfileRawCerts = (Get-ADUser -Server example.com -Filter {EmailAddress -eq $Mail} -Property Certificates).Certificates
}
catch {
    Write-Log -ERROR "Can't contact Global AD directory, exiting..."
    exit 100
}

$handlesToRemove = ($allProfileRawCerts |
    foreach {New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $_} |
    Where-Object { $_.EnhancedKeyUsageList.FriendlyName -eq "Secure Email" }).Handle

$objectToRemove = $allProfileRawCerts | Where-Object Handle -in $handlesToRemove

# first add the new cert
Write-Log -INFO "Adding newly minted certificate to user's AD profile."
$newCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate

try {
    $newCert.Import("$workdir\$ticket.cer")
}
catch {
    Write-Log -ERROR "Can't import new certificate from file, exiting..."
    Write-Log -ERROR "$($PSItem.ToString())"
    exit 103
}

try {
    Get-ADUser -Server example.com -Filter {EmailAddress -eq $Mail} | 
        Set-ADUser -Credential $CACredential -Certificates @{Add=$newCert};@{Remove=$objectToRemove}
}
catch {
    Write-Log -ERROR "Can't add the new certificate to user profile, exiting..."
    Write-Log -ERROR "$($PSItem.ToString())"
    exit 104
}
Write-Log -INFO "New certificate successfully added to user's AD profile."

# now remove old certs
foreach ( $object in $objectToRemove ) { 
    Write-Log -INFO "Certificate with handle $($object.Handle) will be removed, saving to work directory."

    try {
        $null = Export-Certificate -Type CERT -Cert $cert -FilePath "$workdir\$($object.Handle).cer"
    }
    catch {
        Write-Log -FATAL "Can't save certificate to be deleted, exiting!"
        exit 101
    }

    try {
        Get-ADUser -Server example.com -Filter {EmailAddress -eq $Mail} | 
            Set-ADUser -Credential $CACredential -Certificates @{Remove=$object}
    }
    catch {
        Write-Log -ERROR "Problems contacting AD for certificate removal, exiting..."
        Write-Log -ERROR "$($PSItem.ToString())"
        exit 102
    }

    Write-Log -INFO "Certificate has been saved and removed from AD profile."
}

Любые комментарии приветствуются, так как я все еще Powershell n00b.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...