datap 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.
- btsh/__init__.py +36 -0
- btsh/__main__.py +5 -0
- btsh/audio.py +143 -0
- btsh/ble.py +147 -0
- btsh/bt.py +90 -0
- btsh/channel.py +112 -0
- btsh/channels.py +119 -0
- btsh/cli.py +528 -0
- btsh/client.py +75 -0
- btsh/codec.py +120 -0
- btsh/crypto.py +233 -0
- btsh/framing.py +96 -0
- btsh/hub.py +266 -0
- btsh/mcp.py +213 -0
- btsh/modem.py +196 -0
- btsh/node.py +190 -0
- btsh/py.typed +0 -0
- btsh/server.py +194 -0
- btsh/session.py +187 -0
- btsh/transport.py +325 -0
- datap-0.1.0.dist-info/METADATA +207 -0
- datap-0.1.0.dist-info/RECORD +25 -0
- datap-0.1.0.dist-info/WHEEL +5 -0
- datap-0.1.0.dist-info/entry_points.txt +2 -0
- datap-0.1.0.dist-info/top_level.txt +1 -0
btsh/node.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Node: a Python client that both sends requests and answers them.
|
|
2
|
+
|
|
3
|
+
A plain ``Client`` only sends. A ``Node`` is what you want for "client A runs a
|
|
4
|
+
command on client B": it registers a name, keeps a worker thread that answers
|
|
5
|
+
incoming ``exec`` requests with a local shell, and lets the caller send requests
|
|
6
|
+
to the hub or to another peer.
|
|
7
|
+
|
|
8
|
+
Everything is serialised on one thread on purpose: the acoustic link is half
|
|
9
|
+
duplex, so a node must never play and listen at the same time.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import queue
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
from . import framing
|
|
19
|
+
from .channel import Channel
|
|
20
|
+
from . import crypto
|
|
21
|
+
from .server import ShellConfig, execute
|
|
22
|
+
from .session import Session
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Node:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
channel: Channel,
|
|
29
|
+
name: str,
|
|
30
|
+
config: ShellConfig | None = None,
|
|
31
|
+
key: bytes | None = None,
|
|
32
|
+
verbose: bool = False,
|
|
33
|
+
poll: float = 0.15,
|
|
34
|
+
identity: "crypto.Identity | None" = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
self.channel = channel
|
|
37
|
+
self.session = Session(channel, key=key, identity=identity, verbose=verbose)
|
|
38
|
+
self.identity = identity
|
|
39
|
+
self.subscriptions: set[str] = set()
|
|
40
|
+
self.name = name
|
|
41
|
+
self.config = config or ShellConfig()
|
|
42
|
+
self.verbose = verbose
|
|
43
|
+
self.poll = poll
|
|
44
|
+
self.served = 0
|
|
45
|
+
self._pending: queue.Queue[tuple[dict, dict]] = queue.Queue()
|
|
46
|
+
self._stop = threading.Event()
|
|
47
|
+
self._thread: threading.Thread | None = None
|
|
48
|
+
|
|
49
|
+
# -- lifecycle -------------------------------------------------------
|
|
50
|
+
def _log(self, message: str) -> None:
|
|
51
|
+
if self.verbose:
|
|
52
|
+
print(f"[btsh node] {message}", flush=True)
|
|
53
|
+
|
|
54
|
+
def start(self) -> "Node":
|
|
55
|
+
self.session.hello(self.name)
|
|
56
|
+
self._thread = threading.Thread(target=self._loop, name=f"btsh-node-{self.name}", daemon=True)
|
|
57
|
+
self._thread.start()
|
|
58
|
+
self._log(f"registered as {self.name}")
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def stop(self) -> None:
|
|
62
|
+
self._stop.set()
|
|
63
|
+
try:
|
|
64
|
+
self.channel.send(framing.FT_BYE, b"", expect_ack=False)
|
|
65
|
+
except Exception: # noqa: BLE001
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
# -- public API ------------------------------------------------------
|
|
69
|
+
def call(self, message: dict, timeout: float = 120.0, expect: tuple[str, ...] = ()) -> dict:
|
|
70
|
+
box: dict = {}
|
|
71
|
+
done = threading.Event()
|
|
72
|
+
self._pending.put((message, {"box": box, "done": done}))
|
|
73
|
+
if not done.wait(timeout):
|
|
74
|
+
return {"op": "timeout", "error": f"no answer after {timeout}s"}
|
|
75
|
+
return box.get("answer", {"op": "error", "error": "empty answer"})
|
|
76
|
+
|
|
77
|
+
def peers(self, timeout: float = 60.0) -> list[dict]:
|
|
78
|
+
answer = self.call({"op": "peers"}, timeout=timeout)
|
|
79
|
+
return list(answer.get("peers") or [])
|
|
80
|
+
|
|
81
|
+
def exec_on(self, target: str, command: str, timeout: float = 180.0) -> dict:
|
|
82
|
+
return self.call({"op": "exec", "to": target, "cmd": command}, timeout=timeout)
|
|
83
|
+
|
|
84
|
+
def local(self, command: str) -> dict:
|
|
85
|
+
return execute(command, self.config)
|
|
86
|
+
|
|
87
|
+
# -- channels --------------------------------------------------------
|
|
88
|
+
def subscribe(self, channel: str, timeout: float = 60.0) -> dict:
|
|
89
|
+
"""Run every command published on ``channel`` on this machine."""
|
|
90
|
+
answer = self.call({"op": "sub", "channel": channel}, timeout=timeout)
|
|
91
|
+
if answer.get("op") == "subscribed":
|
|
92
|
+
self.subscriptions.add(str(answer["channel"]["channel"]))
|
|
93
|
+
return answer
|
|
94
|
+
|
|
95
|
+
def unsubscribe(self, channel: str, timeout: float = 60.0) -> dict:
|
|
96
|
+
answer = self.call({"op": "unsub", "channel": channel}, timeout=timeout)
|
|
97
|
+
if answer.get("op") == "unsubscribed":
|
|
98
|
+
self.subscriptions.discard(str(answer["channel"]["channel"]))
|
|
99
|
+
return answer
|
|
100
|
+
|
|
101
|
+
def allow(self, channel: str, peer: str, timeout: float = 60.0) -> dict:
|
|
102
|
+
return self.call({"op": "allow", "channel": channel, "peer": peer}, timeout=timeout)
|
|
103
|
+
|
|
104
|
+
def publish(self, channel: str, command: str, timeout: float = 180.0) -> dict:
|
|
105
|
+
"""Publish a command line on a channel; returns one result per subscriber."""
|
|
106
|
+
return self.call({"op": "pub", "channel": channel, "cmd": command}, timeout=timeout)
|
|
107
|
+
|
|
108
|
+
def channels(self, timeout: float = 60.0) -> list[dict]:
|
|
109
|
+
answer = self.call({"op": "channels"}, timeout=timeout)
|
|
110
|
+
return list(answer.get("channels") or [])
|
|
111
|
+
|
|
112
|
+
# -- worker ----------------------------------------------------------
|
|
113
|
+
def _loop(self) -> None:
|
|
114
|
+
while not self._stop.is_set():
|
|
115
|
+
try:
|
|
116
|
+
request, waiter = self._pending.get_nowait()
|
|
117
|
+
except queue.Empty:
|
|
118
|
+
request, waiter = None, None
|
|
119
|
+
|
|
120
|
+
if request is not None:
|
|
121
|
+
self._serve_request(request, waiter)
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
frame = self.channel.recv(self.poll)
|
|
125
|
+
if frame is None:
|
|
126
|
+
continue
|
|
127
|
+
try:
|
|
128
|
+
self._handle_frame(frame)
|
|
129
|
+
except Exception as exc: # noqa: BLE001 - never kill the node
|
|
130
|
+
self._log(f"frame error: {exc}")
|
|
131
|
+
|
|
132
|
+
def _serve_request(self, request: dict, waiter: dict) -> None:
|
|
133
|
+
answer: dict = {"op": "error", "error": "unreachable"}
|
|
134
|
+
try:
|
|
135
|
+
self.session.send_message(request)
|
|
136
|
+
answer = self._await_answer(request)
|
|
137
|
+
except Exception as exc: # noqa: BLE001
|
|
138
|
+
answer = {"op": "error", "error": str(exc)}
|
|
139
|
+
waiter["box"]["answer"] = answer
|
|
140
|
+
waiter["done"].set()
|
|
141
|
+
|
|
142
|
+
def _await_answer(self, request: dict, timeout: float = 180.0) -> dict:
|
|
143
|
+
deadline = time.monotonic() + timeout
|
|
144
|
+
while time.monotonic() < deadline:
|
|
145
|
+
frame = self.channel.recv(max(0.1, deadline - time.monotonic()))
|
|
146
|
+
if frame is None:
|
|
147
|
+
continue
|
|
148
|
+
if frame.ftype == framing.FT_HELLO:
|
|
149
|
+
self.session.answer_hello(frame)
|
|
150
|
+
continue
|
|
151
|
+
if frame.ftype != framing.FT_DATA:
|
|
152
|
+
continue
|
|
153
|
+
message = self.session.receive_from(frame, max(1.0, deadline - time.monotonic()))
|
|
154
|
+
if message is None:
|
|
155
|
+
continue
|
|
156
|
+
if message.get("op") in ("exec", "ping"):
|
|
157
|
+
self._answer_incoming(message)
|
|
158
|
+
continue
|
|
159
|
+
return message
|
|
160
|
+
return {"op": "timeout", "error": "no answer from the hub"}
|
|
161
|
+
|
|
162
|
+
def _handle_frame(self, frame: framing.Frame) -> None:
|
|
163
|
+
if frame.ftype == framing.FT_HELLO:
|
|
164
|
+
self.session.answer_hello(frame)
|
|
165
|
+
return
|
|
166
|
+
if frame.ftype == framing.FT_BYE:
|
|
167
|
+
self._stop.set()
|
|
168
|
+
return
|
|
169
|
+
if frame.ftype != framing.FT_DATA:
|
|
170
|
+
return
|
|
171
|
+
message = self.session.receive_from(frame, 60.0)
|
|
172
|
+
if message is None:
|
|
173
|
+
return
|
|
174
|
+
if message.get("op") in ("exec", "ping"):
|
|
175
|
+
self._answer_incoming(message)
|
|
176
|
+
|
|
177
|
+
def _answer_incoming(self, message: dict) -> None:
|
|
178
|
+
if message.get("op") == "ping":
|
|
179
|
+
self.session.send_message({"op": "pong", "from": self.name, "ts": int(time.time())})
|
|
180
|
+
return
|
|
181
|
+
command = str(message.get("cmd") or "")
|
|
182
|
+
self._log(f"exec from {message.get('from') or 'hub'}: {command!r}")
|
|
183
|
+
self.served += 1
|
|
184
|
+
result = execute(command, self.config)
|
|
185
|
+
result["from"] = self.name
|
|
186
|
+
if message.get("channel"):
|
|
187
|
+
result["channel"] = message["channel"]
|
|
188
|
+
if message.get("rid"):
|
|
189
|
+
result["rid"] = message["rid"]
|
|
190
|
+
self.session.send_message(result)
|
btsh/py.typed
ADDED
|
File without changes
|
btsh/server.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The shell side: execute commands locally, no sshd involved."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import subprocess
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from . import framing
|
|
13
|
+
from .session import AuthError, Session
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class ShellConfig:
|
|
18
|
+
"""What the remote side is allowed to do."""
|
|
19
|
+
|
|
20
|
+
cwd: str = "."
|
|
21
|
+
shell: str = "/bin/sh"
|
|
22
|
+
timeout: float = 20.0
|
|
23
|
+
max_output: int = 4096
|
|
24
|
+
allow: list[str] = field(default_factory=list)
|
|
25
|
+
deny: list[str] = field(default_factory=list)
|
|
26
|
+
env: dict[str, str] | None = None
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_args(cls, cwd: str | None, timeout: float, max_output: int, allow: list[str], deny: list[str]) -> "ShellConfig":
|
|
30
|
+
return cls(
|
|
31
|
+
cwd=os.path.expanduser(cwd or "."),
|
|
32
|
+
timeout=timeout,
|
|
33
|
+
max_output=max_output,
|
|
34
|
+
allow=list(allow),
|
|
35
|
+
deny=list(deny),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _check_policy(cmd: str, config: ShellConfig) -> str | None:
|
|
40
|
+
if config.allow and not any(re.search(pattern, cmd) for pattern in config.allow):
|
|
41
|
+
return f"denied by allow list: {cmd!r}"
|
|
42
|
+
for pattern in config.deny:
|
|
43
|
+
if re.search(pattern, cmd):
|
|
44
|
+
return f"denied by deny rule: {pattern!r}"
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def execute(cmd: str, config: ShellConfig) -> dict:
|
|
49
|
+
"""Run ``cmd`` through a shell and return the result as a message."""
|
|
50
|
+
started = time.monotonic()
|
|
51
|
+
refusal = _check_policy(cmd, config)
|
|
52
|
+
if refusal:
|
|
53
|
+
return {"op": "result", "cmd": cmd, "stdout": "", "stderr": refusal, "rc": 126, "truncated": False}
|
|
54
|
+
env = dict(os.environ if config.env is None else config.env)
|
|
55
|
+
env.setdefault("BTSH", "1")
|
|
56
|
+
try:
|
|
57
|
+
proc = subprocess.run(
|
|
58
|
+
cmd,
|
|
59
|
+
shell=True,
|
|
60
|
+
executable=config.shell,
|
|
61
|
+
cwd=config.cwd,
|
|
62
|
+
env=env,
|
|
63
|
+
capture_output=True,
|
|
64
|
+
text=True,
|
|
65
|
+
errors="replace",
|
|
66
|
+
timeout=config.timeout,
|
|
67
|
+
start_new_session=True,
|
|
68
|
+
)
|
|
69
|
+
stdout, stderr, rc = proc.stdout, proc.stderr, proc.returncode
|
|
70
|
+
except subprocess.TimeoutExpired as exc:
|
|
71
|
+
stdout = exc.stdout if isinstance(exc.stdout, str) else ""
|
|
72
|
+
stderr = (exc.stderr if isinstance(exc.stderr, str) else "") + f"\nbtsh: timeout after {config.timeout}s\n"
|
|
73
|
+
rc = 124
|
|
74
|
+
truncated = False
|
|
75
|
+
if len(stdout) + len(stderr) > config.max_output:
|
|
76
|
+
room = max(0, config.max_output)
|
|
77
|
+
stdout = stdout[:room]
|
|
78
|
+
stderr = stderr[: max(0, room - len(stdout))]
|
|
79
|
+
truncated = True
|
|
80
|
+
return {
|
|
81
|
+
"op": "result",
|
|
82
|
+
"cmd": cmd,
|
|
83
|
+
"stdout": stdout,
|
|
84
|
+
"stderr": stderr,
|
|
85
|
+
"rc": rc,
|
|
86
|
+
"truncated": truncated,
|
|
87
|
+
"duration_ms": int((time.monotonic() - started) * 1000),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ShellServer:
|
|
92
|
+
"""Serve shell requests until stopped."""
|
|
93
|
+
|
|
94
|
+
def __init__(self, session: Session, config: ShellConfig, verbose: bool = False) -> None:
|
|
95
|
+
self.session = session
|
|
96
|
+
self.config = config
|
|
97
|
+
self.verbose = verbose
|
|
98
|
+
self.served = 0
|
|
99
|
+
|
|
100
|
+
def _log(self, message: str) -> None:
|
|
101
|
+
if self.verbose:
|
|
102
|
+
print(f"[btsh] {message}", flush=True)
|
|
103
|
+
|
|
104
|
+
def handle(self, message: dict) -> dict | None:
|
|
105
|
+
op = message.get("op")
|
|
106
|
+
if op == "exec":
|
|
107
|
+
cmd = str(message.get("cmd", ""))
|
|
108
|
+
self._log(f"exec {cmd!r}")
|
|
109
|
+
self.served += 1
|
|
110
|
+
return execute(cmd, self.config)
|
|
111
|
+
if op == "ping":
|
|
112
|
+
return {"op": "pong", "ts": int(time.time())}
|
|
113
|
+
if op == "bye":
|
|
114
|
+
self._log("bye")
|
|
115
|
+
return {"op": "bye"}
|
|
116
|
+
return {"op": "error", "error": f"unknown op {op!r}"}
|
|
117
|
+
|
|
118
|
+
def serve_forever(self, stop=None, poll_timeout: float = 2.0) -> int:
|
|
119
|
+
"""Loop until ``stop()`` returns True (or KeyboardInterrupt)."""
|
|
120
|
+
self._log(f"listening cwd={self.config.cwd} shell={self.config.shell}")
|
|
121
|
+
while True:
|
|
122
|
+
if stop is not None and stop():
|
|
123
|
+
return self.served
|
|
124
|
+
try:
|
|
125
|
+
frame = self.session.channel.recv(poll_timeout)
|
|
126
|
+
except KeyboardInterrupt:
|
|
127
|
+
return self.served
|
|
128
|
+
except Exception as exc: # noqa: BLE001 - keep serving through link noise
|
|
129
|
+
self._log(f"link error: {exc}")
|
|
130
|
+
continue
|
|
131
|
+
if frame is None:
|
|
132
|
+
continue
|
|
133
|
+
if frame.ftype == framing.FT_HELLO:
|
|
134
|
+
try:
|
|
135
|
+
self.session.answer_hello(frame)
|
|
136
|
+
except AuthError as exc:
|
|
137
|
+
self._log(f"handshake refused: {exc}")
|
|
138
|
+
continue
|
|
139
|
+
if frame.ftype == framing.FT_BYE:
|
|
140
|
+
self._log("peer said bye")
|
|
141
|
+
return self.served
|
|
142
|
+
if frame.ftype != framing.FT_DATA:
|
|
143
|
+
continue
|
|
144
|
+
# the frame is already ACKed by the channel; reassemble the message
|
|
145
|
+
try:
|
|
146
|
+
message = self.session.receive_from(frame, self.session.channel.ack_timeout)
|
|
147
|
+
except AuthError as exc:
|
|
148
|
+
self._log(f"rejected frame: {exc}")
|
|
149
|
+
continue
|
|
150
|
+
if message is None:
|
|
151
|
+
continue
|
|
152
|
+
answer = self.handle(message)
|
|
153
|
+
if answer is None:
|
|
154
|
+
continue
|
|
155
|
+
try:
|
|
156
|
+
self.session.send_message(answer)
|
|
157
|
+
except Exception as exc: # noqa: BLE001
|
|
158
|
+
self._log(f"could not answer: {exc}")
|
|
159
|
+
if message.get("op") == "bye":
|
|
160
|
+
return self.served
|
|
161
|
+
|
|
162
|
+
def _reassemble(self, first: framing.Frame) -> dict | None:
|
|
163
|
+
"""Collect the remaining chunks of a message whose first frame arrived."""
|
|
164
|
+
from .session import MAX_BODY, TAG_LEN
|
|
165
|
+
import json
|
|
166
|
+
|
|
167
|
+
body = first.payload[TAG_LEN:]
|
|
168
|
+
if not self.session._verify(first.seq, body, first.payload[:TAG_LEN]):
|
|
169
|
+
raise AuthError(f"bad frame tag (seq {first.seq})")
|
|
170
|
+
buffer = bytearray(body)
|
|
171
|
+
if not first.flags & framing.FLAG_START:
|
|
172
|
+
return None
|
|
173
|
+
while not first.flags & framing.FLAG_END:
|
|
174
|
+
frame = self.session.channel.recv(self.session.channel.ack_timeout)
|
|
175
|
+
if frame is None:
|
|
176
|
+
return None
|
|
177
|
+
if frame.ftype != framing.FT_DATA:
|
|
178
|
+
continue
|
|
179
|
+
chunk = frame.payload[TAG_LEN:]
|
|
180
|
+
if not self.session._verify(frame.seq, chunk, frame.payload[:TAG_LEN]):
|
|
181
|
+
raise AuthError(f"bad frame tag (seq {frame.seq})")
|
|
182
|
+
if len(chunk) > MAX_BODY:
|
|
183
|
+
return None
|
|
184
|
+
buffer.extend(chunk)
|
|
185
|
+
first = frame
|
|
186
|
+
try:
|
|
187
|
+
message = json.loads(bytes(buffer))
|
|
188
|
+
except json.JSONDecodeError:
|
|
189
|
+
return None
|
|
190
|
+
return message if isinstance(message, dict) else None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def quote(cmd: str) -> str:
|
|
194
|
+
return shlex.quote(cmd)
|
btsh/session.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Session layer: authenticated JSON messages over the frame channel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from . import crypto, framing
|
|
12
|
+
from .channel import Channel
|
|
13
|
+
|
|
14
|
+
TAG_LEN = 16
|
|
15
|
+
MAX_BODY = framing.MAX_PAYLOAD - TAG_LEN
|
|
16
|
+
HELLO_CONTEXT = b"btsh-v1"
|
|
17
|
+
HELLO_MARK = b"B2"
|
|
18
|
+
SEAL_AAD = b"btsh-msg-v2"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthError(Exception):
|
|
22
|
+
"""Raised when the peer fails the pre-shared-key handshake."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _digest(key: bytes, data: bytes) -> bytes:
|
|
26
|
+
return hmac.new(key, data, hashlib.sha256).digest()[:TAG_LEN]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Session:
|
|
30
|
+
"""Chunked, optionally authenticated JSON messages.
|
|
31
|
+
|
|
32
|
+
Authentication is a pre-shared key (file contents), HMAC-SHA256, no
|
|
33
|
+
asymmetric crypto: this replaces *sshd*, not SSH's ciphers. Every DATA
|
|
34
|
+
frame carries a 16 byte tag bound to its sequence number, so a frame from
|
|
35
|
+
another session or a replay of an old frame is rejected.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
channel: Channel,
|
|
41
|
+
key: bytes | None = None,
|
|
42
|
+
identity: "crypto.Identity | None" = None,
|
|
43
|
+
verbose: bool = False,
|
|
44
|
+
) -> None:
|
|
45
|
+
self.channel = channel
|
|
46
|
+
self.key = key
|
|
47
|
+
self.identity = identity
|
|
48
|
+
self.verbose = verbose
|
|
49
|
+
self.peer_nonce = b""
|
|
50
|
+
self.peer_name = ""
|
|
51
|
+
self.peer_public = b""
|
|
52
|
+
|
|
53
|
+
# -- helpers ---------------------------------------------------------
|
|
54
|
+
def _log(self, message: str) -> None:
|
|
55
|
+
if self.verbose:
|
|
56
|
+
print(f"[btsh] {message}", flush=True)
|
|
57
|
+
|
|
58
|
+
def _tag(self, seq: int, body: bytes) -> bytes:
|
|
59
|
+
if not self.key:
|
|
60
|
+
return b"\x00" * TAG_LEN
|
|
61
|
+
return _digest(self.key, bytes([seq]) + body)
|
|
62
|
+
|
|
63
|
+
def _verify(self, seq: int, body: bytes, tag: bytes) -> bool:
|
|
64
|
+
if not self.key:
|
|
65
|
+
return True
|
|
66
|
+
return hmac.compare_digest(self._tag(seq, body), tag)
|
|
67
|
+
|
|
68
|
+
# -- handshake -------------------------------------------------------
|
|
69
|
+
@property
|
|
70
|
+
def sealed(self) -> bool:
|
|
71
|
+
"""True when messages to this peer are encrypted end to end per hop."""
|
|
72
|
+
return bool(self.identity is not None and len(self.peer_public) == 32)
|
|
73
|
+
|
|
74
|
+
def hello(self, name: str | None = None) -> None:
|
|
75
|
+
"""Client side handshake: nonce, optional public key, optional name."""
|
|
76
|
+
nonce = os.urandom(16)
|
|
77
|
+
public = self.identity.public if self.identity is not None else b""
|
|
78
|
+
self.channel.send(framing.FT_HELLO, HELLO_MARK + nonce + public + (name.encode() if name else b""))
|
|
79
|
+
deadline = time.monotonic() + self.channel.ack_timeout * 2
|
|
80
|
+
while time.monotonic() < deadline:
|
|
81
|
+
frame = self.channel.recv(max(0.1, deadline - time.monotonic()))
|
|
82
|
+
if frame is None or frame.ftype != framing.FT_HELLO_ACK:
|
|
83
|
+
continue
|
|
84
|
+
payload = frame.payload
|
|
85
|
+
if payload.startswith(HELLO_MARK) and len(payload) >= 16 + 2 + 16:
|
|
86
|
+
payload = payload[2:]
|
|
87
|
+
if len(payload) >= 64:
|
|
88
|
+
self.peer_public = payload[32:64]
|
|
89
|
+
if len(payload) < 32:
|
|
90
|
+
raise AuthError("malformed HELLO_ACK")
|
|
91
|
+
server_nonce, tag = payload[:16], payload[16:32]
|
|
92
|
+
expected = _digest(self.key, HELLO_CONTEXT + nonce + server_nonce) if self.key else b"\x00" * TAG_LEN
|
|
93
|
+
if not hmac.compare_digest(tag, expected):
|
|
94
|
+
raise AuthError("bad pre-shared key")
|
|
95
|
+
self.peer_nonce = server_nonce
|
|
96
|
+
self._log(f"handshake ok (peer nonce {server_nonce.hex()[:8]})")
|
|
97
|
+
return
|
|
98
|
+
raise AuthError("no HELLO_ACK from peer")
|
|
99
|
+
|
|
100
|
+
def answer_hello(self, frame: framing.Frame) -> None:
|
|
101
|
+
"""Server side of the handshake."""
|
|
102
|
+
payload = frame.payload
|
|
103
|
+
if payload.startswith(HELLO_MARK):
|
|
104
|
+
payload = payload[2:]
|
|
105
|
+
client_nonce = payload[:16]
|
|
106
|
+
client_public = payload[16:48] if len(payload) >= 48 else b""
|
|
107
|
+
self.peer_name = payload[48:].decode("utf-8", "replace").strip()
|
|
108
|
+
else: # legacy payload: nonce + name
|
|
109
|
+
client_nonce = payload[:16]
|
|
110
|
+
client_public = b""
|
|
111
|
+
self.peer_name = payload[16:].decode("utf-8", "replace").strip()
|
|
112
|
+
self.peer_public = client_public if len(client_public) == 32 else b""
|
|
113
|
+
nonce = os.urandom(16)
|
|
114
|
+
tag = _digest(self.key, HELLO_CONTEXT + client_nonce + nonce) if self.key else b"\x00" * TAG_LEN
|
|
115
|
+
public = self.identity.public if self.identity is not None else b""
|
|
116
|
+
self.channel.send(framing.FT_HELLO_ACK, HELLO_MARK + nonce + tag + public, expect_ack=False)
|
|
117
|
+
self.peer_nonce = client_nonce
|
|
118
|
+
|
|
119
|
+
# -- messages --------------------------------------------------------
|
|
120
|
+
def _encode(self, obj: dict) -> bytes:
|
|
121
|
+
body = json.dumps(obj, separators=(",", ":")).encode()
|
|
122
|
+
if self.sealed:
|
|
123
|
+
box = crypto.seal(self.peer_public, body, SEAL_AAD)
|
|
124
|
+
body = json.dumps({"s": crypto.b64encode(box)}, separators=(",", ":")).encode()
|
|
125
|
+
return body
|
|
126
|
+
|
|
127
|
+
def send_message(self, obj: dict) -> None:
|
|
128
|
+
body = self._encode(obj)
|
|
129
|
+
chunks = [body[i : i + MAX_BODY] for i in range(0, len(body), MAX_BODY)] or [b""]
|
|
130
|
+
for index, chunk in enumerate(chunks):
|
|
131
|
+
seq = (self.channel.seq + 1) & 0xFF
|
|
132
|
+
flags = 0
|
|
133
|
+
if index == 0:
|
|
134
|
+
flags |= framing.FLAG_START
|
|
135
|
+
if index == len(chunks) - 1:
|
|
136
|
+
flags |= framing.FLAG_END
|
|
137
|
+
self.channel.send(framing.FT_DATA, self._tag(seq, chunk) + chunk, flags=flags, seq=seq)
|
|
138
|
+
|
|
139
|
+
def recv_message(self, timeout: float = 10.0) -> dict | None:
|
|
140
|
+
deadline = time.monotonic() + timeout
|
|
141
|
+
while time.monotonic() < deadline:
|
|
142
|
+
frame = self.channel.recv(max(0.1, deadline - time.monotonic()))
|
|
143
|
+
if frame is None:
|
|
144
|
+
continue
|
|
145
|
+
if frame.ftype != framing.FT_DATA:
|
|
146
|
+
self._log(f"ignore {frame.type_name}")
|
|
147
|
+
continue
|
|
148
|
+
return self.receive_from(frame, max(0.1, deadline - time.monotonic()))
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
def receive_from(self, first: framing.Frame, timeout: float = 10.0) -> dict | None:
|
|
152
|
+
"""Reassemble one message starting at ``first`` (already ACKed)."""
|
|
153
|
+
if not first.flags & framing.FLAG_START:
|
|
154
|
+
return None
|
|
155
|
+
deadline = time.monotonic() + timeout
|
|
156
|
+
body = first.payload[TAG_LEN:]
|
|
157
|
+
if not self._verify(first.seq, body, first.payload[:TAG_LEN]):
|
|
158
|
+
raise AuthError(f"bad frame tag (seq {first.seq})")
|
|
159
|
+
buffer = bytearray(body)
|
|
160
|
+
frame = first
|
|
161
|
+
while not frame.flags & framing.FLAG_END:
|
|
162
|
+
frame = self.channel.recv(max(0.1, deadline - time.monotonic()))
|
|
163
|
+
if frame is None:
|
|
164
|
+
return None
|
|
165
|
+
if frame.ftype != framing.FT_DATA:
|
|
166
|
+
continue
|
|
167
|
+
chunk = frame.payload[TAG_LEN:]
|
|
168
|
+
if not self._verify(frame.seq, chunk, frame.payload[:TAG_LEN]):
|
|
169
|
+
raise AuthError(f"bad frame tag (seq {frame.seq})")
|
|
170
|
+
buffer.extend(chunk)
|
|
171
|
+
try:
|
|
172
|
+
message = json.loads(bytes(buffer))
|
|
173
|
+
except json.JSONDecodeError as exc:
|
|
174
|
+
raise ValueError(f"peer sent invalid json: {exc}") from exc
|
|
175
|
+
if not isinstance(message, dict):
|
|
176
|
+
raise ValueError("peer sent a non-object message")
|
|
177
|
+
if "s" in message:
|
|
178
|
+
if self.identity is None:
|
|
179
|
+
raise AuthError("peer sealed a message but no identity is configured")
|
|
180
|
+
try:
|
|
181
|
+
inner = crypto.open_sealed(self.identity, crypto.b64decode(message["s"]), SEAL_AAD)
|
|
182
|
+
except crypto.CryptoError as exc:
|
|
183
|
+
raise AuthError(f"cannot open sealed message: {exc}") from exc
|
|
184
|
+
message = json.loads(inner)
|
|
185
|
+
if not isinstance(message, dict):
|
|
186
|
+
raise ValueError("sealed payload is not an object")
|
|
187
|
+
return message
|