Public/Create-SubordinateCA.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 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 |
<#
.SYNOPSIS This function creates a new Enterprise Subordinate/Intermediate/Issuing Certification Authority by either... A) Creating a brand new Windows Server VM; or B) Using an existing Windows Server on the network ...and then running a configuration script over a PS Remoting Session. Since this script needs to request a Certificate from the Root CA, in order to avoid the double-hop authentication issue, a one-time-use Scheduled Task is created, immediately run, and deleted immediately after completion. .DESCRIPTION See .SYNOPSIS .NOTES .PARAMETER CreateNewVMs This parameter is OPTIONAL. This parameter is a switch. If used, a new Windows 2016 Standard Server Virtual Machine will be deployed to the localhost. If Hyper-V is not installed, it will be installed (and you will need to reatart the localhost before proceeding). .PARAMETER VMStorageDirectory This parameter is OPTIONAL, but becomes MANDATORY if the -CreateNewVMs parameter is used. This parameter takes a string that represents the full path to a directory on a LOCAL drive that will contain all new VM files (configuration, vhd(x), etc.) .PARAMETER Windows2016VagrantBox This parameter is OPTIONAL, but becomes MANDATORY if the -CreateNewVMs parameter is used. This parameter takes a string that represents the name of a Vagrant Box that can be downloaded from https://app.vagrantup.com/boxes/search. Default value is "jborean93/WindowsServer2016". Another good Windows 2016 Server Vagrant Box is "StefanScherer/windows_2016". You can alternatively specify a Windows 2012 R2 Standard Server Vagrant Box if desired. .PARAMETER ExistingDomain This parameter is MANDATORY. This parameter takes a string that represents the name of the domain that the Subordinate CA will join. Example: alpha.lab .PARAMETER DomainAdminCredentials This parameter is MANDATORY. This parameter takes a PSCredential. The Domain Admin Credentials will be used to join the Subordinate CA Server to the domain as well as configre the new Subordinate CA. This means that the Domain Account provided to this parameter MUST be a member of the following Security Groups in Active Directory: - Domain Admins - Domain Users - Enterprise Admins - Group Policy Creator Owners - Schema Admins .PARAMETER PSRemotingCredentials This parameter is MANDATORY. This parameter takes a PSCredential. The credential provided to this parameter should correspond to a User Account that has permission to remote into the target Windows Server. If you're using a Vagrant Box (which is what will be deployed if you use the -CreateNewVMs switch), then the value for this parameter should be created via: $VagrantVMPassword = ConvertTo-SecureString 'vagrant' -AsPlainText -Force $VagrantVMAdminCreds = [pscredential]::new("vagrant",$VagrantVMPassword) .PARAMETER IPOfServerToBeSubCA This parameter is OPTIONAL, however, if you do NOT use the -CreateNewVMs parameter, this parameter becomes MANDATORY. This parameter takes a string that represents an IPv4 Address referring to an EXISTING Windows Server on the network that will become the new Subordinate CA. .PARAMETER IPofDomainController This parameter is OPTIONAL, however, if you cannot resolve the Domain Name provided to the -ExistingDomain parameter from the localhost, then this parameter becomes MANDATORY. This parameter takes a string that represents an IPv4 address referring to a Domain Controller (not readonly) on the domain specified by the -ExistingDomain parameter. .PARAMETER IPOfRootCA This parameter is MANDATORY. This parameter takes a string that represents an IPv4 address referring to the Root CA on the domain specified by the -ExistingDomain parameter. .PARAMETER PrimaryHyperVHostIPOverride This parameter is OPTIONAL. This parameter takes a string that represents an IPv4 Address that you would like to use as your External Netowrk on your Hyper-V host. .PARAMETER SkipHyperVInstallCheck This parameter is OPTIONAL. This parameter is a switch. If used, this function will not check to make sure Hyper-V is installed on the localhost. .EXAMPLE # Open an elevated PowerShell Session, import the module, and - PS C:\Users\zeroadmin> $VagrantVMPassword = ConvertTo-SecureString 'vagrant' -AsPlainText -Force PS C:\Users\zeroadmin> $VagrantVMAdminCreds = [pscredential]::new("vagrant",$VagrantVMPassword) PS C:\Users\zeroadmin> $DomainAdminCreds = [pscredential]::new("alpha\alphaadmin",$(Read-Host 'Enter Passsword' -AsSecureString)) Enter Passsword: ************ PS C:\Users\zeroadmin> $CreateSubCASplatParams = @{ >> CreateNewVMs = $True >> VMStorageDirectory = "H:\VirtualMachines" >> ExistingDomain = "alpha.lab" >> IPOfDomainController = "192.168.2.112" >> IPOfRootCA = "192.168.2.113" >> PSRemotingCredentials = $VagrantVMAdminCreds >> DomainAdminCredentials = $DomainAdminCreds >> } PS C:\Users\zeroadmin> $CreateSubCAResult = Create-SubordinateCA @CreateSubCASplatParams #> function Create-SubordinateCA { [CmdletBinding()] Param ( [Parameter(Mandatory=$False)] [switch]$CreateNewVMs, [Parameter(Mandatory=$False)] [string]$VMStorageDirectory, [Parameter(Mandatory=$False)] [string]$Windows2016VagrantBox = "jborean93/WindowsServer2016", # Alternate - StefanScherer/windows_2016 [Parameter(Mandatory=$True)] [ValidatePattern("^([a-z0-9]+(-[a-z0-9]+)*\.)+([a-z]){2,}$")] [string]$ExistingDomain, [Parameter(Mandatory=$True)] [pscredential]$DomainAdminCredentials, [Parameter(Mandatory=$True)] [pscredential]$PSRemotingCredentials, [Parameter(Mandatory=$False)] [string]$IPofServerToBeSubCA, [Parameter(Mandatory=$False)] [string]$IPofDomainController, [Parameter(Mandatory=$True)] [string]$IPofRootCA, [Parameter(Mandatory=$False)] [string]$PrimaryHyperVHostIPOverride, [Parameter(Mandatory=$False)] [switch]$SkipHyperVInstallCheck ) #region >> Helper Functions # TestIsValidIPAddress # ResolveHost # GetDomainController # Deploy-HyperVVagrantBoxManually # Get-VagrantBoxManualDownload # New-SubordinateCA #endregion >> Helper Functions #region >> Prep $StartTime = Get-Date $ElevationCheck = [System.Security.Principal.WindowsPrincipal]::new([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) if (!$ElevationCheck) { Write-Error "You must run the build.ps1 as an Administrator (i.e. elevated PowerShell Session)! Halting!" $global:FunctionResult = "1" return } $PrimaryIfIndex = $(Get-CimInstance Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' } | Sort-Object Metric1)[0].InterfaceIndex $NicInfo = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.InterfaceIndex -eq $PrimaryIfIndex} $PrimaryIP = $NicInfo.IPAddress | Where-Object {TestIsValidIPAddress -IPAddress $_} if ($PrimaryHyperVHostIPOverride) { if (!$(TestIsValidIPAddress -IPAddress $PrimaryHyperVHostIPOverride)) { Write-Error "'$PrimaryHyperVHostIPOverride' is not a valid IPv4 ip address! Halting!" $global:FunctionResult = "1" return } $PrimaryIP = $PrimaryHyperVHostIPOverride } if ($PSBoundParameters['CreateNewVMs']-and !$PSBoundParameters['VMStorageDirectory']) { $VMStorageDirectory = Read-Host -Prompt "Please enter the full path to the directory where all VM files will be stored" } if (!$PSBoundParameters['CreateNewVMs'] -and $PSBoundParameters['VMStorageDirectory']) { $CreateNewVMs = $True } if ($CreateNewVMs -and $PSBoundParameters['IPofServerToBeSubCA']) { $ErrMsg = "The parameter-IPofServerToBeSubCA, and was used in conjunction with parameters " + "that indicate that a new VM should be deployed (i.e. -CreateNewVMs and/or -VMStorageDirectory) " + "Please only use -IPofServerToBeSubCA if that server are already exists on the network. Halting!" Write-Error $ErrMsg $global:FunctionResult = "1" return } if (!$CreateNewVMs -and ! $PSBoundParameters['IPofServerToBeSubCA']) { Write-Error "The $($MyInvocation.MyCommand.Name) function requires either the -CreateNewVMs or -IPOfServerToBeSubCA parameter! Halting!" $global:FunctionResult = "1" return } <# if ($PSBoundParameters['IPofServerToBeSubCA']) { # Make sure we can reach RemoteHost IP(s) via WinRM/WSMan if (![bool]$(Test-Connection -Protocol WSMan -ComputerName $IPofServerToBeSubCA -Count 1 -ErrorAction SilentlyContinue)) { Write-Error "Unable to reach '$IPofServerToBeSubCA' via WinRM/WSMan! Halting!" $global:FunctionResult = "1" return } } #> if (!$PSBoundParameters['IPofDomainController']) { # Make sure we can Resolve the Domain/Domain Controller try { [array]$ResolveDomain = Resolve-DNSName -Name $ExistingDomain -ErrorAction Stop $IPofDomainController = $ResolveDomain[0].IPAddress } catch { Write-Error $_ $global:FunctionResult = "1" return } } if (!$(TestIsValidIPAddress -IPAddress $IPofDomainController)) { Write-Error "'$IPOfDomainController' is NOT a valid IPv4 address! Halting!" $global:FunctionResult = "1" return } if (!$(TestIsValidIPAddress -IPAddress $IPofRootCA)) { Write-Error "'$IPofRootCA' is NOT a valid IPv4 address! Halting!" $global:FunctionResult = "1" return } $FinalDomainName = if ($NewDomain) {$NewDomain} else {$ExistingDomain} $DomainShortName = $($FinalDomainName -split '\.')[0] #endregion >> Prep # Create the new VMs if desired if ($CreateNewVMs) { # Check to Make Sure Hyper-V is installed if (!$SkipHyperVInstallCheck) { try { $HyperVFeaturesInstallResults = InstallHyperVFeatures -ParentFunction $MyInvocation.MyCommand.Name } catch { Write-Error $_ Write-Error "The InstallHyperVFeatures function (as executed by the $($MyInvocation.MyCommand.Name) function) failed! Halting!" $global:FunctionResult = "1" return } try { $InstallContainersFeatureDismResult = InstallFeatureDism -Feature Containers -ParentFunction $MyInvocation.MyCommand.Name } catch { Write-Error $_ Write-Error "The InstallFeatureDism function (as executed by the $($MyInvocation.MyCommand.Name) function) failed! Halting!" $global:FunctionResult = "1" return } if ($HyperVFeaturesInstallResults.InstallResults.Count -gt 0 -or $InstallContainersFeatureDismResult.RestartNeeded) { if (!$AllowRestarts) { Write-Warning "You must restart $env:ComputerName before proceeding! Halting!" # IMPORTANT NOTE: The below Write-Output "RestartNeeded" is necessary Write-Output "RestartNeeded" $global:FunctionResult = "1" return } else { Restart-Computer -Confirm:$False -Force } } } #region >> Hardware Resource Check # Make sure we have at least 35GB of Storage and 6GB of READILY AVAILABLE Memory # Check Storage... $LocalDrives = Get-CimInstance Win32_LogicalDisk | Where-Object {$_.Drivetype -eq 3} | foreach {Get-PSDrive $_.DeviceId[0] -ErrorAction SilentlyContinue} if ([bool]$(Get-Item $VMStorageDirectory).LinkType) { $VMStorageDirectoryDriveLetter = $(Get-Item $VMStorageDirectory).Target[0].Substring(0,1) } else { $VMStorageDirectoryDriveLetter = $VMStorageDirectory.Substring(0,1) } if ($LocalDrives.Name -notcontains $VMStorageDirectoryDriveLetter) { Write-Error "'$VMStorageDirectory' does not appear to be a local drive! VMs MUST be stored on a local drive! Halting!" $global:FunctionResult = "1" return } $VMStorageDirectoryDriveInfo = Get-WmiObject Win32_LogicalDisk -ComputerName $env:ComputerName -Filter "DeviceID='$VMStorageDirectoryDriveLetter`:'" if ($([Math]::Round($VMStorageDirectoryDriveInfo.FreeSpace / 1MB)-2000) -lt 35000) { Write-Error "Drive '$VMStorageDirectoryDriveLetter' does not have at least 100GB of free space available! Halting!" $global:FunctionResult = "1" return } # Check Memory... $OSInfo = Get-CimInstance Win32_OperatingSystem $TotalMemory = $OSInfo.TotalVisibleMemorySize $MemoryAvailable = $OSInfo.FreePhysicalMemory $TotalMemoryInGB = [Math]::Round($TotalMemory / 1MB) $MemoryAvailableInGB = [Math]::Round($MemoryAvailable / 1MB) if ($MemoryAvailableInGB -lt 6 -and !$ForceWithLowMemory) { $MemoryErrorMsg = "The Hyper-V hypervisor $env:ComputerName should have at least 12GB of memory " + "readily available in order to run the new VMs. It currently only has about $MemoryAvailableInGB " + "GB available for immediate use. Halting!" Write-Error $MemoryErrorMsg $global:FunctionResult = "1" return } #endregion >> Hardware Resource Check #region >> Deploy New VMs $StartVMDeployment = Get-Date # Prepare To Manage .box Files if (!$(Test-Path "$VMStorageDirectory\BoxDownloads")) { $null = New-Item -ItemType Directory -Path "$VMStorageDirectory\BoxDownloads" -Force } $BoxNameRegex = [regex]::Escape($($Windows2016VagrantBox -split '/')[0]) $BoxFileAlreadyPresentCheck = Get-ChildItem "$VMStorageDirectory\BoxDownloads" -File -Filter "*.box" | Where-Object {$_.Name -match $BoxNameRegex} $DecompressedBoxDirectoryPresentCheck = Get-ChildItem "$VMStorageDirectory\BoxDownloads" -Directory | Where-Object {$_.Name -match $BoxNameRegex} if ([bool]$DecompressedBoxDirectoryPresentCheck) { $DecompressedBoxDirectoryItem = $DecompressedBoxDirectoryPresentCheck $DecompressedBoxDir = $DecompressedBoxDirectoryItem.FullName } elseif ([bool]$BoxFileAlreadyPresentCheck) { $BoxFileItem = $BoxFileAlreadyPresentCheck $BoxFilePath = $BoxFileItem.FullName } else { $BoxFileItem = Get-VagrantBoxManualDownload -VagrantBox $Windows2016VagrantBox -VagrantProvider "hyperv" -DownloadDirectory "$VMStorageDirectory\BoxDownloads" $BoxFilePath = $BoxFileItem.FullName } $NewVMDeploySB = { $DeployBoxSplatParams = @{ VagrantBox = $Windows2016VagrantBox CPUs = 2 Memory = 4096 VagrantProvider = "hyperv" VMName = $DomainShortName + 'SubCA' VMDestinationDirectory = $VMStorageDirectory SkipHyperVInstallCheck = $True } if ($DecompressedBoxDir) { if ($(Get-Item $DecompressedBoxDir).PSIsContainer) { $DeployBoxSplatParams.Add('DecompressedBoxDirectory',$DecompressedBoxDir) } } if ($BoxFilePath) { if (-not $(Get-Item $BoxFilePath).PSIsContainer) { $DeployBoxSplatParams.Add('BoxFilePath',$BoxFilePath) } } Write-Host "Deploying Hyper-V Vagrant Box..." $DeployBoxResult = Deploy-HyperVVagrantBoxManually @DeployBoxSplatParams $DeployBoxResult } if (!$IPofServerToBeSubCA) { $DomainShortName = $($ExistingDomain -split "\.")[0] Write-Host "Deploying New Subordinate CA VM '$DomainShortName`SubCA'..." if ($global:RSSyncHash) { $RunspaceNames = $($global:RSSyncHash.Keys | Where-Object {$_ -match "Result$"}) | foreach {$_ -replace 'Result',''} $NewSubCAVMDeployJobName = NewUniqueString -PossibleNewUniqueString "NewSubCAVM" -ArrayOfStrings $RunspaceNames } else { $NewSubCAVMDeployJobName = "NewSubCAVM" } $NewSubCAVMDeployJobSplatParams = @{ RunspaceName = $NewSubCAVMDeployJobName Scriptblock = $NewVMDeploySB Wait = $True } $NewSubCAVMDeployResult = New-Runspace @NewSubCAVMDeployJobSplatParams $IPofServerToBeSubCA = $NewSubCAVMDeployResult.VMIPAddress while (![bool]$(Get-VM -Name "$DomainShortName`SubCA" -ErrorAction SilentlyContinue)) { Write-Host "Waiting for $DomainShortName`SubCA VM to be deployed..." Start-Sleep -Seconds 15 } if (!$IPofServerToBeSubCA) { $IPofServerToBeSubCA = $(Get-VM -Name "$DomainShortName`SubCA").NetworkAdpaters.IPAddresses | Where-Object {TestIsValidIPAddress -IPAddress $_} } } [System.Collections.ArrayList]$VMsNotReportingIP = @() if (!$(TestIsValidIPAddress -IPAddress $IPofServerToBeSubCA)) { $null = $VMsNotReportingIP.Add("$DomainShortName`SubCA") } if ($VMsNotReportingIP.Count -gt 0) { Write-Error "The following VMs did NOT report thier IP Addresses within 30 minutes:`n$($VMsNotReportingIP -join "`n")`nHalting!" $global:FunctionResult = "1" return } # Make sure IP is a valid IPv4 address if (![bool]$(TestIsValidIPAddress -IPAddress $IPofServerToBeSubCA)) { Write-Error "'$IPofServerToBeSubCA' is NOT a valid IPv4 IP Address! Halting!" $global:FunctionResult = "1" return } Write-Host "Finished Deploying New VMs..." #endregion >> Deploy New VMs } #region >> Update WinRM/WSMAN Write-Host "Updating WinRM/WSMan to allow for PSRemoting to Servers ..." try { $null = Enable-PSRemoting -Force -ErrorAction Stop } catch { $NICsWPublicProfile = @(Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq 0}) if ($NICsWPublicProfile.Count -gt 0) { foreach ($Nic in $NICsWPublicProfile) { Set-NetConnectionProfile -InterfaceIndex $Nic.InterfaceIndex -NetworkCategory 'Private' } } try { $null = Enable-PSRemoting -Force } catch { Write-Error $_ Write-Error "Problem with Enable-PSRemoting WinRM Quick Config! Halting!" $global:FunctionResult = "1" return } } # If $env:ComputerName is not part of a Domain, we need to add this registry entry to make sure WinRM works as expected if (!$(Get-CimInstance Win32_Computersystem).PartOfDomain) { $null = reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f } # Add the New Server's IP Addresses to $env:ComputerName's TrustedHosts $CurrentTrustedHosts = $(Get-Item WSMan:\localhost\Client\TrustedHosts).Value [System.Collections.ArrayList][array]$CurrentTrustedHostsAsArray = $CurrentTrustedHosts -split ',' [System.Collections.ArrayList]$ItemsToAddToWSMANTrustedHosts = @( $IPofServerToBeSubCA ) foreach ($NetItem in $ItemsToAddToWSMANTrustedHosts) { if ($CurrentTrustedHostsAsArray -notcontains $NetItem) { $null = $CurrentTrustedHostsAsArray.Add($NetItem) } } $UpdatedTrustedHostsString = $($CurrentTrustedHostsAsArray | Where-Object {![string]::IsNullOrWhiteSpace($_)}) -join ',' Set-Item WSMan:\localhost\Client\TrustedHosts $UpdatedTrustedHostsString -Force Write-Host "Finished updating WinRM/WSMan..." #endregion >> Update WinRM/WSMAN #region >> Make Sure WinRM/WSMan Is Ready on the Remote Hosts Write-Host "Attempting New PSSession to Remote Hosts for up to 30 minutes to ensure they are ready..." $PSSessionName = NewUniqueString -ArrayOfStrings $(Get-PSSession).Name -PossibleNewUniqueString "ToSubCACheck" $Counter = 0 while (![bool]$(Get-PSSession -Name $PSSessionName -ErrorAction SilentlyContinue)) { try { $SubCAPSSession = New-PSSession -ComputerName $IPofServerToBeSubCA -Credential $PSRemotingCredentials -Name $PSSessionName -ErrorAction SilentlyContinue if (![bool]$(Get-PSSession -Name $PSSessionName -ErrorAction SilentlyContinue)) {throw} } catch { if ($Counter -le 120) { Write-Warning "New-PSSession '$PSSessionName' failed. Trying again in 15 seconds..." Start-Sleep -Seconds 15 } else { Write-Error "Unable to create new PSSession to '$PSSessionName' using account '$($PSRemotingCredentials.UserName)'! Halting!" $global:FunctionResult = "1" return } } $Counter++ } # Clear the PSSessions Get-PSSession | Remove-PSSession if ($CreateNewVMs) { $EndVMDeployment = Get-Date $TotalTime = $EndVMDeployment - $StartVMDeployment Write-Host "VM Deployment took $($TotalTime.Hours) hours and $($TotalTime.Minutes) minutes..." -ForegroundColor Yellow } #endregion >> Make Sure WinRM/WSMan Is Ready on the Remote Hosts #region >> Join the Servers to Domain And Rename If Necessary $JoinDomainRSJobSB = { $JoinDomainSBAsString = @( '# Synchronize time with time servers' '$null = W32tm /resync /rediscover /nowait' '' '# Make sure the DNS Client points to IP of Domain Controller (and others from DHCP)' '$PrimaryIfIndex = $(Get-CimInstance Win32_IP4RouteTable | Where-Object {' ' $_.Destination -eq "0.0.0.0" -and $_.Mask -eq "0.0.0.0"' '} | Sort-Object Metric1)[0].InterfaceIndex' '$NicInfo = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.InterfaceIndex -eq $PrimaryIfIndex}' '$PrimaryIP = $NicInfo.IPAddress | Where-Object {TestIsValidIPAddress -IPAddress $_}' '$CurrentDNSServerListInfo = Get-DnsClientServerAddress -InterfaceIndex $PrimaryIfIndex -AddressFamily IPv4' '$CurrentDNSServerList = $CurrentDNSServerListInfo.ServerAddresses' '$UpdatedDNSServerList = [System.Collections.ArrayList][array]$CurrentDNSServerList' '$UpdatedDNSServerList.Insert(0,$args[0])' '$null = Set-DnsClientServerAddress -InterfaceIndex $PrimaryIfIndex -ServerAddresses $UpdatedDNSServerList' '' '$CurrentDNSSuffixSearchOrder = $(Get-DNSClientGlobalSetting).SuffixSearchList' '[System.Collections.ArrayList]$UpdatedDNSSuffixList = $CurrentDNSSuffixSearchOrder' '$UpdatedDNSSuffixList.Insert(0,$args[2])' 'Set-DnsClientGlobalSetting -SuffixSearchList $UpdatedDNSSuffixList' '' '# Try resolving the Domain for 30 minutes' '$Counter = 0' 'while (![bool]$(Resolve-DNSName $args[2] -ErrorAction SilentlyContinue) -and $Counter -le 120) {' ' Write-Host "Waiting for DNS to resolve Domain Controller..."' ' Start-Sleep -Seconds 15' ' $Counter++' '}' 'if (![bool]$(Resolve-DNSName $args[2] -ErrorAction SilentlyContinue)) {' ' Write-Error "Unable to resolve Domain $($args[2])! Halting!"' ' $global:FunctionResult = "1"' ' return' '}' '' '# Join Domain' 'Rename-Computer -NewName $args[1]' 'Start-Sleep -Seconds 10' 'Add-Computer -DomainName $args[2] -Credential $args[3] -Options JoinWithNewName,AccountCreate -Force -Restart' ) try { $JoinDomainSB = [scriptblock]::Create($($JoinDomainSBAsString -join "`n")) } catch { Write-Error "Problem creating `$JoinDomainSB! Halting!" $global:FunctionResult = "1" return } $InvCmdJoinDomainSplatParams = @{ ComputerName = $IPofServerToBeSubCA Credential = $PSRemotingCredentials ScriptBlock = $JoinDomainSB ArgumentList = $IPofDomainController,$DesiredHostNameSubCA,$ExistingDomain,$DomainAdminCredentials } try { Invoke-Command @InvCmdJoinDomainSplatParams } catch { Write-Error $_ $global:FunctionResult = "1" return } } # Check if SubCA is already part of $ExistingDomain/$NewDomain $InvCmdSubCADomainSplatParams = @{ ComputerName = $IPofServerToBeSubCA Credential = $PSRemotingCredentials ScriptBlock = {$(Get-CimInstance win32_computersystem).Domain} ErrorAction = "Stop" } try { $SubCADomain = Invoke-Command @InvCmdSubCADomainSplatParams } catch { Write-Error $_ $global:FunctionResult = "1" return } if ($SubCADomain -ne $ExistingDomain) { Write-Host "Joining the Sub CA to the Domain..." $DesiredHostNameSubCA = $DomainShortName + "SubCA" $RunspaceNames = $($global:RSSyncHash.Keys | Where-Object {$_ -match "Result$"}) | foreach {$_ -replace 'Result',''} $JoinSubCAJobName = NewUniqueString -PossibleNewUniqueString "JoinSubCA" -ArrayOfStrings $RunspaceNames <# $JoinSubCAArgList = @( $IPofServerToBeSubCA $PSRemotingCredentials $IPofDomainController $DesiredHostNameSubCA $ExistingDomain $DomainAdminCredentials ) #> $JoinSubCAJobSplatParams = @{ RunspaceName = $JoinSubCAJobName Scriptblock = $JoinDomainRSJobSB Wait = $True } $JoinSubCAResult = New-Runspace @JoinSubCAJobSplatParams # Verify Sub CA is Joined to Domain # Try to create a PSSession to the Sub CA for 15 minutes, then give up Write-Host "Trying to remote into SubCA at '$IPofServerToBeSubCA' with Domain Admin Credentials after Joining Domain..." $PSSessionName = NewUniqueString -ArrayOfStrings $(Get-PSSession).Name -PossibleNewUniqueString "ToSubCAPostDomainJoin" $Counter = 0 while (![bool]$(Get-PSSession -Name $PSSessionName -ErrorAction SilentlyContinue)) { try { $SubCAPSSessionPostDomainJoin = New-PSSession -ComputerName $IPofServerToBeSubCA -Credential $DomainAdminCredentials -Name $PSSessionName -ErrorAction SilentlyContinue if (![bool]$(Get-PSSession -Name $PSSessionName -ErrorAction SilentlyContinue)) {throw} } catch { if ($Counter -le 60) { Write-Warning "New-PSSession '$PSSessionName' failed. Trying again in 15 seconds..." Start-Sleep -Seconds 15 } else { Write-Error "Unable to create new PSSession to '$PSSessionName' using account '$($DomainAdminCredentials.UserName)'! Halting!" $global:FunctionResult = "1" return } } $Counter++ } if (!$SubCAPSSessionPostDomainJoin) { Write-Error "Unable to create a PSSession to the Sub CA Server at '$IPofServerToBeSubCA' using Domain Admin Credentials $($DomainAdminCredentials.UserName)! Halting!" $global:FunctionResult = "1" return } # Make sure there is a Reverse DNS PTR record for $IPofServerToBeSubCA if (!$DesiredHostNameSubCA) { try { $SubCANetworkInfo = ResolveHost -HostNameOrIP $IPofServerToBeSubCA $SubCAHostName = $SubCANetworkInfo.HostName } catch { Write-Error $_ $global:FunctionResult = "1" return } } else { $SubCAHostName = $DesiredHostNameSubCA } $SubCAPTRRecordFQDN = $SubCAHostName + '.' + $FinalDomainName $ThisModuleFunctionsStringArray = $(Get-Module MiniLab).Invoke({$FunctionsForSBUse}) try { $UpdateDNSPTRPSSession = New-PSSession -ComputerName $IPofDomainController -Credential $DomainAdminCredentials $UpdatePTRResult = Invoke-Command -Session $UpdateDNSPTRPSSession -ScriptBlock { $PTRRecords = Get-DnsServerResourceRecord -ZoneName $using:FinalDomainName -RRType A $PTRecordIPs = $PTRRecords.RecordData.IPv4Address.IPAddressToString | Sort-Object | Get-Unique if ($PTRecordIPs -notcontains $using:IPOfServerToBeSubCA) { $using:ThisModuleFunctionsStringArray | Where-Object {$_ -ne $null} | foreach {Invoke-Expression $_ -ErrorAction SilentlyContinue} $PrimaryIfIndex = $(Get-CimInstance Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' } | Sort-Object Metric1)[0].InterfaceIndex $NicInfo = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.InterfaceIndex -eq $PrimaryIfIndex} $PrimaryIP = $NicInfo.IPAddress | Where-Object {TestIsValidIPAddress -IPAddress $_} $Prefix = $(Get-NetIPAddress -IPAddress $PrimaryIP).PrefixLength $ip = [ipaddress]$PrimaryIP $MaskString = $(ConvertSubnetMask -CIDR $Prefix).Mask $mask = [ipaddress]$MaskString $netid = ([ipaddress]($ip.Address -band $mask.Address)).IPAddressToString $binary = [convert]::ToString($mask.Address, 2) $mask_length = ($binary -replace 0,$null).Length $NetworkAndSubnetMaskCidr = '{0}/{1}' -f $netid, $mask_length $NetIdOctetArray = $netid -split '\.' $ZoneNameCheck = $NetIdOctetArray[2] + '.' + $NetIdOctetArray[1] + '.' + $NetIdOctetArray[0] + '.' + 'in-addr.arpa' Add-DnsServerResourceRecord -Name $using:SubCAHostName -Ptr -ZoneName $ZoneNameCheck -AllowUpdateAny -PtrDomainName $using:SubCAPTRRecordFQDN } } } catch { Write-Error $_ $global:FunctionResult = "1" return } } #endregion >> Join the Servers to Domain And Rename If Necessary #region >> Create the Sub CA # Remove All Existing PSSessions Get-PSSession | Remove-PSSession Write-Host "Creating the New Subordinate CA..." $NewSubCAResult = New-SubordinateCA -DomainAdminCredentials $DomainAdminCredentials -RootCAIPOrFQDN $IPofRootCA -SubCAIPOrFQDN $IPofServerToBeSubCA -ExpectedDomain $FinalDomainName #endregion >> Create the Sub CA $EndTime = Get-Date $TotalAllOpsTime = $EndTime - $StartTime Write-Host "All operations for the $($MyInvocation.MyCommand.Name) function took $($TotalAllOpsTime.Hours) hours and $($TotalAllOpsTime.Minutes) minutes" -ForegroundColor Yellow $NewSubCAResult } |