-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHTTPowerShell.psm1
More file actions
1560 lines (1333 loc) · 53.8 KB
/
Copy pathHTTPowerShell.psm1
File metadata and controls
1560 lines (1333 loc) · 53.8 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function ConvertTo-ASCII {
Param(
[Parameter(Mandatory)]
[string]
$InputObject
)
$InputBytes = [System.Text.Encoding]::ASCII.GetBytes($InputObject)
$OutputString = [System.Text.Encoding]::ASCII.GetString($InputBytes)
return $OutputString
}
function ConvertTo-UTF8 {
Param(
[Parameter(Mandatory)]
[string]
$InputObject
)
$InputBytes = [System.Text.Encoding]::UTF8.GetBytes($InputObject)
$OutputString = [System.Text.Encoding]::UTF8.GetString($InputBytes)
return $OutputString
}
function Format-Response {
Param(
[Parameter(Mandatory)]
$RawResponse,
[Parameter()]
[string[]]
$DisplayHeaders
)
# ---- Handle byte[] response type
if ($RawResponse -is 'byte[]') {
$RawResponse = [System.Text.Encoding]::UTF8.GetString($RawResponse)
}
$Headers = New-Object -TypeName System.Collections.Generic.List[object]
$StatusPattern = 'HTTP\/[0-9\.]+ (([0-9]+).*)'
# ---- Split Headers and Body
$ResponseComponents = $RawResponse -split "`r?`n`r?`n", 2
$RawHeaders = $ResponseComponents[0].Trim()
$Body = $ResponseComponents[1].Trim()
$HeaderLines = $RawHeaders -split "`r?`n" | Where-Object { $_ -ne '' }
# ---- Parse header lines
foreach ($Line in $HeaderLines) {
if ($Line -Match $StatusPattern) {
$StatusCode = [int] $Matches[2]
$Status = $Line
}
else {
$HeaderName = ($Line -split ':')[0].Trim()
$HeaderValue = ($Line -split ':', 2)[1].Trim()
if ($DisplayHeaders.Count -gt 0 -and $HeaderName -notin $DisplayHeaders) {
Write-Debug "Skipping header: $HeaderName"
continue
}
$Headers.Add( [PSCustomObject] @{
Name = $HeaderName
Value = $HeaderValue
})
}
}
# ---- Sort Headers
$Headers = $Headers | Sort-Object -Property Name, Value
# ---- Determine Content-Type
$ContentType = $Headers |
Where-Object { $_.name.ToLower() -eq 'content-type' } |
Select-Object -First 1 |
Select-Object -ExpandProperty value
# ---- Construct output object
$FormattedResponse = [PSCustomObject] @{
StatusCode = $StatusCode
Status = $Status
Headers = $Headers
ContentType = $ContentType
Body = $Body
}
# ---- Handle multi-part response
if ($ContentType -like 'multipart/form-data*') {
$BoundaryMatch = $ContentType | Select-String -Pattern 'boundary=([^ ]*)'
if ($BoundaryMatch) {
$Boundary = $BoundaryMatch.Matches[0].Groups[1].Value
$Parts = $Body -split "--$Boundary" | Where-Object { $_ -ne "" -and $_ -ne "--" }
Write-Debug "Multi-Part: Found $($Parts.count) parts, separated by boundary $Boundary"
if ($Parts.Count -gt 0) {
$FormattedResponse | Add-Member -NotePropertyName Parts -NotePropertyValue (New-Object -TypeName System.Collections.Generic.List[object])
foreach ($Part in $Parts) {
$FormattedPart = Format-Response -RawResponse $Part.Trim()
$FormattedResponse.Parts.Add($FormattedPart)
}
# Nullify main body, as it is contained in the parts
$FormattedResponse.Body = $null
}
}
else {
Write-Warning "Failed to find boundary in Content-Type header: $ContentType"
}
}
return $FormattedResponse
}
function Get-AkamaiStagingIP {
<#
.SYNOPSIS
Resolve hostname to Akamai Staging Network
.DESCRIPTION
Resolves hostname's CNAME chain to determine local Akamai staging IP
.NOTES
Author: S MAcleod
Date: 29/10/25
.PARAMETER Hostname
Hostname to resolve
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[string]
$Hostname
)
# ---- Get DNS
$DNS = Resolve-GoogleDNS -Name $Hostname
# ---- Determine low-level map
$LLMap = ($DNS | Where-Object { $_.name.contains('.akamai.net') -or $_.name.contains('.akamaiedge.net') }).Name
if ($LLMap.count -gt 1) { $LLMap = $LLMap[0] }
Write-Debug "Get-AkamaiStagingIP: LLMap = $LLMap"
if ($null -eq $LLMap) {
throw "Unable to infer low-level map from response: $($DNS)"
}
# ---- Determine Staging
$StagingLLMap = $LLMap.Replace('akamaiedge.net', 'akamaiedge-staging.net')
$StagingLLMap = $StagingLLMap.Replace('akamai.net', 'akamai-staging.net')
Write-Debug "Get-AkamaiStagingIP: Staging LLMap = $StagingLLMap"
$StagingDNS = Resolve-GoogleDNS -Name $StagingLLMap
$StagingIP = $StagingDNS[-1].data
Write-Debug "Get-AkamaiStagingIP: StagingIP = $StagingIP"
return $StagingIP
}
function Get-BodyString {
Param(
[Parameter(Mandatory)]
$Body
)
# Convert PSCustomObjects or Hashtables
if ($Body -is [PSCustomObject] -or $Body -is [Hashtable]) {
try {
$BodyString = ConvertTo-Json -InputObject $Body -Depth 100
}
catch {
Write-Error "Could not convert object to json"
Write-Error $_
return
}
}
# Convert XML
elseif ($Body -is [System.Xml.XmlDocument]) {
$BodyString = $Body.OuterXml
}
# Fall back to string
else {
$BodyString = $Body
}
return $BodyString
}
function Get-ColourPalette {
[CmdletBinding()]
Param (
[Parameter()]
[string]
$KeyColour = (Get-PSReadLineOption).StringColor,
[Parameter()]
[string]
$StringColour = (Get-PSReadLineOption).ListPredictionColor,
[Parameter()]
[string]
$NumberColour = (Get-PSReadLineOption).NumberColor,
[Parameter()]
[string]
$CommentColour = (Get-PSReadLineOption).CommentColor,
[Parameter()]
[string]
$OtherColour = (Get-PSReadLineOption).ParameterColor
)
$ColourPalette = [PSCustomObject] @{
KeyColour = $KeyColour.SubString(2, 2)
StringColour = $StringColour.SubString(2, 2)
NumberColour = $NumberColour.SubString(2, 2)
CommentColour = $CommentColour.SubString(2, 2)
OtherColour = $OtherColour.SubString(2, 2)
}
return $ColourPalette
}
function Get-EdgegridAuthHeader {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[PSCustomObject]
$Credentials,
[Parameter(Mandatory)]
[string]
$Method,
[Parameter(Mandatory)]
[string]
$ExpandedPath,
[Parameter()]
[string]
$Body,
[Parameter()]
[string]
$InputFile,
[Parameter()]
[string]
$MaxBody = 131072
)
# Sanitize Method param
$Method = $Method.ToUpper()
# Timestamp for request signing
$TimeStamp = [DateTime]::UtcNow.ToString("yyyyMMddTHH:mm:sszz00")
# GUID for request signing
$Nonce = [GUID]::NewGuid()
# Build data string for signature generation
$SignatureData = $Method + "`thttps`t"
$SignatureData += $Credentials.Host + "`t" + $ExpandedPath
#Sanitize body to remove NO-BREAK SPACE Unicode character, which breaks PAPI
$Body = $Body -replace "[\u00a0]", ""
# Add body to signature. Truncate if body is greater than max-body (Akamai default is 131072). PUT Method does not require adding to signature.
if ($Method -eq "POST") {
if ($Body) {
$Body_SHA256 = [System.Security.Cryptography.SHA256]::Create()
if ($Body.Length -gt $MaxBody) {
$Body_Hash = [System.Convert]::ToBase64String($Body_SHA256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Body.Substring(0, $MaxBody))))
}
else {
$Body_Hash = [System.Convert]::ToBase64String($Body_SHA256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Body)))
}
$SignatureData += "`t`t" + $Body_Hash + "`t"
}
elseif ($InputFile) {
$Body_SHA256 = [System.Security.Cryptography.SHA256]::Create()
if ($PSVersionTable.PSVersion.Major -lt 6) {
$Bytes = Get-Content $InputFile -Encoding Byte
}
else {
$Bytes = Get-Content $InputFile -AsByteStream
}
if ($Bytes.Length -gt $MaxBody) {
$Body_Hash = [System.Convert]::ToBase64String($Body_SHA256.ComputeHash($Bytes[0..($MaxBody - 1)]))
}
else {
$Body_Hash = [System.Convert]::ToBase64String($Body_SHA256.ComputeHash($Bytes))
}
$SignatureData += "`t`t" + $Body_Hash + "`t"
Write-Debug "Signature generated from input file $InputFile"
}
else {
$SignatureData += "`t`t`t"
}
}
else {
$SignatureData += "`t`t`t"
}
$SignatureData += "EG1-HMAC-SHA256 "
$SignatureData += "client_token=" + $Credentials.ClientToken + ";"
$SignatureData += "access_token=" + $Credentials.AccessToken + ";"
$SignatureData += "timestamp=" + $TimeStamp + ";"
$SignatureData += "nonce=" + $Nonce + ";"
Write-Debug "SignatureData = $SignatureData"
# Generate SigningKey
$SigningKey = Get-EncryptedMessage -secret $Credentials.ClientSecret -message $TimeStamp
# Generate Auth Signature
$Signature = Get-EncryptedMessage -secret $SigningKey -message $SignatureData
# Create AuthHeader
$AuthorizationHeader = "EG1-HMAC-SHA256 "
$AuthorizationHeader += "client_token=" + $Credentials.ClientToken + ";"
$AuthorizationHeader += "access_token=" + $Credentials.AccessToken + ";"
$AuthorizationHeader += "timestamp=" + $TimeStamp + ";"
$AuthorizationHeader += "nonce=" + $Nonce + ";"
$AuthorizationHeader += "signature=" + $Signature
return $AuthorizationHeader
}
function Get-EdgegridCredentials {
[CmdletBinding()]
Param(
[Parameter()]
[string]
$EdgeRCFile,
[Parameter()]
[string]
$Section,
[Parameter()]
[string]
$AccountSwitchKey
)
## Assign defaults if values not provided
if ($EdgeRCFile -eq '') {
$EdgeRCFile = '~/.edgerc'
}
else {
## If EdgeRCFile is provided we use that, regardless of other auth types being available
$Mode = 'edgerc'
}
if ($Section -eq '') {
$Section = 'default'
}
#----------------------------------------------------------------------------------------------
# 1. Set up auth object
#----------------------------------------------------------------------------------------------
## Instantiate auth object
$Credentials = [PSCustomObject] @{
Host = $null
ClientToken = $null
AccessToken = $null
ClientSecret = $null
AccountKey = $null
}
#----------------------------------------------------------------------------------------------
# 2. Check for environment variables
#----------------------------------------------------------------------------------------------
## 'default' section is implicit. Otherwise env variable starts with section prefix
if ($Mode -ne 'edgerc') {
if ($Section.ToLower() -eq 'default') {
$EnvPrefix = 'AKAMAI'
}
else {
$EnvPrefix = "AKAMAI_$Section".ToUpper()
}
if (Test-Path "env:\$EnvPrefix`_HOST") {
$Credentials.Host = (Get-Item -Path "env:\$EnvPrefix`_HOST").Value
}
if (Test-Path "env:\$EnvPrefix`_CLIENT_TOKEN") {
$Credentials.ClientToken = (Get-Item -Path "env:\$EnvPrefix`_CLIENT_TOKEN").Value
}
if (Test-Path "env:\$EnvPrefix`_ACCESS_TOKEN") {
$Credentials.AccessToken = (Get-Item -Path "env:\$EnvPrefix`_ACCESS_TOKEN").Value
}
if (Test-Path "env:\$EnvPrefix`_CLIENT_SECRET") {
$Credentials.ClientSecret = (Get-Item -Path "env:\$EnvPrefix`_CLIENT_SECRET").Value
}
if (Test-Path "env:\$EnvPrefix`_ACCOUNT_KEY") {
$Credentials.AccountKey = (Get-Item -Path "env:\$EnvPrefix`_ACCOUNT_KEY").Value
}
## Explicit ASK wins over env variable
if ($AccountSwitchKey) {
$Credentials.AccountKey = $AccountSwitchKey
}
## Remove ASK if value is "none"
if ($AccountSwitchKey -eq "none") {
$Credentials.AccountKey = $null
}
## Check essential elements and return
if ($null -ne $Credentials.Host -and $null -ne $Credentials.ClientToken -and $null -ne $Credentials.AccessToken -and $null -ne $Credentials.ClientSecret) {
## Env creds valid
Write-Debug "Obtained credentials from environment variables in section '$Section'"
return $Credentials
}
}
#----------------------------------------------------------------------------------------------
# 3. Read from .edgerc file
#----------------------------------------------------------------------------------------------
# Get credentials from EdgeRC
if (Test-Path $EdgeRCFile) {
$EdgeRCContent = Get-Content $EdgeRCFile -Raw
$SectionPattern = "(?s)(\[$Section\].*?)(\[|$)"
$SectionMatch = $EdgeRCContent | Select-String -Pattern $SectionPattern
if ($SectionMatch -and $SectionMatch.Matches[0].Groups[1].Value) {
$SectionContent = $SectionMatch.Matches[0].Groups[1].Value
$HostMatch = $SectionContent | Select-String -Pattern "\r?\nhost[ ]*=[ ]*([^\s#]+)"
if ($HostMatch) {
$Credentials.host = $HostMatch.Matches[0].Groups[1].Value
}
$ClientTokenMatch = $SectionContent | Select-String -Pattern "\r?\nclient_token[ ]*=[ ]*([^\s#]+)"
if ($ClientTokenMatch) {
$Credentials.ClientToken = $ClientTokenMatch.Matches[0].Groups[1].Value
}
$AccessTokenMatch = $SectionContent | Select-String -Pattern "\r?\naccess_token[ ]*=[ ]*([^\s#]+)"
if ($AccessTokenMatch) {
$Credentials.AccessToken = $AccessTokenMatch.Matches[0].Groups[1].Value
}
$ClientSecretMatch = $SectionContent | Select-String -Pattern "\r?\nclient_secret[ ]*=[ ]*([^\s#]+)"
if ($ClientSecretMatch) {
$Credentials.ClientSecret = $ClientSecretMatch.Matches[0].Groups[1].Value
}
$AccountKeyMatch = $SectionContent | Select-String -Pattern "\r?\naccount_key[ ]*=[ ]*([^\s#]+)"
if ($AccountKeyMatch) {
$Credentials.AccountKey = $AccountKeyMatch.Matches[0].Groups[1].Value
}
}
else {
throw "Error: Section '$Section' not found in edgerc file '$EdgeRCFile'"
}
## Explicit ASK wins over edgerc file entry
if ($AccountSwitchKey) {
$Credentials.AccountKey = $AccountSwitchKey
}
## Remove ASK if value is "none"
if ($AccountSwitchKey -eq "none") {
$Credentials.AccountKey = $null
}
## Check essential elements and return
if ($null -ne $Credentials.host -and $null -ne $Credentials.ClientToken -and $null -ne $Credentials.AccessToken -and $null -ne $Credentials.ClientSecret) {
Write-Debug "Obtained credentials from edgerc file '$EdgeRCFile' in section '$Section'"
return $Credentials
}
}
#----------------------------------------------------------------------------------------------
# 4. Panic!
#----------------------------------------------------------------------------------------------
## Under normal circumstances you should not get this far...
throw "Error: Credentials could not be loaded from either; session, environment variables or edgerc file '$EdgeRCFile'"
}
function Get-EncryptedMessage {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[string]
$Secret,
[Parameter(Mandatory)]
[string]
$Message
)
[byte[]] $KeyByte = [System.Text.Encoding]::UTF8.GetBytes($Secret)
[byte[]] $MessageBytes = [System.Text.Encoding]::UTF8.GetBytes($Message)
$HMAC = new-object System.Security.Cryptography.HMACSHA256((, $keyByte))
[byte[]] $HashMessage = $HMAC.ComputeHash($MessageBytes)
$EncryptedMessage = [System.Convert]::ToBase64String($HashMessage)
return $EncryptedMessage
}
function Get-PFXFromPem {
Param (
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$ClientCertificate,
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$ClientCertificateFile,
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$ClientKey,
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$ClientKeyFile,
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$ClientKeyPassword,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Security.SecureString]
$SecureClientKeyPassword
)
process {
if ($ClientCertificate) {
$CertificateContent = $ClientCertificate
}
elseif ($ClientCertificateFile) {
if (-not (Test-Path $ClientCertificateFile)) {
Write-Error "Client certificate file '$ClientCertificateFile' not found"
return
}
Write-Debug "Reading certificate from file: $ClientCertificateFile"
$CertificateContent = Get-Content -Raw -Path $ClientCertificateFile
}
if ($ClientKey) {
$KeyContent = $ClientKey
}
elseif ($ClientKeyFile) {
if (-not (Test-Path $ClientKeyFile)) {
Write-Error "Client key file '$ClientKeyFile' not found"
return
}
Write-Debug "Reading key from file: $ClientKeyFile"
$KeyContent = Get-Content -Raw -Path $ClientKeyFile
}
# Validate we have both elements
if (-not ($CertificateContent -and $KeyContent)) {
throw "Both client certificate and key are required for mutual TLS."
}
# Handle encrypted keys differently
if ($KeyContent.StartsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----")) {
if (-not $ClientKeyPassword -and -not $SecureClientKeyPassword) {
$SecureClientKeyPassword = Read-Host -Prompt "Enter password for encrypted key" -AsSecureString
}
if ($SecureClientKeyPassword) {
$ClientKeyPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureClientKeyPassword))
}
$PemCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromEncryptedPem($CertificateContent, $KeyContent, $ClientKeyPassword)
}
else {
$PemCertificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromPem($CertificateContent, $KeyContent)
}
$PFXBytes = $PemCertificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
$PFX = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($PFXBytes)
return $PFX
}
}
function Resolve-GoogleDNS {
<#
.SYNOPSIS
Resolve DNS request from Google's DoH
.DESCRIPTION
Make a simple DNS request to Google's DoH server, with optional type
.NOTES
Author: S Macleod
Date: 29/10/25
.PARAMETER Name
Hostname to resolve
.PARAMETER Type
DNS Type to use
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[string]
$Name,
[Parameter()]
[string]
$Type
)
Process {
$Query = "name=$Name"
if ($Type) {
$Query += "&type=$Type"
}
$RequestParams = @{
Method = 'GET'
Uri = "https://dns.google/resolve?$Query"
}
try {
$Result = Invoke-RestMethod @RequestParams
}
catch {
throw "Resolve-GoogleDNS: DNS lookup failed: $_"
}
if ($null -eq $Result.Answer) {
throw "Resolve-GoogleDNS: Hostname $Hostname does not resolve in DNS."
}
return $Result.answer
}
}
function Write-ColourBody {
Param(
[Parameter(Mandatory)]
[AllowEmptyString()]
[string]
$Output,
[Parameter()]
[AllowEmptyString()]
[string]
$ContentType,
[Parameter(Mandatory)]
[object]
$ColourPalette,
[Parameter()]
[switch]
$Always
)
switch -wildcard ($ContentType) {
'application/*json*' { Write-ColourJSON -JSON $Output -ColourPalette $ColourPalette }
'application/*xml*' { Write-Output $Output } # TODO: Write pretty handler
'application/*html*' { Write-Output $Output } # TODO: Write pretty handler
'application/*javascript*' { Write-Output $Output } # TODO: Write pretty handler
'application/x-mpegURL' { Write-Output $Output } # TODO: Write pretty handler
'multipart/form-data*' { Write-Output $Output }
'image/svg*' { Write-Output $Output } # TODO: Write XML handler
'text/*' { Write-Output $Output }
'' { Write-Output $Output } # For no content-type, try printing directly
default {
if ($Always) {
Write-Output $Output
}
else {
Write-ColourOutput "-- Binary data in format '|-$($ColourPalette.KeyColour)-|$ContentType|-!-|' not shown in terminal --"
}
}
}
}
function Write-ColourHeaders {
Param(
[Parameter(Mandatory, ValueFromPipeline)]
[object[]]
$Header,
[Parameter(Mandatory)]
[object]
$ColourPalette
)
Process {
Write-ColourOutput "|-$($ColourPalette.KeyColour)-|$($Header.Name)|-!-|: $($Header.Value)"
}
}
function Write-ColourJSON {
Param(
[Parameter(Mandatory, ValueFromPipeline)]
[string]
$JSON,
[Parameter(Mandatory)]
[object]
$ColourPalette
)
Begin {
$CollatedStrings = New-Object -TypeName System.Collections.Generic.List['String']
}
Process {
if ($MyInvocation.ExpectingInput) {
$CollatedStrings.Add($JSON)
}
}
End {
if ($CollatedStrings.Count -gt 1) {
$JSON = $CollatedStrings -Join "`n"
}
$EOL = "(?=,*\s*$)"
# Format JSON
$FormattedJSON = ConvertFrom-Json -InputObject $JSON | ConvertTo-Json -Depth 100
# Find keys as any line which starts with a double-quoted string followed by a colon
$FormattedJSON = $FormattedJSON -Replace '(?m)([ ]+)("[^"\\\n\r]*(?:\\.[^"\\]*)*"(?=:))', "`$1|-$($ColourPalette.KeyColour)-|`$2|-!-|"
# Find all other sets of characters that the same match but NOT followed by a colon
$FormattedJSON = $FormattedJSON -replace '(?m)([ ]+)("[^"\\\n\r]*(?:\\.[^"\\]*)*"(?!:))', "`$1|-$($ColourPalette.StringColour)-|`$2|-!-|"
#Find true/false/null strings that end a line and colorize
$FormattedJSON = $FormattedJSON -replace "(?m)(true|false|null)$EOL", "|-$($ColourPalette.OtherColour)|`$1|-!-|"
# Find numbers that end a line and colorize
$FormattedJSON = $FormattedJSON -replace "(?m)(:[ ]*)(-?[\d\.]+([eE]{1}[+-][\d]+)?)$EOL", "`$1|-$($ColourPalette.NumberColour)-|`$2|-!-|"
Write-ColourOutput $FormattedJSON
}
}
function Write-ColourRequest {
Param(
[Parameter(Mandatory)]
[string]
$Method,
[Parameter(Mandatory)]
[string]
$HttpVersion,
[Parameter(Mandatory)]
[System.Uri]
$ParsedUri,
[Parameter(Mandatory)]
[object]
$ColourPalette
)
Write-ColourOutput "|-$($ColourPalette.CommentColour)-|$($Method.ToUpper())|-!-| $($ParsedUri.PathAndQuery) |-$($ColourPalette.CommentColour)-|HTTP|-!-|/|-$($ColourPalette.CommentColour)-|$HttpVersion|-!-|"
}
function Write-ColourStatus {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[string]
$RawStatus,
[Parameter(Mandatory)]
[object]
$ColourPalette
)
$StatusRegex = '(http|HTTP)\/([\d\.]+) ([\d]{3}) (.*)'
$StatusMatch = Select-String -InputObject $RawStatus -Pattern $StatusRegex
if ($StatusMatch) {
$HTTPPrefix = $StatusMatch.Matches[0].Groups[1].Value
$HTTPVersion = $StatusMatch.Matches[0].Groups[2].Value
$StatusCode = $StatusMatch.Matches[0].Groups[3].Value
$StatusDescription = $StatusMatch.Matches[0].Groups[4].Value
if ($null -eq $HTTPPrefix -or $null -eq $HTTPVersion -or $null -eq $StatusCode -or $null -eq $StatusDescription) {
throw "Status code '$RawStatus' is in an unknown format"
}
Write-ColourOutput "|-$($ColourPalette.CommentColour)-|$HTTPPrefix|-!-|/|-$($ColourPalette.CommentColour)-|$HTTPVersion |-$($ColourPalette.NumberColour)-|$StatusCode|-!-| $StatusDescription"
}
else {
throw "Status code '$RawStatus' is in an unknown format"
}
}
function Invoke-Http {
<#
.SYNOPSIS
Make an HTTP request and return the output in the desired format.
.DESCRIPTION
Create an HTTP request with user-friendly options for headers, queries and cookies and display the response in the given format. Parameters will result in a call to Invoke-WebRequest, so all IWR parameters are also supported. Note: these may vary based on your version of PowerShell, and will not be validated.
Parameters SkipHeaderValidation and SkipHttpError check are defaulted to $true, and MaximumRedirection is set to 0 so redirects are not chased by default. These can be overridden by supplied parameters if required.
.NOTES
Author: Stuart Macleod (@stuartio)
.PARAMETER Help
Show help and exit
.PARAMETER Uri
Request URI
.PARAMETER Method
Request Method. If a standard HTTP Method the Invoke-WebRequest `Method` parameter will be used. Otherwise the method will be passed to `CustomMethod`. Defaults to 'GET'
.PARAMETER Body
Request body, either as PSCustomObject, hashtable or string. Non-string objects are converted to JSON strings.
.PARAMETER Display
Format to display input and output elements. Can contain one or more of the following options: U - request URI including protocol and hostname, R - full HTTP request, H - request headers, B - request body, s - response status code and description, S - response status code only, h - response headers, b - response body as string, j - response body JSON string converted to PSCustomObject, x - response body XML converted to XML object. In various circumstances, the text printed to the screen will be coloured according to your shell settings, and will adapt accordingly.
.PARAMETER DisplayParts
Array of integers indicating which multi-part response parts to display. If not specified, all parts will be displayed. If specified, only the parts in the array will be displayed.
.PARAMETER DisplayHeaders
Array of strings indicating which response headers to display. If not specified, all headers will be displayed. If specified, only the headers in the array will be displayed.
.PARAMETER Http1
Use HTTP/1.0
.PARAMETER Http11
Use HTTP/1.1
.PARAMETER Http2
Use HTTP/2
.PARAMETER Http3
Use HTTP/3
.PARAMETER ClientCertificate
String containing base64-encoded public key of your client certificate.
.PARAMETER ClientCertificateFile
File containing base64-encoded public key of your client certificate.
.PARAMETER ClientKey
String containing base64-encoded private key of your client certificate. This can be either plain-text or encrypted. If encrypted, you must provide the password with the -ClientKeyPassword parameter, or provide it when prompted.
.PARAMETER ClientKeyFile
File containing base64-encoded private key of your client certificate.
.PARAMETER ClientKeyPassword
Password for your client key, if it is encrypted. Note: the password will be visible in your shell history if provided on the command line. If not provided, you will be prompted for it, but as a secure string so it will not be visible in your shell history.
.PARAMETER SecureClientKeyPassword
Secure string password for your client key, if it is encrypted. This option is more secure than using -ClientKeyPassword, but requires you to create a secure string object first.
.PARAMETER Resolve
Replace hostname in your request Uri, but maintain Host header. Analagous to the --resolve option in cURL.
.PARAMETER AdditionalParams
Placeholder parameter for all unnamed params (such as headers, query string parameters and cookies) that you might provide on the command line.
.PARAMETER Authentication
Authentication type to use, either 'None', 'Bearer', 'Basic', 'OAuth', or 'EdgeGrid'. If set to 'Basic' you must provide your username and password with the -Credentials parameter. If set to 'EdgeGrid', the EdgeGrid authentication header will be calculated and added to the request. This requires the additional parameters EdgeRCFile, Section and optionally AccountSwitchKey to be provided. For other authentication methods, see the associated help with Invoke-WebRequest.
.PARAMETER EdgeRCFile
Path to your .edgerc file containing your EdgeGrid credentials when the value of -Authentication is 'EdgeGrid'. If not provided, the default location of ~/.edgerc will be used.
.PARAMETER Section
Section of your .edgerc file to use when the value of -Authentication is 'EdgeGrid'. If not provided, selected section will be 'default'.
.PARAMETER AccountSwitchKey
Account Switch Key to use when the value of -Authentication is 'EdgeGrid'.
#>
[CmdletBinding(DefaultParameterSetName = 'h2')]
[Alias('web')]
Param(
[Parameter()]
[Alias('h')]
[switch]
$Help,
[Parameter(Position = 0)]
[string]
$Uri,
[Parameter()]
[string]
$Method = 'GET',
[Parameter(ParameterSetName = 'h1')]
[alias('h1')]
[switch]
$Http1,
[Parameter(ParameterSetName = 'h11')]
[Alias('h11')]
[switch]
$Http11,
[Parameter(ParameterSetName = 'h2')]
[Alias('h2')]
[switch]
$Http2,
[Parameter(ParameterSetName = 'h3')]
[Alias('h3')]
[switch]
$Http3,
[Parameter()]
[string]
$ClientCertificate,
[Parameter()]
[string]
$ClientCertificateFile,
[Parameter()]
[string]
$ClientKey,
[Parameter()]
[string]
$ClientKeyFile,
[Parameter()]
[string]
$ClientKeyPassword,
[Parameter()]
[System.Security.SecureString]
$SecureClientKeyPassword,
[Parameter()]
[string]
$Resolve,
[Parameter()]
[Alias('d')]
[string]
$Display = 'shb',
[Parameter()]
[int[]]
$DisplayParts,
[Parameter()]
[string[]]
$DisplayHeaders,
[Parameter(ValueFromPipeline)]
$Body,
[Parameter(ValueFromRemainingArguments)]
$AdditionalParams,
##-------------------- Default IWR Params beyond this point
[Parameter()]
[System.Management.Automation.SwitchParameter]
$AllowUnencryptedAuthentication,
[Parameter()]
[ValidateSet('None', 'Bearer', 'Basic', 'OAuth', 'EdgeGrid')]
[string]
$Authentication,
[Parameter()]
[System.Security.Cryptography.X509Certificates.X509Certificate]
$Certificate,
[Parameter()]
[System.String]
$CertificateThumbprint,
[Parameter()]
[System.String]
$ContentType,
[Parameter()]
[System.Management.Automation.PSCredential]
$Credential,
[Parameter()]
[System.String]
$CustomMethod,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$DisableKeepAlive,
[Parameter()]
[System.Collections.IDictionary]
$Form,
[Parameter()]
[System.Collections.IDictionary]
$Headers,
[Parameter()]
[System.Version]
$HttpVersion,
[Parameter()]
[System.String]
$InFile,
[Parameter()]
[System.Int32]
$MaximumRedirection = 0,
[Parameter()]
[System.Int32]
$MaximumRetryCount,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$NoProxy,
[Parameter()]
[System.String]
$OutFile,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PreserveAuthorizationOnRedirect,
[Parameter()]
[System.Uri]
$Proxy = $env:https_proxy,
[Parameter()]
[System.Management.Automation.PSCredential]
$ProxyCredential,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$ProxyUseDefaultCredentials,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$Resume,