Add secure host CLI bridge and harden OTA workflows
Expose the Full Companion terminal over TCP and add an authenticated, replay-resistant host command service with documented CPU temperature, reboot, and allowlisted program examples.\n\nImprove LoRa OTA diagnostics and persistent CLI handling, reduce clock correction drift to ten minutes, and make mOTA stream flush behavior an explicit transport policy with regression coverage.
This commit is contained in:
1 parent
83c1dd95fe
commit
b699e552ec
46 files changed
+4364
-359
No files matched your search
@@ -0,0 +1,230 @@
|
||||
# LoRa CLI host service example
|
||||
|
||||
This example lets an authenticated remote administrator ask a computer attached
|
||||
to a repeater to perform a small, explicitly allowed operation. The included
|
||||
service implements this fixed allowlist:
|
||||
|
||||
```text
|
||||
host help
|
||||
host cpu-temp
|
||||
host hostname
|
||||
host uptime
|
||||
host load
|
||||
host memory
|
||||
host disk-free
|
||||
host reboot
|
||||
host run <alias> [arguments]
|
||||
```
|
||||
|
||||
The status commands read bounded operating-system APIs or virtual files. The
|
||||
service never invokes a shell and does not accept arbitrary commands,
|
||||
file paths, or executable names. Locally configured program aliases can accept
|
||||
strictly validated arguments. Host reboot is disabled by default.
|
||||
|
||||
Normal repeater firmware includes the host bridge. The specialized Wio-E5
|
||||
RS232 bridge image omits it to stay within that board's fixed 240 KiB
|
||||
application partition; use the normal Wio-E5 repeater image for this service.
|
||||
|
||||
## Using it with meshcoretomqtt
|
||||
|
||||
`meshcoretomqtt` remains the only process that opens the repeater's USB serial
|
||||
port. The data path is:
|
||||
|
||||
```text
|
||||
LoRa admin -> repeater -> USB -> meshcoretomqtt -> MQTT broker
|
||||
MQTT broker -> host endpoint -> signed remote-serial MQTT -> meshcoretomqtt
|
||||
meshcoretomqtt -> USB -> repeater -> LoRa reply
|
||||
```
|
||||
|
||||
Two processes must not read the same serial TTY. The MQTT endpoint avoids that
|
||||
race and can run on the same Pi as the broker and `meshcoretomqtt`, or on a
|
||||
different host.
|
||||
|
||||
The current `meshcoretomqtt` release publishes repeater `DEBUG` records only
|
||||
when it is launched with `--debug`. Add `--debug` to its existing systemd
|
||||
`ExecStart` command and restart it. Keep any existing `--config` arguments.
|
||||
This publishes other firmware debug records too, so use broker ACLs and do not
|
||||
expose the debug topic publicly.
|
||||
|
||||
The host-command authorization does not compare the repeater clock with the Pi
|
||||
clock. Several minutes of drift, an unset repeater wall clock, or a later clock
|
||||
correction cannot make an old request executable. Freshness comes from the
|
||||
live one-time challenge described below. The normal `meshcoretomqtt`
|
||||
`sync_time` setting can remain enabled for its other uses, but this feature does
|
||||
not depend on it.
|
||||
|
||||
Generate a dedicated service signing key with the Python environment already
|
||||
installed by `meshcoretomqtt`:
|
||||
|
||||
```sh
|
||||
sudo /opt/mctomqtt/venv/bin/python3 host_cli_service.py \
|
||||
--generate-key /etc/mctomqtt/host-cli-key.json
|
||||
sudo chown mctomqtt:mctomqtt /etc/mctomqtt/host-cli-key.json
|
||||
sudo chmod 600 /etc/mctomqtt/host-cli-key.json
|
||||
```
|
||||
|
||||
The command prints the public key. Add only that public key to the existing
|
||||
`meshcoretomqtt` configuration:
|
||||
|
||||
```toml
|
||||
[remote_serial]
|
||||
enabled = true
|
||||
allowed_companions = [
|
||||
"SERVICE_PUBLIC_KEY_PRINTED_ABOVE"
|
||||
]
|
||||
nonce_ttl = 120
|
||||
command_timeout = 10
|
||||
```
|
||||
|
||||
The name `allowed_companions` comes from `meshcoretomqtt`; a dedicated service
|
||||
identity works because it uses the same Ed25519 token format. Restart
|
||||
`mctomqtt` after changing the file.
|
||||
|
||||
Run the endpoint against the same broker and topic namespace. Replace `USA`
|
||||
with the exact three-character IATA value used by that broker and replace the
|
||||
repeater key with the repeater's complete 64-hex-character public key:
|
||||
|
||||
```sh
|
||||
sudo -u mctomqtt /opt/mctomqtt/venv/bin/python3 host_cli_service.py \
|
||||
--broker 127.0.0.1 \
|
||||
--iata USA \
|
||||
--repeater-key REPEATER_PUBLIC_KEY \
|
||||
--service-key /etc/mctomqtt/host-cli-key.json
|
||||
```
|
||||
|
||||
For a password-protected broker, add `--username NAME --password-file FILE`.
|
||||
For TLS, add `--tls`, and optionally `--ca-cert FILE`. If the debug or serial
|
||||
command topic is customized in `meshcoretomqtt`, pass the matching
|
||||
`--request-topic` or `--command-topic` value.
|
||||
|
||||
To enable the exact `host reboot` request, give only `systemctl reboot` to the
|
||||
service account in `/etc/sudoers.d/meshcore-host-cli`:
|
||||
|
||||
```text
|
||||
mctomqtt ALL=(root) NOPASSWD: /usr/bin/systemctl reboot
|
||||
```
|
||||
|
||||
Set that file to mode `440`, then add `--allow-reboot` to the endpoint command.
|
||||
The endpoint publishes `OK - host reboot scheduled in 5s`, waits for the MQTT
|
||||
publish, and then runs the fixed argv
|
||||
`/usr/bin/sudo -n /usr/bin/systemctl reboot` after five seconds. Change the
|
||||
delay from 3 through 60 seconds with `--reboot-delay`; no LoRa text is ever
|
||||
inserted into the process invocation. Do not add a broad sudo wildcard.
|
||||
|
||||
## Allowlisted programs with arguments
|
||||
|
||||
Pass `--programs-file FILE` to expose selected local programs as
|
||||
`host run <alias> [arguments]`. Start with `programs.example.json`, replace its
|
||||
example executable paths with installed programs, and keep the file owned by a
|
||||
trusted local account. The service rejects a group- or world-writable allowlist
|
||||
or executable.
|
||||
|
||||
Each entry fixes the executable and any leading arguments in `argv`. Its remote
|
||||
arguments have an exact count and one of three validators:
|
||||
|
||||
- `choice` accepts only one explicitly listed value;
|
||||
- `integer` accepts a canonical nonnegative decimal value inside `min` and
|
||||
`max`;
|
||||
- `token` accepts a bounded ASCII token that starts with a letter or digit and
|
||||
contains only letters, digits, `_`, `.`, `:`, `@`, `+`, `,`, or `-`.
|
||||
|
||||
For the example `fan` entry, the remote command is:
|
||||
|
||||
```text
|
||||
cmd host run fan on 15
|
||||
```
|
||||
|
||||
It always executes this argument vector, without a shell:
|
||||
|
||||
```text
|
||||
/usr/local/bin/mesh-fan-control --source lora on 15
|
||||
```
|
||||
|
||||
An alias cannot select another executable. Extra arguments, option-shaped
|
||||
tokens such as `--help`, invalid choices, out-of-range integers, shell syntax,
|
||||
control characters, and malformed quoting are rejected before a process is
|
||||
started. Program timeouts are limited to 1-5 seconds so the reply fits inside
|
||||
the repeater's 10-second host-service deadline. The selected local program is
|
||||
still trusted code; give its service account only the operating-system
|
||||
permissions that program needs.
|
||||
|
||||
From a companion's authenticated remote CLI, select and log into the repeater,
|
||||
then run:
|
||||
|
||||
```text
|
||||
cmd host help
|
||||
cmd host cpu-temp
|
||||
```
|
||||
|
||||
Use `cmd get host` to view the bridge limits and whether a request is waiting.
|
||||
|
||||
## Injection and replay protection
|
||||
|
||||
The broker is transport, not the trust boundary. The endpoint accepts a request
|
||||
only when all of these checks pass:
|
||||
|
||||
- the LoRa caller was authenticated by the repeater and has administrator
|
||||
permission;
|
||||
- the MQTT `origin_id` is the configured repeater identity;
|
||||
- the complete protocol record has a valid Ed25519 signature from that
|
||||
repeater;
|
||||
- the request contains the pending 32-bit ID and a fresh random 64-bit nonce;
|
||||
- Base64URL framing, UTF-8, and byte limits are valid;
|
||||
- a new random 64-bit service challenge is returned through the signed serial
|
||||
channel and the repeater signs proof that the exact request is still pending;
|
||||
- only after that live proof does the decoded request reach the fixed built-in
|
||||
or locally configured program allowlist.
|
||||
|
||||
For `run`, the request must additionally match a locally configured alias and
|
||||
every argument validator. Execution uses a fixed absolute executable,
|
||||
`shell=False`, a fixed minimal environment, no stdin, and `/` as its working
|
||||
directory.
|
||||
|
||||
The initial signed request never executes an action. The endpoint first stores
|
||||
it in memory and sends `@claim=<random>` with the same ID and nonce. The
|
||||
firmware accepts that claim only through physical USB while that exact LoRa
|
||||
request is pending, then emits a signed `CLAIMED` proof containing the random
|
||||
value. The endpoint removes the proof before running the action, making action
|
||||
execution at most once even if MQTT redelivers a record.
|
||||
|
||||
A captured request can at most make the endpoint issue a new challenge; a
|
||||
repeater with no matching live request will not sign it. A captured `CLAIMED`
|
||||
record cannot match the endpoint's new random challenge, and a service restart
|
||||
forgets all outstanding challenges. These replay properties do not use wall
|
||||
clock time. The final response still travels in a short-lived JWT whose
|
||||
signature, signer allowlist, target, expiration, and independent nonce are
|
||||
checked by `meshcoretomqtt`. When both processes run on the same Pi, that JWT
|
||||
check naturally uses the same host clock; if they run on different computers,
|
||||
those two computers need compatible clocks. Repeater-to-Pi clock drift remains
|
||||
irrelevant.
|
||||
|
||||
Request text is Base64URL encoded before it enters the line-oriented USB stream.
|
||||
Reply controls such as carriage return and newline are converted to spaces, and
|
||||
the firmware independently rejects control characters and malformed UTF-8.
|
||||
This prevents text from becoming a second serial command.
|
||||
|
||||
Protect `host-cli-key.json`: any private key placed in
|
||||
`allowed_companions` is trusted by `meshcoretomqtt` to sign serial requests.
|
||||
Use a dedicated broker account whose ACL can only subscribe to this repeater's
|
||||
debug topic and publish to this repeater's `serial/commands` topic.
|
||||
|
||||
## Limits
|
||||
|
||||
- LoRa `host` command: 155 UTF-8 bytes after `host `, or 152 bytes when the
|
||||
companion uses its legacy three-byte correlation prefix.
|
||||
- LoRa reply: 162 UTF-8 bytes total, including that correlation prefix.
|
||||
- One request can be pending per repeater.
|
||||
- Live-claim deadline: 4 seconds, followed by up to 6 seconds for execution and
|
||||
the reply.
|
||||
- `host.reply` is accepted only from the physical USB serial command path, not
|
||||
from LoRa or the Ethernet CLI.
|
||||
|
||||
Run the dependency-free logic tests with:
|
||||
|
||||
```sh
|
||||
cd examples/host_cli_service
|
||||
python3 -m unittest -v
|
||||
```
|
||||
|
||||
The live service needs Python 3.11 or later, `paho-mqtt`, and
|
||||
`ed25519-orlp`; the standard `/opt/mctomqtt/venv` already contains them.
|
||||
+1107
File diff suppressed because it is too large.
Load diff
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility entry point for the expanded MeshCore host CLI service."""
|
||||
|
||||
from host_cli_service import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"programs": {
|
||||
"fan": {
|
||||
"argv": [
|
||||
"/usr/local/bin/mesh-fan-control",
|
||||
"--source",
|
||||
"lora"
|
||||
],
|
||||
"timeout_seconds": 3,
|
||||
"arguments": [
|
||||
{
|
||||
"name": "state",
|
||||
"type": "choice",
|
||||
"choices": [
|
||||
"on",
|
||||
"off"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "minutes",
|
||||
"type": "integer",
|
||||
"min": 1,
|
||||
"max": 60
|
||||
}
|
||||
]
|
||||
},
|
||||
"label-status": {
|
||||
"argv": [
|
||||
"/usr/local/bin/mesh-label-status"
|
||||
],
|
||||
"timeout_seconds": 3,
|
||||
"arguments": [
|
||||
{
|
||||
"name": "label",
|
||||
"type": "token",
|
||||
"max_bytes": 24
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import host_cli_service as service
|
||||
|
||||
|
||||
PUBLIC_KEY = "11" * 32
|
||||
PRIVATE_KEY = "22" * 64
|
||||
SIGNATURE = bytes([0xA5]) * 64
|
||||
|
||||
|
||||
def request_payload(
|
||||
text: str = "cpu-temp",
|
||||
request_id: str = "89ABCDEF",
|
||||
) -> tuple[str, bytes]:
|
||||
encoded = base64.urlsafe_b64encode(text.encode()).rstrip(b"=").decode()
|
||||
signed = f"HOSTCLI/1 REQUEST {request_id} 0123456789ABCDEF {encoded}"
|
||||
message = "DEBUG " + signed + " " + SIGNATURE.hex().upper()
|
||||
payload = json.dumps(
|
||||
{"type": "DEBUG", "origin_id": PUBLIC_KEY, "message": message}
|
||||
).encode()
|
||||
return signed, payload
|
||||
|
||||
|
||||
def claim_payload(
|
||||
challenge: str = "FEDCBA9876543210",
|
||||
request_id: str = "89ABCDEF",
|
||||
) -> tuple[str, bytes]:
|
||||
signed = (
|
||||
f"HOSTCLI/1 CLAIMED {request_id} 0123456789ABCDEF {challenge}"
|
||||
)
|
||||
message = "DEBUG " + signed + " " + SIGNATURE.hex().upper()
|
||||
payload = json.dumps(
|
||||
{"type": "DEBUG", "origin_id": PUBLIC_KEY, "message": message}
|
||||
).encode()
|
||||
return signed, payload
|
||||
|
||||
|
||||
class HostRequestTests(unittest.TestCase):
|
||||
def test_accepts_only_a_valid_repeater_signature(self) -> None:
|
||||
expected, payload = request_payload()
|
||||
|
||||
def verifier(signature: bytes, message: bytes, public: bytes) -> bool:
|
||||
return (
|
||||
signature == SIGNATURE
|
||||
and message == expected.encode()
|
||||
and public == bytes.fromhex(PUBLIC_KEY)
|
||||
)
|
||||
|
||||
request = service.parse_and_verify_request(
|
||||
payload, PUBLIC_KEY, verifier=verifier,
|
||||
)
|
||||
self.assertEqual(
|
||||
service.HostRequest(
|
||||
"89ABCDEF", "0123456789ABCDEF", "cpu-temp"
|
||||
),
|
||||
request,
|
||||
)
|
||||
|
||||
def test_rejects_forged_content_and_wrong_origin(self) -> None:
|
||||
_expected, payload = request_payload("cpu-temp")
|
||||
forged = payload.replace(b"Y3B1LXRlbXA", b"ZXJhc2U")
|
||||
with self.assertRaisesRegex(ValueError, "signature"):
|
||||
service.parse_and_verify_request(
|
||||
forged, PUBLIC_KEY, verifier=lambda *_args: False,
|
||||
)
|
||||
|
||||
document = json.loads(payload)
|
||||
document["origin_id"] = "33" * 32
|
||||
with self.assertRaisesRegex(ValueError, "origin"):
|
||||
service.parse_and_verify_request(
|
||||
json.dumps(document), PUBLIC_KEY,
|
||||
verifier=lambda *_args: True,
|
||||
)
|
||||
|
||||
def test_ignores_unrelated_debug_records(self) -> None:
|
||||
payload = json.dumps(
|
||||
{"type": "DEBUG", "origin_id": PUBLIC_KEY,
|
||||
"message": "DEBUG ordinary log"}
|
||||
)
|
||||
self.assertIsNone(
|
||||
service.parse_and_verify_request(
|
||||
payload, PUBLIC_KEY, verifier=lambda *_args: True,
|
||||
)
|
||||
)
|
||||
|
||||
def test_accepts_only_a_valid_signed_claim(self) -> None:
|
||||
expected, payload = claim_payload()
|
||||
|
||||
def verifier(signature: bytes, message: bytes, public: bytes) -> bool:
|
||||
return (
|
||||
signature == SIGNATURE
|
||||
and message == expected.encode()
|
||||
and public == bytes.fromhex(PUBLIC_KEY)
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
service.HostClaim(
|
||||
"89ABCDEF", "0123456789ABCDEF", "FEDCBA9876543210"
|
||||
),
|
||||
service.parse_and_verify_claim(
|
||||
payload, PUBLIC_KEY, verifier=verifier
|
||||
),
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "signature"):
|
||||
service.parse_and_verify_claim(
|
||||
payload, PUBLIC_KEY, verifier=lambda *_args: False
|
||||
)
|
||||
|
||||
def test_rejects_a_zero_claim_challenge(self) -> None:
|
||||
_signed, payload = claim_payload("0000000000000000")
|
||||
with self.assertRaisesRegex(ValueError, "must not be zero"):
|
||||
service.parse_and_verify_claim(
|
||||
payload, PUBLIC_KEY, verifier=lambda *_args: True
|
||||
)
|
||||
|
||||
|
||||
class RequestHandlerTests(unittest.TestCase):
|
||||
def test_reads_pi_cpu_temperature(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "temp"
|
||||
path.write_text("47250\n", encoding="ascii")
|
||||
self.assertEqual(
|
||||
service.HostResult("CPU 47.2 C"),
|
||||
service.handle_request("cpu-temp", path),
|
||||
)
|
||||
|
||||
def test_never_executes_or_accepts_injected_commands(self) -> None:
|
||||
response = service.handle_request(
|
||||
"cpu-temp\r\nerase", Path("/does/not/matter")
|
||||
)
|
||||
self.assertEqual(
|
||||
service.HostResult("Err - unsupported host request"), response
|
||||
)
|
||||
|
||||
request = service.HostRequest(
|
||||
"12345678", "FEDCBA9876543210", "cpu-temp"
|
||||
)
|
||||
command = service.make_serial_reply(request, "OK\r\nerase")
|
||||
self.assertEqual(
|
||||
"host.reply 12345678 FEDCBA9876543210 OK erase", command
|
||||
)
|
||||
self.assertNotIn("\r", command)
|
||||
self.assertNotIn("\n", command)
|
||||
self.assertEqual(
|
||||
"OK 31mnot-a-terminal-control",
|
||||
service.bounded_line_text("OK\N{CONTROL SEQUENCE INTRODUCER}31m"
|
||||
"not-a-terminal-control"),
|
||||
)
|
||||
|
||||
def test_exact_fixed_commands_and_opt_in_reboot(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
uptime = root / "uptime"
|
||||
load = root / "loadavg"
|
||||
memory = root / "meminfo"
|
||||
uptime.write_text("183845.2 0.0\n", encoding="ascii")
|
||||
load.write_text("0.12 0.34 0.56 1/1 1\n", encoding="ascii")
|
||||
memory.write_text(
|
||||
"MemTotal: 1024000 kB\nMemAvailable: 512000 kB\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
kwargs = {
|
||||
"uptime_path": uptime,
|
||||
"load_path": load,
|
||||
"memory_path": memory,
|
||||
"disk_path": root,
|
||||
}
|
||||
self.assertEqual(
|
||||
"Uptime 2d 3h 4m",
|
||||
service.handle_request("uptime", root, **kwargs).text,
|
||||
)
|
||||
self.assertEqual(
|
||||
"Load 0.12 0.34 0.56",
|
||||
service.handle_request("load", root, **kwargs).text,
|
||||
)
|
||||
self.assertEqual(
|
||||
"Memory 500/1000 MiB available",
|
||||
service.handle_request("memory", root, **kwargs).text,
|
||||
)
|
||||
self.assertTrue(
|
||||
service.handle_request("disk-free", root, **kwargs).text.startswith(
|
||||
"Disk "
|
||||
)
|
||||
)
|
||||
|
||||
disabled = service.handle_request("reboot", Path("/unused"))
|
||||
self.assertEqual("Err - host reboot is disabled", disabled.text)
|
||||
self.assertFalse(disabled.reboot_requested)
|
||||
enabled = service.handle_request(
|
||||
"reboot", Path("/unused"), allow_reboot=True, reboot_delay=7
|
||||
)
|
||||
self.assertEqual("OK - host reboot scheduled in 7s", enabled.text)
|
||||
self.assertTrue(enabled.reboot_requested)
|
||||
self.assertEqual(
|
||||
service.HostResult("Err - unsupported host request"),
|
||||
service.handle_request("reboot now", Path("/unused"),
|
||||
allow_reboot=True),
|
||||
)
|
||||
|
||||
def test_reply_is_utf8_bounded(self) -> None:
|
||||
text = "x" * 161 + "\N{EURO SIGN}"
|
||||
bounded = service.bounded_line_text(text)
|
||||
self.assertLessEqual(len(bounded.encode()), service.MAX_REPLY_BYTES)
|
||||
self.assertEqual("x" * 161, bounded)
|
||||
|
||||
def test_runs_only_a_fixed_program_with_validated_arguments(self) -> None:
|
||||
programs = {
|
||||
"fan": service.ProgramDefinition(
|
||||
alias="fan",
|
||||
argv=("/usr/local/bin/mesh-fan-control", "--source", "lora"),
|
||||
arguments=(
|
||||
service.ProgramArgumentRule(
|
||||
"state", "choice", choices=("on", "off")
|
||||
),
|
||||
service.ProgramArgumentRule(
|
||||
"minutes", "integer", minimum=1, maximum=60
|
||||
),
|
||||
),
|
||||
timeout_seconds=3,
|
||||
)
|
||||
}
|
||||
completed = subprocess_result = mock.Mock(
|
||||
returncode=0, stdout="fan scheduled\n"
|
||||
)
|
||||
with mock.patch.object(
|
||||
service.subprocess, "run", return_value=completed
|
||||
) as run:
|
||||
result = service.handle_request(
|
||||
"run fan on 15", Path("/unused"), programs=programs
|
||||
)
|
||||
|
||||
self.assertEqual("fan scheduled", result.text)
|
||||
self.assertIs(completed, subprocess_result)
|
||||
argv = run.call_args.args[0]
|
||||
self.assertEqual(
|
||||
[
|
||||
"/usr/local/bin/mesh-fan-control",
|
||||
"--source",
|
||||
"lora",
|
||||
"on",
|
||||
"15",
|
||||
],
|
||||
argv,
|
||||
)
|
||||
self.assertFalse(run.call_args.kwargs["shell"])
|
||||
self.assertEqual("/", run.call_args.kwargs["cwd"])
|
||||
|
||||
def test_rejects_program_alias_and_argument_injection(self) -> None:
|
||||
programs = {
|
||||
"fan": service.ProgramDefinition(
|
||||
alias="fan",
|
||||
argv=("/usr/local/bin/mesh-fan-control",),
|
||||
arguments=(
|
||||
service.ProgramArgumentRule(
|
||||
"state", "choice", choices=("on", "off")
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
rejected = (
|
||||
"run other on",
|
||||
"run fan --help",
|
||||
"run fan on;reboot",
|
||||
"run fan on\nreboot",
|
||||
"run fan on extra",
|
||||
"run fan -1",
|
||||
)
|
||||
with mock.patch.object(service.subprocess, "run") as run:
|
||||
for request in rejected:
|
||||
with self.subTest(request=request):
|
||||
self.assertTrue(
|
||||
service.handle_request(
|
||||
request, Path("/unused"), programs=programs
|
||||
).text.startswith("Err -")
|
||||
)
|
||||
run.assert_not_called()
|
||||
|
||||
def test_loads_a_bounded_program_allowlist(self) -> None:
|
||||
executable = Path("/bin/echo").resolve()
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
config = Path(directory) / "programs.json"
|
||||
config.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"programs": {
|
||||
"sample": {
|
||||
"argv": [str(executable), "fixed"],
|
||||
"timeout_seconds": 2,
|
||||
"arguments": [
|
||||
{
|
||||
"name": "mode",
|
||||
"type": "choice",
|
||||
"choices": ["short", "full"],
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": "integer",
|
||||
"min": 1,
|
||||
"max": 5,
|
||||
},
|
||||
{
|
||||
"name": "label",
|
||||
"type": "token",
|
||||
"max_bytes": 12,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
config.chmod(0o644)
|
||||
programs = service.load_programs_file(config)
|
||||
|
||||
self.assertEqual((str(executable), "fixed"), programs["sample"].argv)
|
||||
self.assertEqual(3, len(programs["sample"].arguments))
|
||||
|
||||
def test_rejects_writable_program_allowlist(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
config = Path(directory) / "programs.json"
|
||||
config.write_text('{"programs": {}}', encoding="ascii")
|
||||
config.chmod(0o666)
|
||||
with self.assertRaisesRegex(ValueError, "group/world writable"):
|
||||
service.load_programs_file(config)
|
||||
|
||||
|
||||
class TokenTests(unittest.TestCase):
|
||||
def test_signed_remote_serial_token_has_required_claims(self) -> None:
|
||||
key = service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY)
|
||||
|
||||
def signer(message: bytes, public: bytes, private: bytes) -> bytes:
|
||||
self.assertEqual(bytes.fromhex(PUBLIC_KEY), public)
|
||||
self.assertEqual(bytes.fromhex(PRIVATE_KEY), private)
|
||||
self.assertEqual(1, message.count(b"."))
|
||||
return SIGNATURE
|
||||
|
||||
token = service.create_auth_token(
|
||||
key,
|
||||
{
|
||||
"command": (
|
||||
"host.reply 12345678 FEDCBA9876543210 CPU 47.2 C"
|
||||
),
|
||||
"target": "44" * 32,
|
||||
"nonce": "nonce-value",
|
||||
},
|
||||
now=1000,
|
||||
signer=signer,
|
||||
)
|
||||
header_part, payload_part, signature_part = token.split(".")
|
||||
del header_part
|
||||
padding = "=" * ((4 - len(payload_part) % 4) % 4)
|
||||
claims = json.loads(base64.urlsafe_b64decode(payload_part + padding))
|
||||
self.assertEqual(PUBLIC_KEY, claims["publicKey"])
|
||||
self.assertEqual(1000, claims["iat"])
|
||||
self.assertEqual(1030, claims["exp"])
|
||||
self.assertEqual("44" * 32, claims["target"])
|
||||
self.assertEqual(SIGNATURE.hex().upper(), signature_part)
|
||||
|
||||
|
||||
class EndpointTests(unittest.TestCase):
|
||||
def test_request_needs_matching_live_claim_before_reboot(self) -> None:
|
||||
events: list[object] = []
|
||||
|
||||
class PublishResult:
|
||||
rc = 0
|
||||
|
||||
def wait_for_publish(self, timeout: float) -> None:
|
||||
events.append(("wait", timeout))
|
||||
|
||||
class Client:
|
||||
def publish(self, topic: str, token: str, qos: int) -> PublishResult:
|
||||
events.append(("publish", topic, token, qos))
|
||||
return PublishResult()
|
||||
|
||||
endpoint = service.HostCliEndpoint(
|
||||
client=Client(),
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
allow_reboot=True,
|
||||
reboot_delay=7,
|
||||
reboot_scheduler=lambda delay: events.append(("reboot", delay)),
|
||||
challenge_generator=lambda: "A1B2C3D4E5F60718",
|
||||
monotonic=lambda: 100.0,
|
||||
)
|
||||
request = service.HostRequest(
|
||||
"12345678", "FEDCBA9876543210", "reboot"
|
||||
)
|
||||
claim = service.HostClaim(
|
||||
request.request_id,
|
||||
request.request_nonce,
|
||||
"A1B2C3D4E5F60718",
|
||||
)
|
||||
|
||||
def make_token(
|
||||
_key: service.ServiceKey, claims: dict[str, object]
|
||||
) -> str:
|
||||
events.append(("token", claims["command"]))
|
||||
return "signed"
|
||||
|
||||
reboot_result = service.HostResult(
|
||||
"OK - host reboot scheduled in 7s", reboot_requested=True
|
||||
)
|
||||
with mock.patch.object(
|
||||
service, "parse_and_verify_request", return_value=request
|
||||
), mock.patch.object(
|
||||
service, "create_auth_token", side_effect=make_token
|
||||
), mock.patch.object(
|
||||
service, "handle_request", return_value=reboot_result
|
||||
) as handler:
|
||||
self.assertTrue(endpoint.handle_mqtt_message(b"request"))
|
||||
handler.assert_not_called()
|
||||
|
||||
with mock.patch.object(
|
||||
service, "parse_and_verify_request", return_value=None
|
||||
), mock.patch.object(
|
||||
service, "parse_and_verify_claim", return_value=claim
|
||||
):
|
||||
self.assertTrue(endpoint.handle_mqtt_message(b"claim"))
|
||||
|
||||
self.assertEqual(
|
||||
(
|
||||
"token",
|
||||
"host.reply 12345678 FEDCBA9876543210 "
|
||||
"@claim=A1B2C3D4E5F60718",
|
||||
),
|
||||
events[0],
|
||||
)
|
||||
self.assertEqual("publish", events[1][0])
|
||||
self.assertEqual(
|
||||
(
|
||||
"token",
|
||||
"host.reply 12345678 FEDCBA9876543210 "
|
||||
"OK - host reboot scheduled in 7s",
|
||||
),
|
||||
events[2],
|
||||
)
|
||||
self.assertEqual("publish", events[3][0])
|
||||
self.assertEqual(("wait", 2.0), events[4])
|
||||
self.assertEqual(("reboot", 7), events[5])
|
||||
|
||||
def test_mismatched_expired_and_replayed_claims_do_not_execute(self) -> None:
|
||||
now = [10.0]
|
||||
|
||||
class Client:
|
||||
def publish(self, _topic: str, _token: str, qos: int) -> mock.Mock:
|
||||
self.qos = qos
|
||||
return mock.Mock(rc=0)
|
||||
|
||||
endpoint = service.HostCliEndpoint(
|
||||
client=Client(),
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
challenge_generator=lambda: "1111222233334444",
|
||||
monotonic=lambda: now[0],
|
||||
)
|
||||
request = service.HostRequest(
|
||||
"12345678", "FEDCBA9876543210", "cpu-temp"
|
||||
)
|
||||
matching = service.HostClaim(
|
||||
request.request_id, request.request_nonce, "1111222233334444"
|
||||
)
|
||||
wrong = service.HostClaim(
|
||||
request.request_id, request.request_nonce, "9999888877776666"
|
||||
)
|
||||
with mock.patch.object(
|
||||
service, "create_auth_token", return_value="signed"
|
||||
), mock.patch.object(
|
||||
service, "handle_request", return_value=service.HostResult("OK")
|
||||
) as handler:
|
||||
endpoint._handle_request(request)
|
||||
endpoint._handle_claim(wrong)
|
||||
handler.assert_not_called()
|
||||
endpoint._handle_claim(matching)
|
||||
handler.assert_called_once()
|
||||
endpoint._handle_claim(matching)
|
||||
handler.assert_called_once()
|
||||
|
||||
restarted = service.HostCliEndpoint(
|
||||
client=Client(),
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
)
|
||||
restarted._handle_claim(matching)
|
||||
handler.assert_called_once()
|
||||
|
||||
later = service.HostCliEndpoint(
|
||||
client=Client(),
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
challenge_generator=lambda: "5555666677778888",
|
||||
challenge_timeout_seconds=8.0,
|
||||
monotonic=lambda: now[0],
|
||||
)
|
||||
later._handle_request(request)
|
||||
now[0] = 19.0
|
||||
later._handle_claim(
|
||||
service.HostClaim(
|
||||
request.request_id,
|
||||
request.request_nonce,
|
||||
"5555666677778888",
|
||||
)
|
||||
)
|
||||
handler.assert_called_once()
|
||||
|
||||
def test_run_program_is_not_started_by_request_record_alone(self) -> None:
|
||||
client = mock.Mock()
|
||||
client.publish.return_value = mock.Mock(rc=0)
|
||||
programs = {
|
||||
"sample": service.ProgramDefinition(
|
||||
alias="sample",
|
||||
argv=("/usr/bin/printf", "%s"),
|
||||
arguments=(
|
||||
service.ProgramArgumentRule(
|
||||
"value", "choice", choices=("safe",)
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
endpoint = service.HostCliEndpoint(
|
||||
client=client,
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
programs=programs,
|
||||
challenge_generator=lambda: "ABCDEF0123456789",
|
||||
)
|
||||
request = service.HostRequest(
|
||||
"12345678", "FEDCBA9876543210", "run sample safe"
|
||||
)
|
||||
with mock.patch.object(
|
||||
service, "create_auth_token", return_value="signed"
|
||||
), mock.patch.object(service.subprocess, "run") as run:
|
||||
endpoint._handle_request(request)
|
||||
run.assert_not_called()
|
||||
run.return_value = mock.Mock(returncode=0, stdout="done\n")
|
||||
endpoint._handle_claim(
|
||||
service.HostClaim(
|
||||
request.request_id,
|
||||
request.request_nonce,
|
||||
"ABCDEF0123456789",
|
||||
)
|
||||
)
|
||||
run.assert_called_once()
|
||||
|
||||
def test_failed_challenge_publish_clears_pending_state(self) -> None:
|
||||
client = mock.Mock()
|
||||
client.publish.return_value = mock.Mock(rc=7)
|
||||
endpoint = service.HostCliEndpoint(
|
||||
client=client,
|
||||
repeater_public_key="44" * 32,
|
||||
service_key=service.ServiceKey(PUBLIC_KEY, PRIVATE_KEY),
|
||||
command_topic="serial/commands",
|
||||
temperature_path=Path("/unused"),
|
||||
challenge_generator=lambda: "ABCDEF0123456789",
|
||||
)
|
||||
request = service.HostRequest(
|
||||
"12345678", "FEDCBA9876543210", "cpu-temp"
|
||||
)
|
||||
with mock.patch.object(
|
||||
service, "create_auth_token", return_value="signed"
|
||||
), self.assertRaisesRegex(RuntimeError, "publish failed"):
|
||||
endpoint._handle_request(request)
|
||||
self.assertIsNone(endpoint.pending)
|
||||
self.assertEqual({}, endpoint.seen)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user