Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ tools/phone-mirror # the phone's screen in a window here, mouse and
```

- **An SSH key that needs a touch per connection** (a security key): set `OMAMOBILE_SSH_SHARE=1`, and `tools/phone-ssh` (so `push` too) shares one connection and asks once. Check that SSH still works after a USB or firewall step with `tools/phone-ssh --fresh`, which never shares.
- **An explicit SSH connection:** set `OMAMOBILE_SSH_HOST` (`user@host`), `OMAMOBILE_SSH_KEY` (identity file) or `OMAMOBILE_SSH_KNOWN_HOSTS` (strict host-key checking with that file); these options need Python 3 and keep shared connections separate for each target, identity and known-hosts policy.
- **The device** comes from `DEVICE` (default `cheetah`, in [`omamobile.conf`](omamobile.conf)) and its descriptor `device/<codename>/device.conf`: `DEVICE=<codename> bin/omamobile images`. How builds and releases work for several devices: [docs/RELEASES.md](docs/RELEASES.md).
- **One worktree per subsystem branch.** Each branch gets its own output directory (`KERNEL_DIR=~/omamobile-kernel/wt-gnss KERNEL_OUT=~/omamobile-kernel/out-gnss bin/omamobile kernel`), so builds don't step on each other.
- **The kernel command line goes in the DTB** (`/chosen/bootargs`), not in `vendor_boot`: the Pixel bootloader (ABL) ignores the vendor_boot cmdline.
Expand Down
3 changes: 3 additions & 0 deletions tests/all
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ if [[ -n $latest ]]; then
else
echo "ok - # skip: no root image in out/ for tests/rootfs-smoke (tools/build-rootfs)"
fi

echo "# tests/phone-ssh"
tests/phone-ssh
118 changes: 118 additions & 0 deletions tests/phone-ssh
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#!/bin/bash
# SPDX-License-Identifier: MIT
# Validate host configuration without opening a connection.
# shellcheck disable=SC2016
set -euo pipefail
cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.."
scratch=$(mktemp -d)
scratch=$(cd "$scratch" && pwd -P)
trap 'rm -rf "$scratch"' EXIT
cat >"$scratch/ssh" <<'SH'
#!/bin/sh
printf '%s\n' "$@"
SH
chmod +x "$scratch/ssh"
real_ssh=$(command -v ssh || true)
export PATH="$scratch:$PATH"
unset OMAMOBILE_SSH_HOST OMAMOBILE_SSH_KEY OMAMOBILE_SSH_KNOWN_HOSTS OMAMOBILE_SSH_SHARE
tools/phone-ssh 'printf "%s" "$HOME"' >"$scratch/default"
grep -Fx root@172.16.42.1 "$scratch/default" >/dev/null
grep -Fx 'printf "%s" "$HOME"' "$scratch/default" >/dev/null
export OMAMOBILE_SSH_HOST='root@fe80::1234%usb-test'
export OMAMOBILE_SSH_KEY="$scratch/key with spaces"
printf 'fake identity\n' >"$OMAMOBILE_SSH_KEY"
export OMAMOBILE_SSH_KNOWN_HOSTS="$scratch/known hosts"
printf 'fake known host\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS"
tools/phone-ssh 'uname -r' >"$scratch/configured"
grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/configured" >/dev/null
grep -Fx -- "$OMAMOBILE_SSH_KEY" "$scratch/configured" >/dev/null
grep -Fx -- 'UserKnownHostsFile="'"$OMAMOBILE_SSH_KNOWN_HOSTS"'"' "$scratch/configured" >/dev/null
grep -Fx StrictHostKeyChecking=yes "$scratch/configured" >/dev/null
grep -Fx ControlPath=none "$scratch/configured" >/dev/null
if OMAMOBILE_SSH_HOST=-V tools/phone-ssh true >"$scratch/bad" 2>/dev/null; then
echo 'not ok - option-like SSH host accepted' >&2; exit 1
fi
[[ ! -s $scratch/bad ]]
export OMAMOBILE_SSH_SHARE=1
tools/phone-ssh 'uname -r' >"$scratch/shared"
grep -Fx ControlMaster=auto "$scratch/shared" >/dev/null
grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/shared" >/dev/null
shared=$(sed -n '/^ControlPath=/p' "$scratch/shared")
[[ $shared =~ /omamobile-ssh-[0-9a-f]{12}-%C$ ]]
# OpenSSH appends a dot and 16 random characters while binding a master.
# Cover a normal Linux runtime directory and the longest decimal UID path.
for runtime in /run/user/1000 /run/user/4294967294; do
XDG_RUNTIME_DIR=$runtime tools/phone-ssh true >"$scratch/socket-length"
python3 - "$scratch/socket-length" <<'PY'
import sys
from pathlib import Path
options = Path(sys.argv[1]).read_text().splitlines()
path, = (option.removeprefix('ControlPath=') for option in options
if option.startswith('ControlPath='))
expanded = path.replace('%C', 'a' * 40)
temporary = expanded + '.' + 'a' * 16
size = len(temporary.encode())
assert size <= 107, f'master socket needs {size} bytes, Linux permits 107: {temporary}'
print(f'ok - shared master socket with temporary suffix fits ({size}/107 bytes)')
PY
done
# -G reads only this fixture config: no connection or user ssh_config.
if [[ -n $real_ssh ]]; then
OMAMOBILE_SSH_HOST=root@fixture.invalid tools/phone-ssh true >"$scratch/alias-options"
python3 - "$real_ssh" "$scratch" <<'PY'
import subprocess, sys
from pathlib import Path
scratch = Path(sys.argv[2])
args = (scratch / 'alias-options').read_text().splitlines()
config = scratch / 'ssh_config'
def control_path(host, port):
config.write_text(f'Host *\n HostName {host}\n Port {port}\n')
result = subprocess.run([sys.argv[1], '-G', '-F', str(config), *args],
check=True, capture_output=True, text=True)
path, = (line for line in result.stdout.splitlines()
if line.startswith('controlpath '))
return path
paths = (control_path('one.invalid', 2201), control_path('one.invalid', 2202),
control_path('two.invalid', 2201))
assert len(set(paths)) == 3, 'SSH alias host/port changes must select separate masters'
print('ok - OpenSSH keeps alias host/port changes on separate masters')
PY
else
echo 'ok - # skip: no OpenSSH for alias host/port configuration check'
fi
tools/phone-ssh --fresh 'uname -r' >"$scratch/fresh"
grep -Fx ControlPath=none "$scratch/fresh" >/dev/null
grep -Fx ControlMaster=no "$scratch/fresh" >/dev/null
if grep -Fx ControlMaster=auto "$scratch/fresh"; then exit 1; fi
tools/phone-ssh --stop >"$scratch/stop"
grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/stop" >/dev/null
grep -Fx -- "$shared" "$scratch/stop" >/dev/null
grep -Fx -- -O "$scratch/stop" >/dev/null
printf 'other fake identity\n' >"$scratch/other identity"
OMAMOBILE_SSH_KEY="$scratch/other identity" tools/phone-ssh true >"$scratch/other"
[[ $(sed -n '/^ControlPath=/p' "$scratch/other") != "$shared" ]]
printf 'changed host key\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS"
tools/phone-ssh true >"$scratch/changed"
[[ $(sed -n '/^ControlPath=/p' "$scratch/changed") != "$shared" ]]
printf 'rotated fake identity\n' >"$OMAMOBILE_SSH_KEY"
tools/phone-ssh true >"$scratch/rotated"
[[ $(sed -n '/^ControlPath=/p' "$scratch/rotated") != $(sed -n '/^ControlPath=/p' "$scratch/changed") ]]
mkdir -p "$scratch/one" "$scratch/two"
printf 'first fake identity\n' >"$scratch/one/id"
printf 'second fake identity\n' >"$scratch/two/id"
repo=$PWD
(cd "$scratch/one"; OMAMOBILE_SSH_KEY=id "$repo/tools/phone-ssh" true) >"$scratch/relative-one"
(cd "$scratch/two"; OMAMOBILE_SSH_KEY=id "$repo/tools/phone-ssh" true) >"$scratch/relative-two"
[[ $(sed -n '/^ControlPath=/p' "$scratch/relative-one") != $(sed -n '/^ControlPath=/p' "$scratch/relative-two") ]]
printf 'fake key\n' >"$scratch/token%key"
if OMAMOBILE_SSH_KEY="$scratch/token%key" tools/phone-ssh true >"$scratch/token" 2>/dev/null; then
echo 'not ok - ambiguous SSH expansion in explicit path'; exit 1
fi
[[ ! -s $scratch/token ]]
# Default connections retain upstream's socket and --stop target.
unset OMAMOBILE_SSH_HOST OMAMOBILE_SSH_KEY OMAMOBILE_SSH_KNOWN_HOSTS
tools/phone-ssh true >"$scratch/default-shared"
grep -Fx 'ControlPath='"${XDG_RUNTIME_DIR:-/tmp}"'/omamobile-ssh-%C' "$scratch/default-shared" >/dev/null
tools/phone-ssh --fresh true >"$scratch/default-fresh"
grep -Fx ControlPath=none "$scratch/default-fresh" >/dev/null
echo 'ok - phone SSH options preserve sharing/fresh/stop and isolate identity/host-key policy'
73 changes: 68 additions & 5 deletions tools/phone-ssh
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,85 @@
#
# tools/phone-ssh [--fresh | --stop] [COMMAND...]
#
# OMAMOBILE_SSH_HOST overrides root@172.16.42.1 (user@host).
# OMAMOBILE_SSH_KEY selects an identity file (IdentitiesOnly=yes).
# OMAMOBILE_SSH_KNOWN_HOSTS selects a file with strict host-key checking.
# Explicit connection options require Python 3.
#
# OMAMOBILE_SSH_SHARE=1 makes every call share one connection (OpenSSH
# ControlMaster, kept 60 s after the last call), so a key that needs a touch
# per connection asks once instead of once per call: `bin/omamobile push`
# makes about 25. A shared connection outlives what happens to new ones, so
# a check that a step left SSH working (a USB or firewall change, AGENTS.md
# section 1) must use --fresh, which never shares. --stop closes the shared
# connection.
opts=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=6)
set -euo pipefail
target=${OMAMOBILE_SSH_HOST:-root@172.16.42.1}
[[ $target != -* && $target != *[[:space:]]* ]] || {
echo 'phone-ssh: invalid OMAMOBILE_SSH_HOST' >&2; exit 1;
}
key=${OMAMOBILE_SSH_KEY:-}
known=${OMAMOBILE_SSH_KNOWN_HOSTS:-}
custom=0
path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-%C"
if [[ $target != root@172.16.42.1 || -n $key$known ]]; then
custom=1
# OpenSSH's %C omits identity/trust policy. Normalize explicit paths and
# include contents so cwd changes and key rotations never reuse a master.
# Python 3 is required only for these explicit connection options.
normalized=$(python3 - "$target" "$key" "$known" <<'PYCONTEXT'
import hashlib, sys
from pathlib import Path
h = hashlib.sha256(); h.update(sys.argv[1].encode() + b'\0')
paths = []
for label, value in zip(('identity', 'known-hosts'), sys.argv[2:]):
if any(token in value for token in ('\n', '\r', '%', '${')):
sys.exit('phone-ssh: file paths must be literal, without newlines or OpenSSH expansion tokens')
path = Path(value).expanduser().resolve() if value else None
paths.append(str(path) if path else '')
h.update((str(path) if path else '').encode() + b'\0')
if path:
try:
if not path.is_file():
raise OSError('not a regular file')
h.update(path.read_bytes())
except OSError:
sys.exit('phone-ssh: cannot read explicit ' + label + ' file')
h.update(b'\0')
print(*paths, h.hexdigest()[:12], sep='\n')
PYCONTEXT
)
key=${normalized%%$'\n'*}
normalized=${normalized#*$'\n'}
known=${normalized%%$'\n'*}
context=${normalized#*$'\n'}
# Keep %C for the effective HostName/Port resolved from ssh_config. The
# short policy hash leaves room for OpenSSH's temporary 17-byte suffix.
path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-$context-%C"
fi
opts=(-o LogLevel=ERROR -o ConnectTimeout=6)
if [[ -n $known ]]; then
# This -o value is parsed again as ssh_config: protect spaces and quotes.
quoted=${known//\\/\\\\}
quoted=${quoted//\"/\\\"}
opts+=(-o StrictHostKeyChecking=yes -o "UserKnownHostsFile=\"$quoted\"")
else
opts+=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null)
fi
[[ -z $key ]] || opts+=(-o IdentitiesOnly=yes -i "$key")
case ${1:-} in
--fresh) shift; opts+=(-o ControlMaster=no -o ControlPath=none) ;;
--stop) exec ssh "${opts[@]}" -o ControlPath="$path" -O exit root@172.16.42.1 2>/dev/null ;;
--stop) exec ssh "${opts[@]}" -o ControlPath="$path" -O exit "$target" 2>/dev/null ;;
*)
# Keepalives end a master whose phone rebooted within about 6 s, so
# calls after a reboot don't wait on a dead connection.
[[ ${OMAMOBILE_SSH_SHARE:-0} == 1 ]] && opts+=(-o ControlMaster=auto -o ControlPath="$path"
-o ControlPersist=60 -o ServerAliveInterval=2 -o ServerAliveCountMax=3) ;;
if [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 ]]; then
opts+=(-o ControlMaster=auto -o ControlPath="$path"
-o ControlPersist=60 -o ServerAliveInterval=2 -o ServerAliveCountMax=3)
elif ((custom)); then
# A user's ssh_config may enable sharing globally. Explicit identity
# and trust options must apply to a new connection unless requested.
opts+=(-o ControlMaster=no -o ControlPath=none)
fi ;;
esac
exec ssh "${opts[@]}" root@172.16.42.1 "$@"
exec ssh "${opts[@]}" "$target" "$@"