WLAN-Profile, portables OpenVPN und automatischer AD-Join
- WLAN-Tab: SSIDs (WPA2/WPA3/offen, versteckt) in Blaupausen speichern, fuer alle Benutzer anlegen, Profile eines Referenzgeraets uebernehmen - OpenVPN portabel: offizielles MSI per msiexec /a entpackt + Microsoft- signierter TAP-Treiber in tools\openvpn; Treiber wird nur temporaer geladen und danach entfernt (--disable-dco, --dev-node) - .ovpn/Zertifikate je Kunde hochladen, Benutzer/Kennwort optional - AD-Join mit DC-Test (SRV+LDAP), OU, Umbenennung, lokalen Admins, optional ueber VPN; VPN optional als Dienst fuer die erste Anmeldung - Fehlende Kennwoerter werden beim Start abgefragt und nicht gespeichert Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -468,6 +468,7 @@ $script:UploadTypes = @{
|
||||
installers = '.exe', '.msi', '.msix', '.msixbundle', '.appx', '.appxbundle', '.ps1', '.cmd', '.bat'
|
||||
icons = '.ico', '.exe', '.dll'
|
||||
rdp = '.rdp'
|
||||
vpn = '.ovpn', '.conf', '.crt', '.pem', '.key', '.p12', '.pfx'
|
||||
}
|
||||
|
||||
function Resolve-UploadTarget {
|
||||
@@ -1038,6 +1039,402 @@ function Remove-Bloatware {
|
||||
|
||||
#endregion
|
||||
|
||||
#region WLAN --------------------------------------------------------------------
|
||||
|
||||
function New-WifiProfileXml {
|
||||
param($W)
|
||||
$e = [Security.SecurityElement]::Escape([string]$W.ssid)
|
||||
$hex = -join ([Text.Encoding]::UTF8.GetBytes([string]$W.ssid) | ForEach-Object { $_.ToString('X2') })
|
||||
$auth = switch ($W.auth) { 'WPA3SAE' { 'WPA3SAE' } 'open' { 'open' } default { 'WPA2PSK' } }
|
||||
$sec = if ($auth -eq 'open') {
|
||||
'<authEncryption><authentication>open</authentication><encryption>none</encryption><useOneX>false</useOneX></authEncryption>'
|
||||
} else {
|
||||
if ("$($W.key)".Length -lt 8) { throw "WLAN '$($W.ssid)': Kennwort muss mindestens 8 Zeichen haben" }
|
||||
"<authEncryption><authentication>$auth</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption>" +
|
||||
"<sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>$([Security.SecurityElement]::Escape([string]$W.key))</keyMaterial></sharedKey>"
|
||||
}
|
||||
@"
|
||||
<?xml version="1.0"?>
|
||||
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
|
||||
<name>$e</name>
|
||||
<SSIDConfig><SSID><hex>$hex</hex><name>$e</name></SSID><nonBroadcast>$(if (Test-True $W.hidden) { 'true' } else { 'false' })</nonBroadcast></SSIDConfig>
|
||||
<connectionType>ESS</connectionType>
|
||||
<connectionMode>$(if ($W.auto -eq $false) { 'manual' } else { 'auto' })</connectionMode>
|
||||
<MSM><security>$sec</security></MSM>
|
||||
</WLANProfile>
|
||||
"@
|
||||
}
|
||||
|
||||
function Add-WifiProfiles {
|
||||
param($Data)
|
||||
$list = @($Data.wifi | Where-Object { $_.ssid })
|
||||
if (-not $list.Count) { Write-Log 'Keine WLAN-Profile konfiguriert.' 'WARN'; return }
|
||||
$tmp = Join-Path $env:TEMP "kds-wlan-$([guid]::NewGuid()).xml"
|
||||
foreach ($w in $list) {
|
||||
try {
|
||||
[IO.File]::WriteAllText($tmp, (New-WifiProfileXml $w), (New-Object Text.UTF8Encoding($false)))
|
||||
$out = netsh wlan add profile filename="$tmp" user=all 2>&1
|
||||
if ($LASTEXITCODE -ne 0) { throw ($out -join ' ') }
|
||||
Write-Log "WLAN '$($w.ssid)' gespeichert (alle Benutzer)" 'OK'
|
||||
if (Test-True $w.connect) {
|
||||
netsh wlan connect name="$($w.ssid)" | Out-Null
|
||||
Write-Log " Verbindung zu '$($w.ssid)' angefordert"
|
||||
}
|
||||
} catch { Write-Log "WLAN '$($w.ssid)': $_" 'ERROR' }
|
||||
finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
function Get-WifiState {
|
||||
$profiles = @(netsh wlan show profiles 2>$null | Where-Object { $_ -match '^\s{4}.+?\s:\s(.+)$' } | ForEach-Object { $Matches[1].Trim() })
|
||||
$networks = @(netsh wlan show networks 2>$null | Where-Object { $_ -match '^SSID \d+ : (.*)$' } | ForEach-Object { $Matches[1].Trim() } | Where-Object { $_ } | Sort-Object -Unique)
|
||||
$cur = netsh wlan show interfaces 2>$null | Where-Object { $_ -match '^\s+SSID\s+:\s(.+)$' } | ForEach-Object { $Matches[1].Trim() } | Select-Object -First 1
|
||||
[pscustomobject]@{ profiles = $profiles; networks = $networks; connected = [string]$cur; hasWifi = [bool](Get-NetAdapter -Physical -ErrorAction SilentlyContinue | Where-Object { $_.NdisPhysicalMedium -eq 9 }) }
|
||||
}
|
||||
|
||||
function Export-WifiProfiles {
|
||||
# Liest die WLAN-Profile dieses Geraets inkl. Kennwort (fuer die Uebernahme in eine Blaupause)
|
||||
$dir = Join-Path $env:TEMP "kds-wlan-export-$([guid]::NewGuid())"
|
||||
New-Item $dir -ItemType Directory | Out-Null
|
||||
try {
|
||||
netsh wlan export profile key=clear folder="$dir" | Out-Null
|
||||
@(Get-ChildItem $dir -Filter *.xml | ForEach-Object {
|
||||
[xml]$x = [IO.File]::ReadAllText($_.FullName)
|
||||
$sec = $x.WLANProfile.MSM.security
|
||||
$a = [string]$sec.authEncryption.authentication
|
||||
if ($a -notin 'WPA2PSK', 'WPA3SAE', 'open', 'WPAPSK') { return } # Enterprise-Profile ueberspringen
|
||||
[pscustomobject]@{
|
||||
ssid = [string]$x.WLANProfile.SSIDConfig.SSID.name
|
||||
auth = $(if ($a -eq 'WPAPSK') { 'WPA2PSK' } else { $a })
|
||||
key = [string]$sec.sharedKey.keyMaterial
|
||||
hidden = ([string]$x.WLANProfile.SSIDConfig.nonBroadcast -eq 'true')
|
||||
auto = ([string]$x.WLANProfile.connectionMode -ne 'manual')
|
||||
}
|
||||
})
|
||||
} finally { Remove-Item $dir -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region OpenVPN -----------------------------------------------------------------
|
||||
|
||||
function Get-KdsVpnDir { $d = Join-Path $env:ProgramData 'KDS-Agent\vpn'; New-Item $d -ItemType Directory -Force | Out-Null; $d }
|
||||
|
||||
function Get-PortableOvpnDir { Join-Path $global:KdsRoot 'tools\openvpn' }
|
||||
|
||||
function Get-OpenVpnExe {
|
||||
# Portable Version vom Stick bevorzugen, sonst eine installierte
|
||||
param([switch]$Installed)
|
||||
$c = @("$env:ProgramFiles\OpenVPN\bin\openvpn.exe", "${env:ProgramFiles(x86)}\OpenVPN\bin\openvpn.exe")
|
||||
if (-not $Installed) { $c = @((Join-Path (Get-PortableOvpnDir) 'bin\openvpn.exe')) + $c }
|
||||
$c | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
}
|
||||
|
||||
function Get-OpenVpnPortableInfo {
|
||||
$d = Get-PortableOvpnDir
|
||||
[pscustomobject]@{
|
||||
portable = Test-Path (Join-Path $d 'bin\openvpn.exe')
|
||||
driver = Test-Path (Join-Path $d 'driver\OemVista.inf')
|
||||
setup = [bool](Get-ChildItem (Join-Path $d 'setup') -Filter *.msi -ErrorAction SilentlyContinue)
|
||||
version = [string](Get-Content (Join-Path $d 'version.txt') -ErrorAction SilentlyContinue)
|
||||
installed = [bool](Get-OpenVpnExe -Installed)
|
||||
}
|
||||
}
|
||||
|
||||
function New-OpenVpnPortable {
|
||||
# Erstellt tools\openvpn auf dem Stick aus den offiziellen Paketen (einmalig, braucht Internet)
|
||||
param($Data)
|
||||
$dst = Get-PortableOvpnDir
|
||||
$tmp = Join-Path $env:TEMP "kds-ovpn-$([guid]::NewGuid())"
|
||||
New-Item "$tmp\dl", "$dst\bin", "$dst\driver", "$dst\setup" -ItemType Directory -Force | Out-Null
|
||||
try {
|
||||
if (-not (Install-Winget)) { throw 'winget nicht verfuegbar' }
|
||||
Write-Log 'Lade offizielles OpenVPN-Paket (winget) ...'
|
||||
Invoke-Winget @('download', '--id', 'OpenVPNTechnologies.OpenVPN', '--exact', '--architecture', 'x64', '--download-directory', "$tmp\dl", '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity') | Out-Null
|
||||
$msi = Get-ChildItem "$tmp\dl" -Filter *.msi | Select-Object -First 1
|
||||
if (-not $msi) { throw 'OpenVPN-MSI konnte nicht geladen werden' }
|
||||
Write-Log "Entpacke $($msi.Name) (ohne Installation) ..."
|
||||
$p = Start-Process msiexec.exe -ArgumentList "/a `"$($msi.FullName)`" /qn TARGETDIR=`"$tmp\x`"" -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { throw "msiexec /a ExitCode $($p.ExitCode)" }
|
||||
Copy-Item "$tmp\x\OpenVPN\bin\*" "$dst\bin" -Force
|
||||
if (Test-Path "$tmp\x\OpenVPN\ssl") { Copy-Item "$tmp\x\OpenVPN\ssl" $dst -Recurse -Force }
|
||||
Get-ChildItem "$dst\setup" -Filter *.msi | Remove-Item -Force
|
||||
Copy-Item $msi.FullName "$dst\setup" -Force # fuer die dauerhafte Dienst-Installation (offline)
|
||||
|
||||
Write-Log 'Lade TAP-Windows6-Treiber (Microsoft-signiert) ...'
|
||||
$rel = Invoke-RestMethod 'https://api.github.com/repos/OpenVPN/tap-windows6/releases/latest' -UseBasicParsing
|
||||
$zip = $rel.assets | Where-Object name -eq 'dist.win10.zip' | Select-Object -First 1
|
||||
if (-not $zip) { throw 'dist.win10.zip im TAP-Release nicht gefunden' }
|
||||
Invoke-WebRequest $zip.browser_download_url -OutFile "$tmp\tap.zip" -UseBasicParsing
|
||||
Expand-Archive "$tmp\tap.zip" "$tmp\tap" -Force
|
||||
$amd = Get-ChildItem "$tmp\tap" -Recurse -Directory -Filter amd64 | Select-Object -First 1
|
||||
Copy-Item "$($amd.FullName)\*" "$dst\driver" -Force
|
||||
$ver = if ($msi.BaseName -match '_(\d+\.\d+\.\d+)_') { $Matches[1] } else { $msi.BaseName }
|
||||
Set-Content "$dst\version.txt" "OpenVPN $ver, TAP $($rel.tag_name), erstellt $(Get-Date -Format 'dd.MM.yyyy')"
|
||||
Write-Log "Portables OpenVPN erstellt: $dst" 'OK'
|
||||
} finally { Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
|
||||
function Get-TapAdapter {
|
||||
Get-NetAdapter -IncludeHidden -ErrorAction SilentlyContinue | Where-Object InterfaceDescription -like 'TAP-Windows Adapter V9*' | Select-Object -First 1
|
||||
}
|
||||
|
||||
function Initialize-PortableTap {
|
||||
# Laedt den TAP-Treiber vom Stick nur, wenn noch kein TAP-Adapter existiert
|
||||
$a = Get-TapAdapter
|
||||
if ($a) { return $a.Name }
|
||||
$drv = Join-Path (Get-PortableOvpnDir) 'driver'
|
||||
if (-not (Test-Path "$drv\devcon.exe")) { throw 'TAP-Treiber fehlt in tools\openvpn\driver - zuerst "Portables OpenVPN erstellen"' }
|
||||
Write-Log 'Lade TAP-Treiber vom Stick (temporaer) ...'
|
||||
$p = Start-Process "$drv\devcon.exe" -ArgumentList "install `"$drv\OemVista.inf`" tap0901" -Wait -PassThru -WindowStyle Hidden
|
||||
if ($p.ExitCode -notin 0, 1) { throw "TAP-Treiberinstallation fehlgeschlagen (devcon ExitCode $($p.ExitCode))" }
|
||||
Set-Content (Join-Path (Get-KdsVpnDir) 'tap-created.txt') (Get-Date)
|
||||
for ($i = 0; $i -lt 10 -and -not $a; $i++) { Start-Sleep 1; $a = Get-TapAdapter }
|
||||
if (-not $a) { throw 'TAP-Adapter wurde nicht angelegt' }
|
||||
Rename-NetAdapter -Name $a.Name -NewName 'KDS-VPN' -ErrorAction SilentlyContinue
|
||||
Write-Log 'TAP-Adapter "KDS-VPN" bereit' 'OK'
|
||||
return 'KDS-VPN'
|
||||
}
|
||||
|
||||
function Remove-PortableTap {
|
||||
# Entfernt nur einen vom Agent angelegten TAP-Adapter samt Treiber
|
||||
$flag = Join-Path (Get-KdsVpnDir) 'tap-created.txt'
|
||||
if (-not (Test-Path $flag)) { return }
|
||||
$devcon = Join-Path (Get-PortableOvpnDir) 'driver\devcon.exe'
|
||||
if (Test-Path $devcon) { Start-Process $devcon -ArgumentList 'remove tap0901' -Wait -WindowStyle Hidden | Out-Null }
|
||||
Get-WindowsDriver -Online -ErrorAction SilentlyContinue | Where-Object { $_.OriginalFileName -match 'oemvista\.inf$' -and $_.ProviderName -match 'TAP' } | ForEach-Object {
|
||||
pnputil /delete-driver $_.Driver /uninstall /force | Out-Null
|
||||
}
|
||||
Remove-Item $flag -Force
|
||||
Write-Log 'Portabler TAP-Treiber wieder entfernt' 'OK'
|
||||
}
|
||||
|
||||
function Install-OpenVpn {
|
||||
# Dauerhafte Installation (nur fuer den Dienstbetrieb noetig) - bevorzugt offline vom Stick
|
||||
$exe = Get-OpenVpnExe -Installed
|
||||
if ($exe) { return $exe }
|
||||
$msi = Get-ChildItem (Join-Path (Get-PortableOvpnDir) 'setup') -Filter *.msi -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($msi) {
|
||||
Write-Log "Installiere OpenVPN vom Stick ($($msi.Name)) ..."
|
||||
$p = Start-Process msiexec.exe -ArgumentList "/i `"$($msi.FullName)`" /qn /norestart" -Wait -PassThru
|
||||
if ($p.ExitCode -notin 0, 3010) { throw "OpenVPN-MSI ExitCode $($p.ExitCode)" }
|
||||
} else {
|
||||
Write-Log 'Kein OpenVPN-Setup auf dem Stick - installiere ueber winget ...'
|
||||
if (-not (Install-Winget)) { throw 'winget nicht verfuegbar' }
|
||||
Invoke-Winget @('install', '--id', 'OpenVPNTechnologies.OpenVPN', '--exact', '--silent', '--scope', 'machine', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity') | Out-Null
|
||||
}
|
||||
$exe = Get-OpenVpnExe -Installed
|
||||
if (-not $exe) { throw 'OpenVPN-Installation fehlgeschlagen' }
|
||||
Write-Log 'OpenVPN installiert' 'OK'
|
||||
return $exe
|
||||
}
|
||||
|
||||
function Get-OpenVpnProcesses {
|
||||
@(Get-CimInstance Win32_Process -Filter "Name='openvpn.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -match 'kds-openvpn' })
|
||||
}
|
||||
|
||||
function Get-VpnStatus {
|
||||
$log = Join-Path (Get-KdsVpnDir) 'kds-openvpn.log'
|
||||
$procs = Get-OpenVpnProcesses
|
||||
$tail = if (Test-Path $log) { @(Get-Content $log -Tail 12 -ErrorAction SilentlyContinue | ForEach-Object { [string]$_ }) } else { @() }
|
||||
$connected = $procs.Count -gt 0 -and (Test-Path $log) -and (Select-String -Path $log -Pattern 'Initialization Sequence Completed' -Quiet)
|
||||
# nur den vom Agent genutzten Adapter auswerten (andere VPN-Clients ignorieren)
|
||||
$devFile = Join-Path (Get-KdsVpnDir) 'kds-dev.txt'
|
||||
$ip = @()
|
||||
if ($connected -and (Test-Path $devFile)) {
|
||||
$ip = @(Get-NetIPAddress -InterfaceAlias ([string](Get-Content $devFile)) -AddressFamily IPv4 -ErrorAction SilentlyContinue | ForEach-Object { [string]$_.IPAddress })
|
||||
}
|
||||
$inst = Get-OpenVpnExe -Installed
|
||||
$kdsSvc = $inst -and [bool](Get-ChildItem (Join-Path (Split-Path (Split-Path $inst)) 'config-auto') -Filter 'kds-*.ovpn' -ErrorAction SilentlyContinue)
|
||||
$svc = Get-Service OpenVPNService -ErrorAction SilentlyContinue
|
||||
[pscustomobject]@{
|
||||
installed = [bool]$inst; running = $procs.Count -gt 0; connected = [bool]$connected; ip = ($ip -join ', ')
|
||||
kdsService = $kdsSvc; service = $(if ($kdsSvc -and $svc) { "$($svc.Status) / $($svc.StartType)" } else { '' }); log = ($tail -join "`n")
|
||||
}
|
||||
}
|
||||
|
||||
function Get-VpnAdapters {
|
||||
@(Get-NetAdapter -ErrorAction SilentlyContinue | Where-Object { $_.Status -eq 'Up' -and $_.InterfaceDescription -match 'TAP-Windows|Wintun|OpenVPN|Data Channel Offload' })
|
||||
}
|
||||
|
||||
function Get-OvpnPath {
|
||||
param([string]$Name)
|
||||
if (-not $Name) { throw 'Keine VPN-Konfiguration (.ovpn) ausgewaehlt' }
|
||||
$p = Join-Path $global:KdsRoot "vpn\$(Split-Path $Name -Leaf)"
|
||||
if (-not (Test-Path $p)) { throw "VPN-Konfiguration nicht gefunden: $p" }
|
||||
return $p
|
||||
}
|
||||
|
||||
function Write-VpnAuthFile {
|
||||
param([string]$Path, $V)
|
||||
Set-Content -Path $Path -Value @($V.user, $V.password) -Encoding ASCII
|
||||
# nur SYSTEM und Administratoren duerfen die Datei lesen
|
||||
icacls "$Path" /inheritance:r /grant:r '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
|
||||
}
|
||||
|
||||
function Connect-KdsVpn {
|
||||
param($Data)
|
||||
$v = $Data.vpn
|
||||
$cfg = Get-OvpnPath $v.config
|
||||
if ((Get-VpnStatus).connected) { Write-Log 'VPN ist bereits verbunden.' 'OK'; return }
|
||||
Disconnect-KdsVpn | Out-Null
|
||||
$exe = Get-OpenVpnExe
|
||||
if (-not $exe) { throw 'Kein OpenVPN gefunden - im Tab "VPN & Domaene" zuerst "Portables OpenVPN erstellen"' }
|
||||
Write-Log "OpenVPN: $exe"
|
||||
$dev = Initialize-PortableTap
|
||||
Set-Content (Join-Path (Get-KdsVpnDir) 'kds-dev.txt') $dev
|
||||
|
||||
$dir = Get-KdsVpnDir
|
||||
$log = Join-Path $dir 'kds-openvpn.log'
|
||||
$auth = Join-Path $dir 'kds-openvpn-auth.txt'
|
||||
$a = @('--config', "`"$cfg`"", '--cd', "`"$(Split-Path $cfg)`"", '--log', "`"$log`"", '--verb', '3', '--setenv', 'KDS', 'kds-openvpn',
|
||||
'--disable-dco', '--dev-node', "`"$dev`"") # TAP-Adapter statt DCO (DCO-Treiber waere nicht portabel)
|
||||
if ($v.user) { Write-VpnAuthFile $auth $v; $a += '--auth-user-pass', "`"$auth`"" }
|
||||
Write-Log "Starte OpenVPN mit $(Split-Path $cfg -Leaf) ..."
|
||||
$p = Start-Process $exe -ArgumentList $a -WindowStyle Hidden -PassThru
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(90)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
Start-Sleep 2
|
||||
$txt = if (Test-Path $log) { Get-Content $log -Raw -ErrorAction SilentlyContinue } else { '' }
|
||||
if ($txt -match 'Initialization Sequence Completed') { break }
|
||||
if ($txt -match 'AUTH_FAILED') { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue; throw 'VPN-Anmeldung fehlgeschlagen (AUTH_FAILED) - Benutzer/Kennwort pruefen' }
|
||||
if ($p.HasExited) { throw "OpenVPN wurde beendet. Log:`n$((Get-Content $log -Tail 15 -ErrorAction SilentlyContinue) -join "`n")" }
|
||||
}
|
||||
if (-not ((Get-Content $log -Raw -ErrorAction SilentlyContinue) -match 'Initialization Sequence Completed')) {
|
||||
Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
|
||||
throw 'Zeitueberschreitung beim VPN-Aufbau (90 s)'
|
||||
}
|
||||
Start-Sleep 3
|
||||
if ($v.dns) {
|
||||
$servers = @($v.dns -split '[,; ]+' | Where-Object { $_ })
|
||||
Get-VpnAdapters | ForEach-Object { Set-DnsClientServerAddress -InterfaceIndex $_.ifIndex -ServerAddresses $servers }
|
||||
Write-Log "DNS-Server am VPN-Adapter gesetzt: $($servers -join ', ')"
|
||||
}
|
||||
Write-Log "VPN verbunden ($((Get-VpnStatus).ip))" 'OK'
|
||||
}
|
||||
|
||||
function Disconnect-KdsVpn {
|
||||
$procs = Get-OpenVpnProcesses
|
||||
$procs | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
||||
Remove-Item (Join-Path (Get-KdsVpnDir) 'kds-openvpn-auth.txt') -Force -ErrorAction SilentlyContinue
|
||||
if ($procs.Count) { Write-Log 'VPN getrennt' 'OK' }
|
||||
return $procs.Count
|
||||
}
|
||||
|
||||
function Install-KdsVpnService {
|
||||
# VPN dauerhaft ueber den OpenVPN-Dienst (config-auto) - noetig, damit die erste Domaenenanmeldung den DC erreicht
|
||||
param($Data)
|
||||
$v = $Data.vpn
|
||||
$cfg = Get-OvpnPath $v.config
|
||||
Disconnect-KdsVpn | Out-Null
|
||||
Remove-PortableTap
|
||||
$exe = Install-OpenVpn
|
||||
$auto = Join-Path (Split-Path (Split-Path $exe)) 'config-auto'
|
||||
New-Item $auto -ItemType Directory -Force | Out-Null
|
||||
Get-ChildItem $auto -Filter 'kds-*' | Remove-Item -Force
|
||||
|
||||
$lines = @(Get-Content $cfg | Where-Object { $_ -notmatch '^\s*auth-user-pass\b' })
|
||||
# referenzierte Zertifikats-/Schluesseldateien mitkopieren
|
||||
foreach ($l in $lines) {
|
||||
if ($l -match '^\s*(ca|cert|key|tls-auth|tls-crypt|tls-crypt-v2|pkcs12|crl-verify|dh)\s+"?([^"\s]+)"?') {
|
||||
$src = Join-Path (Split-Path $cfg) $Matches[2]
|
||||
if (Test-Path $src) { Copy-Item $src $auto -Force }
|
||||
}
|
||||
}
|
||||
if ($v.user) {
|
||||
Write-VpnAuthFile (Join-Path $auto 'kds-auth.txt') $v
|
||||
$lines += 'auth-user-pass kds-auth.txt'
|
||||
}
|
||||
$name = 'kds-' + ([IO.Path]::GetFileNameWithoutExtension($cfg) -replace '[^\w\-]', '_') + '.ovpn'
|
||||
Set-Content -Path (Join-Path $auto $name) -Value $lines -Encoding ASCII
|
||||
icacls "$auto" /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
|
||||
|
||||
Set-Service OpenVPNService -StartupType Automatic
|
||||
Restart-Service OpenVPNService
|
||||
Write-Log "VPN als Dienst eingerichtet ($name, startet automatisch vor der Anmeldung)" 'OK'
|
||||
}
|
||||
|
||||
function Remove-KdsVpnService {
|
||||
$exe = Get-OpenVpnExe -Installed
|
||||
if ($exe) { Get-ChildItem (Join-Path (Split-Path (Split-Path $exe)) 'config-auto') -Filter 'kds-*' -ErrorAction SilentlyContinue | Remove-Item -Force }
|
||||
Restart-Service OpenVPNService -ErrorAction SilentlyContinue
|
||||
Write-Log 'VPN-Dienstkonfiguration entfernt' 'OK'
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Domaene -----------------------------------------------------------------
|
||||
|
||||
function Test-KdsDomain {
|
||||
param([string]$Name)
|
||||
$r = [ordered]@{ domain = $Name; dns = $false; dcs = @(); ldap = $false; joined = ((Get-CimInstance Win32_ComputerSystem).Domain -eq $Name) }
|
||||
try {
|
||||
$srv = @(Resolve-DnsName "_ldap._tcp.dc._msdcs.$Name" -Type SRV -DnsOnly -ErrorAction Stop | Where-Object Type -eq 'SRV')
|
||||
$r.dns = $srv.Count -gt 0
|
||||
$r.dcs = @($srv | ForEach-Object { [string]$_.NameTarget })
|
||||
if ($r.dcs) {
|
||||
$c = New-Object Net.Sockets.TcpClient
|
||||
$r.ldap = $c.ConnectAsync($r.dcs[0], 389).Wait(3000) -and $c.Connected
|
||||
$c.Close()
|
||||
}
|
||||
} catch { $r.error = $_.Exception.Message }
|
||||
[pscustomobject]$r
|
||||
}
|
||||
|
||||
function Join-KdsDomain {
|
||||
param($Data)
|
||||
$d = $Data.domain
|
||||
if (-not $d.name) { throw 'Keine Domaene angegeben' }
|
||||
if ((Get-CimInstance Win32_ComputerSystem).Domain -eq $d.name) { Write-Log "Bereits Mitglied von $($d.name)" 'OK'; return }
|
||||
|
||||
if (Test-True $d.useVpn) { Connect-KdsVpn $Data }
|
||||
|
||||
Write-Log "Pruefe Erreichbarkeit von $($d.name) ..."
|
||||
$t = Test-KdsDomain $d.name
|
||||
if (-not $t.dns) { throw "Domaenencontroller nicht per DNS auffindbar (_ldap._tcp.dc._msdcs.$($d.name)). VPN/DNS pruefen. $($t.error)" }
|
||||
Write-Log " DCs: $($t.dcs -join ', ') - LDAP erreichbar: $($t.ldap)"
|
||||
|
||||
$user = [string]$d.user
|
||||
if ($user -notmatch '[\\@]') { $user = "$($d.name)\$user" }
|
||||
$cred = New-Object PSCredential($user, (ConvertTo-SecureString ([string]$d.password) -AsPlainText -Force))
|
||||
$p = @{ DomainName = $d.name; Credential = $cred; Force = $true; ErrorAction = 'Stop' }
|
||||
if ($d.ou) { $p.OUPath = $d.ou }
|
||||
$newName = $Data.system.computerName
|
||||
if ($newName -and $newName -ne $env:COMPUTERNAME) { $p.NewName = $newName; $p.Options = 'JoinWithNewName', 'AccountCreate' }
|
||||
|
||||
Write-Log "Trete Domaene $($d.name) bei$(if ($d.ou) { " (OU: $($d.ou))" })$(if ($p.NewName) { " als $($p.NewName)" }) ..."
|
||||
Add-Computer @p
|
||||
Write-Log "Domaenenbeitritt erfolgreich - Neustart erforderlich" 'OK'
|
||||
|
||||
# Domaenengruppen/-benutzer zu lokalen Administratoren
|
||||
$admins = @("$($d.admins)" -split '[,;\r\n]+' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||
if ($admins.Count) {
|
||||
$grp = (Get-LocalGroup -SID 'S-1-5-32-544').Name
|
||||
$pending = @()
|
||||
foreach ($a in $admins) {
|
||||
$m = if ($a -match '\\') { $a } else { "$($d.name.Split('.')[0])\$a" }
|
||||
net localgroup "$grp" "$m" /add 2>&1 | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { Write-Log " $m -> lokale Administratoren" 'OK' } else { $pending += $m }
|
||||
}
|
||||
if ($pending) {
|
||||
# nach dem Neustart per einmaliger Aufgabe nachholen
|
||||
$cmd = ($pending | ForEach-Object { "net localgroup `"$grp`" `"$_`" /add" }) -join ' & '
|
||||
schtasks /Create /TN 'KDS-LocalAdmins' /SC ONSTART /RU SYSTEM /RL HIGHEST /F /TR "cmd /c $cmd & schtasks /Delete /TN KDS-LocalAdmins /F" | Out-Null
|
||||
Write-Log " Lokale Admins werden nach dem Neustart gesetzt: $($pending -join ', ')"
|
||||
}
|
||||
}
|
||||
|
||||
if ((Test-True $d.useVpn) -and (Test-True $d.vpnService)) { Install-KdsVpnService $Data }
|
||||
if (Test-True $d.reboot) { $global:KdsRebootAfter = $true }
|
||||
if ((Test-True $d.reboot) -and -not $global:KdsInProfile) {
|
||||
shutdown /r /t 60 /c "KDS Install Agent: Neustart nach Domaenenbeitritt in 60 Sekunden"
|
||||
Write-Log 'Neustart in 60 Sekunden (abbrechen: shutdown /a)' 'WARN'
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Gesamtprofil ------------------------------------------------------------
|
||||
|
||||
function Invoke-FullProfile {
|
||||
@@ -1049,7 +1446,9 @@ function Invoke-FullProfile {
|
||||
Write-Log "===== $title ====="
|
||||
try { & $block } catch { Write-Log "$title fehlgeschlagen: $_" 'ERROR' }
|
||||
}
|
||||
$global:KdsInProfile = $true
|
||||
if ('system' -in $steps) { & $run 'System' { Set-SystemConfig $Data } }
|
||||
if ('wifi' -in $steps) { & $run 'WLAN' { Add-WifiProfiles $Data } }
|
||||
if ('bloatware' -in $steps) { & $run 'Bloatware entfernen' { Remove-Bloatware $Data } }
|
||||
if ('security' -in $steps) { & $run 'Sicherheit' { Set-SecurityConfig $Data } }
|
||||
if ('power' -in $steps) { & $run 'Energie' { Set-PowerConfig $Data } }
|
||||
@@ -1058,8 +1457,17 @@ function Invoke-FullProfile {
|
||||
if ('shortcuts' -in $steps) { & $run 'Desktop-Verknuepfungen' { Set-DesktopShortcuts $Data } }
|
||||
if ('drivers' -in $steps) { & $run 'Hersteller-Treiber' { Invoke-VendorDriverUpdate $Data } }
|
||||
if ('updates' -in $steps) { & $run 'Windows Update' { Install-WindowsUpdates ([pscustomobject]@{ all = $true; type = 'all' }) | Out-Null } }
|
||||
if ('domain' -in $steps) { & $run 'VPN & Domaenenbeitritt' { Join-KdsDomain $Data } }
|
||||
if ('bitlocker' -in $steps) { & $run 'BitLocker' { Set-BitLockerConfig $Data } }
|
||||
# Portables VPN wieder abbauen (ausser es laeuft als Dienst weiter)
|
||||
if ((Get-OpenVpnProcesses).Count -or (Test-Path (Join-Path (Get-KdsVpnDir) 'tap-created.txt'))) {
|
||||
& $run 'VPN trennen' { Disconnect-KdsVpn | Out-Null; Remove-PortableTap }
|
||||
}
|
||||
Write-Log 'Profil abgeschlossen.' 'OK'
|
||||
if ($global:KdsRebootAfter) {
|
||||
shutdown /r /t 120 /c "KDS Install Agent: Einrichtung abgeschlossen - Neustart in 2 Minuten"
|
||||
Write-Log 'Neustart in 2 Minuten (abbrechen: shutdown /a)' 'WARN'
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
Reference in New Issue
Block a user