functions/Restore-DbaDbCertificate.ps1

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
function Restore-DbaDbCertificate {
    <#
    .SYNOPSIS
        Imports certificates from .cer files using SMO.
 
    .DESCRIPTION
        Imports certificates from.cer files using SMO.
 
    .PARAMETER SqlInstance
        The target SQL Server instance or instances.
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER Path
        The Path the contains the certificate and private key files. The path can be a directory or a specific certificate.
 
    .PARAMETER SecurePassword
        Secure string used to decrypt the private key.
 
    .PARAMETER EncryptionPassword
        If specified this will be used to encrypt the private key.
 
    .PARAMETER Database
        The database where the certificate imports into. Defaults to master.
 
    .PARAMETER WhatIf
        Shows what would happen if the command were to run. No actions are actually performed.
 
    .PARAMETER Confirm
        Prompts you for confirmation before executing any changing operations within the command.
 
    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
    .NOTES
        Tags: Migration, Certificate
        Author: Jess Pomfret (@jpomfret), jesspomfret.com
 
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Restore-DbaDbCertificate
 
    .EXAMPLE
        PS C:\> $securepass = Get-Credential usernamedoesntmatter | Select-Object -ExpandProperty Password
        PS C:\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates -SecurePassword $securepass
 
        Restores all the certificates in the specified path, password is used to both decrypt and encrypt the private key.
 
    .EXAMPLE
        PS C:\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\Server1\Certificates\DatabaseTDE.cer -SecurePassword (Get-Credential usernamedoesntmatter).Password
 
        Restores the DatabaseTDE certificate to Server1 and uses the MasterKey to encrypt the private key.
 
    #>

    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = "High")]
    param (
        [Parameter(Mandatory)]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("FullName")]
        [object[]]$Path,
        [Security.SecureString]$EncryptionPassword,
        [string]$Database = "master",
        [Alias("Password", "DecryptionPassword")]
        [Security.SecureString]$SecurePassword = (Read-Host "Password" -AsSecureString),
        [switch]$EnableException
    )
    process {
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlcredential
        } catch {
            Stop-Function -Message "Failed to connect to: $SqlInstance" -Target $SqlInstance -ErrorRecord $_
            return
        }

        foreach ($dir in $Path) {
            if (-not $SqlInstance.IsLocalHost -and -not $dir.StartsWith('\')) {
                Stop-Function -Message "Path ($dir) must be a UNC share when SQL instance is not local." -Continue -Target $fullname
            }

            if (-not (Test-DbaPath -SqlInstance $server -Path $dir)) {
                Stop-Function -Message "$SqlInstance cannot access $dir" -Continue -Target $dir
            }

            if (Test-Path $dir -PathType Container) {
                Write-Message -Level Verbose -Message "Path is a directory - processing all cer's within"
                $path = Get-ChildItem $dir "*.cer" | Select-Object -expand FullName
            }

            foreach ($fullname in $path) {
                Write-Message -Level Verbose -Message ("Processing {0}" -f $fullname)

                $directory = Split-Path $fullname
                $filename = Split-Path $fullname -Leaf
                $certname = [io.path]::GetFileNameWithoutExtension($filename)

                if ($Pscmdlet.ShouldProcess("$certname on $SqlInstance", "Importing Certificate")) {
                    $smocert = New-Object Microsoft.SqlServer.Management.Smo.Certificate
                    $smocert.Name = $certname
                    $smocert.Parent = $server.Databases[$Database]
                    Write-Message -Level Verbose -Message "Creating Certificate: $certname"
                    $fullcertname = "$directory\$certname.cer"
                    $privatekey = "$directory\$certname.pvk"
                    Write-Message -Level Verbose -Message "Full certificate path: $fullcertname"
                    Write-Message -Level Verbose -Message "Private key: $privatekey"
                    try {
                        if ($EncryptionPassword) {
                            $smocert.Create($fullcertname, 1, $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)), [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($EncryptionPassword)))
                        } else {
                            $smocert.Create($fullcertname, 1, $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)))
                        }
                    } catch {
                        try {
                            if ($EncryptionPassword) {
                                $smocert.Create($fullcertname, $([Microsoft.SqlServer.Management.Smo.CertificateSourceType]::"File"), $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)), [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($EncryptionPassword)))
                            } else {
                                $smocert.Create($fullcertname, $([Microsoft.SqlServer.Management.Smo.CertificateSourceType]::"File"), $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecurePassword)))
                            }
                        } catch {
                            Stop-Function -Message $_ -ErrorRecord $_ -Target $instance -Continue
                        }
                    }
                }
            }
            Get-DbaDbCertificate -SqlInstance $server -Database $Database -Certificate $smocert.Name
        }
    }
}