Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
CmsMessage.Tests.ps1376 linesDownload Raw Back to Microsoft.PowerShell.Security
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3 4[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')]5param()6 7Import-Module (Join-Path -Path $PSScriptRoot 'certificateCommon.psm1') -Force8 9Describe "CmsMessage cmdlets and Get-PfxCertificate basic tests" -Tags "CI" {10 11    BeforeAll {12        $certLocation = New-GoodCertificate13        $certLocation | Should -Not -BeNullOrEmpty | Out-Null14 15        $protectedCertLocation = New-ProtectedCertificate16        $protectedCertLocation | Should -Not -BeNullOrEmpty | Out-Null17    }18 19    It "Verify Get-PfxCertificate -FilePath" {20        $cert = Get-PfxCertificate -FilePath $certLocation21        $cert.Subject | Should -Be "CN=MyDataEnciphermentCert"22    }23 24    It "Verify Get-PfxCertificate -LiteralPath" {25        $cert = Get-PfxCertificate -LiteralPath $certLocation26        $cert.Subject | Should -Be "CN=MyDataEnciphermentCert"27    }28 29    It "Verify Get-PfxCertificate positional argument" {30        $cert = Get-PfxCertificate $certLocation31        $cert.Subject | Should -Be "CN=MyDataEnciphermentCert"32    }33 34    It "Verify Get-PfxCertificate right password" {35        $password = Get-CertificatePassword36        $cert = Get-PfxCertificate $protectedCertLocation -Password $password37        $cert.Subject | Should -Be "CN=localhost"38    }39 40    It "Verify Get-PfxCertificate wrong password" {41        #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Test secret.")]42        $pass = ConvertTo-SecureString "wrongpass" -AsPlainText -Force43        { Get-PfxCertificate $protectedCertLocation -Password $pass -ErrorAction Stop } |44            Should -Throw -ErrorId "GetPfxCertificateUnknownCryptoError,Microsoft.PowerShell.Commands.GetPfxCertificateCommand"45    }46 47    It "Verify CMS message recipient resolution by path" -Skip:(!$IsWindows) {48        $errors = $null49        $recipient = [System.Management.Automation.CmsMessageRecipient] $certLocation50        $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)51 52        $recipient.Certificates.Count | Should -Be 153        $recipient.Certificates[0].Subject | Should -Match 'CN=MyDataEnciphermentCert'54    }55 56    It "Verify CMS message recipient resolution by cert" -Skip:(!$IsWindows) {57        $errors = $null58        $cert = Get-PfxCertificate $certLocation59        $recipient = [System.Management.Automation.CmsMessageRecipient] $cert60        $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)61 62        $recipient.Certificates.Count | Should -Be 163        $recipient.Certificates[0].Subject | Should -Match 'CN=MyDataEnciphermentCert'64    }65 66    It "Verify a CMS message can be protected / unprotected" -Skip:(!$IsWindows) {67        $protected = "Hello World","How are you?" | Protect-CmsMessage -To $certLocation68        $protected.IndexOf("-----BEGIN CMS-----") | Should -Be 069 70        $message = $protected | Get-CmsMessage71        $message.Recipients.Count | Should -Be 172        $message.Recipients[0].IssuerName | Should -Be "CN=MyDataEnciphermentCert"73 74        $expected = "Hello World" + [System.Environment]::NewLine + "How are you?"75        $decrypted = $message | Unprotect-CmsMessage -To $certLocation76        $decrypted | Should -Be $expected77 78        $decrypted = $protected | Unprotect-CmsMessage -To $certLocation79        $decrypted | Should -Be $expected80    }81}82 83Describe "CmsMessage cmdlets thorough tests" -Tags "Feature" {84 85    BeforeAll{86        if($IsWindows)87        {88            if (-not (Install-TestCertificates) ) {89                $SetupFailure = $true90            } else {91                Push-Location Cert:\92                $SetupFailure = $false93            }94        }95        else96        {97            # Skip for non-Windows platforms98            $defaultParamValues = $PSDefaultParameterValues.Clone()99            $PSDefaultParameterValues = @{ "it:skip" = $true }100        }101    }102 103    AfterAll {104        if($IsWindows -and -not $SetupFailure)105        {106            Remove-TestCertificates107        }108        else109        {110            if ($defaultParamValues -ne $null) {111                $global:PSDefaultParameterValues = $defaultParamValues112            }113 114        }115    }116 117    It "Verify message recipient resolution by Base64Cert" {118        $certContent = "119            -----BEGIN CERTIFICATE-----120            MIIDXTCCAkWgAwIBAgIQRTsRwsx0LZBHrx9z5Dag2zANBgkqhkiG9w0BAQUFADAh121            MR8wHQYDVQQDDBZNeURhdGFFbmNpcGhlcm1lbnRDZXJ0MCAXDTE0MDcyNTIyMjkz122            OVoYDzMwMTQwNzI1MjIzOTM5WjAhMR8wHQYDVQQDDBZNeURhdGFFbmNpcGhlcm1l123            bnRDZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx3SuShUvnRqn124            tYOIouJdP3wPZ5rtDi2KYPurpngGNZjM0EGDTrnhmEAI8DL4Kp6n/zz1mYVoX73+125            6uCpZX/13VDXg1neebJ261XpBX6FzxtclIQr8ywdUtrEgCnUAhgqgvO1Wwm4ogNR126            tWGCGkmlnqyaoV1j/V4KSn4WvKqSUIOZm0umGCTtNAJ6VtdpYO+uxxnRAapPUCY+127            qQ7DFzTUECIo1lMlBcuMiXj6NSFr4/D7ltkZ27jCdsZmzI7ZvRnDlfSYTPQnAO/E128            0uYn9uyKY/xfngWkUX/pe+j+10Lm1ypbASrj2Ezgf0KeZRXBwqKUOLhKheEmBJ18129            rLV27qwHeQIDAQABo4GOMIGLMA4GA1UdDwEB/wQEAwIEMDAUBgNVHSUEDTALBgkr130            BgEEAYI3UAEwRAYJKoZIhvcNAQkPBDcwNTAOBggqhkiG9w0DAgICAIAwDgYIKoZI131            hvcNAwQCAgCAMAcGBSsOAwIHMAoGCCqGSIb3DQMHMB0GA1UdDgQWBBRIyIzwInLJ132            3B+FajVUFMACf1hrxjANBgkqhkiG9w0BAQUFAAOCAQEAfFt4rmUmWfCbbwi2mCrZ133            Osq0lfVNUiZ+iLlEKga4VAI3sJZRtErnVM70eXUt7XpRaOdIfxjuXFpsgc37KyLi134            ByCORLuRC0itZVs3aba48opfMDXivxBy0ngqCPPLQsyaN9K7WnpvYV1QxiudYwwU135            8U5rFmzlwNLvc3XiyoGWaVZluk2DIJawQ5QYAU9/NMBBCbPHjTG7k0l4cpcEC+Ex136            od3RlO6/MOYuK2WB4VTxKsV80EdA3ljlu7Td8P4movnrbB4rG4wpCpk05eREkg/5137            Y54Ilo9m5OSAWtdx4yfS779eebLgUs3P+dk6EKwovXMokVveZA8cenIp3QkqSpeT138            cQ==139            -----END CERTIFICATE-----140            "141 142            $errors = $null143            $recipient = [System.Management.Automation.CmsMessageRecipient] $certContent144            $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)145 146            $recipient.Certificates.Count | Should -Be 1147            $recipient.Certificates[0].Subject | Should -Match 'CN=MyDataEnciphermentCert'148    }149 150    It "Verify wildcarded recipient resolution by path [Decryption]" {151        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}152        $errors = $null153        $recipient = [System.Management.Automation.CmsMessageRecipient] ((Get-GoodCertificateLocation) + "*")154        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)155 156        # Should have resolved single cert157        $recipient.Certificates.Count | Should -Be 1158    }159 160    It "Verify wildcarded recipient resolution by path [Encryption]" {161        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}162        $errors = $null163        $recipient = [System.Management.Automation.CmsMessageRecipient] ((Get-GoodCertificateLocation) + "*")164        $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)165 166        $recipient.Certificates.Count | Should -Be 1167    }168 169    It "Verify resolution by directory" {170        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}171        $protectedEventLoggingCertPath = Join-Path $TestDrive ProtectedEventLoggingDir172        $null = New-Item -ItemType Directory $protectedEventLoggingCertPath -Force173        Copy-Item (Get-GoodCertificateLocation) $protectedEventLoggingCertPath174        Copy-Item (Get-GoodCertificateLocation) (Join-Path $protectedEventLoggingCertPath "SecondCert.pfx")175        Copy-Item (Get-GoodCertificateLocation) (Join-Path $protectedEventLoggingCertPath "ThirdCert.pfx")176 177        $errors = $null178        $recipient = [System.Management.Automation.CmsMessageRecipient] $protectedEventLoggingCertPath179        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)180 181        $recipient.Certificates.Count | Should -Be 1182    }183 184    It "Verify resolution by thumbprint" {185        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}186        $errors = $null187        $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-GoodCertificateObject).Thumbprint188        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)189 190        # "Should have certs from thumbprint in 'My' store"191        $recipient.Certificates.Count | Should -Be 1192        $recipient.Certificates[0].Thumbprint | Should -Be (Get-GoodCertificateObject).Thumbprint193    }194 195    It "Verify resolution by subject name" {196        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}197        $errors = $null198        $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-GoodCertificateObject).Subject199        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)200 201        $recipient.Certificates.Count | Should -Be 1202        $recipient.Certificates[0].Thumbprint | Should -Be (Get-GoodCertificateObject).Thumbprint203    }204 205    It "Verify error when no cert found in encryption for encryption" {206        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}207        $errors = $null208        $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist*"209        $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)210 211        $errors.Count | Should -Be 1212        $errors[0].FullyQualifiedErrorId | Should -Be "NoCertificateFound"213    }214 215    It "Verify error when encrypting to non-wildcarded identifier for decryption" {216        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}217        $errors = $null218        $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist"219        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)220 221        $errors.Count | Should -Be 1222        $errors[0].FullyQualifiedErrorId | Should -Be "NoCertificateFound"223    }224 225    It "Verify error when encrypting to wrong cert" {226        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}227        $errors = $null228        $recipient = [System.Management.Automation.CmsMessageRecipient] (Get-BadCertificateObject).Thumbprint229        $recipient.Resolve($ExecutionContext.SessionState, "Encryption", [ref] $errors)230 231        $errors.Count | Should -Be 1232        $errors[0].FullyQualifiedErrorId | Should -Be "CertificateCannotBeUsedForEncryption"233    }234 235    It "Verify no error when encrypting to wildcarded identifier for decryption" {236        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}237        $errors = $null238        $recipient = [System.Management.Automation.CmsMessageRecipient] "SomeCertificateThatDoesNotExist*"239        $recipient.Resolve($ExecutionContext.SessionState, "Decryption", [ref] $errors)240 241        $errors | Should -Be $null242        $recipient.Certificates.Count | Should -Be 0243    }244 245    It "Verify Protect-CmsMessage emits recipient errors" {246        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}247        { "Hello World" | Protect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -ErrorAction Stop } |248            Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.ProtectCmsMessageCommand"249    }250 251    It "Verify CmsMessage cmdlets works with paths" {252        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}253 254        try {255            $randomNum = Get-Random -Minimum 1000 -Maximum 9999256            $tempPath = Join-Path $TestDrive "$randomNum-Path-Test-File"257            $encryptedPath = $tempPath + ".encrypted.txt"258            "Hello World","How are you?" | Set-Content $tempPath259 260            Protect-CmsMessage -Path $tempPath -To (Get-GoodCertificateLocation) -OutFile $encryptedPath261 262            $message = Get-CmsMessage -LiteralPath $encryptedPath263            $message.Recipients.Count | Should -Be 1264            $message.Recipients[0].IssuerName | Should -Be "CN=MyDataEnciphermentCert"265 266            $expected = "Hello World" + [System.Environment]::NewLine + "How are you?" + [System.Environment]::NewLine267            $decrypted = $message | Unprotect-CmsMessage -To (Get-GoodCertificateLocation)268            $decrypted | Should -Be $expected269 270            $decrypted = Unprotect-CmsMessage -Path $encryptedPath -To (Get-GoodCertificateLocation)271            $decrypted | Should -Be $expected272        } finally {273            Remove-Item $tempPath, $encryptedPath -Force -ErrorAction SilentlyContinue274        }275    }276 277    It "Verify Unprotect-CmsMessage works with local store" {278        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}279 280        try {281            $randomNum = Get-Random -Minimum 1000 -Maximum 9999282            $tempPath = Join-Path $TestDrive "$randomNum-Path-Test-File"283            "Hello World" | Protect-CmsMessage -To (Get-GoodCertificateLocation) -OutFile $tempPath284 285            # Decrypt using $importedCert in the Cert store286            $decrypted = Unprotect-CmsMessage -Path $tempPath287            $decrypted | Should -Be "Hello World"288        } finally {289            Remove-Item $tempPath -Force -ErrorAction SilentlyContinue290        }291    }292 293    It "Verify Unprotect-CmsMessage emits recipient errors" {294        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}295 296        { "" | Unprotect-CmsMessage -To "SomeThumbprintThatDoesNotExist" -IncludeContext -ErrorAction Stop } |297            Should -Throw -ErrorId "NoCertificateFound,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand"298    }299 300    It "Verify failure to extract Ascii armor generates an error [Unprotect-CmsMessage]" {301        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}302 303        { "Hello World" | Unprotect-CmsMessage -ErrorAction Stop } |304            Should -Throw -ErrorId "InputContainedNoEncryptedContentIncludeContext,Microsoft.PowerShell.Commands.UnprotectCmsMessageCommand"305    }306 307    It "Verify failure to extract Ascii armor generates an error [Get-CmsMessage]" {308        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}309 310        { "Hello World" | Get-CmsMessage -ErrorAction Stop } |311            Should -Throw -ErrorId "InputContainedNoEncryptedContent,Microsoft.PowerShell.Commands.GetCmsMessageCommand"312    }313 314    It "Verify 'Unprotect-CmsMessage -IncludeContext' with no encrypted input" {315        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}316 317        # Should have round-tripped content318        $result = "Hello World" | Unprotect-CmsMessage -IncludeContext319        $result | Should -Be "Hello World"320    }321 322    It "Verify Unprotect-CmsMessage lets you include context" {323        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}324 325        $protected = "Hello World" | Protect-CmsMessage -To (Get-GoodCertificateLocation)326        $adjustedProtected = "Pre content" + [System.Environment]::NewLine + $protected + [System.Environment]::NewLine + "Post content"327 328        $decryptedNoContext = $adjustedProtected | Unprotect-CmsMessage -To (Get-GoodCertificateLocation)329        $decryptedWithContext = $adjustedProtected | Unprotect-CmsMessage -To (Get-GoodCertificateLocation) -IncludeContext330 331        $decryptedNoContext | Should -Be "Hello World"332 333        $expected = "Pre content" + [System.Environment]::NewLine + "Hello World" + [System.Environment]::NewLine + "Post content"334        $decryptedWithContext | Should -Be $expected335    }336 337    It "Verify Unprotect-CmsMessage treats event logs as a first class citizen" {338        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}339 340        $protected = "Encrypted Message1","Encrypted Message2" | Protect-CmsMessage -To (Get-GoodCertificateLocation)341        $virtualEventLog = Get-WinEvent Microsoft-Windows-PowerShell/Operational -MaxEvents 1342        $savedId = $virtualEventLog.Id343        $virtualEventLog.Message = $protected344 345        $expected = "Encrypted Message1" + [System.Environment]::NewLine + "Encrypted Message2"346        $decrypted = $virtualEventLog | Unprotect-CmsMessage -To (Get-GoodCertificateLocation)347        $decrypted | Should -Be $expected348 349        $processed = $virtualEventLog | Unprotect-CmsMessage -To (Get-GoodCertificateLocation) -IncludeContext350        $processed.Id | Should -Be $savedId351        $processed.Message | Should -Be $expected352    }353 354    # Pending due to #3847355    It "Verify -DocumentEncryptionCert parameter works" -Pending {356        $foundCerts = Get-ChildItem Cert:\CurrentUser -Recurse -DocumentEncryptionCert357 358        # Validate they all match the EKU359        $correctMatching = $foundCerts | Where-Object {360            ($_.EnhancedKeyUsageList.Count -gt 0) -and361            ($_.EnhancedKeyUsageList[0].ObjectId -eq '1.3.6.1.4.1.311.80.1')362        }363        # "All Document Encryption Cert should have had correct EKU"364        @($foundCerts).Count | Should -Be @($correctMatching).Count365    }366 367    It "Verify protect message using OutString" {368        if ($SetupFailure) { Set-ItResult -Inconclusive -Because "Test certificates are not installed"}369 370        $protected = Get-Process -Id $PID | Protect-CmsMessage -To (Get-GoodCertificateLocation)371        $decrypted = $protected | Unprotect-CmsMessage -To (Get-GoodCertificateLocation)372        # Should have had PID in output373        $decrypted | Should -Match $PID374    }375}376