lanpair 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.
- lanpair/__init__.py +23 -0
- lanpair/envelope.py +271 -0
- lanpair/identity.py +97 -0
- lanpair/py.typed +0 -0
- lanpair-0.1.0.dist-info/METADATA +195 -0
- lanpair-0.1.0.dist-info/RECORD +8 -0
- lanpair-0.1.0.dist-info/WHEEL +4 -0
- lanpair-0.1.0.dist-info/licenses/LICENSE +21 -0
lanpair/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Secure pairing and signed messaging between devices on the same LAN."""
|
|
2
|
+
|
|
3
|
+
from .envelope import (
|
|
4
|
+
EnvelopeError,
|
|
5
|
+
JsonFileSeqStore,
|
|
6
|
+
MemorySeqStore,
|
|
7
|
+
Opener,
|
|
8
|
+
Sealer,
|
|
9
|
+
SeqStore,
|
|
10
|
+
)
|
|
11
|
+
from .identity import Identity, PublicIdentity
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"EnvelopeError",
|
|
15
|
+
"Identity",
|
|
16
|
+
"JsonFileSeqStore",
|
|
17
|
+
"MemorySeqStore",
|
|
18
|
+
"Opener",
|
|
19
|
+
"PublicIdentity",
|
|
20
|
+
"Sealer",
|
|
21
|
+
"SeqStore",
|
|
22
|
+
]
|
|
23
|
+
__version__ = "0.1.0"
|
lanpair/envelope.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""Encrypted, signed message envelopes bound to a recipient, with replay protection.
|
|
2
|
+
|
|
3
|
+
Bodies are encrypted to the recipient (X25519 with a fresh key per message, HKDF-SHA256,
|
|
4
|
+
ChaCha20-Poly1305), so they cannot be read on the LAN. The ciphertext is bound to the
|
|
5
|
+
header as associated data, and the signature covers version, sender, recipient,
|
|
6
|
+
timestamp, sequence number and ciphertext, so a message meant for one device cannot be
|
|
7
|
+
redirected to another, and a recorded message cannot be played back later, also not
|
|
8
|
+
after either side restarts:
|
|
9
|
+
|
|
10
|
+
- The sender's sequence numbers start from the current time in microseconds, so they
|
|
11
|
+
keep increasing across restarts without the sender storing anything.
|
|
12
|
+
- The receiver keeps the last sequence number it accepted from each peer in a
|
|
13
|
+
``SeqStore``. With a persistent store (``JsonFileSeqStore``) nothing recorded before a
|
|
14
|
+
restart can be replayed after it. With the default in-memory store, the receiver
|
|
15
|
+
instead refuses every message stamped earlier than ``max_skew`` after it started, so
|
|
16
|
+
nothing sent before the restart is accepted again; that costs one ``max_skew`` window
|
|
17
|
+
of messages after each start.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import base64
|
|
23
|
+
import json
|
|
24
|
+
import math
|
|
25
|
+
import os
|
|
26
|
+
import tempfile
|
|
27
|
+
import threading
|
|
28
|
+
import time
|
|
29
|
+
from collections.abc import Callable
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any, Protocol
|
|
33
|
+
|
|
34
|
+
from cryptography.exceptions import InvalidTag
|
|
35
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
36
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
|
37
|
+
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
|
38
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
39
|
+
|
|
40
|
+
from .identity import Identity, PublicIdentity
|
|
41
|
+
|
|
42
|
+
VERSION = 2
|
|
43
|
+
DEFAULT_MAX_SKEW = 30.0 # seconds
|
|
44
|
+
_NONCE = bytes(12) # every message has its own key, so a fixed nonce is safe
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class EnvelopeError(Exception):
|
|
48
|
+
"""Raised when an incoming envelope must be rejected."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SeqStore(Protocol):
|
|
52
|
+
"""Where a receiver keeps the last accepted sequence number per peer."""
|
|
53
|
+
|
|
54
|
+
persistent: bool
|
|
55
|
+
|
|
56
|
+
def get(self, device_id: str) -> int: ...
|
|
57
|
+
def set(self, device_id: str, seq: int) -> None: ...
|
|
58
|
+
def forget(self, device_id: str) -> None: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class MemorySeqStore:
|
|
62
|
+
"""Forgets everything on restart; ``Opener`` compensates with a start-up window."""
|
|
63
|
+
|
|
64
|
+
persistent = False
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self._seqs: dict[str, int] = {}
|
|
68
|
+
|
|
69
|
+
def get(self, device_id: str) -> int:
|
|
70
|
+
return self._seqs.get(device_id, 0)
|
|
71
|
+
|
|
72
|
+
def set(self, device_id: str, seq: int) -> None:
|
|
73
|
+
self._seqs[device_id] = seq
|
|
74
|
+
|
|
75
|
+
def forget(self, device_id: str) -> None:
|
|
76
|
+
self._seqs.pop(device_id, None)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class JsonFileSeqStore:
|
|
80
|
+
"""Keeps sequence numbers in a JSON file, written atomically on every change."""
|
|
81
|
+
|
|
82
|
+
persistent = True
|
|
83
|
+
|
|
84
|
+
def __init__(self, path: str | os.PathLike[str]) -> None:
|
|
85
|
+
self._path = Path(path)
|
|
86
|
+
self._lock = threading.Lock()
|
|
87
|
+
try:
|
|
88
|
+
data = json.loads(self._path.read_text(encoding="utf-8"))
|
|
89
|
+
except FileNotFoundError:
|
|
90
|
+
data = {}
|
|
91
|
+
if not isinstance(data, dict) or not all(
|
|
92
|
+
isinstance(k, str) and type(v) is int for k, v in data.items()
|
|
93
|
+
):
|
|
94
|
+
raise ValueError(f"{self._path} is not a lanpair sequence file")
|
|
95
|
+
self._seqs: dict[str, int] = data
|
|
96
|
+
|
|
97
|
+
def get(self, device_id: str) -> int:
|
|
98
|
+
return self._seqs.get(device_id, 0)
|
|
99
|
+
|
|
100
|
+
def set(self, device_id: str, seq: int) -> None:
|
|
101
|
+
with self._lock:
|
|
102
|
+
self._seqs[device_id] = seq
|
|
103
|
+
self._write()
|
|
104
|
+
|
|
105
|
+
def forget(self, device_id: str) -> None:
|
|
106
|
+
with self._lock:
|
|
107
|
+
if self._seqs.pop(device_id, None) is not None:
|
|
108
|
+
self._write()
|
|
109
|
+
|
|
110
|
+
def _write(self) -> None:
|
|
111
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
fd, tmp = tempfile.mkstemp(dir=self._path.parent, prefix=".lanpair-seq-")
|
|
113
|
+
try:
|
|
114
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
115
|
+
json.dump(self._seqs, f)
|
|
116
|
+
f.flush()
|
|
117
|
+
os.fsync(f.fileno())
|
|
118
|
+
os.replace(tmp, self._path)
|
|
119
|
+
except BaseException:
|
|
120
|
+
Path(tmp).unlink(missing_ok=True)
|
|
121
|
+
raise
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _canonical(fields: dict[str, Any]) -> bytes:
|
|
125
|
+
return json.dumps(
|
|
126
|
+
fields, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
127
|
+
).encode()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _signed_fields(
|
|
131
|
+
sender: str, recipient: str, ts: float, seq: int, eph: str, ct: str
|
|
132
|
+
) -> dict[str, Any]:
|
|
133
|
+
return {
|
|
134
|
+
"v": VERSION,
|
|
135
|
+
"from": sender,
|
|
136
|
+
"to": recipient,
|
|
137
|
+
"ts": ts,
|
|
138
|
+
"seq": seq,
|
|
139
|
+
"eph": eph,
|
|
140
|
+
"ct": ct,
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _body_key(shared: bytes, eph_pub: bytes, recipient_box: bytes) -> bytes:
|
|
145
|
+
hkdf = HKDF(hashes.SHA256(), 32, salt=eph_pub + recipient_box, info=b"lanpair body v2")
|
|
146
|
+
return hkdf.derive(shared)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _header(fields: dict[str, Any]) -> bytes:
|
|
150
|
+
"""Everything except the ciphertext, used as AEAD associated data."""
|
|
151
|
+
return _canonical({k: v for k, v in fields.items() if k != "ct"})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _b64(data: bytes) -> str:
|
|
155
|
+
return base64.b64encode(data).decode()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass
|
|
159
|
+
class Sealer:
|
|
160
|
+
"""Signs outgoing messages. One sealer can serve every recipient."""
|
|
161
|
+
|
|
162
|
+
identity: Identity
|
|
163
|
+
clock: Callable[[], float] = time.time
|
|
164
|
+
_seq: int = 0
|
|
165
|
+
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
166
|
+
|
|
167
|
+
def _next_seq(self) -> int:
|
|
168
|
+
# Microseconds since the epoch, or one more than the last: increases across restarts.
|
|
169
|
+
with self._lock:
|
|
170
|
+
self._seq = max(self._seq + 1, int(self.clock() * 1_000_000))
|
|
171
|
+
return self._seq
|
|
172
|
+
|
|
173
|
+
def seal(self, recipient: PublicIdentity, body: Any) -> bytes:
|
|
174
|
+
plaintext = _canonical({"body": body})
|
|
175
|
+
eph = X25519PrivateKey.generate()
|
|
176
|
+
eph_pub = eph.public_key().public_bytes(
|
|
177
|
+
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
|
178
|
+
)
|
|
179
|
+
shared = eph.exchange(X25519PublicKey.from_public_bytes(recipient.box_key))
|
|
180
|
+
key = _body_key(shared, eph_pub, recipient.box_key)
|
|
181
|
+
fields = _signed_fields(
|
|
182
|
+
self.identity.public.device_id,
|
|
183
|
+
recipient.device_id,
|
|
184
|
+
self.clock(),
|
|
185
|
+
self._next_seq(),
|
|
186
|
+
_b64(eph_pub),
|
|
187
|
+
"",
|
|
188
|
+
)
|
|
189
|
+
fields["ct"] = _b64(ChaCha20Poly1305(key).encrypt(_NONCE, plaintext, _header(fields)))
|
|
190
|
+
sig = self.identity.sign(_canonical(fields))
|
|
191
|
+
return _canonical({**fields, "sig": _b64(sig)})
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class Opener:
|
|
196
|
+
"""Verifies and decrypts incoming messages for this device against paired peers."""
|
|
197
|
+
|
|
198
|
+
me: Identity
|
|
199
|
+
peers: dict[str, PublicIdentity] = field(default_factory=dict)
|
|
200
|
+
clock: Callable[[], float] = time.time
|
|
201
|
+
max_skew: float = DEFAULT_MAX_SKEW
|
|
202
|
+
store: SeqStore = field(default_factory=MemorySeqStore)
|
|
203
|
+
_started: float = field(init=False)
|
|
204
|
+
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
205
|
+
|
|
206
|
+
def __post_init__(self) -> None:
|
|
207
|
+
self._started = self.clock()
|
|
208
|
+
|
|
209
|
+
def add_peer(self, peer: PublicIdentity) -> None:
|
|
210
|
+
self.peers[peer.device_id] = peer
|
|
211
|
+
|
|
212
|
+
def remove_peer(self, device_id: str) -> None:
|
|
213
|
+
self.peers.pop(device_id, None)
|
|
214
|
+
self.store.forget(device_id)
|
|
215
|
+
|
|
216
|
+
def open(self, raw: bytes) -> tuple[PublicIdentity, Any]:
|
|
217
|
+
try:
|
|
218
|
+
msg = json.loads(raw)
|
|
219
|
+
sig = base64.b64decode(msg.pop("sig"), validate=True)
|
|
220
|
+
fields = _signed_fields(
|
|
221
|
+
msg["from"], msg["to"], msg["ts"], msg["seq"], msg["eph"], msg["ct"]
|
|
222
|
+
)
|
|
223
|
+
except (ValueError, KeyError, TypeError, AttributeError) as e:
|
|
224
|
+
raise EnvelopeError("malformed envelope") from e
|
|
225
|
+
if msg.get("v") != VERSION or set(msg) != set(fields):
|
|
226
|
+
raise EnvelopeError("unsupported envelope")
|
|
227
|
+
sender, recipient, ts, seq = fields["from"], fields["to"], fields["ts"], fields["seq"]
|
|
228
|
+
if not (
|
|
229
|
+
isinstance(sender, str)
|
|
230
|
+
and isinstance(recipient, str)
|
|
231
|
+
and isinstance(fields["eph"], str)
|
|
232
|
+
and isinstance(fields["ct"], str)
|
|
233
|
+
and type(seq) is int
|
|
234
|
+
and type(ts) in (int, float)
|
|
235
|
+
and math.isfinite(ts)
|
|
236
|
+
):
|
|
237
|
+
raise EnvelopeError("malformed envelope")
|
|
238
|
+
|
|
239
|
+
peer = self.peers.get(sender)
|
|
240
|
+
if peer is None:
|
|
241
|
+
raise EnvelopeError("unknown sender")
|
|
242
|
+
try:
|
|
243
|
+
signed = _canonical(fields)
|
|
244
|
+
except ValueError as e:
|
|
245
|
+
raise EnvelopeError("malformed envelope") from e
|
|
246
|
+
if not peer.verify(signed, sig):
|
|
247
|
+
raise EnvelopeError("bad signature")
|
|
248
|
+
if recipient != self.me.public.device_id:
|
|
249
|
+
raise EnvelopeError("not addressed to this device")
|
|
250
|
+
now = self.clock()
|
|
251
|
+
if abs(now - ts) > self.max_skew:
|
|
252
|
+
raise EnvelopeError("stale or future timestamp")
|
|
253
|
+
if not self.store.persistent and ts < self._started + self.max_skew:
|
|
254
|
+
raise EnvelopeError("sent before this receiver started")
|
|
255
|
+
with self._lock:
|
|
256
|
+
if seq <= self.store.get(peer.device_id):
|
|
257
|
+
raise EnvelopeError("replayed message")
|
|
258
|
+
body = self._decrypt(fields)
|
|
259
|
+
self.store.set(peer.device_id, seq)
|
|
260
|
+
return peer, body
|
|
261
|
+
|
|
262
|
+
def _decrypt(self, fields: dict[str, Any]) -> Any:
|
|
263
|
+
try:
|
|
264
|
+
eph_pub = base64.b64decode(fields["eph"], validate=True)
|
|
265
|
+
ct = base64.b64decode(fields["ct"], validate=True)
|
|
266
|
+
box = self.me.public.box_key
|
|
267
|
+
key = _body_key(self.me.exchange(eph_pub), eph_pub, box)
|
|
268
|
+
plaintext = ChaCha20Poly1305(key).decrypt(_NONCE, ct, _header(fields))
|
|
269
|
+
return json.loads(plaintext)["body"]
|
|
270
|
+
except (ValueError, KeyError, TypeError, InvalidTag) as e:
|
|
271
|
+
raise EnvelopeError("cannot decrypt") from e
|
lanpair/identity.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""A device's long-term identity: an Ed25519 signing key and an X25519 encryption key.
|
|
2
|
+
|
|
3
|
+
Both keys come from one 32-byte seed, so storing the seed is enough to restore the device.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from cryptography.exceptions import InvalidSignature
|
|
13
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
|
16
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
17
|
+
|
|
18
|
+
_RAW = serialization.Encoding.Raw
|
|
19
|
+
_PUB = serialization.PublicFormat.Raw
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class PublicIdentity:
|
|
24
|
+
"""Another device's public keys. Safe to share and store."""
|
|
25
|
+
|
|
26
|
+
key: bytes
|
|
27
|
+
"""Ed25519 public key, for verifying signatures."""
|
|
28
|
+
box_key: bytes
|
|
29
|
+
"""X25519 public key, for encrypting messages to this device."""
|
|
30
|
+
|
|
31
|
+
def __post_init__(self) -> None:
|
|
32
|
+
if len(self.key) != 32 or len(self.box_key) != 32:
|
|
33
|
+
raise ValueError("lanpair public keys are 32 bytes each")
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def device_id(self) -> str:
|
|
37
|
+
"""Stable short id derived from the signing key."""
|
|
38
|
+
return hashlib.sha256(self.key).hexdigest()[:16]
|
|
39
|
+
|
|
40
|
+
def to_bytes(self) -> bytes:
|
|
41
|
+
"""64 bytes: signing key, then encryption key. Use this for QR codes and storage."""
|
|
42
|
+
return self.key + self.box_key
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_bytes(cls, raw: bytes) -> PublicIdentity:
|
|
46
|
+
if len(raw) != 64:
|
|
47
|
+
raise ValueError("a lanpair public identity is 64 bytes")
|
|
48
|
+
return cls(raw[:32], raw[32:])
|
|
49
|
+
|
|
50
|
+
def verify(self, data: bytes, signature: bytes) -> bool:
|
|
51
|
+
try:
|
|
52
|
+
Ed25519PublicKey.from_public_bytes(self.key).verify(signature, data)
|
|
53
|
+
except (InvalidSignature, ValueError):
|
|
54
|
+
return False
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Identity:
|
|
59
|
+
"""This device's key pair. The private keys never leave the process."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, seed: bytes) -> None:
|
|
62
|
+
if len(seed) != 32:
|
|
63
|
+
raise ValueError("a lanpair seed is 32 bytes")
|
|
64
|
+
self._seed = bytes(seed)
|
|
65
|
+
self._key = Ed25519PrivateKey.from_private_bytes(self._seed)
|
|
66
|
+
box_seed = HKDF(hashes.SHA256(), 32, salt=None, info=b"lanpair x25519 v1").derive(seed)
|
|
67
|
+
self._box = X25519PrivateKey.from_private_bytes(box_seed)
|
|
68
|
+
self._public = PublicIdentity(
|
|
69
|
+
self._key.public_key().public_bytes(_RAW, _PUB),
|
|
70
|
+
self._box.public_key().public_bytes(_RAW, _PUB),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def generate(cls) -> Identity:
|
|
75
|
+
return cls(os.urandom(32))
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def from_seed(cls, seed: bytes) -> Identity:
|
|
79
|
+
return cls(seed)
|
|
80
|
+
|
|
81
|
+
def seed(self) -> bytes:
|
|
82
|
+
"""Raw 32-byte private seed, for handing to a secure key store."""
|
|
83
|
+
return self._seed
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def public(self) -> PublicIdentity:
|
|
87
|
+
return self._public
|
|
88
|
+
|
|
89
|
+
def sign(self, data: bytes) -> bytes:
|
|
90
|
+
return self._key.sign(data)
|
|
91
|
+
|
|
92
|
+
def exchange(self, peer_box_key: bytes) -> bytes:
|
|
93
|
+
"""X25519 shared secret with another public encryption key."""
|
|
94
|
+
return self._box.exchange(X25519PublicKey.from_public_bytes(peer_box_key))
|
|
95
|
+
|
|
96
|
+
def __repr__(self) -> str: # never leak the key in logs
|
|
97
|
+
return f"Identity(device_id={self.public.device_id!r})"
|
lanpair/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lanpair
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Secure pairing and signed messaging between devices on the same LAN
|
|
5
|
+
Project-URL: Homepage, https://github.com/TonyD365/lanpair
|
|
6
|
+
Author: TonyD365
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Security :: Cryptography
|
|
12
|
+
Classifier: Topic :: System :: Networking
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: cryptography>=50.0.2
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: mypy>=2.4.1; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest>=9.2.0; extra == 'dev'
|
|
19
|
+
Requires-Dist: ruff>=0.17.5; extra == 'dev'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<img src="https://raw.githubusercontent.com/TonyD365/lanpair/main/docs/assets/banner.svg" alt="lanpair: pair once, then every message is signed, encrypted and replay-proof on your LAN" width="760">
|
|
24
|
+
</p>
|
|
25
|
+
|
|
26
|
+
<p align="center">
|
|
27
|
+
<a href="https://github.com/TonyD365/lanpair/actions/workflows/ci.yml"><img src="https://github.com/TonyD365/lanpair/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
28
|
+
<a href="https://github.com/TonyD365/lanpair/actions/workflows/security.yml"><img src="https://github.com/TonyD365/lanpair/actions/workflows/security.yml/badge.svg" alt="Security"></a>
|
|
29
|
+
<a href="https://scorecard.dev/viewer/?uri=github.com/TonyD365/lanpair"><img src="https://api.scorecard.dev/projects/github.com/TonyD365/lanpair/badge" alt="OpenSSF Scorecard"></a>
|
|
30
|
+
<img src="https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue" alt="Python 3.10 to 3.13">
|
|
31
|
+
<img src="https://img.shields.io/badge/typed-mypy%20strict-informational" alt="Typed, mypy strict">
|
|
32
|
+
<a href="https://github.com/TonyD365/lanpair/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT"></a>
|
|
33
|
+
</p>
|
|
34
|
+
|
|
35
|
+
<p align="center">
|
|
36
|
+
<b>Secure device pairing and messaging for the local network, in a few lines of Python.</b>
|
|
37
|
+
</p>
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
You have a desk PC and ten room PCs. Or a Raspberry Pi and a phone. Or a game host and its
|
|
42
|
+
controllers. They sit on the same Wi-Fi, and you want one to send commands to the other.
|
|
43
|
+
|
|
44
|
+
The usual answer is an HTTP endpoint or a UDP broadcast with **no authentication at all**:
|
|
45
|
+
anyone on the network can read the traffic, send "unlock" themselves, or record a command
|
|
46
|
+
and play it back tomorrow. Doing it properly means TLS certificates, key exchange, nonce
|
|
47
|
+
handling and replay windows: a week of security work for a side feature.
|
|
48
|
+
|
|
49
|
+
**lanpair** is that week of work, packaged. Devices pair once, then every message is
|
|
50
|
+
encrypted to its recipient, signed by its sender and checked for replay before your code
|
|
51
|
+
ever sees it.
|
|
52
|
+
|
|
53
|
+
> **Status: early development (0.x).** The cryptographic core works and is tested;
|
|
54
|
+
> discovery, pairing and the high-level API are being built. The API may change, and there
|
|
55
|
+
> has been no external security review yet. Don't protect anything valuable with it yet.
|
|
56
|
+
|
|
57
|
+
## Contents
|
|
58
|
+
|
|
59
|
+
- [Quick look](#quick-look)
|
|
60
|
+
- [What you get](#what-you-get)
|
|
61
|
+
- [How it works](#how-it-works)
|
|
62
|
+
- [Where it's going](#where-its-going)
|
|
63
|
+
- [Compared with alternatives](#compared-with-alternatives)
|
|
64
|
+
- [Install](#install)
|
|
65
|
+
- [Contributing](#contributing)
|
|
66
|
+
|
|
67
|
+
## Quick look
|
|
68
|
+
|
|
69
|
+
The building blocks available today. You choose the transport (UDP, TCP, WebSocket,
|
|
70
|
+
anything that carries bytes); lanpair makes the bytes safe.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from lanpair import Identity, JsonFileSeqStore, Opener, Sealer
|
|
74
|
+
|
|
75
|
+
desk, room3 = Identity.generate(), Identity.generate() # one per device, keep the seed
|
|
76
|
+
|
|
77
|
+
# Pairing: each side stores the other's public identity (64 bytes, fits in a QR code).
|
|
78
|
+
# The store remembers what was already received, so replays fail even after a restart.
|
|
79
|
+
inbox = Opener(room3, store=JsonFileSeqStore("room3-seqs.json"))
|
|
80
|
+
inbox.add_peer(desk.public)
|
|
81
|
+
|
|
82
|
+
# The desk sends...
|
|
83
|
+
wire = Sealer(desk).seal(room3.public, {"type": "close", "reason": "checkout"})
|
|
84
|
+
|
|
85
|
+
# ...and room 3 receives. Anything forged, tampered, replayed, stale or meant for
|
|
86
|
+
# another device raises EnvelopeError instead.
|
|
87
|
+
peer, body = inbox.open(wire)
|
|
88
|
+
assert peer == desk.public and body["type"] == "close"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Without a store, `Opener` keeps its memory in RAM and, to stay replay-safe, refuses
|
|
92
|
+
messages for the first 30 seconds after it starts.
|
|
93
|
+
|
|
94
|
+
What an eavesdropper sees on the network: who is talking to whom and how much, nothing
|
|
95
|
+
more.
|
|
96
|
+
|
|
97
|
+
```json
|
|
98
|
+
{"ct":"m1Zq…","eph":"ZJ8v…","from":"4f1c0a9e7b2d1c33","seq":1763683200123456,
|
|
99
|
+
"sig":"Gx0k…","to":"a87e5512c0de9b41","ts":1763683200.12,"v":2}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## What you get
|
|
103
|
+
|
|
104
|
+
| Attack from someone on your LAN | What lanpair does |
|
|
105
|
+
|---|---|
|
|
106
|
+
| Reads your messages | Bodies are encrypted to the recipient (X25519 + ChaCha20-Poly1305) |
|
|
107
|
+
| Sends fake commands | Every message is signed (Ed25519); unknown or unpaired senders are dropped |
|
|
108
|
+
| Changes a message in flight | Signature and AEAD tag both fail |
|
|
109
|
+
| Redirects a message to another device | The recipient is signed in, and only it holds the decryption key |
|
|
110
|
+
| Records a message and replays it | Increasing sequence numbers, checked per peer |
|
|
111
|
+
| Replays after you restart the app | Sequence numbers survive restarts (time-based sender, persistent or start-window receiver) |
|
|
112
|
+
| Replays an old message much later | Timestamps outside ±30 s are refused |
|
|
113
|
+
| Sends junk to crash your parser | Strict validation; everything becomes `EnvelopeError` |
|
|
114
|
+
|
|
115
|
+
Also: fully typed (mypy strict), one dependency ([`cryptography`](https://cryptography.io)),
|
|
116
|
+
tested on Linux, macOS and Windows with Python 3.10 to 3.13.
|
|
117
|
+
|
|
118
|
+
## How it works
|
|
119
|
+
|
|
120
|
+
```mermaid
|
|
121
|
+
sequenceDiagram
|
|
122
|
+
participant D as Desk (sender)
|
|
123
|
+
participant N as LAN (untrusted)
|
|
124
|
+
participant R as Room 3 (receiver)
|
|
125
|
+
Note over D,R: Once: pair, each side stores the other's public keys
|
|
126
|
+
D->>D: fresh X25519 key, encrypt body to Room 3, sign header + ciphertext
|
|
127
|
+
D->>N: envelope (v, from, to, ts, seq, eph, ct, sig)
|
|
128
|
+
N->>R: maybe tampered, replayed, delayed, or for someone else
|
|
129
|
+
R->>R: known sender? signature? for me? fresh? new seq? decrypts?
|
|
130
|
+
R-->>R: only then: (peer, body) to your code
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
One 32-byte seed per device gives both its Ed25519 signing key and its X25519 encryption
|
|
134
|
+
key. The full threat model, the reasoning behind each layer, and the known limits are in
|
|
135
|
+
[docs/design.md](https://github.com/TonyD365/lanpair/blob/main/docs/design.md).
|
|
136
|
+
|
|
137
|
+
## Where it's going
|
|
138
|
+
|
|
139
|
+
The goal is a two-object API where you never touch keys:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
# Host, e.g. a front desk # Device, e.g. a room PC
|
|
143
|
+
from lanpair import Host from lanpair import Device
|
|
144
|
+
|
|
145
|
+
host = Host("Desk") dev = Device("Room 3")
|
|
146
|
+
print(host.pairing_qr()) dev.pair(scanned_code) # once
|
|
147
|
+
host.send("room-3", {"type": "close"})
|
|
148
|
+
for msg in dev.messages(): # already verified
|
|
149
|
+
handle(msg)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
| Piece | State |
|
|
153
|
+
|---|---|
|
|
154
|
+
| Identity, signed + encrypted envelopes | ✅ done |
|
|
155
|
+
| Replay protection across restarts | ✅ done |
|
|
156
|
+
| Keys in the OS key store (Keychain, Credential Manager, Secret Service) | 🔜 next |
|
|
157
|
+
| mDNS / zeroconf discovery | 🔜 |
|
|
158
|
+
| QR code pairing | 🔜 |
|
|
159
|
+
| 6-digit code pairing with a PAKE | 🔜 |
|
|
160
|
+
| `Host` / `Device` API | 🔜 |
|
|
161
|
+
| Published on PyPI | ✅ 0.1.0 |
|
|
162
|
+
|
|
163
|
+
Want to help with one of these? See the [open issues](https://github.com/TonyD365/lanpair/issues).
|
|
164
|
+
|
|
165
|
+
## Compared with alternatives
|
|
166
|
+
|
|
167
|
+
| | lanpair | Plain HTTP / UDP | Self-managed TLS | Noise / libsodium directly |
|
|
168
|
+
|---|---|---|---|---|
|
|
169
|
+
| Authenticated messages | ✅ | ❌ | ✅ | ✅ |
|
|
170
|
+
| Encrypted | ✅ | ❌ | ✅ | ✅ |
|
|
171
|
+
| Replay protection | ✅ built in | ❌ | per connection | you build it |
|
|
172
|
+
| Pairing flow (QR / code) | 🔜 built in | ❌ | you build a CA | you build it |
|
|
173
|
+
| Lines of code for you | a few | a few | many | many |
|
|
174
|
+
|
|
175
|
+
## Install
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
pip install lanpair
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Contributing
|
|
182
|
+
|
|
183
|
+
Bug reports, ideas and pull requests are welcome. Start with
|
|
184
|
+
[CONTRIBUTING.md](https://github.com/TonyD365/lanpair/blob/main/CONTRIBUTING.md). Found a security issue? Please report it privately as
|
|
185
|
+
described in [SECURITY.md](https://github.com/TonyD365/lanpair/blob/main/SECURITY.md), not in a public issue.
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
git clone https://github.com/TonyD365/lanpair && cd lanpair
|
|
189
|
+
pip install -e ".[dev]"
|
|
190
|
+
pytest && ruff check . && mypy src
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
[MIT](https://github.com/TonyD365/lanpair/blob/main/LICENSE)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
lanpair/__init__.py,sha256=XsGhIiRXYcQvd6OMdyXPgA5ulGtOHTF9hK1gT_kz9Ks,434
|
|
2
|
+
lanpair/envelope.py,sha256=vwb47GZmsxRD4zRjijLQIAUL3cNO4qbmj3C_iyaB8XQ,9965
|
|
3
|
+
lanpair/identity.py,sha256=7cA7zUG3s6eRwzLRGSbbri3CBhmWTgixGq8Dv6BXkIM,3418
|
|
4
|
+
lanpair/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
lanpair-0.1.0.dist-info/METADATA,sha256=eCymOZFkrICAjn6Ee72k9-sm4-EodgTu6JEEaaye-ss,8390
|
|
6
|
+
lanpair-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
lanpair-0.1.0.dist-info/licenses/LICENSE,sha256=KG4NeO2jajMb4-YZetjiD0TkW0nkhW-8m3Y2Vvv3hsc,1065
|
|
8
|
+
lanpair-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TonyD365
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|