- verwaltung.env ohne Passwort, Passwort in verwaltung.passwort (DPAPI, LocalMachine, nur Administratoren und SYSTEM), an psql/pg_dump/Node nur per PGPASSWORD - aktualisieren.ps1 uebernimmt ein Passwort aus verwaltung.env automatisch - neues verwalterpasswort.ps1; installieren.ps1 fragt das Passwort ab - Nachtlauf als SYSTEM, LocalService ohne Zugriff auf app.env - aktualisieren.ps1 kopiert die Betriebsskripte zuerst und richtet die geplanten Aufgaben neu ein - sicherung.ps1 und nachtlauf.ps1 mit festem Ziel C:\AlpenwerkHR - Betriebshandbuch: vollstaendige Pfade, Tabelle welche Datei welches Skript liest
280 lines
14 KiB
PowerShell
280 lines
14 KiB
PowerShell
#Requires -RunAsAdministrator
|
|
<#
|
|
.SYNOPSIS
|
|
Installiert Alpenwerk HR auf einem Windows-Server, im IIS.
|
|
|
|
.DESCRIPTION
|
|
Aufruf aus dem entpackten Paket heraus (dort, wo app\ und windows\ liegen):
|
|
|
|
.\windows\installieren.ps1
|
|
|
|
Der erste Aufruf legt app.env und verwaltung.env an, erzeugt die Geheimnisse,
|
|
fragt das Passwort des PostgreSQL-Benutzers postgres ab (es wird
|
|
verschluesselt in verwaltung.passwort abgelegt) und hoert mit einer Liste
|
|
auf, was in app.env noch einzutragen ist. Nach dem Eintragen derselbe Befehl
|
|
noch einmal: Datenbank, Migrationen, IIS (Anwendungspool, Website,
|
|
Zertifikat), geplante Aufgaben.
|
|
|
|
Wiederholbar. Eine bestehende Installation wird uebernommen: app.env,
|
|
verwaltung.env, verwaltung.passwort, Datenbank und Sicherungen bleiben. Ein
|
|
Windows-Dienst gleichen Namens wird entfernt; die Anwendung laeuft im IIS.
|
|
|
|
Fuer neue Staende danach aktualisieren.ps1.
|
|
|
|
.PARAMETER Ziel
|
|
Installationsverzeichnis, ohne Leerzeichen.
|
|
|
|
.PARAMETER HostName
|
|
Name, unter dem die Anwendung erreichbar ist. Ohne Angabe der Name aus
|
|
AUTH_URL in app.env.
|
|
|
|
.PARAMETER Zertifikat
|
|
Fingerabdruck des Zertifikats. Ohne Angabe das gueltige Zertifikat fuer den
|
|
Hostnamen aus Cert:\LocalMachine\My, das am laengsten gilt.
|
|
|
|
.PARAMETER Konto
|
|
Eigenes Konto fuer den Anwendungspool (Get-Credential). Ohne Angabe das
|
|
virtuelle Konto "IIS AppPool\AlpenwerkHR", das keine Administratorrechte hat.
|
|
|
|
.PARAMETER PgBin
|
|
Verzeichnis mit psql.exe und pg_dump.exe. Ohne Angabe die neueste
|
|
Installation unter "C:\Program Files\PostgreSQL".
|
|
#>
|
|
param(
|
|
[string]$Ziel = 'C:\AlpenwerkHR',
|
|
[string]$HostName,
|
|
[string]$Zertifikat,
|
|
[System.Management.Automation.PSCredential]$Konto,
|
|
[string]$PgBin
|
|
)
|
|
|
|
. (Join-Path $PSScriptRoot 'gemeinsam.ps1')
|
|
|
|
$paket = Split-Path $PSScriptRoot -Parent
|
|
if (-not (Test-Path -LiteralPath (Join-Path $paket 'app\server.js'))) {
|
|
throw "Kein Paket gefunden: $paket\app\server.js fehlt. Das Skript aus dem entpackten Paket aufrufen."
|
|
}
|
|
# Die Pfade stehen ohne Anfuehrungszeichen in den Argumenten von Node.
|
|
if ($Ziel -match '\s') { throw "Das Installationsverzeichnis darf keine Leerzeichen enthalten: $Ziel" }
|
|
|
|
# -- Voraussetzungen ----------------------------------------------------
|
|
Write-Host '== Voraussetzungen'
|
|
Assert-NodeVersion
|
|
$pgBin = Get-PgBin $PgBin
|
|
Write-Host "PostgreSQL-Programme: $pgBin"
|
|
foreach ($feature in @('Web-Server', 'Web-AppInit')) {
|
|
if ((Get-WindowsFeature -Name $feature).InstallState -ne 'Installed') {
|
|
Install-WindowsFeature -Name $feature -IncludeManagementTools | Out-Null
|
|
Write-Host "Windows-Feature $feature installiert."
|
|
}
|
|
}
|
|
Import-Module WebAdministration
|
|
if (-not (Get-WebGlobalModule -Name 'httpPlatformHandler' -ErrorAction SilentlyContinue)) {
|
|
throw 'Das IIS-Modul "HttpPlatformHandler" fehlt: https://www.iis.net/downloads/microsoft/httpplatformhandler'
|
|
}
|
|
if (-not (Get-WebGlobalModule -Name 'RewriteModule' -ErrorAction SilentlyContinue)) {
|
|
throw 'Das IIS-Modul "URL Rewrite" fehlt: https://www.iis.net/downloads/microsoft/url-rewrite'
|
|
}
|
|
|
|
# -- Verzeichnisse ------------------------------------------------------
|
|
#
|
|
# Die Vererbung von C:\ wird gekappt: dort duerfen angemeldete Benutzer neue
|
|
# Ordner aendern, und in app.env stehen Geheimnisse. Danach gilt:
|
|
# Administratoren und SYSTEM alles; was die Anwendung darf, setzt
|
|
# Set-AppRechte weiter unten.
|
|
Write-Host "== Verzeichnis $Ziel"
|
|
foreach ($v in @($Ziel, "$Ziel\logs", "$Ziel\sicherungen", "$Ziel\iis")) {
|
|
New-Item -ItemType Directory -Force -Path $v | Out-Null
|
|
}
|
|
Invoke-Icacls @($Ziel, '/inheritance:r', '/grant:r', "${SidAdministratoren}:(OI)(CI)F", "${SidSystem}:(OI)(CI)F")
|
|
# Sicherungen enthalten saemtliche Personaldaten im Klartext.
|
|
Invoke-Icacls @("$Ziel\sicherungen", '/inheritance:r', '/grant:r',
|
|
"${SidAdministratoren}:(OI)(CI)F", "${SidSystem}:(OI)(CI)F")
|
|
|
|
# -- Konfiguration ------------------------------------------------------
|
|
$appEnv = "$Ziel\app.env"
|
|
$verwaltungEnv = "$Ziel\verwaltung.env"
|
|
|
|
if (-not (Test-Path -LiteralPath $appEnv)) {
|
|
$text = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'app.env.vorlage') -Raw -Encoding UTF8
|
|
$text = $text.Replace('{{APP_DB_PASSWORD}}', (New-Geheimnis 24))
|
|
$text = $text.Replace('{{AUTH_SECRET}}', (New-Geheimnis 32))
|
|
$text = $text.Replace('{{CRON_SECRET}}', (New-Geheimnis 32))
|
|
[System.IO.File]::WriteAllText($appEnv, $text, (New-Object System.Text.UTF8Encoding $false))
|
|
Write-Host "Angelegt: $appEnv (Geheimnisse erzeugt)"
|
|
}
|
|
if (-not (Test-Path -LiteralPath $verwaltungEnv)) {
|
|
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'verwaltung.env.vorlage') -Destination $verwaltungEnv
|
|
Write-Host "Angelegt: $verwaltungEnv"
|
|
}
|
|
# Nur Administratoren und SYSTEM -- die Anwendung braucht den Verwalterzugang nicht.
|
|
Invoke-Icacls @($verwaltungEnv, '/inheritance:r', '/grant:r', "${SidAdministratoren}:F", "${SidSystem}:F")
|
|
|
|
$app = Read-EnvDatei $appEnv
|
|
$verwaltung = Read-EnvDatei $verwaltungEnv
|
|
# Das Passwort des Verwalters wird abgefragt, nicht eingetragen. Steht es noch
|
|
# in der URL in verwaltung.env, uebernimmt es Use-Verwaltungszugang weiter
|
|
# unten.
|
|
if (-not (Test-Path -LiteralPath "$Ziel\verwaltung.passwort") -and -not (Split-VerbindungMitPasswort $verwaltung['MIGRATE_DATABASE_URL'])) {
|
|
Set-Verwalterpasswort -Ziel $Ziel -PgBin $pgBin
|
|
$verwaltung = Read-EnvDatei $verwaltungEnv
|
|
}
|
|
$fehlend = @()
|
|
$fehlend += Get-FehlendeWerte $app $PflichtApp | ForEach-Object { "app.env: $_" }
|
|
$fehlend += Get-FehlendeWerte $verwaltung $PflichtVerwaltung | ForEach-Object { "verwaltung.env: $_" }
|
|
if ($fehlend.Count -gt 0) {
|
|
Write-Host ''
|
|
Write-Host 'Noch einzutragen:' -ForegroundColor Yellow
|
|
$fehlend | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow }
|
|
Write-Host ''
|
|
Write-Host "Dateien in $Ziel bearbeiten (z. B. notepad $appEnv) und dieses Skript erneut aufrufen."
|
|
exit 0
|
|
}
|
|
$port = [int]$app['PORT']
|
|
|
|
$ausAuthUrl = ([Uri]$app['AUTH_URL']).Host
|
|
if (-not $HostName) { $HostName = $ausAuthUrl }
|
|
if ($HostName -ne $ausAuthUrl) {
|
|
Write-Host "Achtung: AUTH_URL nennt $ausAuthUrl, eingerichtet wird $HostName." -ForegroundColor Yellow
|
|
}
|
|
# Vor jeder Aenderung am IIS: ohne Zertifikat gibt es keine Anmeldung.
|
|
$zert = Find-Zertifikat -HostName $HostName -Fingerabdruck $Zertifikat
|
|
Write-Host "Zertifikat: $($zert.Subject), gueltig bis $($zert.NotAfter.ToString('yyyy-MM-dd')), $($zert.Thumbprint)"
|
|
|
|
# -- Ein Windows-Dienst gleichen Namens ---------------------------------
|
|
$dienst = Get-Service -Name $PoolName -ErrorAction SilentlyContinue
|
|
if ($dienst) {
|
|
Write-Host "== Windows-Dienst $PoolName entfernen (die Anwendung laeuft im IIS)"
|
|
if ($dienst.Status -ne 'Stopped') { Stop-Service -Name $PoolName -Force }
|
|
& sc.exe delete $PoolName | Out-Null
|
|
if ($LASTEXITCODE -ne 0) { throw "Der Dienst $PoolName liess sich nicht entfernen." }
|
|
}
|
|
|
|
# -- Anwendungspool -----------------------------------------------------
|
|
Write-Host "== Anwendungspool $PoolName"
|
|
$poolPfad = "IIS:\AppPools\$PoolName"
|
|
if (-not (Test-Path $poolPfad)) { New-WebAppPool -Name $PoolName | Out-Null }
|
|
Stop-AlpenwerkPool -Ziel $Ziel
|
|
# Kein .NET: der Pool startet nur Node. AlwaysRunning mit preloadEnabled an
|
|
# der Website: Node laeuft ab dem Start des Servers, nicht erst ab der ersten
|
|
# Anfrage. Kein Leerlauf-Ende und kein Recycling nach Zeit: sonst fiele die
|
|
# Anwendung mitten am Tag fuer einige Sekunden aus.
|
|
Set-ItemProperty $poolPfad -Name managedRuntimeVersion -Value ''
|
|
Set-ItemProperty $poolPfad -Name startMode -Value 'AlwaysRunning'
|
|
Set-ItemProperty $poolPfad -Name processModel.idleTimeout -Value ([TimeSpan]::Zero)
|
|
Set-ItemProperty $poolPfad -Name recycling.periodicRestart.time -Value ([TimeSpan]::Zero)
|
|
Set-ItemProperty $poolPfad -Name recycling.disallowOverlappingRotation -Value $true
|
|
if ($Konto) {
|
|
Set-ItemProperty $poolPfad -Name processModel -Value @{
|
|
identityType = 'SpecificUser'; userName = $Konto.UserName; password = $Konto.GetNetworkCredential().Password
|
|
}
|
|
# Ein eigenes Konto braucht die Gruppe IIS_IUSRS, um als Arbeitsprozess
|
|
# laufen zu duerfen; das virtuelle Konto hat sie von selbst.
|
|
Add-LocalGroupMember -SID 'S-1-5-32-568' -Member $Konto.UserName -ErrorAction SilentlyContinue
|
|
} else {
|
|
Set-ItemProperty $poolPfad -Name processModel.identityType -Value 'ApplicationPoolIdentity'
|
|
}
|
|
Write-Host "Konto: $(Get-PoolKonto)"
|
|
|
|
# -- Anwendung ----------------------------------------------------------
|
|
Write-Host '== Anwendung kopieren'
|
|
Copy-Verzeichnis -Quelle (Join-Path $paket 'app') -Ziel "$Ziel\app" -Spiegeln
|
|
Copy-Verzeichnis -Quelle $PSScriptRoot -Ziel "$Ziel\windows" -Spiegeln
|
|
Copy-Item -LiteralPath (Join-Path $paket 'VERSION.txt') -Destination "$Ziel\VERSION.txt" -Force -ErrorAction SilentlyContinue
|
|
Set-AppRechte -Ziel $Ziel
|
|
|
|
# -- Datenbank ----------------------------------------------------------
|
|
Write-Host '== Datenbank einrichten'
|
|
$null = Use-Verwaltungszugang -Ziel $Ziel
|
|
try {
|
|
Invoke-NodeSkript -AppVerzeichnis "$Ziel\app" -Ziel $Ziel -Skript 'scripts/db-setup.mjs'
|
|
Write-Host '== Migrationen'
|
|
Invoke-NodeSkript -AppVerzeichnis "$Ziel\app" -Ziel $Ziel -Skript 'scripts/migrate.mjs'
|
|
} finally {
|
|
Close-Verwaltungszugang
|
|
}
|
|
|
|
# -- Website ------------------------------------------------------------
|
|
Write-Host "== Website $SiteName"
|
|
Write-AlpenwerkWebConfig -Ziel $Ziel -Vorlage (Join-Path $PSScriptRoot 'web.config')
|
|
# Der IIS-Arbeitsprozess liest die web.config.
|
|
Invoke-Icacls @("$Ziel\iis", '/grant', "${SidIisIusrs}:(OI)(CI)RX")
|
|
|
|
# URL Rewrite darf die beiden X-Forwarded-Kopfzeilen nur setzen, wenn sie
|
|
# serverweit freigegeben sind.
|
|
$apphost = 'MACHINE/WEBROOT/APPHOST'
|
|
$erlaubt = @(Get-WebConfigurationProperty -PSPath $apphost -Filter 'system.webServer/rewrite/allowedServerVariables' -Name 'collection' | ForEach-Object { $_.name })
|
|
foreach ($variable in @('HTTP_X_FORWARDED_PROTO', 'HTTP_X_FORWARDED_HOST')) {
|
|
if ($erlaubt -notcontains $variable) {
|
|
Add-WebConfigurationProperty -PSPath $apphost -Filter 'system.webServer/rewrite/allowedServerVariables' -Name '.' -Value @{ name = $variable }
|
|
}
|
|
}
|
|
|
|
# Gefiltert wird hier und nicht ueber -Name: `Get-Website -Name <x>` liefert in
|
|
# mehreren Fassungen von WebAdministration alle Sites zurueck.
|
|
if (Get-Website | Where-Object { $_.Name -eq $SiteName }) { Remove-Website -Name $SiteName }
|
|
if (Test-Path "IIS:\SslBindings\!443!$HostName") { Remove-Item "IIS:\SslBindings\!443!$HostName" }
|
|
New-Website -Name $SiteName -PhysicalPath "$Ziel\iis" -ApplicationPool $PoolName -HostHeader $HostName -Port 443 -Ssl -SslFlags 1 | Out-Null
|
|
(Get-WebBinding -Name $SiteName -Protocol 'https').AddSslCertificate($zert.Thumbprint, 'My')
|
|
# Port 80 nur fuer die Umleitung auf HTTPS.
|
|
New-WebBinding -Name $SiteName -Protocol 'http' -Port 80 -HostHeader $HostName
|
|
# Lokal und unverschluesselt, nur von diesem Server aus: fuer den naechtlichen
|
|
# Lauf und die Pruefungen der Betriebsskripte.
|
|
New-WebBinding -Name $SiteName -Protocol 'http' -IPAddress '127.0.0.1' -Port $port
|
|
Set-ItemProperty "IIS:\Sites\$SiteName" -Name applicationDefaults.preloadEnabled -Value $true
|
|
# Der Abschnitt "handlers" ist im IIS serverweit gesperrt; ohne Freigabe
|
|
# antwortet die Website mit 500.19, weil die web.config HttpPlatformHandler
|
|
# eintraegt. Freigegeben wird nur fuer diese Website.
|
|
Set-WebConfiguration -PSPath $apphost -Location $SiteName -Filter 'system.webServer/handlers' -Metadata overrideMode -Value Allow
|
|
Write-Host "https://$HostName (Zertifikat gebunden), http://$HostName leitet um, lokal http://127.0.0.1:$port"
|
|
|
|
# Erneuert die automatische Registrierung das Zertifikat, zieht diese Aufgabe
|
|
# die Bindung auf das neue nach. Ohne sie zeigte die Website nach der
|
|
# Erneuerung weiter auf das alte Zertifikat, bis es ablaeuft.
|
|
$protokoll = 'Microsoft-Windows-CertificateServicesClient-Lifecycle-System/Operational'
|
|
$abfrage = [System.Security.SecurityElement]::Escape("<QueryList><Query Id=`"0`" Path=`"$protokoll`"><Select Path=`"$protokoll`">*[System[(EventID=1001)]]</Select></Query></QueryList>")
|
|
$aufgabe = @"
|
|
<?xml version="1.0" encoding="UTF-16"?>
|
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
<RegistrationInfo><Description>Bindet die Website $SiteName nach einer Erneuerung des Zertifikats an das neue Zertifikat.</Description></RegistrationInfo>
|
|
<Triggers>
|
|
<EventTrigger>
|
|
<Enabled>true</Enabled>
|
|
<Subscription>$abfrage</Subscription>
|
|
<ValueQueries>
|
|
<Value name="OldCertHash">Event/UserData/CertNotificationData/OldCertificateDetails/@Thumbprint</Value>
|
|
<Value name="NewCertHash">Event/UserData/CertNotificationData/NewCertificateDetails/@Thumbprint</Value>
|
|
</ValueQueries>
|
|
</EventTrigger>
|
|
</Triggers>
|
|
<Principals><Principal id="System"><UserId>S-1-5-18</UserId><RunLevel>HighestAvailable</RunLevel></Principal></Principals>
|
|
<Settings><ExecutionTimeLimit>PT5M</ExecutionTimeLimit><StartWhenAvailable>true</StartWhenAvailable></Settings>
|
|
<Actions Context="System">
|
|
<Exec>
|
|
<Command>%SystemRoot%\System32\inetsrv\appcmd.exe</Command>
|
|
<Arguments>renew binding /oldcert:`$(OldCertHash) /newcert:`$(NewCertHash)</Arguments>
|
|
</Exec>
|
|
</Actions>
|
|
</Task>
|
|
"@
|
|
Register-ScheduledTask -TaskName 'AlpenwerkHR Zertifikat nachziehen' -Xml $aufgabe -Force | Out-Null
|
|
Write-Host 'AlpenwerkHR Zertifikat nachziehen: bei jeder Erneuerung'
|
|
|
|
Start-AlpenwerkPool
|
|
Write-Host "Warte auf http://127.0.0.1:$port/login ..."
|
|
if (-not (Wait-Gesund -Port $port)) {
|
|
throw "Die Anwendung antwortet nicht. Protokoll: $Ziel\logs\app_*.log"
|
|
}
|
|
Write-Host 'Anwendung laeuft.' -ForegroundColor Green
|
|
|
|
# -- Geplante Aufgaben --------------------------------------------------
|
|
Write-Host '== Geplante Aufgaben'
|
|
Register-AlpenwerkAufgaben -Ziel $Ziel -PgBin $pgBin
|
|
|
|
Write-Host ''
|
|
Write-Host 'Installation fertig.' -ForegroundColor Green
|
|
Write-Host 'Naechste Schritte:'
|
|
Write-Host " 1. Entra: Umleitungs-URI $($app['AUTH_URL'].TrimEnd('/'))/api/auth/callback/microsoft-entra-id"
|
|
Write-Host " 2. Zugang: $Ziel\windows\freischalten.ps1 -Domain <domain> oder -Email <adresse>"
|
|
Write-Host " 3. Pruefen: Abnahme-Liste im Betriebshandbuch (Betriebshandbuch_Alpenwerk_HR.pdf im Paket)"
|