PSModules/Carbon.Windows.HttpServer/1.0.0/Carbon.Windows.HttpServer.psm1
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 |
# Copyright WebMD Health Services # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License #Requires -Version 5.1 Set-StrictMode -Version 'Latest' # Functions should use $script:moduleRoot as the relative root from which to find # things. A published module has its function appended to this file, while a # module in development has its functions in the Functions directory. $script:moduleRoot = $PSScriptRoot Add-Type -TypeDefinition (Get-Content -Raw -Path (Join-Path -Path $script:moduleRoot -ChildPath 'src\Http.cs' -Resolve)) # Store each of your module's functions in its own file in the Functions # directory. On the build server, your module's functions will be appended to # this file, so only dot-source files that exist on the file system. This allows # developers to work on a module without having to build it first. Grab all the # functions that are in their own files. $functionsPath = Join-Path -Path $script:moduleRoot -ChildPath 'Functions\*.ps1' if( (Test-Path -Path $functionsPath) ) { foreach( $functionPath in (Get-Item $functionsPath) ) { . $functionPath.FullName } } function Get-CHttpsCertificateBinding { <# .SYNOPSIS Gets the HTTPS certificate bindings on this computer. .DESCRIPTION The `Get-CHttpsCertificateBinding` returns all the HTTPS certificate bindings on the current computer. You can get specific bindings using an IP address, port, certificate thumbprint, and/or application ID, by using the `IPAddress`, `Port`, `Thumbprint`, and `ApplicationID` parameters. If a certificate that matches all the search criteria isn't found, the function writes an error. Uses the Windows API. .OUTPUTS Carbon.Windows.HttpServer.HttpsCertificateBinding. .EXAMPLE > Get-CHttpsCertificateBinding Demonstrates how to gets all the HTTPS certificate bindings on the local computer. .EXAMPLE > Get-CHttpsCertificateBinding -IPAddress 42.37.80.47 -Port 443 Demonstrates how to get the binding for a specific IP address and port. .EXAMPLE Get-HttpsCertificateBinding -IPAddress '1.2.3.4' Demonstrates how to get all bindings on a specific IP address by passing the IP address number to the `IPAddress` parameter. .EXAMPLE > Get-CHttpsCertificateBinding -Port 443 Demonstrates how to get all bindings on a specific port by passing the port number to the `Port` parameter. .EXAMPLE Get-CHttpsCertificateBinding -Thumbprint '4789073458907345907434789073458907345907' Demonstrates how to get all bindings using a specific certificate by passing the certificate's thumbprint to the `Thumbprint` parameter. .EXAMPLE Get-CHttpsCertificateBinding -ApplicationID '0c5a28db-f7e0-42f8-912b-9524fb49f054' Demonstrates how to get all bindings for a specific application by passing the application id to the `ApplicationID` parameter. #> [CmdletBinding()] [OutputType([Carbon.Windows.HttpServer.HttpsCertificateBinding])] param( # An IP address. Only bindings with this IP address are returned. [ipaddress] $IPAddress, # A port. Only bindings with this port number are returned. [UInt16] $Port, # A certificate thumbprint. Only bindings whose certificate hash matches this thumbprint are returned. [String] $Thumbprint, # An application ID. Only bindings whose application ID matches this value are returned. [Guid] $ApplicationID ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $WhatIfPreference = $false $searching = $IPAddress -or $Port -or $Thumbprint -or $ApplicationID $bindings = @() [Carbon.Windows.HttpServer.HttpsCertificateBinding]::GetHttpsCertificateBindings() | Where-Object { if( $IPAddress ) { return $_.IPAddress -eq $IPAddress } return $true } | Where-Object { if( $Port ) { return $_.Port -eq $Port } return $true } | Where-Object { if( $Thumbprint ) { return $_.CertificateHash -eq $Thumbprint } return $true } | Where-Object { if( $ApplicationID ) { return $_.ApplicationID -eq $ApplicationID } return $true } | Tee-Object -Variable 'bindings' | Write-Output if (-not $searching -or $bindings) { return } $ipPortMsg = '' if (-not $IPAddress) { $IPAddress = [ipaddress]'0.0.0.0' } $ipPortMsg = "$($IPAddress.IPAddressToString)" if ($IPAddress.AddressFamily -eq 'InterNetworkV6') { $ipPortMsg = "[$($ipPortMsg)]" } if ($Port) { $ipPortMsg = "$($ipPortMsg.TrimEnd()):$($Port)" } $thumbprintMsg = '' if ($Thumbprint) { $ipPortMsg = " using certificate $($Thumbprint)" } $appIdMsg = '' if ($ApplicationID) { $appIdMsg = " for application $($ApplicationID.ToString('B'))" } $msg = "HTTPS certificate binding $($ipPortMsg)$($thumbprintMsg)$($appIdMsg) does not exist." Write-Error -Message $msg -ErrorAction $ErrorActionPreference } function Invoke-Netsh { <# .SYNOPSIS INTERNAL. .DESCRIPTION INTERNAL. .EXAMPLE INTERNAL. #> [CmdletBinding(SupportsShouldProcess)] param( # The target of the action. [Parameter(Mandatory)] [String] $Target, # The action/command being performed. [Parameter(Mandatory)] [String] $Action, # The command to run. [Parameter(Mandatory, ValueFromRemainingArguments, Position=0)] [String[]] $ArgumentList, # A comment to show at the end of the information message. [String] $Comment ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if (-not $PSCmdlet.ShouldProcess($Target, $Action)) { return } if ($Comment) { $Comment = " # $($Comment)" } Write-Information "netsh $($ArgumentList -join ' ')$($Comment)" $output = netsh $ArgumentList if( $LASTEXITCODE ) { $output = $output -join [Environment]::NewLine $msg = "Netsh command ""$($Action)"" on ""$($Target)"" exited with code $($LASTEXITCODE): $($output)" Write-Error -Message $msg -ErrorAction $ErrorActionPreference return } $output | Where-Object { $null -ne $_ } | Write-Verbose } function Remove-CHttpsCertificateBinding { <# .SYNOPSIS Removes HTTPS certificate bindings. .DESCRIPTION Uses the netsh command line application to remove HTTPS certificate bindings. Pass any combination of IP address, port, thumbprint, or application ID to the `IPAddress`, `Port`, `Thumbprint`, and `ApplicationID` parmeters, respectively. All bindings that match all of the parameters you pass will be deleted. You must pass at least one. .EXAMPLE > Remove-CHttpsCertificateBinding -IPAddress '45.72.89.57' Demonstrates how to remove all HTTPS certificate bindings on a specific IP address. In this example, all bindings to IP address `45.72.89.57` will be removed. .EXAMPLE > Remove-CHttpsCertificateBinding -Port 443 Demonstrates how to remove all HTTPS certificate bindings on a specific port. In this example, all bindings to port `44444` will be removed. .EXAMPLE Remove-CHttpsCertificateBinding -Thumbprint '7d5ce4a8a5ec059b829ed135e9ad8607977691cc' Demonstrates how to remove all HTTPS certificate bindings using a specific certificate by passing its thumbprint to the `Thumbprint` parameter.. In this example, all bindings to certificate with thumbprint `7d5ce4a8a5ec059b829ed135e9ad8607977691cc` are deleted. .EXAMPLE Remove-CHttpsCertificateBinding -ApplicationID 'd27985ca-2fa5-4794-9a87-76de4ed7d3e8' Demonstrates how to remove all HTTPS certificate bindings for a specific application by passing the application ID to the `ApplicationID` parameter. In this example, all bindings for application `d27985ca-2fa5-4794-9a87-76de4ed7d3e8` will be removed. .EXAMPLE Get-CHttpsCertificateBinding -ApplicationID 'd27985ca-2fa5-4794-9a87-76de4ed7d3e8' | Remove-CHttpsCertificateBinding Demonstrates that you can pipe the output of `Get-CHttpsCertificateBinding` to `Remove-CHttpsCertificateBinding` to remove bindings. #> [Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '')] [CmdletBinding(SupportsShouldProcess)] param( # The IP address whose bindings to remove. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [ipaddress] $IPAddress, # The port of the bindings to remove. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [UInt16] $Port, # The thumbprint whose bindings to remove. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('CertificateHash')] [String] $Thumbprint, # The application whose bindings to remove. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [Guid] $ApplicationID, # If calling `Remove-CHttpsCertificateBinding` with no arguments, the function prompts for confirmation to delete # all bindings. Use this switch to skip the confirmation prompt. [switch] $Force ) process { Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if (-not $Force -and (-not $IPAddress -and -not $Port -and -not $Thumbprint -and -not $ApplicationID)) { $query = 'Delete all HTTPS certificate bindings on this computer?' $caption = 'If you choose Yes, *all* HTTPS certificates will be deleted on this computer. This will ' + 'break any HTTPS applications. If you choose No, no changes will be made. To delete all ' + 'bindings without being prompted to confirm, use the Force (switch).' if (-not $PSCmdlet.ShouldContinue($query, $caption)) { return } } $getArgs = @{} if ($IPAddress) { $getArgs['IPAddress'] = $IPAddress } if ($Port) { $getArgs['Port'] = $Port } if ($Thumbprint) { $getArgs['Thumbprint'] = $Thumbprint } if ($ApplicationID) { $getArgs['ApplicationID'] = $ApplicationID } $foundOne = $false foreach ($binding in (Get-CHttpsCertificateBinding @getArgs -ErrorAction Ignore)) { $foundOne = $true if( $binding.IPAddress.AddressFamily -eq [Net.Sockets.AddressFamily]::InterNetworkV6 ) { $ipPort = '[{0}]:{1}' -f $binding.IPAddress,$binding.Port } else { $ipPort = '{0}:{1}' -f $binding.IPAddress,$binding.Port } $target = "$($ipPort) that uses certificate $($binding.CertificateHash) for application " + "$($binding.ApplicationID.ToString('B'))." Invoke-Netsh http delete sslcert "ipPort=$($ipPort)" ` -Comment "certhash=$($binding.CertificateHash) appid=$($binding.ApplicationID.ToSTring('B'))" ` -Target $target ` -Action "removing HTTPS certificate binding" } if ($foundOne) { return } $ipMsg = '0.0.0.0' if ($IPAddress) { $ipMsg = "$($IPAddress.IPAddressToString)" if ($IPAddress.AddressFamily -eq [Net.Sockets.AddressFamily]::InterNetworkV6) { $ipMsg = "[$($ipMsg)]" } } $portMsg = '*' if ($Port) { $portMsg = $Port } $ipMsg = "$($ipMsg):$($portMsg)" $thumbprintMsg = '' if ($Thumbprint) { $thumbprintMsg = " that uses certificate with thumbprint $($Thumbprint)" } $appIdMsg = '' if ($ApplicationID) { $appIdMsg = " for application $($ApplicationID.ToString('B'))" } "Unable to delete HTTPS certificate binding $($ipMsg)$($thumbprintMsg)$($appIdMsg) because it does not exist." | Write-Error -ErrorAction $ErrorActionPreference } } function Set-CHttpsCertificateBinding { <# .SYNOPSIS Creates or updates an HTTPS certificate binding. .DESCRIPTION The `Set-CHttpsCertificateBinding` creates an HTTPS certificate binding. Pass the IP address of the binding to the `IPAddress` parameter. Pass the port number of the binding to the `Port` parameter. Pass the certificate thumbprint for the binding to the `Thumbprint` parameter. Pass the application ID of the binding to the `ApplicationID` parameter. Only one binding is allowed per IP address and port. If a binding exists on the given IP address and port that doesn't match the given application ID and certificate, the existing binding is removed, and a new binding is created. If you want an object representing the binding to be returned, use the `PassThru` switch. Uses the `netsh http add sslcert` command. .OUTPUTS Carbon.Windows.HttpServer.HttpsCertificateBinding. .EXAMPLE Set-CHttpsCertificateBinding -IPAddress 43.27.89.54 -Port 443 -ApplicationID 88d1f8da-aeb5-40a2-a5e5-0e6107825df7 -Thumbprint 4789073458907345907434789073458907345907 Configures the computer to use the 478907345890734590743 certificate on IP 43.27.89.54, port 443. #> [Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '')] [CmdletBinding(SupportsShouldProcess)] [OutputType([Carbon.Windows.HttpServer.HttpsCertificateBinding])] param( # The IP address for the binding. [Parameter(Mandatory)] [ipaddress] $IPAddress, # The port for the binding. [Parameter(Mandatory)] [UInt16] $Port, # The thumbprint of the certificate to use. The certificate must be installed. [Parameter(Mandatory)] [ValidatePattern("^[0-9a-f]{40}$")] [String] $Thumbprint, # A unique ID representing the application using the binding. Create your own. [Parameter(Mandatory)] [Guid] $ApplicationID, # The name of the store where the certificate can be found. Defaults to `My`. Certificates must be stored in # the LocalMachine location/context. [String] $StoreName = 'My', # Return a `Carbon.Windows.HttpServer.HttpsCertificateBinding` for the configured binding. [switch] $PassThru ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState # Only one binding can exist on an IP address and port. $bindingExists = Test-CHttpsCertificateBinding -IPAddress $IPAddress -Port $Port if ($bindingExists) { # If the existing binding is for the same application using the same thumbprint, we don't need to do anything. $bindingExists = Test-CHttpsCertificateBinding -IPAddress $IPAddress ` -Port $Port ` -Thumbprint $Thumbprint ` -ApplicationID $ApplicationID if ($bindingExists) { return } Remove-CHttpsCertificateBinding -IPAddress $IPAddress -Port $Port } if( $IPAddress.AddressFamily -eq [Net.Sockets.AddressFamily]::InterNetworkV6 ) { $ipPort = '[{0}]:{1}' -f $IPAddress,$Port } else { $ipPort = '{0}:{1}' -f $IPAddress,$Port } $appID = $ApplicationID.ToString('B') Invoke-Netsh http add sslcert ipport=$ipPort certhash=$Thumbprint appid=$appID certstore=$StoreName ` -Target $ipPort ` -Action 'creating HTTPS certificate binding' if( $PassThru ) { $errorActionArg = @{} if ($WhatIfPreference) { $errorActionArg['ErrorAction'] = 'Ignore' } Get-CHttpsCertificateBinding -IPAddress $IPAddress -Port $Port @errorActionArg } } function Test-CHttpsCertificateBinding { <# .SYNOPSIS Tests if an HTTPS certificate binding exists. .DESCRIPTION The `Test-CHttpsCertificateBinding` tests if an HTTPS certificate binding exists. You can check if a binding exists by passing an IP address, port, certificate thumbprint, and/or application ID to the `IPAddress`, `Port`, `Thumbprint`, and `ApplicationID` parameters, respectively. If a cert exists that matches all the criteria you pass, the function returns `$true`, otherwise it returns `$false`. If you pass no arguments, the function tests if *any* bindings exist. .EXAMPLE Test-CHttpsCertificateBinding -Port 443 Tests if there are any bindings on port 443. .EXAMPLE Test-CHttpsCertificateBinding -IPAddress 10.0.1.1 Tests if there are any bindings on IP address `10.0.1.1`. .EXAMPLE Test-CHttpsCertificateBinding -Thumbprint '7d5ce4a8a5ec059b829ed135e9ad8607977691cc' Tests if there are any bindings to certificate with thumbprint `7d5ce4a8a5ec059b829ed135e9ad8607977691cc`. .EXAMPLE Test-CHttpsCertificateBinding -ApplicationID '71740b45-ea65-48c4-a8bd-6f2110c52ba7' Tests if there are any bindings for application whose ID is `71740b45-ea65-48c4-a8bd-6f2110c52ba7`. .EXAMPLE Test-CHttpsCertificateBinding Tests if there are any bindings on the machine. #> [CmdletBinding()] param( # The IP address. [ipaddress] $IPAddress, # The port. [Uint16] $Port, # The certificate thumbprint. [String] $Thumbprint, # The application ID [Guid] $ApplicationID ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $getArgs = @{ } if ($IPAddress) { $getArgs['IPAddress'] = $IPAddress } if ($Port) { $getArgs['Port']= $Port } if ($Thumbprint) { $getArgs['Thumbprint'] = $Thumbprint } if ($ApplicationID) { $getArgs['ApplicationID'] = $ApplicationID } $binding = Get-CHttpsCertificateBinding @getArgs -ErrorAction Ignore if ($binding) { return $true } return $false } function Use-CallerPreference { <# .SYNOPSIS Sets the PowerShell preference variables in a module's function based on the callers preferences. .DESCRIPTION Script module functions do not automatically inherit their caller's variables, including preferences set by common parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't get passed into any function that belongs to a module. When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the function's caller: * ErrorAction * Debug * Confirm * InformationAction * Verbose * WarningAction * WhatIf This function should be used in a module's function to grab the caller's preference variables so the caller doesn't have to explicitly pass common parameters to the module function. This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d). There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get fixed. .LINK about_Preference_Variables .LINK about_CommonParameters .LINK https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d .LINK http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/ .EXAMPLE Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Demonstrates how to set the caller's common parameter preference variables in a module function. #> [CmdletBinding()] param ( [Parameter(Mandatory)] #[Management.Automation.PSScriptCmdlet] # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]` # attribute. $Cmdlet, [Parameter(Mandatory)] # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the # `[CmdletBinding()]` attribute. # # Used to set variables in its callers' scope, even if that caller is in a different script module. [Management.Automation.SessionState]$SessionState ) Set-StrictMode -Version 'Latest' # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken # from about_CommonParameters). $commonPreferences = @{ 'ErrorActionPreference' = 'ErrorAction'; 'DebugPreference' = 'Debug'; 'ConfirmPreference' = 'Confirm'; 'InformationPreference' = 'InformationAction'; 'VerbosePreference' = 'Verbose'; 'WarningPreference' = 'WarningAction'; 'WhatIfPreference' = 'WhatIf'; } foreach( $prefName in $commonPreferences.Keys ) { $parameterName = $commonPreferences[$prefName] # Don't do anything if the parameter was passed in. if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) ) { continue } $variable = $Cmdlet.SessionState.PSVariable.Get($prefName) # Don't do anything if caller didn't use a common parameter. if( -not $variable ) { continue } if( $SessionState -eq $ExecutionContext.SessionState ) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } } |