Public/Set-PAAccount.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
function Set-PAAccount {
    [CmdletBinding(SupportsShouldProcess,DefaultParameterSetName='Normal')]
    param(
        [Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]$ID,
        [Parameter(ParameterSetName='Normal',Position=1)]
        [string[]]$Contact,
        [Parameter(ParameterSetName='Normal')]
        [switch]$Deactivate,
        [Parameter(ParameterSetName='Normal')]
        [switch]$Force,
        [Parameter(ParameterSetName='Rollover',Mandatory)]
        [switch]$KeyRollover,
        [Parameter(ParameterSetName='Rollover')]
        [ValidateScript({Test-ValidKeyLength $_ -ThrowOnFail})]
        [Alias('AccountKeyLength')]
        [string]$KeyLength='ec-256',
        [switch]$NoSwitch
    )

    Begin {
        # make sure we have a server configured
        if (!(Get-PAServer)) {
            throw "No ACME server configured. Run Set-PAServer first."
        }

        # make sure all Contacts have a mailto: prefix which is the only
        # type of contact currently supported.
        if ($Contact.Count -gt 0) {
            0..($Contact.Count-1) | ForEach-Object {
                if ($Contact[$_] -notlike 'mailto:*') {
                    $Contact[$_] = "mailto:$($Contact[$_])"
                }
            }
        }
    }

    Process {

        # throw an error if there's no current account and no ID
        # passed in
        if (!$script:Acct -and !$ID) {
            throw "No ACME account configured. Run New-PAAccount or specify an account ID."
        }

        # There are 3 types of calls the user might be making here.
        # - account switch
        # - account switch and modification
        # - modification only (possibly bulk via pipeline)
        # The default is to switch accounts. So we have a -NoSwitch parameter to
        # indicate a non-switching modification. But there's a chance they could forget
        # to use it for a bulk update. For now, we'll just let it happen and switch
        # to whatever account came through the pipeline last.

        if ($NoSwitch -and $ID) {
            # This is a non-switching modification, so grab a cached reference to the
            # account specified
            $acct = Get-PAAccount $ID

            if ($null -eq $acct) {
                Write-Warning "Specified account ID ($ID) was not found. No changes made."
                return
            }

        } elseif (!$script:Acct -or ($ID -and ($ID -ne $script:Acct.id))) {
            # This is a definite account switch

            # refresh the cached copy
            Update-PAAccount $ID

            Write-Debug "Switching to account $ID"

            # save it as current
            $ID | Out-File (Join-Path $script:DirFolder 'current-account.txt') -Force -EA Stop

            # reset child object references
            $script:Order = $null
            $script:OrderFolder = $null

            # reload the cache from disk
            Import-PAConfig 'Account'

            # grab a local reference to the newly current account
            $acct = $script:Acct

        } else {
            # This is effectively a non-switching modification because they didn't
            # specify an ID. So just use the current account.
            $acct = $script:Acct
        }

        # check if there's anything to change
        if ('Contact' -in $PSBoundParameters.Keys -or $Deactivate) {

            # build the header
            $header = @{
                alg   = $acct.alg;
                kid   = $acct.location;
                nonce = $script:Dir.nonce;
                url   = $acct.location;
            }

            # build the payload
            $payload = @{}
            if ('Contact' -in $PSBoundParameters.Keys) {
                # We want to allow people to clear their contact field either by specifying $null or an empty array @()
                # But currently, Boulder only works by sending the empty array. So use that if they sent $null.
                if (!$Contact) {
                    $payload.contact = @()
                } else {
                    $payload.contact = $Contact
                }
            }
            if ($Deactivate) {
                if (!$Force) {
                    if (!$PSCmdlet.ShouldContinue("Are you sure you wish to deactivate account $($acct.id)?",
                    "Deactivating an account is irreversible and will prevent modifications or renewals for associated orders and certificates.")) {
                        Write-Verbose "Modification aborted for account $($acct.id)."
                        return
                    }
                }
                $payload.status = 'deactivated'
            }

            # convert it to json
            $payloadJson = $payload | ConvertTo-Json -Compress

            # send the request
            try {
                $response = Invoke-ACME $header $payloadJson $acct -EA Stop
            } catch { throw }
            Write-Debug "Response: $($response.Content)"

            $respObj = ($response.Content | ConvertFrom-Json)

            # update the things that could have changed
            $acct.status = $respObj.status
            $acct.contact = $respObj.contact

            # save it to disk
            $acctFolder = Join-Path $script:DirFolder $acct.id
            $acct | ConvertTo-Json | Out-File (Join-Path $acctFolder 'acct.json') -Force -EA Stop

        } elseif ($KeyRollover) {

            # We've been asked to rollover the account key which effectively means replace it
            # with a new one. The spec describes the process in the following link.
            # https://tools.ietf.org/html/rfc8555#section-7.3.5

            # build the standard outer header
            $header = @{
                alg   = $acct.alg;
                kid   = $acct.location;
                nonce = $script:Dir.nonce;
                url   = $script:Dir.keyChange;
            }

            # create the new account key
            $newKey = New-PAKey $KeyLength

            # create the algorithm identifier as described by
            # https://tools.ietf.org/html/rfc7518#section-3.1
            # and what we know LetsEncrypt supports today which includes
            # RS256 for all RSA keys
            # ES256 for P-256 keys, ES384 for P-384 keys, ES512 for P-521 keys
            $alg = 'RS256'
            if     ($KeyLength -eq 'ec-256') { $alg = 'ES256' }
            elseif ($KeyLength -eq 'ec-384') { $alg = 'ES384' }
            elseif ($KeyLength -eq 'ec-521') { $alg = 'ES512' }

            # build the inner header
            $innerHead = @{
                alg  = $alg;
                jwk  = ($newKey | ConvertTo-Jwk -PublicOnly);
                url  = $script:Dir.keyChange;
            }

            # build the inner payload
            $innerPayloadJson = @{
                account = $acct.location;
                oldKey  = $acct.Key | ConvertFrom-Jwk | ConvertTo-Jwk -PublicOnly
            } | ConvertTo-Json -Compress

            # build the outer payload by creating a signed JWS from
            # the inner header/payload and new key
            $payloadJson = New-Jws $newKey $innerHead $innerPayloadJson -NoHeaderValidation

            # send the request
            try {
                $response = Invoke-ACME $header $payloadJson $acct -EA Stop
            } catch { throw }
            Write-Debug "Response: $($response.Content)"

            $respObj = ($response.Content | ConvertFrom-Json)
            if ($respObj.status -eq 'valid') {
                # update the account with the new key
                $acct.key = $newKey | ConvertTo-Jwk
                $acct.alg = $alg
                $acct.KeyLength = $KeyLength

                # save it to disk
                $acctFolder = Join-Path $script:DirFolder $acct.id
                $acct | ConvertTo-Json | Out-File (Join-Path $acctFolder 'acct.json') -Force -EA Stop
            }
        }

    }





    <#
    .SYNOPSIS
        Set the current ACME account and/or update account details.
 
    .DESCRIPTION
        This function allows you to switch between ACME accounts for a particular server. It also allows you to update the contact information associated with an account, deactivate the account, or replace the account key with a new one.
 
    .PARAMETER ID
        The account id value as returned by the ACME server. If not specified, the function will attempt to use the currently active account.
 
    .PARAMETER Contact
        One or more email addresses to associate with this account. These addresses will be used by the ACME server to send certificate expiration notifications or other important account notices.
 
    .PARAMETER Deactivate
        If specified, a request will be sent to the associated ACME server to deactivate the account. Clients may wish to do this if the account key is compromised or decommissioned.
 
    .PARAMETER Force
        If specified, confirmation prompts for account deactivation will be skipped.
 
    .PARAMETER KeyRollover
        If specified, generate a new account key and replace the current one with it. Clients may choose to do this to recover from a key compromise or proactively mitigate the impact of an unnoticed key compromise.
 
    .PARAMETER KeyLength
        The type and size of private key to use. For RSA keys, specify a number between 2048-4096 (divisible by 128). For ECC keys, specify either 'ec-256' or 'ec-384'. Defaults to 'ec-256'.
 
    .PARAMETER NoSwitch
        If specified, the currently active account will not change. Useful primarily for bulk updating contact information across accounts. This switch is ignored if no ID is specified.
 
    .EXAMPLE
        Set-PAAccount -ID 1234567
 
        Switch to the specified account.
 
    .EXAMPLE
        Set-PAAccount -Contact 'user1@example.com','user2@example.com'
 
        Set new contacts for the current account.
 
    .EXAMPLE
        Set-PAAccount -ID 1234567 -Contact 'user1@example.com','user2@example.com'
 
        Set new contacts for the specified account.
 
    .EXAMPLE
        Get-PAAccount -List | Set-PAAccount -Contact user1@example.com -NoSwitch
 
        Set a new contact for all known accounts without switching from the current.
 
    .EXAMPLE
        Set-PAAccount -Deactivate
 
        Deactivate the current account.
 
    .EXAMPLE
        Set-PAAccount -KeyRollover -KeyLength ec-384
 
        Replace the current account key with a new ECC key using P-384 curve.
 
    .LINK
        Project: https://github.com/rmbolger/Posh-ACME
 
    .LINK
        Get-PAAccount
 
    .LINK
        New-PAAccount
 
    #>

}