Public/Revoke-PACertificate.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
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
function Revoke-PACertificate {
    [CmdletBinding(
        DefaultParameterSetName='MainDomain',
        SupportsShouldProcess,
        ConfirmImpact='High'
    )]
    param(
        [Parameter(ParameterSetName='MainDomain',Mandatory,Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]$MainDomain,
        [Parameter(ParameterSetName='CertFile',Mandatory,ValueFromPipelineByPropertyName)]
        [string]$CertFile,
        [Parameter(ParameterSetName='CertFile',ValueFromPipelineByPropertyName)]
        [string]$KeyFile,
        [PoshACME.RevocationReasons]$Reason,
        [switch]$Force
    )

    Begin {
        # grab a reference to the current account if it exists
        $acct = Get-PAAccount

        if ($Force){
            $ConfirmPreference = 'None'
        }
    }

    Process {

        if ('MainDomain' -eq $PSCmdlet.ParameterSetName) {

            # check for an existing certificate associated with the name
            if (-not ($paCert = $MainDomain | Get-PACertificate)) {
                try { throw "No existing certificate found for $MainDomain." }
                catch { $PSCmdlet.ThrowTerminatingError($_) }
            }

            # set the cert/key file paths
            $CertFile = $paCert.CertFile
            $KeyFile = $paCert.KeyFile
        }

        $pemHeader = '-----BEGIN CERTIFICATE-----'
        $pemFooter = '-----END CERTIFICATE-----'

        # do some minimal sanity checking on the cert file contents
        try {
            $certStr = (Get-Content $CertFile -EA Stop) -join ''
            if (-not ($certStr.StartsWith($pemHeader) -and $certStr.EndsWith($pemFooter))) {
                throw "Malformed certificate file: $CertFile"
            }
        }
        catch { $PSCmdlet.ThrowTerminatingError($_) }

        # remove the header/footer and convert to Base64Url as ACME expects
        $certStr = $certStr.Replace($pemHeader,'').Replace($pemFooter,'') |
            ConvertTo-Base64Url -FromBase64

        # Now we need to decide how we're going to sign to request. It can either
        # be signed with the private key that matches the cert or an ACME account
        # key. The ACME account must either be the one that orderd the cert
        # or one that has currently valid authorizations for all identifiers in
        # the cert.
        # https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1
        #
        # We're always going to try and use the cert's private key if
        # it is specified even if we could also use the current account's key.

        # check the private key
        if ($KeyFile) {
            if (Test-Path $KeyFile -PathType Leaf) {
                try {
                    $certKey = Import-Pem -InputFile $KeyFile | ConvertFrom-BCKey
                }
                catch {
                    Write-Warning "Unable to import private key file $($KeyFile): $($_.Exception.Message). Will attempt revocation with account key."
                }
            }
            else {
                Write-Warning "Private key $KeyFile was not found. Will attempt revocation with account key."
            }
        }
        else { Write-Debug "No KeyFile passed. Will attempt revocation with account key." }

        # start building the splat for Invoke-ACME
        $acmeParams = @{
            ErrorAction = 'Stop'
        }

        if ($certKey) {
            Write-Debug "Attempting to use cert key"

            # determine the alg from the key
            $alg = 'RS256'
            if ($certKey -is [Security.Cryptography.ECDsa]) {
                if     ($certKey.KeySize -eq 256) { $alg = 'ES256' }
                elseif ($certKey.KeySize -eq 384) { $alg = 'ES384' }
                elseif ($certKey.KeySize -eq 521) { $alg = 'ES512' }
            }

            # build the protected header
            $acmeParams.Header = @{
                alg   = $alg
                jwk   = ($certKey | ConvertTo-Jwk -PublicOnly)
                nonce = $script:Dir.nonce
                url   = $script:Dir.revokeCert
            }

            # set the key
            $acmeParams.Key = $certKey

        } elseif (-not $acct) {
            try { throw "No ACME account configured. Run Set-PAAccount or New-PAAccount first." }
            catch { $PSCmdlet.ThrowTerminatingError($_) }

        } else {
            Write-Debug "Attempting to use account key"

            # build the protected header
            $acmeParams.Header = @{
                alg   = $acct.alg
                kid   = $acct.location
                nonce = $script:Dir.nonce
                url   = $script:Dir.revokeCert
            }

            # set the account
            $acmeParams.Account = $acct
        }

        # build the payload
        $payload = @{ certificate = $certStr }
        if ($Reason) {
            $payload.reason = $Reason
        }
        $acmeParams.PayloadJson = $payload | ConvertTo-Json -Depth 5 -Compress

        # send the request
        if ($PSCmdlet.ShouldProcess($CertFile)){
            try {
                Invoke-ACME @acmeParams | Out-Null
            } catch { $PSCmdlet.ThrowTerminatingError($_) }
        }

    }

    <#
    .SYNOPSIS
        Revoke an ACME certificate

    .DESCRIPTION
        Revokes a previously created ACME certificate.

    .PARAMETER MainDomain
        The primary domain associated with the certificate to be revoked.

    .PARAMETER CertFile
        A PEM-encoded certificate file to be revoked.

    .PARAMETER KeyFile
        The PEM-encoded private key associated with CertFile. If not specified, the current ACME account will be used to sign the request.

    .PARAMETER Reason
        The reason for cert revocation. This must be one of the reasons defined in RFC 5280 including keyCompromise, cACompromise, affiliationChanged, superseded, cessationOfOperation, certificateHold, removeFromCRL, privilegeWithdrawn, and aACompromise. NOTE: Not all reason codes are supported by all ACME certificate authorities.

    .PARAMETER Force
        If specified, the revocation confirmation prompt will be skipped.

    .EXAMPLE
        Revoke-PACertificate example.com

        Revokes the certificate for the specified domain.

    .EXAMPLE
        Get-PAOrder | Revoke-PACertificate -Force

        Revokes the certificate associated with the current order and skips the confirmation prompt.

    .EXAMPLE
        Get-PACertificate | Revoke-PACertificate -Reason keyCompromise

        Revokes the current certificate with the specified reason.

    .EXAMPLE
       Revoke-PACertificate -CertFile mycert.crt -KeyFile mycert.key

       Revokes the specified cert using the specified private key.

    .LINK
        Project: https://github.com/rmbolger/Posh-ACME

    .LINK
        New-PACertificate

    #>

}

# Define an enum to represent the revocations reasons defined in RFC 5280
# that ACME supports.
# https://datatracker.ietf.org/doc/html/rfc8555#section-7.6
# https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1
if (-not ([System.Management.Automation.PSTypeName]'PoshACME.RevocationReasons').Type)
{
    Add-Type @"
        namespace PoshACME {
            public enum RevocationReasons {
                keyCompromise = 1,
                cACompromise = 2,
                affiliationChanged = 3,
                superseded = 4,
                cessationOfOperation = 5,
                certificateHold = 6,
                removeFromCRL = 8,
                privilegeWithdrawn = 9,
                aACompromise = 10
            }
        }
"@

}