feat(usb-can): add isolated adapter runtime and confirmed CAN transactions

Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent f32c7b400b
commit 8b210258ca
30 changed files with 3336 additions and 0 deletions
@@ -0,0 +1,2 @@
# Mission Core USB-CAN-FD-B profile. No port reset, bind, or channel start.
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{idVendor}=="04d8", ATTR{idProduct}=="0053", ATTR{product}=="USB CANFD DEBUG", GROUP="mission-core-usb-can", MODE="0660"
+39
View File
@@ -0,0 +1,39 @@
"""Fetch the exact reviewed SDK; never execute vendor examples."""
import hashlib
import io
import json
import urllib.request
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def fetch():
lock = json.loads((ROOT / "packaging/sdk-lock.json").read_text())
with urllib.request.urlopen(lock["url"], timeout=30) as response:
data = response.read(lock["bytes"] + 1)
if len(data) != lock["bytes"] or hashlib.sha256(data).hexdigest() != lock["sha256"]:
raise ValueError("Vendor SDK differs from the reviewed lock")
with zipfile.ZipFile(io.BytesIO(data)) as archive:
content = archive.read(lock["library_member"])
if len(content) != lock["library_bytes"] or content[:6] != b"\x7fELF\x02\x01":
raise ValueError("Expected the pinned 64-bit little-endian ELF")
target = ROOT / "build/sdk"
target.mkdir(parents=True, exist_ok=True)
(target / "libcontrolcanfd.so").write_bytes(content)
result = {
"file": "libcontrolcanfd.so",
"bytes": len(content),
"sha256": hashlib.sha256(content).hexdigest(),
"source_sha256": lock["sha256"],
}
(target / "manifest.json").write_text(json.dumps(result, indent=2) + "\n")
for name in ("controlcanfd.h", "config.h", "main.cpp"):
(target / name).write_bytes(archive.read("USB-CAN-FD-B-Linux/VMware/x86-c/" + name))
print(json.dumps(result))
if __name__ == "__main__":
fetch()
@@ -0,0 +1,7 @@
[Unit]
Description=Prepare the versioned USB-CAN-FD-B profile
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-usb-can/prepare.py
TimeoutStartSec=90
UMask=0022
@@ -0,0 +1,38 @@
[Unit]
Description=Mission Core USB-CAN-FD-B service
After=systemd-udev-settle.service
[Service]
Type=simple
User=mission-core-usb-can
Group=mission-core-node
SupplementaryGroups=mission-core-usb-can
WorkingDirectory=/usr/lib/mission-core-usb-can
ExecStart=/usr/bin/python3 -B -m runtime.server
RuntimeDirectory=mission-core-usb-can
RuntimeDirectoryMode=0750
StateDirectory=mission-core-usb-can
StateDirectoryMode=0700
UMask=0007
Restart=on-failure
RestartSec=5
NoNewPrivileges=yes
CapabilityBoundingSet=
AmbientCapabilities=
PrivateNetwork=yes
ProtectSystem=strict
ProtectHome=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
RestrictAddressFamilies=AF_UNIX AF_NETLINK
DevicePolicy=closed
DeviceAllow=char-usb_device rw
MemoryMax=512M
TasksMax=80
LogRateLimitIntervalSec=30s
LogRateLimitBurst=30
[Install]
WantedBy=multi-user.target
+17
View File
@@ -0,0 +1,17 @@
"""Checks loadability and exact ABI; does not enumerate or open USB."""
import hashlib
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from runtime.sdk import library
path = Path("/usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so")
if (
hashlib.sha256(path.read_bytes()).hexdigest()
!= "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c"
):
raise RuntimeError("Pinned USB-CAN SDK hash changed")
library(str(path))
print("USB-CAN SDK load and packed ABI verified; no hardware opened")
+50
View File
@@ -0,0 +1,50 @@
"""Immutable USB-CAN runtime included in the standard Node package."""
import hashlib
from pathlib import Path
def payload():
root = Path(__file__).resolve().parents[1]
files = [
("usr/lib/mission-core-usb-can/runtime/" + p.name, p.read_bytes(), 0o644)
for p in sorted((root / "runtime").glob("*.py"))
]
files.append(("usr/lib/mission-core-usb-can/runtime/maintenance.py",
(root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py").read_bytes(), 0o644))
for name in ("prepare.py", "native_check.py"):
files.append(
(
"usr/lib/mission-core-usb-can/" + name,
(root / "packaging" / name).read_bytes(),
0o644,
)
)
for name in ("mission-core-usb-can.service", "mission-core-node-usb-can-prepare.service"):
files.append(
("usr/lib/systemd/system/" + name, (root / "packaging" / name).read_bytes(), 0o644)
)
name = "70-mission-core-usb-can.rules"
files.append(
(
"usr/share/mission-core-node/profiles/usb-can/" + name,
(root / "packaging" / name).read_bytes(),
0o644,
)
)
data = (root / "build/sdk/libcontrolcanfd.so").read_bytes()
if (
len(data) != 235000
or hashlib.sha256(data).hexdigest()
!= "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c"
):
raise ValueError("USB-CAN SDK differs from the reviewed pin")
files.append(("usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so", data, 0o644))
files.append(
(
"usr/lib/mission-core-usb-can/sdk/source.json",
(root / "packaging/sdk-lock.json").read_bytes(),
0o644,
)
)
return files
+158
View File
@@ -0,0 +1,158 @@
"""Versioned, idempotent USB-CAN profile; no packages downloaded and no motor I/O."""
import fcntl
import hashlib
import json
import os
import platform
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from runtime.discovery import discover
def atomic(path, value):
temp = path.with_suffix(".tmp")
temp.write_text(json.dumps(value, ensure_ascii=False))
temp.replace(path)
STATE = Path("/var/lib/mission-core-node-profiles/usb-can")
def prepare():
if os.geteuid() != 0 or sys.argv[1:]:
raise RuntimeError("Fixed system profile only")
release = platform.freedesktop_os_release()
if (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != (
"ubuntu",
"24.04",
"x86_64",
):
raise RuntimeError("Ubuntu 24.04 amd64 required")
STATE.mkdir(mode=0o755, parents=True, exist_ok=True)
for directory in (STATE.parent, STATE):
info = directory.lstat()
if directory.is_symlink() or info.st_uid != 0 or info.st_mode & 0o022:
raise RuntimeError("Untrusted profile state")
lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
report_previous = (
json.loads((STATE / "preparation.json").read_text())
if (STATE / "preparation.json").exists()
else {}
)
report = {
"schema": "missioncore.node.device-preparation/v1",
"model_id": "waveshare.usb-can-fd-b",
"version": "0.2.7",
"run_id": uuid.uuid4().hex,
"started_at": time.time(),
"monotonic_started": time.monotonic(),
"state": "running",
"steps": [],
}
def publish():
atomic(STATE / "preparation.json", report)
os.chmod(STATE / "preparation.json", 0o644)
def run(name, label, args):
step = {"id": name, "label": label, "state": "running"}
report["steps"].append(step)
publish()
result = subprocess.run(
args,
capture_output=True,
timeout=45,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8"},
)
step["state"] = "complete" if result.returncode == 0 else "error"
publish()
if result.returncode:
raise RuntimeError("Не завершён этап: " + label)
try:
import pwd
try:
pwd.getpwnam("mission-core-usb-can")
except KeyError:
run(
"account",
"Подготовка доступа",
[
"/usr/sbin/adduser",
"--system",
"--group",
"--home",
"/var/lib/mission-core-usb-can",
"--no-create-home",
"--disabled-login",
"mission-core-usb-can",
],
)
run(
"native",
"Проверка USB-CAN Tool",
[
"/usr/sbin/runuser",
"-u",
"mission-core-usb-can",
"--",
"/usr/bin/python3",
"-I",
"/usr/lib/mission-core-usb-can/native_check.py",
],
)
source = Path("/usr/share/mission-core-node/profiles/usb-can/70-mission-core-usb-can.rules")
rules = source.read_bytes()
report["udev_sha256"] = hashlib.sha256(rules).hexdigest()
target = Path("/etc/udev/rules.d/70-mission-core-usb-can.rules")
if target.is_symlink():
raise RuntimeError("Untrusted udev destination")
if target.exists() and target.read_bytes() != rules:
previous = report_previous.get("udev_sha256")
if hashlib.sha256(target.read_bytes()).hexdigest() != previous:
raise RuntimeError("Существующее USB-правило изменено вне профиля; сохранено.")
target.write_bytes(rules)
target.chmod(0o644)
run("rules", "Настройка USB-доступа", ["/usr/bin/udevadm", "control", "--reload-rules"])
for i, device in enumerate(discover()):
run(
"usb" + str(i),
"Применение USB-доступа",
[
"/usr/bin/udevadm",
"trigger",
"--action=change",
"/sys/bus/usb/devices/" + device.usb,
],
)
run("settle", "Проверка USB-доступа", ["/usr/bin/udevadm", "settle", "--timeout=10"])
run(
"enable",
"Подготовка службы",
["/usr/bin/systemctl", "enable", "mission-core-usb-can.service"],
)
run(
"runtime",
"Обнаружение адаптеров",
["/usr/bin/systemctl", "restart", "mission-core-usb-can.service"],
)
report["state"] = "complete"
except (OSError, RuntimeError, subprocess.SubprocessError) as error:
report.update(state="error", message=str(error)[:300])
finally:
report["duration_seconds"] = time.monotonic() - report["monotonic_started"]
publish()
os.close(lock)
return report["state"] == "complete"
if __name__ == "__main__":
sys.exit(0 if prepare() else 1)
+16
View File
@@ -0,0 +1,16 @@
{
"schema": "missioncore.usb-can.sdk/v1",
"version": "waveshare-linux-e009c7b1740d",
"url": "https://files.waveshare.com/wiki/USB-CAN-FD/USB-CAN-FD-B-Linux.zip",
"bytes": 1326766,
"sha256": "e009c7b1740d35cda6f1f68fc699d25eb363a37c8b2f2e80609732d394142a85",
"library_member": "USB-CAN-FD-B-Linux/VMware/x86-c/libcontrolcanfd.so",
"library_bytes": 235000,
"platform": {
"os": "ubuntu",
"version": "24.04",
"architecture": "x86_64"
},
"api": "https://files.waveshare.com/wiki/USB-CAN-FD/Manual/USB-CAN-FD-B-API-Manual.pdf",
"license": "Vendor-distributed SDK; archive contains no separate open-source license."
}