@@ -35,6 +35,10 @@ These rules apply to every `.ps1` and `.psm1` file.
3535- ** SEC-08** Hold sensitive data in a ` SecureString ` . A script that a person runs interactively
3636 reads it with ` Read-Host -AsSecureString ` ; a function or an unattended script does not prompt
3737 (SEC-05).
38+ - ** SEC-09** A web request that carries a credential MUST pass ` -MaximumRedirection 0 ` , so that a
39+ redirect is an error, and MUST NOT be paged with ` -FollowRelLink ` . Follow a redirect or a link in
40+ the function, and send the credential again only when the address has the scheme, host, and port
41+ of the first request.
3842
3943### Input and execution
4044
@@ -170,6 +174,174 @@ foreach ($key in $context.Keys) {
170174}
171175```
172176
177+ ** SEC-09.** Measured on PowerShell 7.6.10 and 7.7.0, against a local server that answers as two
178+ hosts:
179+
180+ | Where the request goes | ` Authorization ` header | A key in another header, such as ` X-Api-Key ` |
181+ | --- | --- | --- |
182+ | A link followed by ` -FollowRelLink ` | Not sent, since PowerShell 7.6.5 | Sent, to another host as well |
183+ | The same with ` -PreserveAuthorizationOnRedirect ` | Sent, to another host as well | Sent, to another host as well |
184+ | The target of a redirect | Not sent | Sent, to another host as well |
185+
186+ With ` -FollowRelLink ` alone, every page after the first is requested as an anonymous caller. The
187+ service refuses, or answers with only what an anonymous caller may see, and then no error is raised.
188+ With ` -PreserveAuthorizationOnRedirect ` , the credential goes wherever a reply points. Windows
189+ PowerShell 5.1 has no ` -FollowRelLink ` , and it treats a redirect as the last row says.
190+
191+ A redirect does the same to any request, paged or not: the cmdlet follows it without the
192+ ` Authorization ` header, to the same host as well. The caller gets an error where the address needs
193+ the credential, and the answer for an anonymous caller, with no error, where it does not. A key in
194+ another header goes with the redirect to any host. A credential passed as ` -Credential ` alone was
195+ not sent to the other host, and that request ended with an error. With ` -UseDefaultCredentials ` ,
196+ the versions differ. When the other host asked for Windows authentication, PowerShell 7 did not
197+ answer and ended with an error, and Windows PowerShell 5.1 began to authenticate there as the
198+ current user. The test server ended that exchange after its first message.
199+
200+ With ` -MaximumRedirection 0 ` , no request reaches the address that the redirect names, on all three
201+ versions. PowerShell 7 raises the refused redirect as an error whose exception carries the reply,
202+ with the address in ` Response.Headers.Location ` . Windows PowerShell 5.1, and PowerShell 7 with
203+ ` -SkipHttpErrorCheck ` , return the reply, with the address in ` Headers['Location'] ` , and write a
204+ non-terminating error, so ` -ErrorAction Stop ` loses the address. A service that redirects by
205+ design, such as a download that answers with a signed address on another host, is followed in the
206+ function, and the credential goes with it only to the scheme, host, and port of the first request.
207+
208+ The function below follows the links itself and lets no redirect be followed. ` $Request ` holds the
209+ parameters of ` Invoke-WebRequest ` , the credential among them. The function and its tests are files
210+ in the standards repository, under ` standards/examples ` :
211+
212+ ``` powershell
213+ function Get-PagedResponse {
214+ <#
215+ .SYNOPSIS
216+ Gets every page of a paged web request that carries a credential.
217+
218+ .DESCRIPTION
219+ Requests the first page, follows each link that a reply marks as rel="next" in its Link header,
220+ and writes the body of each page as text. The credential in the request is sent with every
221+ page, and only to the scheme, host, and port of the first request. A next link to another
222+ host, a next link to a page that was already requested, a redirect, and a failed request each
223+ end the function with a terminating error.
224+
225+ .PARAMETER Request
226+ The parameters of Invoke-WebRequest for the first page, as a hashtable. It must have a Uri key,
227+ and it holds the credential, for example in Headers, or in Authentication and Token. The
228+ function sets UseBasicParsing, ErrorAction, and MaximumRedirection itself.
229+
230+ .EXAMPLE
231+ Get-PagedResponse -Request @{ Uri = 'https://api.example.com/items'; Headers = $headers } | ConvertFrom-Json
232+
233+ Gets every page of the item list and converts each one from JSON. $headers holds the
234+ Authorization header.
235+
236+ .INPUTS
237+ None.
238+
239+ .OUTPUTS
240+ System.String. The body of each page.
241+ #>
242+ [CmdletBinding()]
243+ [OutputType([string])]
244+ param(
245+ [Parameter(Mandatory)]
246+ [ValidateScript({ $_.ContainsKey('Uri') })]
247+ [hashtable]$Request
248+ )
249+
250+ $firstUri = [uri]$Request['Uri']
251+ $pageRequest = $Request.Clone()
252+ $pageRequest['UseBasicParsing'] = $true
253+ $pageRequest['ErrorAction'] = 'Stop'
254+ # Invoke-WebRequest follows a redirect without the Authorization header, and the page then
255+ # arrives as an anonymous caller sees it. With this value a redirect is an error instead.
256+ $pageRequest['MaximumRedirection'] = 0
257+ $requestedUris = [System.Collections.Generic.HashSet[string]]::new()
258+ $pageUri = $firstUri
259+ while ($null -ne $pageUri) {
260+ $null = $requestedUris.Add($pageUri.AbsoluteUri)
261+ $pageRequest['Uri'] = $pageUri
262+ try {
263+ $response = Invoke-WebRequest @pageRequest
264+ } catch {
265+ # PowerShell 7 puts the refused reply on the exception. Windows PowerShell 5.1 has no
266+ # reply there and names the error instead.
267+ $status = 0
268+ $reply = $_.Exception.PSObject.Properties['Response']
269+ if ($null -ne $reply -and $null -ne $reply.Value) {
270+ $status = [int]$reply.Value.StatusCode
271+ }
272+ $isRedirect = ($status -in 301, 302, 303, 307, 308 -or
273+ $_.FullyQualifiedErrorId -like 'MaximumRedirectExceeded*')
274+ if (-not $isRedirect) {
275+ $PSCmdlet.ThrowTerminatingError($_)
276+ }
277+
278+ # The address is reported without its query string, which can carry a token.
279+ $target = $pageUri.GetLeftPart([System.UriPartial]::Path)
280+ $message = "The request for '$target' was answered with a redirect. It was not followed."
281+ $exception = [System.InvalidOperationException]::new($message, $_.Exception)
282+ $category = [System.Management.Automation.ErrorCategory]::InvalidResult
283+ $errorRecord = [System.Management.Automation.ErrorRecord]::new(
284+ $exception, 'PageRedirected', $category, $target)
285+ $PSCmdlet.ThrowTerminatingError($errorRecord)
286+ }
287+
288+ # A body whose content type is not a text type, such as application/vnd.api+json, is bytes.
289+ if ($response.Content -is [byte[]]) {
290+ [System.Text.Encoding]::UTF8.GetString($response.Content)
291+ } else {
292+ $response.Content
293+ }
294+
295+ # The header value is a string on Windows PowerShell 5.1 and a list of strings on PowerShell 7.
296+ $linkText = ($response.Headers.GetEnumerator() |
297+ Where-Object -Property Key -EQ -Value 'Link' |
298+ ForEach-Object { $_.Value }) -join ','
299+ $nextUri = $null
300+ foreach ($link in $linkText -split ',\s*(?=<)') {
301+ $match = [regex]::Match($link, '^\s*<([^>]+)>.*\brel="?[^";]*\bnext\b')
302+ if ($match.Success) {
303+ $nextUri = [uri]::new($pageUri, $match.Groups[1].Value)
304+ break
305+ }
306+ }
307+
308+ $errorId = $null
309+ if ($null -ne $nextUri) {
310+ $sameOrigin = ($nextUri.Scheme -eq $firstUri.Scheme -and $nextUri.Host -eq $firstUri.Host -and
311+ $nextUri.Port -eq $firstUri.Port)
312+ if (-not $sameOrigin) {
313+ $errorId = 'NextPageOnAnotherHost'
314+ $category = [System.Management.Automation.ErrorCategory]::SecurityError
315+ $message = "The next page is on another host, '$($nextUri.Host)'. It was not requested."
316+ } elseif ($requestedUris.Contains($nextUri.AbsoluteUri)) {
317+ $errorId = 'NextPageAlreadyRequested'
318+ $category = [System.Management.Automation.ErrorCategory]::InvalidResult
319+ $message = 'The next link names a page that was already requested. It was not requested again.'
320+ }
321+ }
322+
323+ if ($null -ne $errorId) {
324+ $exception = [System.InvalidOperationException]::new($message)
325+ $target = $nextUri.GetLeftPart([System.UriPartial]::Path)
326+ $errorRecord = [System.Management.Automation.ErrorRecord]::new(
327+ $exception, $errorId, $category, $target)
328+ $PSCmdlet.ThrowTerminatingError($errorRecord)
329+ }
330+
331+ $pageUri = $nextUri
332+ }
333+ }
334+ ```
335+
336+ Run on PowerShell 7.7.0, PowerShell 7.6.10, and Windows PowerShell 5.1 under strict mode, against the
337+ same server. Three pages arrived with the credential on each, whether the link was absolute or
338+ relative, stood among other relations, or came in a header named ` link ` . Each of these ended the
339+ function with an error and without a further request: a next link on another host, a next link
340+ back to the first page, and a redirect, at the first page or at a later one. The function reports
341+ the redirect as ` PageRedirected ` on all three versions, where the errors of the cmdlet differ. A
342+ body with the content type ` application/vnd.api+json ` arrived as text, where ` Invoke-WebRequest `
343+ returns bytes.
344+
173345** SEC-10.** Arguments passed as an array reach a native executable as separate arguments, so input
174346cannot add switches or commands:
175347
0 commit comments