#Requires -Version 5.1 [CmdletBinding(DefaultParameterSetName = 'Install')] param( [Parameter(ParameterSetName = 'Status', Mandatory = $true)] [switch]$Status, [Parameter(ParameterSetName = 'Uninstall', Mandatory = $true)] [switch]$Uninstall, [string]$CertAdminBaseUrl = 'https://cert-admin.triargos.de' ) Set-StrictMode -Version 3 $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $TraefikVersion = 'v3.7.20' $TraefikArchiveSha256 = '00c1db52ca40f22e4689b6cb66a831c0ff92581b50e8824642a934f87a3d6d7f' $WinswVersion = 'v2.12.0' $WinswExecutableSha256 = '05b82d46ad331cc16bdc00de5c6332c1ef818df8ceefcd49c726553209b3a0da' $GatewayServiceName = 'procurat-gateway' $FirewallRuleGroup = 'Procurat Gateway' $PublicDnsOverHttpsEndpoints = @('https://cloudflare-dns.com/dns-query', 'https://dns.google/resolve') $BaseDomainPattern = '^(?=.{1,237}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$' $TlsProbeTimeoutMilliseconds = 5000 $ProcuratApiPath = '/procurat/api' $StepProgress = [pscustomobject]@{ StepCount = 0; CurrentStepNumber = 0; CurrentStepTitle = '' } function Write-InstallerBanner { param([string]$Title) Write-Host '' Write-Host " $Title" -ForegroundColor White Write-Host (' ' + ('=' * $Title.Length)) -ForegroundColor DarkGray } function Start-StepProgress { param([int]$StepCount) $StepProgress.StepCount = $StepCount $StepProgress.CurrentStepNumber = 0 $StepProgress.CurrentStepTitle = '' } function Invoke-InstallerStep { param([string]$Title, [scriptblock]$Action) $StepProgress.CurrentStepNumber++ $StepProgress.CurrentStepTitle = $Title Write-Host '' Write-Host (" [{0}/{1}] {2}" -f $StepProgress.CurrentStepNumber, $StepProgress.StepCount, $Title) -ForegroundColor Cyan $stepStopwatch = [Diagnostics.Stopwatch]::StartNew() & $Action Write-Host (" done in {0:N1}s" -f $stepStopwatch.Elapsed.TotalSeconds) -ForegroundColor Green $StepProgress.CurrentStepTitle = '' } function Write-StepDetail { param([string]$Message) Write-Host " $Message" -ForegroundColor Gray } function Write-StepWarning { param([string]$Message) Write-Host " ! $Message" -ForegroundColor Yellow } function Write-InstallerFailure { param($ErrorRecord) Write-Host '' if ([string]::IsNullOrEmpty($StepProgress.CurrentStepTitle)) { Write-Host ' FAILED' -ForegroundColor Red } else { Write-Host (" FAILED at step {0}/{1}: {2}" -f $StepProgress.CurrentStepNumber, $StepProgress.StepCount, $StepProgress.CurrentStepTitle) -ForegroundColor Red } Write-Host " $($ErrorRecord.Exception.Message)" -ForegroundColor Red Write-Host ' Fix the cause and run the installer again; finished steps are kept.' -ForegroundColor DarkGray } function Test-RunningAsAdministrator { $principal = New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent()) $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } function Start-ElevatedInstaller { $installerArguments = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-NoExit', '-File', "`"$PSCommandPath`"") if ($Status) { $installerArguments += '-Status' } if ($Uninstall) { $installerArguments += '-Uninstall' } $installerArguments += @('-CertAdminBaseUrl', "`"$CertAdminBaseUrl`"") Write-Host 'The gateway installer needs administrator rights; confirm the Windows prompt to continue in a new window.' Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList $installerArguments -Verb RunAs } function Get-GatewayLocations { param([string]$ProgramFilesDirectory, [string]$ProgramDataDirectory) $programDirectory = Join-Path $ProgramFilesDirectory 'ProcuratGateway' $dataDirectory = Join-Path $ProgramDataDirectory 'ProcuratGateway' [pscustomobject]@{ ProgramDirectory = $programDirectory TraefikExecutable = Join-Path $programDirectory 'traefik.exe' ServiceWrapperExecutable = Join-Path $programDirectory "$GatewayServiceName.exe" ServiceWrapperXml = Join-Path $programDirectory "$GatewayServiceName.xml" DataDirectory = $dataDirectory LogDirectory = Join-Path $dataDirectory 'logs' InstallationRecord = Join-Path $dataDirectory 'installation.json' AcmeDnsAccountFile = Join-Path $dataDirectory 'acme-dns.json' AcmeCertificateStorage = Join-Path $dataDirectory 'acme.json' TraefikStaticConfiguration = Join-Path $dataDirectory 'traefik.yml' TraefikDynamicConfiguration = Join-Path $dataDirectory 'dynamic.yml' } } function Get-GatewayHostNames { param([string]$BaseDomain) [pscustomobject]@{ App = $BaseDomain Webdav = "webdav.$BaseDomain" Api = "api.$BaseDomain" } } function Test-BaseDomain { param([string]$BaseDomain) $BaseDomain -cmatch $BaseDomainPattern } function ConvertTo-YamlQuotedString { param([string]$Value) "'" + $Value.Replace("'", "''") + "'" } function New-TraefikStaticConfiguration { param($Installation, $Locations) $logFile = ConvertTo-YamlQuotedString (Join-Path $Locations.LogDirectory 'traefik.log') $acmeStorage = ConvertTo-YamlQuotedString $Locations.AcmeCertificateStorage $dynamicConfiguration = ConvertTo-YamlQuotedString $Locations.TraefikDynamicConfiguration @" global: checkNewVersion: false sendAnonymousUsage: false log: level: INFO filePath: $logFile entryPoints: web: address: ':$($Installation.HttpPort)' http: redirections: entryPoint: to: internal scheme: https internal: address: ':$($Installation.InternalPort)' http: aliasHeadersStrategy: delete transport: respondingTimeouts: readTimeout: 0 public: address: ':$($Installation.PublicPort)' http: aliasHeadersStrategy: delete certificatesResolvers: le: acme: storage: $acmeStorage dnsChallenge: provider: acme-dns propagation: disableChecks: true delayBeforeChecks: 10s providers: file: filename: $dynamicConfiguration "@ } function New-TraefikDynamicConfiguration { param($Installation) $hostNames = Get-GatewayHostNames $Installation.BaseDomain @" http: routers: app-internal: entryPoints: [internal] rule: Host(``$($hostNames.App)``) service: procurat tls: certResolver: le domains: - main: '$($hostNames.App)' sans: ['*.$($hostNames.App)'] webdav-internal: entryPoints: [internal] rule: Host(``$($hostNames.Webdav)``) service: webdav tls: {} app-api-public: entryPoints: [public] rule: Host(``$($hostNames.Api)``) && (Path(``$ProcuratApiPath``) || PathPrefix(``$ProcuratApiPath/``)) service: procurat tls: {} services: procurat: loadBalancer: serversTransport: loopback-self-signed servers: - url: 'https://127.0.0.1:$($Installation.AppBackendPort)' webdav: loadBalancer: serversTransport: loopback-self-signed servers: - url: 'https://127.0.0.1:$($Installation.WebdavBackendPort)' serversTransports: loopback-self-signed: insecureSkipVerify: true "@ } function New-ServiceWrapperConfiguration { param($Installation, $Locations) $traefikArguments = [Security.SecurityElement]::Escape("--configFile=`"$($Locations.TraefikStaticConfiguration)`"") $acmeDnsApiBase = [Security.SecurityElement]::Escape($Installation.AcmeDnsApiBase) $acmeDnsAccountFile = [Security.SecurityElement]::Escape($Locations.AcmeDnsAccountFile) $logDirectory = [Security.SecurityElement]::Escape($Locations.LogDirectory) @" $GatewayServiceName Procurat Gateway Traefik in front of Procurat and its WebDAV share, with certificates through cert-admin's acme-dns. %BASE%\traefik.exe $traefikArguments $logDirectory 10240 8 Automatic 15 sec "@ } function Get-AcmeCertificateSummaries { param([string]$AcmeCertificateStorageJson) $storage = $AcmeCertificateStorageJson | ConvertFrom-Json if ($null -eq $storage.PSObject.Properties['le'] -or $null -eq $storage.le.PSObject.Properties['Certificates'] -or $null -eq $storage.le.Certificates) { return @() } foreach ($storedCertificate in $storage.le.Certificates) { $certificatePem = [Text.Encoding]::ASCII.GetString([Convert]::FromBase64String($storedCertificate.certificate)) $leafCertificateBase64 = [regex]::Match($certificatePem, '-----BEGIN CERTIFICATE-----([^-]+)-----END CERTIFICATE-----').Groups[1].Value -replace '\s', '' $leafCertificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 (, [Convert]::FromBase64String($leafCertificateBase64)) $alternativeNames = @() if ($null -ne $storedCertificate.domain.PSObject.Properties['sans'] -and $null -ne $storedCertificate.domain.sans) { $alternativeNames = @($storedCertificate.domain.sans) } [pscustomobject]@{ Names = @($storedCertificate.domain.main) + $alternativeNames Issuer = $leafCertificate.Issuer NotAfter = $leafCertificate.NotAfter } } } function ConvertFrom-IisBindingInformation { param([string]$BindingInformation) $bindingMatch = [regex]::Match($BindingInformation, '^(?
.*):(?\d+):(?[^:]*)$') if (-not $bindingMatch.Success) { throw "IIS binding information $BindingInformation is not address:port:host" } [pscustomobject]@{ IPAddress = $bindingMatch.Groups['address'].Value Port = [int]$bindingMatch.Groups['port'].Value HostHeader = $bindingMatch.Groups['hostHeader'].Value } } function Get-HttpStatusCodeFromError { param($ErrorRecord) $response = $ErrorRecord.Exception.PSObject.Properties['Response'] if ($null -eq $response -or $null -eq $response.Value) { return 0 } [int]$response.Value.StatusCode } function Write-Utf8FileWithoutBom { param([string]$Path, [string]$Content) [IO.File]::WriteAllText($Path, $Content, (New-Object Text.UTF8Encoding $false)) } function Read-ValueWithDefault { param([string]$Prompt, [string]$DefaultValue) $answer = Read-Host " $Prompt [$DefaultValue]" if ([string]::IsNullOrWhiteSpace($answer)) { return $DefaultValue } $answer.Trim() } function Read-PortWithDefault { param([string]$Prompt, [int]$DefaultPort) while ($true) { $answer = Read-ValueWithDefault -Prompt $Prompt -DefaultValue $DefaultPort $port = 0 if ([int]::TryParse($answer, [ref]$port) -and $port -ge 1 -and $port -le 65535) { return $port } Write-StepWarning "$answer is not a port between 1 and 65535." } } function Read-BaseDomain { param([string]$DefaultValue) while ($true) { if ([string]::IsNullOrEmpty($DefaultValue)) { $answer = (Read-Host ' Base domain, e.g. procurat.muster.de').Trim().ToLowerInvariant() } else { $answer = (Read-ValueWithDefault -Prompt 'Base domain' -DefaultValue $DefaultValue).ToLowerInvariant() } if (Test-BaseDomain $answer) { return $answer } Write-StepWarning "$answer is not a host name like procurat.muster.de." } } function Read-IisSiteName { $iisSites = @(Get-Website | Sort-Object -Property Name) if ($iisSites.Count -eq 0) { throw 'IIS has no sites; create the WebDAV site first' } $suggestedSiteIndex = 0 Write-StepDetail 'IIS sites on this server:' for ($siteIndex = 0; $siteIndex -lt $iisSites.Count; $siteIndex++) { $iisSite = $iisSites[$siteIndex] $siteBindings = @($iisSite.bindings.Collection) $bindsWebPorts = @($siteBindings | Where-Object { @(80, 443) -contains (ConvertFrom-IisBindingInformation $_.bindingInformation).Port }).Count -gt 0 if ($bindsWebPorts -and $suggestedSiteIndex -eq 0) { $suggestedSiteIndex = $siteIndex } $bindingSummary = ($siteBindings | ForEach-Object { "$($_.protocol) $($_.bindingInformation)" }) -join ', ' Write-StepDetail (" {0}) {1} ({2}) {3}" -f ($siteIndex + 1), $iisSite.Name, $iisSite.State, $bindingSummary) } if ($iisSites.Count -eq 1) { Write-StepDetail "Using the only site, $($iisSites[0].Name)." return $iisSites[0].Name } while ($true) { $answer = Read-ValueWithDefault -Prompt 'Number of the IIS site that serves WebDAV' -DefaultValue ($suggestedSiteIndex + 1) $chosenSiteNumber = 0 if ([int]::TryParse($answer, [ref]$chosenSiteNumber) -and $chosenSiteNumber -ge 1 -and $chosenSiteNumber -le $iisSites.Count) { return $iisSites[$chosenSiteNumber - 1].Name } Write-StepWarning "$answer is not a number from 1 to $($iisSites.Count)." } } function Read-InstallationSettings { param($PreviousInstallation) if ($null -eq $PreviousInstallation) { $baseDomain = Read-BaseDomain -DefaultValue '' $iisSiteName = Read-IisSiteName $defaultPorts = [pscustomobject]@{ InternalPort = 443; HttpPort = 80; PublicPort = 55554; AppBackendPort = 8443; WebdavBackendPort = 8444 } } else { $baseDomain = Read-BaseDomain -DefaultValue $PreviousInstallation.BaseDomain $iisSiteName = $PreviousInstallation.IisSiteName $defaultPorts = $PreviousInstallation Write-StepDetail "IIS site $iisSiteName stays on https://127.0.0.1:$($PreviousInstallation.WebdavBackendPort); uninstall first to change either." } $hostNames = Get-GatewayHostNames $baseDomain Write-StepDetail "Hosts: $($hostNames.App), $($hostNames.Webdav), $($hostNames.Api)" while ($true) { $internalPort = Read-PortWithDefault -Prompt 'Internal HTTPS port (LAN)' -DefaultPort $defaultPorts.InternalPort $httpPort = Read-PortWithDefault -Prompt 'HTTP port, redirects to HTTPS' -DefaultPort $defaultPorts.HttpPort $publicPort = Read-PortWithDefault -Prompt 'Public API port (port-forwarded)' -DefaultPort $defaultPorts.PublicPort $appBackendPort = Read-PortWithDefault -Prompt 'Procurat backend port' -DefaultPort $defaultPorts.AppBackendPort $webdavBackendPort = $defaultPorts.WebdavBackendPort if ($null -eq $PreviousInstallation) { $webdavBackendPort = Read-PortWithDefault -Prompt 'IIS WebDAV backend port' -DefaultPort $defaultPorts.WebdavBackendPort } $chosenPorts = @($internalPort, $httpPort, $publicPort, $appBackendPort, $webdavBackendPort) if (@($chosenPorts | Sort-Object -Unique).Count -eq $chosenPorts.Count) { break } Write-StepWarning "every port must differ; got $($chosenPorts -join ', ')." } [pscustomobject]@{ BaseDomain = $baseDomain IisSiteName = $iisSiteName InternalPort = $internalPort HttpPort = $httpPort PublicPort = $publicPort AppBackendPort = $appBackendPort WebdavBackendPort = $webdavBackendPort } } function New-GatewayInstallationRecord { param($Settings, $AcmeDnsAccount, $PreviousInstallation) $installation = [pscustomobject]@{ BaseDomain = $Settings.BaseDomain IisSiteName = $Settings.IisSiteName InternalPort = $Settings.InternalPort HttpPort = $Settings.HttpPort PublicPort = $Settings.PublicPort AppBackendPort = $Settings.AppBackendPort WebdavBackendPort = $Settings.WebdavBackendPort AcmeDnsApiBase = $AcmeDnsAccount.server_url IisBackupName = $null WebdavBackendCertificateThumbprint = $null MovedIisBindings = @() } if ($null -ne $PreviousInstallation) { $installation.IisBackupName = $PreviousInstallation.IisBackupName $installation.WebdavBackendCertificateThumbprint = $PreviousInstallation.WebdavBackendCertificateThumbprint $installation.MovedIisBindings = @($PreviousInstallation.MovedIisBindings) } $installation } function Read-GatewayInstallationRecord { param($Locations) if (-not (Test-Path -LiteralPath $Locations.InstallationRecord)) { return $null } Get-Content -LiteralPath $Locations.InstallationRecord -Raw | ConvertFrom-Json } function Read-ExistingGatewayInstallationRecord { param($Locations) $installation = Read-GatewayInstallationRecord $Locations if ($null -eq $installation) { throw "the gateway is not installed: $($Locations.InstallationRecord) is missing" } $installation } function Save-GatewayInstallationRecord { param($Installation, $Locations) Write-Utf8FileWithoutBom -Path $Locations.InstallationRecord -Content ($Installation | ConvertTo-Json -Depth 5) } function Assert-SupportedWindowsWithIis { if ([Environment]::OSVersion.Version.Major -lt 10) { throw 'the gateway installer needs Windows Server 2016 or later' } if ($null -eq (Get-Service -Name 'W3SVC' -ErrorAction SilentlyContinue)) { throw 'IIS is not installed: the W3SVC service is missing' } if (Get-Command -Name 'Get-WindowsFeature' -ErrorAction SilentlyContinue) { if (-not (Get-WindowsFeature -Name 'Web-DAV-Publishing').Installed) { throw 'the IIS feature WebDAV Publishing (Web-DAV-Publishing) is not installed' } } Import-Module WebAdministration Write-StepDetail "$([Environment]::OSVersion.VersionString), IIS with WebDAV Publishing" } function Assert-CertAdminReachable { try { Invoke-RestMethod -Method Get -Uri ($CertAdminBaseUrl.TrimEnd('/') + '/health') | Out-Null } catch { throw "cert-admin at $CertAdminBaseUrl is not reachable: $($_.Exception.Message)" } Write-StepDetail "cert-admin at $CertAdminBaseUrl answers" } function Get-PortListenerProcessNames { param([int]$Port) $listeners = @(Get-NetTCPConnection -State Listen -LocalPort $Port -ErrorAction SilentlyContinue) @($listeners | ForEach-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName } | Sort-Object -Unique) } function Get-IisBindingsOnPorts { param([string]$IisSiteName, [int[]]$Ports) @(Get-WebBinding -Name $IisSiteName | Where-Object { ($_.protocol -eq 'http' -or $_.protocol -eq 'https') -and $Ports -contains (ConvertFrom-IisBindingInformation $_.bindingInformation).Port }) } function Get-TraefikPorts { param($Settings) @($Settings.InternalPort, $Settings.HttpPort, $Settings.PublicPort) } function Assert-PortsFreeForTraefik { param([int[]]$Ports, [int[]]$PortsReleasedByIis) foreach ($port in $Ports) { $allowedProcessNames = @('traefik') if ($PortsReleasedByIis -contains $port) { $allowedProcessNames += 'System' } $blockingProcessNames = @(Get-PortListenerProcessNames $port | Where-Object { $allowedProcessNames -notcontains $_ }) if ($blockingProcessNames.Count -gt 0) { throw "port $port is taken by $($blockingProcessNames -join ', ') (System means http.sys: another IIS site or Windows HTTP service); free it or choose another port" } } } function Assert-GatewayPortsAvailable { param($Settings) if ($null -eq (Get-Website -Name $Settings.IisSiteName)) { throw "IIS has no site named $($Settings.IisSiteName)" } $traefikPorts = Get-TraefikPorts $Settings $portsReleasedByIis = @(Get-IisBindingsOnPorts -IisSiteName $Settings.IisSiteName -Ports $traefikPorts | ForEach-Object { (ConvertFrom-IisBindingInformation $_.bindingInformation).Port }) Assert-PortsFreeForTraefik -Ports $traefikPorts -PortsReleasedByIis $portsReleasedByIis Write-StepDetail "ports $($traefikPorts -join ', ') are free for Traefik" if ($portsReleasedByIis.Count -gt 0) { Write-StepDetail "IIS site $($Settings.IisSiteName) gives up $($portsReleasedByIis -join ', ') when it moves to loopback" } if (@(Get-PortListenerProcessNames $Settings.AppBackendPort).Count -eq 0) { Write-StepWarning "nothing listens on port $($Settings.AppBackendPort) yet; Procurat has to serve HTTPS there." } } function New-GatewayDataDirectory { param($Locations) foreach ($directory in @($Locations.ProgramDirectory, $Locations.DataDirectory, $Locations.LogDirectory)) { New-Item -ItemType Directory -Force -Path $directory | Out-Null } & icacls.exe $Locations.DataDirectory /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null if ($LASTEXITCODE -ne 0) { throw "restrict access to $($Locations.DataDirectory): icacls exited with $LASTEXITCODE" } } function Invoke-CertAdminApi { param([string]$Method, [string]$Path, [string]$ApiKey, $Body) $requestParameters = @{ Method = $Method Uri = $CertAdminBaseUrl.TrimEnd('/') + $Path Headers = @{ Authorization = "Bearer $ApiKey" } } if ($null -ne $Body) { $requestParameters.Body = [Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-Json -Depth 5)) $requestParameters.ContentType = 'application/json' } Invoke-RestMethod @requestParameters } function Read-CertAdminApiKey { $secureApiKey = Read-Host ' cert-admin API key' -AsSecureString $apiKeyPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureApiKey) try { [Runtime.InteropServices.Marshal]::PtrToStringBSTR($apiKeyPointer) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($apiKeyPointer) } } function Request-CustomerSetupLink { param([string]$BaseDomain, [string]$ApiKey) while ($true) { $customerName = '' while ([string]::IsNullOrWhiteSpace($customerName)) { $customerName = Read-Host ' School name for cert-admin, e.g. Gymnasium Muster' } try { $registration = Invoke-CertAdminApi -Method Post -Path '/customers' -ApiKey $ApiKey -Body @{ name = $customerName.Trim(); certificateDomain = $BaseDomain } Write-StepDetail "registered $BaseDomain as $($customerName.Trim())" return $registration.setupLink.url } catch { if ((Get-HttpStatusCodeFromError $_) -ne 409) { throw } } $customerList = Invoke-CertAdminApi -Method Get -Path '/customers' -ApiKey $ApiKey $customerWithDomain = @($customerList.customers | Where-Object { $_.certificateDomain -eq $BaseDomain }) if ($customerWithDomain.Count -eq 1) { Write-StepDetail "$BaseDomain is already registered; issued a new setup, which rotates its acme-dns password" $regeneration = Invoke-CertAdminApi -Method Post -Path "/customers/$($customerWithDomain[0].id)/regenerate-setup" -ApiKey $ApiKey return $regeneration.setupLink.url } Write-StepWarning "cert-admin already has a customer named $($customerName.Trim()); choose another name." } } function Save-AcmeDnsAccount { param([string]$BaseDomain, $Locations) if (Test-Path -LiteralPath $Locations.AcmeDnsAccountFile) { Write-StepDetail "reusing the acme-dns account in $($Locations.AcmeDnsAccountFile)" return } $apiKey = Read-CertAdminApiKey $setupLinkUrl = Request-CustomerSetupLink -BaseDomain $BaseDomain -ApiKey $apiKey $setupDownload = Invoke-WebRequest -Method Get -Uri $setupLinkUrl -UseBasicParsing $partialAccountFile = "$($Locations.AcmeDnsAccountFile).download" Write-Utf8FileWithoutBom -Path $partialAccountFile -Content $setupDownload.Content Move-Item -LiteralPath $partialAccountFile -Destination $Locations.AcmeDnsAccountFile -Force Write-StepDetail "saved the acme-dns account to $($Locations.AcmeDnsAccountFile)" } function Read-AcmeDnsAccount { param([string]$BaseDomain, $Locations) $accountsByDomain = Get-Content -LiteralPath $Locations.AcmeDnsAccountFile -Raw | ConvertFrom-Json $account = $accountsByDomain.PSObject.Properties[$BaseDomain] if ($null -eq $account) { throw "$($Locations.AcmeDnsAccountFile) holds no acme-dns account for $BaseDomain; delete it and run the installer again" } $account.Value } function Save-IisBackupBeforeMove { param($Installation, $Locations) $bindingsToMove = @(Get-IisBindingsOnPorts -IisSiteName $Installation.IisSiteName -Ports (Get-TraefikPorts $Installation)) $backendCertificate = New-SelfSignedCertificate -DnsName 'localhost' -CertStoreLocation 'Cert:\LocalMachine\My' -FriendlyName 'Procurat Gateway WebDAV backend' -NotAfter (Get-Date).AddYears(10) $backupName = 'procurat-gateway-' + (Get-Date -Format 'yyyyMMdd-HHmmss') & "$env:windir\system32\inetsrv\appcmd.exe" add backup $backupName | Out-Null if ($LASTEXITCODE -ne 0) { throw "back up the IIS configuration: appcmd exited with $LASTEXITCODE" } $Installation.IisBackupName = $backupName $Installation.WebdavBackendCertificateThumbprint = $backendCertificate.Thumbprint $Installation.MovedIisBindings = @($bindingsToMove | ForEach-Object { [pscustomobject]@{ Protocol = $_.protocol BindingInformation = $_.bindingInformation SslFlags = [int]$_.sslFlags CertificateHash = [string]$_.certificateHash CertificateStoreName = [string]$_.certificateStoreName } }) Save-GatewayInstallationRecord -Installation $Installation -Locations $Locations Write-StepDetail "backed up the IIS configuration as $backupName" Write-StepDetail "recorded $($bindingsToMove.Count) binding(s) to give back on uninstall" } function Move-IisSiteToLoopback { param($Installation) Get-IisBindingsOnPorts -IisSiteName $Installation.IisSiteName -Ports (Get-TraefikPorts $Installation) | Remove-WebBinding $loopbackBinding = Get-WebBinding -Name $Installation.IisSiteName -Protocol https -IPAddress '127.0.0.1' -Port $Installation.WebdavBackendPort if ($null -eq $loopbackBinding) { New-WebBinding -Name $Installation.IisSiteName -Protocol https -IPAddress '127.0.0.1' -Port $Installation.WebdavBackendPort | Out-Null $loopbackBinding = Get-WebBinding -Name $Installation.IisSiteName -Protocol https -IPAddress '127.0.0.1' -Port $Installation.WebdavBackendPort } if ([string]$loopbackBinding.certificateHash -ne $Installation.WebdavBackendCertificateThumbprint) { $loopbackBinding.AddSslCertificate($Installation.WebdavBackendCertificateThumbprint, 'My') } Write-StepDetail "IIS site $($Installation.IisSiteName) now serves https://127.0.0.1:$($Installation.WebdavBackendPort) only" } function Restore-MovedIisBindings { param($Installation) Get-WebBinding -Name $Installation.IisSiteName -Protocol https -IPAddress '127.0.0.1' -Port $Installation.WebdavBackendPort | Remove-WebBinding & netsh.exe http delete sslcert "ipport=127.0.0.1:$($Installation.WebdavBackendPort)" | Out-Null foreach ($movedBinding in @($Installation.MovedIisBindings)) { $bindingAddress = ConvertFrom-IisBindingInformation $movedBinding.BindingInformation $bindingFilter = @{ Name = $Installation.IisSiteName; Protocol = $movedBinding.Protocol; IPAddress = $bindingAddress.IPAddress; Port = $bindingAddress.Port; HostHeader = $bindingAddress.HostHeader } if ($null -eq (Get-WebBinding @bindingFilter)) { $sniAndCentralCertificateStoreFlags = 3 New-WebBinding @bindingFilter -SslFlags ($movedBinding.SslFlags -band $sniAndCentralCertificateStoreFlags) | Out-Null if ($movedBinding.SslFlags -gt $sniAndCentralCertificateStoreFlags) { Set-WebConfigurationProperty -PSPath 'MACHINE/WEBROOT/APPHOST' -Filter "system.applicationHost/sites/site[@name='$($Installation.IisSiteName)']/bindings/binding[@protocol='$($movedBinding.Protocol)' and @bindingInformation='$($movedBinding.BindingInformation)']" -Name sslFlags -Value $movedBinding.SslFlags } } if ($movedBinding.Protocol -eq 'https' -and -not [string]::IsNullOrEmpty($movedBinding.CertificateHash)) { try { (Get-WebBinding @bindingFilter).AddSslCertificate($movedBinding.CertificateHash, $movedBinding.CertificateStoreName) } catch { Write-StepWarning "IIS binding $($movedBinding.BindingInformation) kept its existing certificate: $($_.Exception.Message)" } } Write-StepDetail "gave back $($movedBinding.Protocol) $($movedBinding.BindingInformation)" } } function Write-DownloadProgress { param([long]$DownloadedBytes, [long]$TotalBytes, [double]$ElapsedSeconds) $bytesPerMegabyte = 1MB $downloadedMegabytes = $DownloadedBytes / $bytesPerMegabyte $megabytesPerSecond = 0 if ($ElapsedSeconds -gt 0) { $megabytesPerSecond = $downloadedMegabytes / $ElapsedSeconds } if ($TotalBytes -gt 0) { $progressLine = '{0,6:N1} of {1:N1} MB {2,3:N0}% {3:N1} MB/s' -f $downloadedMegabytes, ($TotalBytes / $bytesPerMegabyte), (100 * $DownloadedBytes / $TotalBytes), $megabytesPerSecond } else { $progressLine = '{0,6:N1} MB {1:N1} MB/s' -f $downloadedMegabytes, $megabytesPerSecond } Write-Host "`r $progressLine " -ForegroundColor Gray -NoNewline } function Save-DownloadWithProgress { param([string]$Uri, [string]$Path) $downloadTimeoutMilliseconds = 30000 $progressIntervalMilliseconds = 250 $request = [Net.HttpWebRequest]::Create($Uri) $request.Timeout = $downloadTimeoutMilliseconds $request.ReadWriteTimeout = $downloadTimeoutMilliseconds $response = $request.GetResponse() try { $responseStream = $response.GetResponseStream() $fileStream = [IO.File]::Create($Path) try { $buffer = New-Object byte[] (1MB) $downloadedBytes = [long]0 $downloadStopwatch = [Diagnostics.Stopwatch]::StartNew() $lastProgressMilliseconds = [long]0 while (($readBytes = $responseStream.Read($buffer, 0, $buffer.Length)) -gt 0) { $fileStream.Write($buffer, 0, $readBytes) $downloadedBytes += $readBytes if ($downloadStopwatch.ElapsedMilliseconds - $lastProgressMilliseconds -ge $progressIntervalMilliseconds) { Write-DownloadProgress -DownloadedBytes $downloadedBytes -TotalBytes $response.ContentLength -ElapsedSeconds $downloadStopwatch.Elapsed.TotalSeconds $lastProgressMilliseconds = $downloadStopwatch.ElapsedMilliseconds } } Write-DownloadProgress -DownloadedBytes $downloadedBytes -TotalBytes $response.ContentLength -ElapsedSeconds $downloadStopwatch.Elapsed.TotalSeconds Write-Host '' } finally { $fileStream.Dispose() $responseStream.Dispose() } } finally { $response.Dispose() } } function Save-VerifiedDownload { param([string]$Uri, [string]$ExpectedSha256, [string]$Path) Save-DownloadWithProgress -Uri $Uri -Path $Path $actualSha256 = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash if ($actualSha256 -ne $ExpectedSha256) { Remove-Item -LiteralPath $Path -Force throw "download of $Uri has sha256 $actualSha256, expected $ExpectedSha256" } } function Install-TraefikExecutable { param($Locations) if (Test-Path -LiteralPath $Locations.TraefikExecutable) { if ((& $Locations.TraefikExecutable version | Out-String) -match "Version:\s+$([regex]::Escape($TraefikVersion.TrimStart('v')))\b") { Write-StepDetail "Traefik $TraefikVersion is already installed" return } } Write-StepDetail "downloading Traefik $TraefikVersion from GitHub" $downloadDirectory = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString()) New-Item -ItemType Directory -Path $downloadDirectory | Out-Null try { $archivePath = Join-Path $downloadDirectory 'traefik.zip' Save-VerifiedDownload -Uri "https://github.com/traefik/traefik/releases/download/$TraefikVersion/traefik_${TraefikVersion}_windows_amd64.zip" -ExpectedSha256 $TraefikArchiveSha256 -Path $archivePath Expand-Archive -LiteralPath $archivePath -DestinationPath $downloadDirectory Copy-Item -LiteralPath (Join-Path $downloadDirectory 'traefik.exe') -Destination $Locations.TraefikExecutable -Force } finally { Remove-Item -LiteralPath $downloadDirectory -Recurse -Force } Write-StepDetail "installed Traefik $TraefikVersion, sha256 verified" } function Install-ServiceWrapperExecutable { param($Locations) if (Test-Path -LiteralPath $Locations.ServiceWrapperExecutable) { if ((Get-FileHash -LiteralPath $Locations.ServiceWrapperExecutable -Algorithm SHA256).Hash -eq $WinswExecutableSha256) { Write-StepDetail "WinSW $WinswVersion is already installed" return } } Write-StepDetail "downloading WinSW $WinswVersion from GitHub" Save-VerifiedDownload -Uri "https://github.com/winsw/winsw/releases/download/$WinswVersion/WinSW-x64.exe" -ExpectedSha256 $WinswExecutableSha256 -Path $Locations.ServiceWrapperExecutable Write-StepDetail "installed WinSW $WinswVersion, sha256 verified" } function Save-GatewayConfiguration { param($Installation, $Locations) Write-Utf8FileWithoutBom -Path $Locations.TraefikStaticConfiguration -Content (New-TraefikStaticConfiguration -Installation $Installation -Locations $Locations) Write-Utf8FileWithoutBom -Path $Locations.TraefikDynamicConfiguration -Content (New-TraefikDynamicConfiguration $Installation) Write-Utf8FileWithoutBom -Path $Locations.ServiceWrapperXml -Content (New-ServiceWrapperConfiguration -Installation $Installation -Locations $Locations) foreach ($configurationFile in @($Locations.TraefikStaticConfiguration, $Locations.TraefikDynamicConfiguration, $Locations.ServiceWrapperXml)) { Write-StepDetail "wrote $configurationFile" } } function Invoke-ServiceWrapper { param($Locations, [string]$Command) & $Locations.ServiceWrapperExecutable $Command | Out-Null if ($LASTEXITCODE -ne 0) { throw "WinSW $Command of $GatewayServiceName exited with $LASTEXITCODE; see $($Locations.LogDirectory)" } } function Start-GatewayService { param($Locations) if ($null -eq (Get-Service -Name $GatewayServiceName -ErrorAction SilentlyContinue)) { Invoke-ServiceWrapper -Locations $Locations -Command 'install' Write-StepDetail "registered the Windows service $GatewayServiceName (automatic start)" } if ((Get-Service -Name $GatewayServiceName).Status -eq 'Running') { Restart-Service -Name $GatewayServiceName Write-StepDetail "restarted $GatewayServiceName with the new configuration" } else { Start-Service -Name $GatewayServiceName Write-StepDetail "started $GatewayServiceName" } } function Remove-GatewayService { param($Locations) $gatewayService = Get-Service -Name $GatewayServiceName -ErrorAction SilentlyContinue if ($null -eq $gatewayService) { Write-StepDetail "$GatewayServiceName is not installed" return } if ($gatewayService.Status -ne 'Stopped') { Stop-Service -Name $GatewayServiceName } Invoke-ServiceWrapper -Locations $Locations -Command 'uninstall' Write-StepDetail "stopped and removed $GatewayServiceName" } function Set-GatewayFirewallRules { param($Installation) Get-NetFirewallRule -Group $FirewallRuleGroup -ErrorAction SilentlyContinue | Remove-NetFirewallRule New-NetFirewallRule -Group $FirewallRuleGroup -DisplayName 'Procurat Gateway HTTP (LAN)' -Direction Inbound -Protocol TCP -LocalPort $Installation.HttpPort -Profile Domain, Private -Action Allow | Out-Null New-NetFirewallRule -Group $FirewallRuleGroup -DisplayName 'Procurat Gateway HTTPS (LAN)' -Direction Inbound -Protocol TCP -LocalPort $Installation.InternalPort -Profile Domain, Private -Action Allow | Out-Null New-NetFirewallRule -Group $FirewallRuleGroup -DisplayName 'Procurat Gateway public API' -Direction Inbound -Protocol TCP -LocalPort $Installation.PublicPort -Profile Any -Action Allow | Out-Null Write-StepDetail "TCP $($Installation.HttpPort) and $($Installation.InternalPort): Domain and Private networks" Write-StepDetail "TCP $($Installation.PublicPort): all networks" } function Remove-GatewayFirewallRules { Get-NetFirewallRule -Group $FirewallRuleGroup -ErrorAction SilentlyContinue | Remove-NetFirewallRule Write-StepDetail "removed the firewall rules of group $FirewallRuleGroup" } function Write-SchoolToDoList { param($Installation, $AcmeDnsAccount) $hostNames = Get-GatewayHostNames $Installation.BaseDomain Write-Host '' Write-Host ' Installed. The school still has to:' -ForegroundColor Green Write-Host '' Write-Host ' 1. Add this DNS record:' Write-Host " _acme-challenge.$($hostNames.App) CNAME $($AcmeDnsAccount.fulldomain)" -ForegroundColor Yellow Write-Host " 2. Point $($hostNames.App) and $($hostNames.Webdav) at this server's LAN address" Write-Host " 3. Point $($hostNames.Api) at the school's public IP" Write-Host " 4. Forward TCP $($Installation.PublicPort) on the router to this server" Write-Host '' Write-Host ' Then check with: .\install-procurat-gateway.ps1 -Status' -ForegroundColor DarkGray } function Install-Gateway { param($Locations) Write-InstallerBanner 'Procurat gateway installer' Start-StepProgress -StepCount 9 $previousInstallation = Read-GatewayInstallationRecord $Locations Invoke-InstallerStep 'Check this server' { Assert-SupportedWindowsWithIis Assert-CertAdminReachable } $settings = Invoke-InstallerStep 'Settings' { Read-InstallationSettings -PreviousInstallation $previousInstallation } Invoke-InstallerStep 'Check ports' { Assert-GatewayPortsAvailable $settings } $acmeDnsAccount = Invoke-InstallerStep 'acme-dns account from cert-admin' { New-GatewayDataDirectory $Locations Save-AcmeDnsAccount -BaseDomain $settings.BaseDomain -Locations $Locations Read-AcmeDnsAccount -BaseDomain $settings.BaseDomain -Locations $Locations } $installation = New-GatewayInstallationRecord -Settings $settings -AcmeDnsAccount $acmeDnsAccount -PreviousInstallation $previousInstallation Invoke-InstallerStep 'Download Traefik and WinSW' { Install-TraefikExecutable $Locations Install-ServiceWrapperExecutable $Locations } Invoke-InstallerStep 'Write the configuration' { Save-GatewayConfiguration -Installation $installation -Locations $Locations } Invoke-InstallerStep 'Move the IIS site to loopback' { if ([string]::IsNullOrEmpty($installation.IisBackupName)) { Save-IisBackupBeforeMove -Installation $installation -Locations $Locations } else { Save-GatewayInstallationRecord -Installation $installation -Locations $Locations Write-StepDetail "keeping IIS backup $($installation.IisBackupName) from the first install" } Move-IisSiteToLoopback $installation } Invoke-InstallerStep 'Start the gateway service' { Assert-PortsFreeForTraefik -Ports (Get-TraefikPorts $installation) -PortsReleasedByIis @() Start-GatewayService $Locations } Invoke-InstallerStep 'Open the Windows firewall' { Set-GatewayFirewallRules $installation } Write-SchoolToDoList -Installation $installation -AcmeDnsAccount $acmeDnsAccount } function Resolve-PublicDnsRecordLookup { param([string]$Name, [string]$RecordType) $recordTypeNumbers = @{ A = 1; CNAME = 5 } $dnsNameDoesNotExistStatus = 3 $endpointFailures = @() foreach ($dnsOverHttpsEndpoint in $PublicDnsOverHttpsEndpoints) { try { $dnsResponse = Invoke-RestMethod -Method Get -Uri "$($dnsOverHttpsEndpoint)?name=$([Uri]::EscapeDataString($Name))&type=$RecordType" -Headers @{ Accept = 'application/dns-json' } -TimeoutSec 10 } catch { $endpointFailures += "$dnsOverHttpsEndpoint`: $($_.Exception.Message)" continue } if ($dnsResponse.Status -ne 0 -and $dnsResponse.Status -ne $dnsNameDoesNotExistStatus) { $endpointFailures += "$dnsOverHttpsEndpoint`: DNS status $($dnsResponse.Status)" continue } $answers = @() if ($null -ne $dnsResponse.PSObject.Properties['Answer']) { $answers = @($dnsResponse.Answer | Where-Object { $_.type -eq $recordTypeNumbers[$RecordType] }) } return [pscustomobject]@{ Values = @($answers | ForEach-Object { $_.data.TrimEnd('.').ToLowerInvariant() }); Source = $dnsOverHttpsEndpoint; LookupFailure = $null } } [pscustomobject]@{ Values = @(); Source = $null; LookupFailure = $endpointFailures -join '; ' } } function Resolve-LocalDnsRecordLookup { param([string]$Name, [string]$RecordType) $dnsNameDoesNotExistCode = 9003 $dnsNoRecordsCode = 9501 try { $answers = @(Resolve-DnsName -Name $Name -Type $RecordType -DnsOnly -QuickTimeout -ErrorAction Stop | Where-Object { $_.Type -eq $RecordType }) } catch { $nativeErrorCode = $_.Exception.PSObject.Properties['NativeErrorCode'] if ($null -ne $nativeErrorCode -and @($dnsNameDoesNotExistCode, $dnsNoRecordsCode) -contains $nativeErrorCode.Value) { return [pscustomobject]@{ Values = @(); LookupFailure = $null } } return [pscustomobject]@{ Values = @(); LookupFailure = $_.Exception.Message } } $recordValues = switch ($RecordType) { 'CNAME' { @($answers | ForEach-Object { $_.NameHost.TrimEnd('.').ToLowerInvariant() }) } default { @($answers | ForEach-Object { $_.IPAddress }) } } [pscustomobject]@{ Values = @($recordValues); LookupFailure = $null } } function Get-TlsEndpointProbe { param([string]$HostName, [int]$Port, [string]$Path) $tcpClient = New-Object Net.Sockets.TcpClient try { if (-not $tcpClient.ConnectAsync('127.0.0.1', $Port).Wait($TlsProbeTimeoutMilliseconds)) { throw "no connection within $TlsProbeTimeoutMilliseconds ms" } $tcpClient.ReceiveTimeout = $TlsProbeTimeoutMilliseconds $tcpClient.SendTimeout = $TlsProbeTimeoutMilliseconds $acceptAnyCertificate = [Net.Security.RemoteCertificateValidationCallback] { $true } $tlsStream = New-Object Net.Security.SslStream ($tcpClient.GetStream(), $false, $acceptAnyCertificate) $tlsStream.ReadTimeout = $TlsProbeTimeoutMilliseconds $tlsStream.WriteTimeout = $TlsProbeTimeoutMilliseconds $tlsStream.AuthenticateAsClient($HostName) $servedCertificate = New-Object Security.Cryptography.X509Certificates.X509Certificate2 ($tlsStream.RemoteCertificate) $request = [Text.Encoding]::ASCII.GetBytes("GET $Path HTTP/1.1`r`nHost: $HostName`r`nConnection: close`r`n`r`n") $tlsStream.Write($request, 0, $request.Length) $statusLine = (New-Object IO.StreamReader ($tlsStream)).ReadLine() [pscustomobject]@{ ServesIssuedCertificate = $servedCertificate.Subject -notmatch 'TRAEFIK DEFAULT CERT' Detail = "$statusLine; certificate $($servedCertificate.Subject) from $($servedCertificate.Issuer), valid until $($servedCertificate.NotAfter.ToString('yyyy-MM-dd'))" } } catch { [pscustomobject]@{ ServesIssuedCertificate = $false; Detail = "unreachable: $($_.Exception.Message)" } } finally { $tcpClient.Dispose() } } function Write-StatusLine { param([bool]$IsHealthy, [string]$Subject, [string]$Detail) if ($IsHealthy) { Write-Host ' [ ok ] ' -ForegroundColor Green -NoNewline } else { Write-Host ' [fail] ' -ForegroundColor Red -NoNewline } Write-Host "$Subject" -ForegroundColor White -NoNewline Write-Host " $Detail" -ForegroundColor Gray } function Write-GatewayServiceStatus { $gatewayService = Get-Service -Name $GatewayServiceName -ErrorAction SilentlyContinue if ($null -eq $gatewayService) { Write-StatusLine -IsHealthy $false -Subject 'Service' -Detail "$GatewayServiceName is not installed" return } Write-StatusLine -IsHealthy ($gatewayService.Status -eq 'Running') -Subject 'Service' -Detail "$GatewayServiceName is $($gatewayService.Status)" } function Write-NetworkProfileStatus { param($Installation) foreach ($connectionProfile in @(Get-NetConnectionProfile)) { Write-StatusLine -IsHealthy ($connectionProfile.NetworkCategory -ne 'Public') -Subject "Network $($connectionProfile.InterfaceAlias)" -Detail "firewall profile $($connectionProfile.NetworkCategory); ports $($Installation.HttpPort) and $($Installation.InternalPort) are open for Domain and Private only" } } function Write-ChallengeCnameStatus { param($HostNames, $AcmeDnsAccount) $challengeName = "_acme-challenge.$($HostNames.App)" $expectedCnameTarget = $AcmeDnsAccount.fulldomain.TrimEnd('.').ToLowerInvariant() $cnameLookup = Resolve-PublicDnsRecordLookup -Name $challengeName -RecordType CNAME if ($null -ne $cnameLookup.LookupFailure) { Write-StatusLine -IsHealthy $false -Subject 'CNAME' -Detail "could not ask public DNS over HTTPS: $($cnameLookup.LookupFailure)" return } if ($cnameLookup.Values.Count -eq 0) { Write-StatusLine -IsHealthy $false -Subject 'CNAME' -Detail "public DNS ($($cnameLookup.Source)) has no $challengeName; add it in the public zone, pointing to $expectedCnameTarget" return } Write-StatusLine -IsHealthy ($cnameLookup.Values -contains $expectedCnameTarget) -Subject 'CNAME' -Detail "public DNS ($($cnameLookup.Source)) has $challengeName pointing to $($cnameLookup.Values -join ', '), expected $expectedCnameTarget" } function Write-HostNameStatus { param($HostNames) foreach ($lanHostName in @($HostNames.App, $HostNames.Webdav)) { $lanLookup = Resolve-LocalDnsRecordLookup -Name $lanHostName -RecordType A $lanDetail = if ($null -ne $lanLookup.LookupFailure) { "lookup at this server's DNS failed: $($lanLookup.LookupFailure)" } else { "this server's DNS resolves it to $($lanLookup.Values -join ', ')" } Write-StatusLine -IsHealthy ($lanLookup.Values.Count -gt 0) -Subject $lanHostName -Detail $lanDetail } $publicLookup = Resolve-PublicDnsRecordLookup -Name $HostNames.Api -RecordType A $publicDetail = if ($null -ne $publicLookup.LookupFailure) { "could not ask public DNS over HTTPS: $($publicLookup.LookupFailure)" } else { "public DNS ($($publicLookup.Source)) resolves it to $($publicLookup.Values -join ', ')" } Write-StatusLine -IsHealthy ($publicLookup.Values.Count -gt 0) -Subject $HostNames.Api -Detail $publicDetail } function Get-LastTraefikError { param($Locations) $traefikLog = Join-Path $Locations.LogDirectory 'traefik.log' if (-not (Test-Path -LiteralPath $traefikLog)) { return $null } $lastErrorLine = Get-Content -LiteralPath $traefikLog -Tail 2000 | Select-String -Pattern ' ERR ' | Select-Object -Last 1 if ($null -eq $lastErrorLine) { return $null } $lastErrorLine.Line } function Write-CertificateStatus { param($HostNames, $Locations) $storedCertificates = @() if (Test-Path -LiteralPath $Locations.AcmeCertificateStorage) { $storedCertificates = @(Get-AcmeCertificateSummaries (Get-Content -LiteralPath $Locations.AcmeCertificateStorage -Raw)) } if ($storedCertificates.Count -eq 0) { Write-StatusLine -IsHealthy $false -Subject 'Certificate' -Detail "none issued yet; see $($Locations.LogDirectory)\traefik.log" $lastTraefikError = Get-LastTraefikError $Locations if ($null -ne $lastTraefikError) { Write-Host " last Traefik error: $lastTraefikError" -ForegroundColor DarkYellow } return } foreach ($storedCertificate in $storedCertificates) { $coversGatewayHosts = ($storedCertificate.Names -contains $HostNames.App) -and ($storedCertificate.Names -contains "*.$($HostNames.App)") Write-StatusLine -IsHealthy ($coversGatewayHosts -and $storedCertificate.NotAfter -gt (Get-Date).AddDays(14)) -Subject 'Certificate' -Detail "$($storedCertificate.Names -join ', ') from $($storedCertificate.Issuer), valid until $($storedCertificate.NotAfter.ToString('yyyy-MM-dd'))" } } function Write-TlsEndpointStatus { param([string]$HostName, [int]$Port, [string]$Path) $probe = Get-TlsEndpointProbe -HostName $HostName -Port $Port -Path $Path Write-StatusLine -IsHealthy $probe.ServesIssuedCertificate -Subject "https://${HostName}:$Port$Path" -Detail $probe.Detail } function Show-GatewayStatus { param($Locations) Write-InstallerBanner 'Procurat gateway status' $installation = Read-ExistingGatewayInstallationRecord $Locations $hostNames = Get-GatewayHostNames $installation.BaseDomain $acmeDnsAccount = Read-AcmeDnsAccount -BaseDomain $installation.BaseDomain -Locations $Locations Write-Host '' Write-GatewayServiceStatus Write-NetworkProfileStatus $installation Write-ChallengeCnameStatus -HostNames $hostNames -AcmeDnsAccount $acmeDnsAccount Write-HostNameStatus $hostNames Write-CertificateStatus -HostNames $hostNames -Locations $Locations Write-TlsEndpointStatus -HostName $hostNames.App -Port $installation.InternalPort -Path '/' Write-TlsEndpointStatus -HostName $hostNames.Webdav -Port $installation.InternalPort -Path '/' Write-TlsEndpointStatus -HostName $hostNames.Api -Port $installation.PublicPort -Path $ProcuratApiPath Write-Host '' Write-Host " From outside the school network only: https://$($hostNames.Api):$($installation.PublicPort)$ProcuratApiPath tests the router's port forward." -ForegroundColor DarkGray } function Uninstall-Gateway { param($Locations) Write-InstallerBanner 'Procurat gateway uninstaller' Start-StepProgress -StepCount 4 Import-Module WebAdministration $installation = Read-ExistingGatewayInstallationRecord $Locations Invoke-InstallerStep 'Remove the gateway service' { Remove-GatewayService $Locations } Invoke-InstallerStep 'Close the Windows firewall' { Remove-GatewayFirewallRules } Invoke-InstallerStep 'Give IIS its bindings back' { if (-not [string]::IsNullOrEmpty($installation.IisBackupName)) { Restore-MovedIisBindings $installation Remove-Item -LiteralPath "Cert:\LocalMachine\My\$($installation.WebdavBackendCertificateThumbprint)" -ErrorAction SilentlyContinue Write-StepDetail 'removed the WebDAV backend certificate' } } Invoke-InstallerStep 'Remove the program files' { Remove-Item -LiteralPath $Locations.ProgramDirectory -Recurse -Force -ErrorAction SilentlyContinue Remove-Item -LiteralPath $Locations.InstallationRecord -Force Write-StepDetail "removed $($Locations.ProgramDirectory)" } Write-Host '' Write-Host ' Uninstalled.' -ForegroundColor Green Write-Host " The IIS configuration from before the install stays as appcmd backup $($installation.IisBackupName)." -ForegroundColor DarkGray Write-Host " The acme-dns account and certificates stay in $($Locations.DataDirectory); a new install reuses them." -ForegroundColor DarkGray } if (-not (Test-RunningAsAdministrator)) { Start-ElevatedInstaller return } [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $gatewayLocations = Get-GatewayLocations -ProgramFilesDirectory $env:ProgramFiles -ProgramDataDirectory $env:ProgramData try { switch ($PSCmdlet.ParameterSetName) { 'Status' { Show-GatewayStatus $gatewayLocations } 'Uninstall' { Uninstall-Gateway $gatewayLocations } default { Install-Gateway $gatewayLocations } } } catch { Write-InstallerFailure $_ }