okieselbach / Intune

Intune Scripts and Helpers.
463 stars 187 forks source link

GetDecryptionInfoFromLogFile.ps1 doesn't work if Intune cert is in user store #21

Open SMSAgentSoftware opened 10 months ago

SMSAgentSoftware commented 10 months ago

In some cases the Intune certificate is not installed in the local machine store but in the current user store. In this case the Decrypt function will fail.

The following code update to the function will check the user store if no cert is found in the localmachine store:

[System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
  $content = [Convert]::FromBase64String($base64string)
  $envelopedCms = [Security.Cryptography.Pkcs.EnvelopedCms]::new()
  $x509Store = [System.Security.Cryptography.X509Certificates.X509Store]::new([System.Security.Cryptography.X509Certificates.StoreName]::My,[System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
  $x509Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
  [System.Object]$certExtension = "1.2.840.113556.5.6"
  $certCollection = $x509Store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByExtension,$certExtension,$false)
  $x509Store.Close()
  if ($certCollection.Count -eq 0)
  {
      $x509Store = [System.Security.Cryptography.X509Certificates.X509Store]::new([System.Security.Cryptography.X509Certificates.StoreName]::My,[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser)
      $x509Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
      $certCollection = $x509Store.Certificates.Find([System.Security.Cryptography.X509Certificates.X509FindType]::FindByExtension,$certExtension,$false)
      $x509Store.Close()
  }
  $envelopedCms.Decode($content)
  $envelopedCms.Decrypt($certCollection)

  $utf8content = [text.encoding]::UTF8.getstring($envelopedCms.ContentInfo.Content)

  return $utf8content