setup-ssh-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
setup_ssh/state.py ADDED
@@ -0,0 +1,159 @@
1
+ """Public inventory only: account passwords and private keys never go here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ import uuid
11
+ from dataclasses import asdict, dataclass, field
12
+ from pathlib import Path
13
+
14
+
15
+ class SetupError(Exception):
16
+ """An actionable error safe to display to the user."""
17
+
18
+
19
+ def identifier() -> str:
20
+ return uuid.uuid4().hex[:12]
21
+
22
+
23
+ def default_path() -> Path:
24
+ if os.environ.get("SETUP_SSH_CONFIG"):
25
+ return Path(os.environ["SETUP_SSH_CONFIG"]).expanduser()
26
+ if os.name == "nt":
27
+ base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
28
+ else:
29
+ base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
30
+ return base / "setup-ssh" / "inventory.json"
31
+
32
+
33
+ def validate_key(value: str) -> str:
34
+ parts = value.strip().split()
35
+ if len(parts) < 2 or parts[0] != "ssh-ed25519":
36
+ raise SetupError("Expected an Ed25519 public key from ssh-keygen.")
37
+ try:
38
+ raw = base64.b64decode(parts[1], validate=True)
39
+ except (ValueError, TypeError) as exc:
40
+ raise SetupError("Invalid public key encoding.") from exc
41
+ # SSH wire format: length + algorithm + length + 32-byte public key.
42
+ if raw[:19] != b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20" or len(raw) != 51:
43
+ raise SetupError("Invalid Ed25519 public key.")
44
+ return f"{parts[0]} {parts[1]}"
45
+
46
+
47
+ @dataclass
48
+ class Device:
49
+ name: str
50
+ host: str
51
+ user: str
52
+ port: int = 22
53
+ platform: str = "auto"
54
+ local: bool = False
55
+ id: str = field(default_factory=identifier)
56
+ public_key: str | None = None
57
+ host_key: dict[str, str] | None = None
58
+
59
+ def validate(self) -> None:
60
+ if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}", self.name):
61
+ raise SetupError("Device names need 1–63 letters, digits, underscores, or hyphens.")
62
+ if not re.fullmatch(r"[0-9a-f]{12}", self.id):
63
+ raise SetupError(f"Invalid device identifier for {self.name}.")
64
+ if (
65
+ not self.host
66
+ or self.host.startswith("-")
67
+ or not re.fullmatch(r"[a-zA-Z0-9_.:%-]+", self.host)
68
+ ):
69
+ raise SetupError("Use a LAN/NetBird IP or hostname, without a URL, username, or port.")
70
+ if not self.user or any(ord(c) < 32 for c in self.user) or '"' in self.user:
71
+ raise SetupError(
72
+ "Provide a valid username without control characters or double quotes."
73
+ )
74
+ if type(self.port) is not int or not 1 <= self.port <= 65535:
75
+ raise SetupError("SSH port must be between 1 and 65535.")
76
+ if self.platform not in {"auto", "linux", "macos", "windows"}:
77
+ raise SetupError("OS must be auto, linux, macos, or windows.")
78
+ if type(self.local) is not bool:
79
+ raise SetupError("The local field must be true or false.")
80
+ if self.public_key is not None:
81
+ self.public_key = validate_key(self.public_key)
82
+ if self.host_key is not None:
83
+ if not isinstance(self.host_key, dict) or set(self.host_key) != {"type", "data"}:
84
+ raise SetupError(f"Invalid host key for {self.name}.")
85
+ if not all(isinstance(v, str) for v in self.host_key.values()):
86
+ raise SetupError(f"Invalid host key for {self.name}.")
87
+ if not re.fullmatch(r"[a-zA-Z0-9@._+-]+", self.host_key["type"]):
88
+ raise SetupError(f"Invalid host key type for {self.name}.")
89
+ try:
90
+ base64.b64decode(self.host_key["data"], validate=True)
91
+ except ValueError as exc:
92
+ raise SetupError(f"Invalid host key for {self.name}.") from exc
93
+
94
+
95
+ @dataclass
96
+ class Inventory:
97
+ group_id: str = field(default_factory=identifier)
98
+ devices: list[Device] = field(default_factory=list)
99
+ version: int = 1
100
+
101
+ def validate(self) -> None:
102
+ if self.version != 1 or not re.fullmatch(r"[0-9a-f]{12}", self.group_id):
103
+ raise SetupError("Unsupported or malformed inventory.")
104
+ names: set[str] = set()
105
+ ids: set[str] = set()
106
+ accounts: set[tuple[str, int, str]] = set()
107
+ for device in self.devices:
108
+ device.validate()
109
+ account = (device.host.lower(), device.port, device.user.lower())
110
+ if device.name.lower() in names or device.id in ids or account in accounts:
111
+ raise SetupError(f"Duplicate device name or account: {device.name}.")
112
+ names.add(device.name.lower())
113
+ ids.add(device.id)
114
+ accounts.add(account)
115
+ if sum(device.local for device in self.devices) > 1:
116
+ raise SetupError("Only one device can be this computer.")
117
+
118
+ def add(self, device: Device) -> None:
119
+ self.devices.append(device)
120
+ try:
121
+ self.validate()
122
+ except Exception:
123
+ self.devices.pop()
124
+ raise
125
+
126
+ def find(self, name: str) -> Device:
127
+ for device in self.devices:
128
+ if device.name.lower() == name.lower():
129
+ return device
130
+ raise SetupError(f"Unknown device: {name}.")
131
+
132
+ @classmethod
133
+ def load(cls, path: Path) -> Inventory:
134
+ if not path.exists():
135
+ return cls()
136
+ try:
137
+ data = json.loads(path.read_text(encoding="utf-8"))
138
+ inventory = cls(
139
+ group_id=data["group_id"],
140
+ devices=[Device(**item) for item in data["devices"]],
141
+ version=data["version"],
142
+ )
143
+ inventory.validate()
144
+ return inventory
145
+ except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
146
+ raise SetupError(f"Cannot read inventory {path}: {exc}") from exc
147
+
148
+ def save(self, path: Path) -> None:
149
+ self.validate()
150
+ path.parent.mkdir(parents=True, exist_ok=True)
151
+ fd, temp = tempfile.mkstemp(prefix=".inventory-", dir=path.parent)
152
+ try:
153
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
154
+ json.dump(asdict(self), stream, indent=2)
155
+ stream.write("\n")
156
+ os.replace(temp, path)
157
+ finally:
158
+ if os.path.exists(temp):
159
+ os.unlink(temp)
@@ -0,0 +1,110 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ umask 077
4
+
5
+ decode() {
6
+ printf '%s' "$1" | base64 -d 2>/dev/null || printf '%s' "$1" | base64 -D
7
+ }
8
+ __PAYLOAD__
9
+
10
+ SSH_DIR="$HOME/.ssh"
11
+ GROUP_DIR="$SSH_DIR/setup-ssh/$GROUP"
12
+ KEY="$GROUP_DIR/id_ed25519"
13
+ BEGIN="# BEGIN setup-ssh $GROUP"
14
+ END="# END setup-ssh $GROUP"
15
+ WORK=""
16
+ trap 'if [ -n "$WORK" ]; then rm -rf "$WORK"; fi' EXIT HUP INT TERM
17
+
18
+ fail() { printf '%s\n' "$*" >&2; exit 1; }
19
+
20
+ # Replace only this group's balanced block. Refuse malformed blocks and symlinks.
21
+ # Back up changed existing files; atomically replace with a mode-600 file.
22
+ managed() {
23
+ target=$1
24
+ body=$2
25
+ position=$3
26
+ [ ! -L "$target" ] || fail "Refusing symlink: $target"
27
+ [ ! -e "$target" ] || [ -f "$target" ] || fail "Not a regular file: $target"
28
+ original="$WORK/original"
29
+ remainder="$WORK/remainder"
30
+ if [ -f "$target" ]; then cat "$target" > "$original"; else : > "$original"; fi
31
+ awk -v begin="$BEGIN" -v end="$END" '
32
+ $0 == begin { if (inside || seen) exit 2; inside=1; seen=1; next }
33
+ $0 == end { if (!inside) exit 2; inside=0; next }
34
+ !inside { print }
35
+ END { if (inside) exit 2 }
36
+ ' "$original" > "$remainder" || fail "Malformed setup-ssh block in $target; restore its backup."
37
+ replacement=$(mktemp "$target.tmp.XXXXXXXX")
38
+ if [ "$position" = prepend ] && [ -n "$body" ]; then
39
+ printf '%s\n%s\n%s\n' "$BEGIN" "$body" "$END" > "$replacement"
40
+ cat "$remainder" >> "$replacement"
41
+ else
42
+ cat "$remainder" > "$replacement"
43
+ if [ -n "$body" ]; then printf '%s\n%s\n%s\n' "$BEGIN" "$body" "$END" >> "$replacement"; fi
44
+ fi
45
+ if [ -f "$target" ] && cmp -s "$target" "$replacement"; then
46
+ rm "$replacement"
47
+ chmod 600 "$target"
48
+ else
49
+ if [ -f "$target" ]; then
50
+ cp -p "$target" "$target.setup-ssh.bak"
51
+ chmod 600 "$target.setup-ssh.bak"
52
+ fi
53
+ chmod 600 "$replacement"
54
+ mv -f "$replacement" "$target"
55
+ fi
56
+ }
57
+
58
+ write_owned() {
59
+ target=$1
60
+ content=$2
61
+ [ ! -L "$target" ] || fail "Refusing symlink: $target"
62
+ if [ -f "$target" ] && [ "$(cat "$target")" = "$content" ]; then return; fi
63
+ replacement=$(mktemp "$target.tmp.XXXXXXXX")
64
+ printf '%s\n' "$content" > "$replacement"
65
+ chmod 600 "$replacement"
66
+ mv -f "$replacement" "$target"
67
+ }
68
+
69
+ case "$ACTION" in
70
+ prepare)
71
+ for tool in ssh ssh-keygen base64 awk mktemp; do
72
+ command -v "$tool" >/dev/null 2>&1 || fail "Missing $tool. Run setup-ssh doctor for instructions."
73
+ done
74
+ mkdir -p "$GROUP_DIR"
75
+ chmod 700 "$SSH_DIR" "$SSH_DIR/setup-ssh" "$GROUP_DIR"
76
+ [ ! -L "$KEY" ] && [ ! -L "$KEY.pub" ] || fail "Refusing a symlinked managed key."
77
+ if [ ! -f "$KEY" ]; then
78
+ [ ! -e "$KEY.pub" ] || fail "Managed private key is missing; restore it. To replace it, remove this device and delete its orphaned .pub file before re-enrolling."
79
+ ssh-keygen -q -t ed25519 -N '' -C "setup-ssh:$GROUP:$DEVICE" -f "$KEY" < /dev/null
80
+ fi
81
+ chmod 600 "$KEY"
82
+ public=$(ssh-keygen -y -P '' -f "$KEY" < /dev/null) || fail "Cannot read managed key; it must be an unencrypted Ed25519 key."
83
+ write_owned "$KEY.pub" "$public setup-ssh:$GROUP:$DEVICE"
84
+ printf 'SETUP_SSH_KEY=%s\n' "$public"
85
+ ;;
86
+ apply|remove)
87
+ mkdir -p "$GROUP_DIR"
88
+ chmod 700 "$SSH_DIR" "$SSH_DIR/setup-ssh" "$GROUP_DIR"
89
+ WORK=$(mktemp -d "$GROUP_DIR/.work.XXXXXXXX")
90
+ if [ "$ACTION" = apply ]; then
91
+ [ -f "$KEY" ] || fail "Managed private key is missing. Run sync."
92
+ write_owned "$GROUP_DIR/config" "$CONFIG"
93
+ write_owned "$GROUP_DIR/known_hosts" "$KNOWN_HOSTS"
94
+ managed "$SSH_DIR/authorized_keys" "$AUTHORIZED_KEYS" append
95
+ managed "$SSH_DIR/config" "Include \"~/.ssh/setup-ssh/$GROUP/config\"" prepend
96
+ else
97
+ managed "$SSH_DIR/authorized_keys" '' append
98
+ managed "$SSH_DIR/config" '' prepend
99
+ fi
100
+ ;;
101
+ check)
102
+ [ -f "$GROUP_DIR/config" ] || fail "No managed SSH configuration. Run sync first."
103
+ exec ssh -F "$GROUP_DIR/config" \
104
+ -o BatchMode=yes -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
105
+ -o PreferredAuthentications=publickey -o IdentityAgent=none \
106
+ -o ConnectionAttempts=1 -o "ConnectTimeout=$TIMEOUT" \
107
+ "$DESTINATION" 'echo setup-ssh-ok'
108
+ ;;
109
+ *) fail "Unknown action: $ACTION" ;;
110
+ esac
@@ -0,0 +1,184 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ $ProgressPreference = 'SilentlyContinue'
3
+ $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__')) | ConvertFrom-Json
4
+ $utf8 = New-Object Text.UTF8Encoding($false)
5
+ $sshDir = Join-Path $env:USERPROFILE '.ssh'
6
+ $groupDir = Join-Path $sshDir ('setup-ssh/' + $p.group)
7
+ $keyPath = Join-Path $groupDir 'id_ed25519'
8
+ $begin = '# BEGIN setup-ssh ' + $p.group
9
+ $end = '# END setup-ssh ' + $p.group
10
+
11
+ function Assert-RegularPath([string]$Path) {
12
+ if (Test-Path -LiteralPath $Path) {
13
+ $item = Get-Item -Force -LiteralPath $Path
14
+ if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
15
+ throw "Refusing a directory or reparse point: $Path"
16
+ }
17
+ }
18
+ }
19
+
20
+ function Protect-UserPath([string]$Path) {
21
+ $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User
22
+ $system = New-Object Security.Principal.SecurityIdentifier('S-1-5-18')
23
+ $item = Get-Item -Force -LiteralPath $Path
24
+ if ($item.PSIsContainer) {
25
+ $acl = New-Object Security.AccessControl.DirectorySecurity
26
+ } else {
27
+ $acl = New-Object Security.AccessControl.FileSecurity
28
+ }
29
+ $acl.SetAccessRuleProtection($true, $false)
30
+ $acl.SetOwner($owner)
31
+ foreach ($sid in @($owner, $system)) {
32
+ if ($item.PSIsContainer) {
33
+ $rule = [Security.AccessControl.FileSystemAccessRule]::new(
34
+ $sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
35
+ } else {
36
+ $rule = [Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'Allow')
37
+ }
38
+ $acl.AddAccessRule($rule)
39
+ }
40
+ Set-Acl -LiteralPath $Path -AclObject $acl
41
+ }
42
+
43
+ function Write-Owned([string]$Path, [string]$Content) {
44
+ Assert-RegularPath $Path
45
+ $value = $Content.TrimEnd("`r", "`n") + "`n"
46
+ if ((Test-Path -LiteralPath $Path) -and [IO.File]::ReadAllText($Path) -ceq $value) { return }
47
+ $temp = $Path + '.tmp.' + [Guid]::NewGuid().ToString('N')
48
+ try {
49
+ [IO.File]::WriteAllText($temp, $value, $utf8)
50
+ Protect-UserPath $temp
51
+ if (Test-Path -LiteralPath $Path) {
52
+ [IO.File]::Replace($temp, $Path, [NullString]::Value)
53
+ } else {
54
+ [IO.File]::Move($temp, $Path)
55
+ }
56
+ } finally {
57
+ if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp -Force }
58
+ }
59
+ }
60
+
61
+ function Write-Managed([string]$Path, [string]$Body, [bool]$Prepend) {
62
+ Assert-RegularPath $Path
63
+ $original = ''
64
+ if (Test-Path -LiteralPath $Path) { $original = [IO.File]::ReadAllText($Path) }
65
+ $lines = $original.Replace("`r`n", "`n").Split([char]10)
66
+ $kept = New-Object 'Collections.Generic.List[string]'
67
+ $inside = $false
68
+ $seen = $false
69
+ foreach ($line in $lines) {
70
+ if ($line -ceq $begin) {
71
+ if ($inside -or $seen) { throw "Malformed setup-ssh block in $Path" }
72
+ $inside = $true; $seen = $true; continue
73
+ }
74
+ if ($line -ceq $end) {
75
+ if (-not $inside) { throw "Malformed setup-ssh block in $Path" }
76
+ $inside = $false; continue
77
+ }
78
+ if (-not $inside) { $kept.Add($line) }
79
+ }
80
+ if ($inside) { throw "Malformed setup-ssh block in $Path; restore its backup." }
81
+ $remainder = [string]::Join("`n", $kept).TrimEnd("`n")
82
+ $block = ''
83
+ if ($Body) { $block = $begin + "`n" + $Body.TrimEnd("`r", "`n") + "`n" + $end }
84
+ $pieces = @()
85
+ if ($Prepend -and $block) { $pieces += $block }
86
+ if ($remainder) { $pieces += $remainder }
87
+ if (-not $Prepend -and $block) { $pieces += $block }
88
+ $value = [string]::Join("`n", $pieces) + "`n"
89
+ if ($original.Replace("`r`n", "`n") -cne $value) {
90
+ if (Test-Path -LiteralPath $Path) {
91
+ Copy-Item -LiteralPath $Path -Destination ($Path + '.setup-ssh.bak') -Force
92
+ }
93
+ Write-Owned $Path $value
94
+ }
95
+ }
96
+
97
+ function Authorized-Path {
98
+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
99
+ # Membership also detects UAC-filtered administrator tokens in a local shell.
100
+ if ($identity.Groups.Value -contains 'S-1-5-32-544') {
101
+ return Join-Path $env:ProgramData 'ssh/administrators_authorized_keys'
102
+ }
103
+ return Join-Path $sshDir 'authorized_keys'
104
+ }
105
+
106
+ try {
107
+ if ($p.action -eq 'check') {
108
+ $configPath = Join-Path $groupDir 'config'
109
+ if (-not (Test-Path -LiteralPath $configPath)) { throw 'No managed configuration. Run sync.' }
110
+ & ssh.exe '-F' $configPath '-o' 'BatchMode=yes' '-o' 'PasswordAuthentication=no' `
111
+ '-o' 'KbdInteractiveAuthentication=no' '-o' 'PreferredAuthentications=publickey' `
112
+ '-o' 'IdentityAgent=none' '-o' 'ConnectionAttempts=1' `
113
+ '-o' ('ConnectTimeout=' + $p.timeout) $p.destination 'echo setup-ssh-ok'
114
+ exit $LASTEXITCODE
115
+ }
116
+ New-Item -ItemType Directory -Path $groupDir -Force | Out-Null
117
+ Protect-UserPath $groupDir
118
+ if ($p.action -eq 'prepare') {
119
+ Get-Command ssh.exe, ssh-keygen.exe -ErrorAction Stop | Out-Null
120
+ Assert-RegularPath $keyPath
121
+ Assert-RegularPath ($keyPath + '.pub')
122
+ if (-not (Test-Path -LiteralPath $keyPath)) {
123
+ if (Test-Path -LiteralPath ($keyPath + '.pub')) {
124
+ throw 'Managed private key is missing; restore it. To replace it, remove this device and delete its orphaned .pub file before re-enrolling.'
125
+ }
126
+ # ProcessStartInfo preserves the empty -N argument on Windows PowerShell 5.1.
127
+ $start = New-Object Diagnostics.ProcessStartInfo
128
+ $start.FileName = (Get-Command ssh-keygen.exe).Source
129
+ $start.UseShellExecute = $false
130
+ $start.CreateNoWindow = $true
131
+ $start.Arguments = '-q -t ed25519 -N "" -f "' + $keyPath + '" -C "setup-ssh:' + $p.group + ':' + $p.device + '"'
132
+ $process = [Diagnostics.Process]::Start($start)
133
+ $process.WaitForExit()
134
+ if ($process.ExitCode -ne 0) { throw 'ssh-keygen failed.' }
135
+ }
136
+ Protect-UserPath $keyPath
137
+ $start = New-Object Diagnostics.ProcessStartInfo
138
+ $start.FileName = (Get-Command ssh-keygen.exe).Source
139
+ $start.UseShellExecute = $false
140
+ $start.RedirectStandardOutput = $true
141
+ $start.RedirectStandardError = $true
142
+ $start.Arguments = '-y -P "" -f "' + $keyPath + '"'
143
+ $process = [Diagnostics.Process]::Start($start)
144
+ $public = $process.StandardOutput.ReadToEnd().Trim()
145
+ $keyError = $process.StandardError.ReadToEnd()
146
+ $process.WaitForExit()
147
+ if ($process.ExitCode -ne 0) { throw ('Cannot read managed key: ' + $keyError) }
148
+ Write-Owned ($keyPath + '.pub') ($public + ' setup-ssh:' + $p.group + ':' + $p.device)
149
+ Write-Output ('SETUP_SSH_KEY=' + $public)
150
+ } elseif ($p.action -eq 'apply' -or $p.action -eq 'remove') {
151
+ $authorized = Authorized-Path
152
+ if ($p.action -eq 'apply') {
153
+ if (-not (Test-Path -LiteralPath $keyPath)) { throw 'Managed private key missing. Run sync.' }
154
+ Write-Owned (Join-Path $groupDir 'config') $p.config
155
+ Write-Owned (Join-Path $groupDir 'known_hosts') $p.known_hosts
156
+ Write-Managed $authorized $p.authorized_keys $false
157
+ Write-Managed (Join-Path $sshDir 'config') ('Include "~/.ssh/setup-ssh/' + $p.group + '/config"') $true
158
+ } else {
159
+ Write-Managed $authorized '' $false
160
+ Write-Managed (Join-Path $sshDir 'config') '' $true
161
+ }
162
+ if ($authorized -eq (Join-Path $env:ProgramData 'ssh/administrators_authorized_keys')) {
163
+ # These SIDs work on localized Windows installations too.
164
+ $acl = New-Object Security.AccessControl.FileSecurity
165
+ $acl.SetAccessRuleProtection($true, $false)
166
+ foreach ($sidValue in @('S-1-5-18', 'S-1-5-32-544')) {
167
+ $sid = New-Object Security.Principal.SecurityIdentifier($sidValue)
168
+ $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow')
169
+ $acl.AddAccessRule($rule)
170
+ }
171
+ Set-Acl -LiteralPath $authorized -AclObject $acl
172
+ if (Test-Path -LiteralPath ($authorized + '.setup-ssh.bak')) {
173
+ Set-Acl -LiteralPath ($authorized + '.setup-ssh.bak') -AclObject $acl
174
+ }
175
+ } else {
176
+ Protect-UserPath $authorized
177
+ }
178
+ } else {
179
+ throw ('Unknown action: ' + $p.action)
180
+ }
181
+ } catch {
182
+ [Console]::Error.WriteLine($_.Exception.Message)
183
+ exit 1
184
+ }