Private/HelperUtilities.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 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 |
Function Out-Verbose { Param($out) Write-Verbose "$((Get-Variable MyInvocation -Scope 1).Value.MyCommand.Name): $out" } Function Out-Warning { Param($out) Write-Warning "$((Get-Variable MyInvocation -Scope 1).Value.MyCommand.Name): $out" } Function IsAdfsSyncPrimaryRole([switch] $force) { if ((IsAdfsServiceRunning) -and (-not $script:adfsSyncRole -or $force)) { try { $stsrole = Get-ADFSSyncProperties | Select-Object -ExpandProperty Role $script:isAdfsSyncPrimaryRole = $stsrole -eq "PrimaryComputer" } catch { #Write-Verbose "Could not tell if running on a primary WID sync node. Returning false..." return $false } } return $script:isAdfsSyncPrimaryRole } Function Retrieve-AdfsProperties([switch] $force) { if ((IsAdfsServiceRunning) -and (-not $script:adfsProperties -or $force)) { $isPrimary = IsAdfsSyncPrimaryRole -force $force if ($isPrimary) { $script:adfsProperties = Get-AdfsProperties } } return $script:adfsProperties } Function Test-RunningOnAdfsSecondaryServer { return -not (IsAdfsSyncPrimaryRole) } Function Test-RunningRemotely { return (Get-Host).Name -eq "ServerRemoteHost"; } Function Get-AdfsVersion { $OSVersion = [System.Environment]::OSVersion.Version If ($OSVersion.Major -eq 6) { # Windows 2012 R2 If ($OSVersion.Minor -ge 3) { return $adfs3; } Else { #Windows 2012, 2008 R2, 2008 If ($OSVersion.Minor -lt 3) { return $adfs2x; } } } If ($OSVersion.Major -eq 10) { # Windows Server 10 If ($OSVersion.Minor -eq 0) { return $adfs3; } } return $null } Function EnvOSVersionWrapper { return [System.Environment]::OSVersion.Version; } Function Get-OsVersion { $OSVersion = EnvOSVersionWrapper if (($OSVersion.Major -eq 10) -and ($OSVersion.Minor -eq 0)) { # Windows Server 2016 return [OSVersion]::WS2016; } elseif ($OSVersion.Major -eq 6) { # Windows 2012 R2 if ($OSVersion.Minor -ge 3) { return [OSVersion]::WS2012R2; } elseif ($OSVersion.Minor -lt 3) { #Windows 2012 return [OSVersion]::WS2012; } } return [OSVersion]::Unknown; } Function Import-ADFSAdminModule() { #Used to avoid extra calls to Add-PsSnapin so DFTs function appropriately on WS 2008 R2 if ($testMode) { return } $OSVersion = [System.Environment]::OSVersion.Version If ($OSVersion.Major -eq 6) { # Windows 2012 R2 and 2012 If ($OSVersion.Minor -ge 2) { Import-Module ADFS } Else { #Windows 2008 R2, 2008 If ($OSVersion.Minor -lt 2) { if ( (Get-PSSnapin -Name Microsoft.Adfs.Powershell -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin Microsoft.Adfs.Powershell } } } } } Function Get-AdfsRole() { #ADFS 2012 R2 STS: hklm:\software\microsoft\adfs FSConfigurationStatus = 2 $adfs3StsRegValue = Get-ItemProperty "hklm:\software\microsoft\adfs" -Name FSConfigurationStatus -ErrorAction SilentlyContinue if ($adfs3StsRegValue.FSConfigurationStatus -eq 2) { return $adfsRoleSTS } #ADFS 2012 R2 Proxy: hklm:\software\microsoft\adfs ProxyConfigurationStatus = 2 $adfs3ProxyRegValue = Get-ItemProperty "hklm:\software\microsoft\adfs" -Name ProxyConfigurationStatus -ErrorAction SilentlyContinue if ($adfs3ProxyRegValue.ProxyConfigurationStatus -eq 2) { return $adfsRoleProxy } #ADFS 2.x STS: HKLM:\Software\Microsoft\ADFS2.0\Components SecurityTokenServer = 1 $adfs2STSRegValue = Get-ItemProperty "hklm:\software\microsoft\ADFS2.0\Components" -Name SecurityTokenServer -ErrorAction SilentlyContinue if ($adfs2STSRegValue.SecurityTokenServer -eq 1) { return $adfsRoleSTS } #ADFS 2.x Proxy: HKLM:\Software\Microsoft\ADFS2.0\Components ProxyServer = 1 $adfs2STSRegValue = Get-ItemProperty "hklm:\software\microsoft\ADFS2.0\Components" -Name ProxyServer -ErrorAction SilentlyContinue if ($adfs2STSRegValue.ProxyServer -eq 1) { return $adfsRoleProxy } return "none" } Function Get-ServiceState($serviceName) { return (Get-Service $serviceName -ErrorAction SilentlyContinue).Status } Function IsAdfsServiceRunning() { $adfsSrv = Get-ServiceState($adfsServiceName) return $adfsSrv -ne $null -and ($adfsSrv -eq "Running") } Function IsAdfsProxyServiceRunning() { $adfsSrv = Get-ServiceState($adfsProxyServiceName) return $adfsSrv -ne $null -and ($adfsSrv -eq "Running") } Function GetHttpsPort { $stsrole = Get-ADFSSyncProperties | Select-Object -ExpandProperty Role if (IsAdfsSyncPrimaryRole) { return (Retrieve-AdfsProperties).HttpsPort } else { #TODO: How to find the Https Port in secondaries generically? return 443; } } Function GetSslBinding() { #Get ssl bindings from registry. Due to limitations on the IIS powershell, we cannot use the iis:\sslbindings #provider $httpsPort = GetHttpsPort $adfsVersion = Get-AdfsVersion if ( $adfsVersion -eq $adfs2x) { $portRegExp = "^.*" + ":" + $httpsPort.ToString() + "$"; $bindingRegKeys = dir hklm:\system\currentcontrolset\services\http\parameters\SslBindingInfo -ErrorAction SilentlyContinue | where {$_.Name -match $portRegExp} if ($bindingRegKeys -eq $null) { #no bindings found in the given port. Returning null return $null } else { $bindingFound = ($bindingRegKeys)[0]; $bindingProps = $bindingFound | Get-ItemProperty $name = $bindingFound.PSChildName $bindingHost = $name.Split(':')[0] #if the binding is the fallback 0.0.0.0 address, then point to localhost if ($bindingHost -eq "0.0.0.0") { $bindingHost = "localhost" } $hostNamePort = $bindingHost.ToString() + ":" + $httpsPort.ToString() $thumbprintBytes = $bindingProps.SslCertHash; $thumbprint = "" $thumbprintBytes | % { $thumbprint = $thumbprint + $_.ToString("X2"); } $sslCert = dir Cert:\LocalMachine\My\$thumbprint -ErrorAction SilentlyContinue $result = New-Object PSObject $result | Add-Member NoteProperty -name "Name" -value $name $result | Add-Member NoteProperty -name "Host" -value $bindingHost $result | Add-Member NoteProperty -name "Port" -value $httpsPort $result | Add-Member NoteProperty -name "HostNamePort" -value $hostNamePort $result | Add-Member NoteProperty -name "Thumbprint" -value $thumbprint $result | Add-Member NoteProperty -name "Certificate" -value $sslCert return $result } } else { if ($adfsVersion -eq $adfs3) { #select the first binding for the https port found in configuration $sslBinding = Get-AdfsSslCertificate | Where-Object {$_.PortNumber -eq $httpsPort} | Select-Object -First 1 $thumbprint = $sslBinding.CertificateHash $sslCert = dir Cert:\LocalMachine\My\$thumbprint -ErrorAction SilentlyContinue $result = New-Object PSObject $result | Add-Member NoteProperty -name "Name" -value $sslBinding.HostName $result | Add-Member NoteProperty -name "Host" -value "localhost" $result | Add-Member NoteProperty -name "Port" -value $httpsPort $result | Add-Member NoteProperty -name "HostNamePort" -value ("localhost:" + $httpsPort.ToString()); $result | Add-Member NoteProperty -name "Thumbprint" -value $thumbprint $result | Add-Member NoteProperty -name "Certificate" -value $sslCert return $result } } } Function GetAdfsCertificatesToCheck($primaryFilter) { #Skip service communication cert if there are no message security endpoints $endpoints = Get-AdfsEndpoint | where {$_.SecurityMode -eq 'Message' -and $_.Enabled -eq $true -and $_.AddressPath -ne '/adfs/services/trusttcp/windows'} $skipCommCert = ($endpoints -eq $null) #get all certs $adfsCertificates = Get-AdfsCertificate | where {$_.IsPrimary -eq $primaryFilter} if ($skipCommCert) { $adfsCertificates = $adfsCertificates | where {$_.CertificateType -ne "Service-Communications"} } return $adfsCertificates } function GetAdHealthAgentRegistryKeyValue($valueName, $defaultValue) { $agentRegistryValue = Get-ItemProperty -path $AdHealthAgentRegistryKeyPath -Name $valueName -ErrorAction SilentlyContinue if ($agentRegistryValue -eq $null) { return $defaultValue; } else { return $agentRegistryValue.$valueName; } } Function IsLocalUser { $isLocal = ($env:COMPUTERNAME -eq $env:USERDOMAIN) return $isLocal } Function GetObjectsFromAD ($domain, $filter) { Out-Verbose "Domain = $domain, filter = $filter"; $rootDomain = New-Object System.DirectoryServices.DirectoryEntry $searcher = New-Object System.DirectoryServices.DirectorySearcher $domain $searcher.SearchRoot = $rootDomain $searcher.SearchScope = "SubTree" $props = $searcher.PropertiestoLoad.Add("distinguishedName") $props = $searcher.PropertiestoLoad.Add("objectGuid") $searcher.Filter = $filter return $searcher.FindAll() } Function Get-FirstEnabledWIAEndpointUri() { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $cli = New-Object net.WebClient; $sslBinding = GetSslBinding $mexString = $cli.DownloadString("https://" + $sslBinding.HostNamePort + "/adfs/services/trust/mex") $xmlMex = [xml]$mexString $wiaendpoint = $xmlMex.definitions.service.port | where {$_.EndpointReference.Address -match "trust/\d+/(windows|kerberos)"} | select -First 1 if ($wiaendpoint -eq $null) { return $null } else { return $wiaendpoint.EndpointReference.Address } } Function Get-ADFSIdentifier { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $cli = New-Object net.WebClient; $sslBinding = GetSslBinding $cli.Encoding = [System.Text.Encoding]::UTF8 $fedmetadataString = $cli.DownloadString("https://" + $sslBinding.HostNamePort + "/federationmetadata/2007-06/federationmetadata.xml") $fedmetadata = [xml]$fedmetadataString return $fedmetadata.EntityDescriptor.entityID } Function NetshHttpShowSslcert { return (netsh http show sslcert) } Function GetSslBindings { $output = NetshHttpShowSslcert | ForEach-Object {$tok = $_.Split(":"); IF ($tok.Length -gt 1 -and $tok[1].TrimEnd() -ne "" -and $tok[0].StartsWith(" ")) {$_}} $bindings = @{}; $bindingName = ""; foreach ($bindingLine in $output) { $splitLine = $bindingLine.Split(":"); switch -WildCard ($bindingLine.Trim().ToLower()) { "ip:port*" { $bindingName = $splitLine[2].Trim() + ":" + $splitLine[3].Trim(); $bindings[$bindingName] = @{}; } "hostname:port*" { $bindingName = $splitLine[2].Trim() + ":" + $splitLine[3].Trim(); $bindings[$bindingName] = @{}; } "certificate hash*" { $bindings[$bindingName].Add("Thumbprint", $splitLine[1].Trim()); } "application id*" { $bindings[$bindingName].Add("Application ID", $splitLine[1].Trim()); } "ctl store name*" { $bindings[$bindingName].Add("Ctl Store Name", $splitLine[1].Trim()); } } } $bindings; } Function IsSslBindingValid { Param ( # The SSL bindings dictionary [Parameter(Mandatory = $true)] [Object] $Bindings, # The IP port or hostname port # Format: "127.0.0.0:443" or "localhost:443" [Parameter(Mandatory = $true)] [string] $BindingIpPortOrHostnamePort, # The thumbprint of the AD FS SSL certificate [Parameter(Mandatory = $true)] [string] $CertificateThumbprint, # Bool to check for Ctl Store [Parameter(Mandatory = $false)] [boolean] $VerifyCtlStoreName = $true ) $returnVal = @{} Out-Verbose "Validating SSL binding for $BindingIpPortOrHostnamePort."; if (!$Bindings[$BindingIpPortOrHostnamePort]) { Out-Verbose "Fail: No binding could be found with $BindingIpPortOrHostnamePort"; $returnVal["Detail"] = "The following SSL certificate binding could not be found $BindingIpPortOrHostnamePort."; $returnVal["IsValid"] = $false; return $returnVal; } $binding = $Bindings[$BindingIpPortOrHostnamePort]; if ($binding["Thumbprint"] -ne $CertificateThumbprint) { Out-Verbose "Fail: Not matching thumbprint"; $returnVal["Detail"] = "The following SSL certificate binding $BindingIpPortOrHostnamePort did not match the AD FS SSL thumbprint: $CertificateThumbprint."; $returnVal["IsValid"] = $false; return $returnVal; } if ($VerifyCtlStoreName -and $binding["Ctl Store Name"] -ne $ctlStoreName) { Out-Verbose "Fail: Not matching Ctl store name"; $returnVal["Detail"] = "The following SSL certificate binding $BindingIpPortOrHostnamePort did not have the correct Ctl Store Name: AdfsTrustedDevices."; $returnVal["IsValid"] = $false; return $returnVal; } Out-Verbose "Successfully validated SSL binding for $BindingIpPortOrHostnamePort."; $returnVal["IsValid"] = $true; return $returnVal; } Function IsUserPrincipalNameFormat { Param ( [string] $toValidate ) if ([string]::IsNullOrEmpty($toValidate)) { return $false; } return $toValidate -Match $EmailAddressRegex; } Function CheckRegistryKeyExist($key) { return (Get-Item -LiteralPath $key -ErrorAction SilentlyContinue) -ne $null; } Function IsTlsVersionEnabled($version) { $TlsVersionPath = $TlsPath -f "$version"; Out-Verbose "Checking if TLS $version is enabled"; if (CheckRegistryKeyExist($TlsVersionPath)) { Out-Verbose "The registry key exists for this TLS version"; $clientPath = $TlsClientPath -f $TlsVersionPath; $serverPath = $TlsServerPath -f $TlsVersionPath; if (CheckRegistryKeyExist($clientPath) -and CheckRegistryKeyExist($serverPath)) { Out-Verbose "Both Client and Server keys exist."; $clientEnabled = IsTlsVersionEnabledInternal $clientPath; $serverEnabled = IsTlsVersionEnabledInternal $serverPath return $clientEnabled -and $serverEnabled; } } else { Out-Verbose "The registry key for this TLS version does not exist at $TlsVersionPath"; } return $true; } Function GetValueFromRegistryKey($key, $name) { return $key.GetValue($name); } Function IsTlsVersionEnabledInternal($path) { Out-Verbose "Checking if version is enabled for $path"; $key = Get-Item -LiteralPath $path; $enabled = GetValueFromRegistryKey $key "Enabled" $disabledByDefault = GetValueFromRegistryKey $key "DisabledByDefault" Out-Verbose "Enabled = $enabled"; Out-Verbose "DisabledByDefault = $disabledByDefault"; if (($enabled -ne $null -and $enabled -eq 0) -and ($disabledByDefault -ne $null -and $disabledByDefault -eq 1)) { Out-Verbose "It is properly disabled"; return $false; } Out-Verbose "It is enabled"; return $true; } Function IsServerTimeInSyncWithReliableTimeServer { Out-Verbose "Comparing server time with reliable time server"; $originalCallback = [System.Net.ServicePointManager]::ServerCertificateValidationCallback; [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null; $originalSecurityProtocol = [Net.ServicePointManager]::SecurityProtocol; [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"; $request = Invoke-WebRequest -Uri 'http://nist.time.gov/actualtime.cgi?lzbc=siqm9b' -UseBasicParsing; [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $originalCallback; [Net.ServicePointManager]::SecurityProtocol = $originalSecurityProtocol; $currentRtsTimeUtc = (New-Object -TypeName DateTime -ArgumentList (1970, 1, 1)).AddMilliseconds(([Xml]$request.Content).timestamp.time / 1000); Out-Verbose "Current reliable time server time UTC $currentRtsTimeUtc"; $currentTimeFromServerUtc = (Get-Date).ToUniversalTime(); Out-Verbose "Current server time UTC $currentTimeFromServerUtc"; $timeDifferenceInSeconds = [int]($currentRtsTimeUtc - $currentTimeFromServerUtc).TotalSeconds; Out-Verbose "Time difference in seconds $timeDifferenceInSeconds"; if ($timeDifferenceInSeconds -eq $null -or $timeDifferenceInSeconds -lt ($timeDifferenceMaximum * -1) -or $timeDifferenceInSeconds -gt $timeDifferenceMaximum) { Out-Verbose "Detected that the time difference between reliable time server and the current server time is greater $timeDifferenceMaximum or less than -$timeDifferenceMaximum"; return $false; } return $true; } Function GetCertificatesFromAdfsTrustedDevices { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store($ctlStoreName, $localMachine); $store.open("ReadOnly"); return $store.Certificates; } Function VerifyCertificatesArePresent($certificatesInPrimaryStore) { $certificatesInStore = @(GetCertificatesFromAdfsTrustedDevices); $missingCerts = @(); foreach ($certificate in $certificatesInPrimaryStore) { if (!$certificatesInStore.Contains($certificate)) { $missingCerts += $certificate; } } return $missingCerts; } function GenerateDiagnosticData() { Param ( [switch] $includeTrusts, [string] $sslThumbprint, [string[]] $adfsServers, [switch] $local ) # configs # cmdlets to be run and have results output into the diagnostic file # structured as follows: # modules = @{module1 = @{cmdlet1.1 = arrayList of arguments, # cmdlet1.2 = arrayList of arguments, ...} # module2 = @{cmdlet2.1 = arrayList of arguments, ...} # ... # } # (the arguments will be joined and run with the cmdlet.) $modules = @{ADFSDiagnostics = @{ 'Test-AdfsServerHealth' = New-Object System.Collections.ArrayList; }; }; # version number of the output (updated when the function is changed) $outputVersion = $Script:ModuleVersion # end configs Out-Verbose "Binding each argument to relevant cmdlets" if ($includeTrusts) { $modules['ADFSDiagnostics']['Test-AdfsServerHealth'].Add('-includeTrusts') > $null } if ($sslThumbprint) { $modules['ADFSDiagnostics']['Test-AdfsServerHealth'].Add(-join('-sslThumbprint ', $sslThumbprint)) > $null } if ($adfsServers) { $modules['ADFSDiagnostics']['Test-AdfsServerHealth'].Add(-join('-AdfsServers ', $adfsServers)) > $null } if ($local) { $modules['ADFSDiagnostics']['Test-AdfsServerHealth'].Add('-local') > $null } # create aggregate object to store diagnostic output from each cmdlet run $diagnosticData = New-Object -TypeName PSObject foreach($module in $modules.keys) { $moduleData = New-Object -TypeName PSObject foreach($cmdlet in (($modules[$module]).keys)) { # join the arguments together $args = $modules[$module][$cmdlet]-join -' ' # join the command with the arguments $cmd = -join($module,'\', $cmdlet, ' ', $args) # upon success, add the cmdlet results; # otherwise add the error message Out-Verbose "Attempting to run cmdlet $cmdlet" try { $res = (Invoke-Expression -Command $cmd) Add-Member -InputObject $moduleData -MemberType NoteProperty -Name $cmdlet -Value $res Add-Member -InputObject $diagnosticData -MemberType NoteProperty -Name $module -Value $moduleData Out-Verbose "Successfully ran cmdlet $cmdlet" } catch { Write-Error -Message (-join("Error running cmdlet ", $cmd, ": ", $_.Exception.Message)) return $null } } } # add the cmdlet version to the output Add-Member -InputObject $diagnosticData -MemberType NoteProperty -Name "Version" -Value $outputVersion return $diagnosticData } function GenerateJSONDiagnosticData() { Param ( [switch] $includeTrusts, [string] $sslThumbprint, [string[]] $adfsServers, [switch] $local ) # configs # maximum global JSON depth in the diagnostic file $jsonDepth = 8 # end configs Out-Verbose "Generating diagnostic data" $diagnosticData = GenerateDiagnosticData -includeTrusts:$includeTrusts -sslThumbprint $sslThumbprint -adfsServers $adfsServers -local:$local; Out-Verbose "Successfully generated diagnostic data" return ConvertTo-JSON -InputObject $diagnosticData -Depth $jsonDepth } |