fectp 0.2.1__py3-none-win_amd64.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.
- fectp/__init__.py +483 -0
- fectp/_native/fectp.dll +0 -0
- fectp-0.2.1.dist-info/METADATA +122 -0
- fectp-0.2.1.dist-info/RECORD +7 -0
- fectp-0.2.1.dist-info/WHEEL +5 -0
- fectp-0.2.1.dist-info/licenses/LICENSE +28 -0
- fectp-0.2.1.dist-info/top_level.txt +1 -0
fectp/__init__.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
"""FECTP from Python, over the C ABI in ``crates/ffi``.
|
|
2
|
+
|
|
3
|
+
This is the sans-IO session layer. It turns payloads into frames and frames
|
|
4
|
+
back into payloads, and does no I/O at all: you own the socket, the thread and
|
|
5
|
+
the event loop. That is deliberate — see ``docs/OTHER-LANGUAGES.md`` — and it
|
|
6
|
+
is why nothing here blocks, holds the GIL over a handshake, or hands you memory
|
|
7
|
+
you have to remember to free.
|
|
8
|
+
|
|
9
|
+
**Not audited.** Nothing in this project has been reviewed by someone who
|
|
10
|
+
breaks protocols for a living. Do not put it in front of an adversary yet.
|
|
11
|
+
|
|
12
|
+
``ctypes`` rather than ``cffi`` so that this is the standard library and
|
|
13
|
+
nothing else. Installed from PyPI, the shared library comes inside the wheel.
|
|
14
|
+
From a checkout it is built by cargo::
|
|
15
|
+
|
|
16
|
+
cargo build -p fectp-ffi --release
|
|
17
|
+
|
|
18
|
+
and found automatically, or named through ``FECTP_LIBRARY``.
|
|
19
|
+
|
|
20
|
+
The secret key
|
|
21
|
+
--------------
|
|
22
|
+
|
|
23
|
+
There is no way to read a private key out of an :class:`Identity`. That is not
|
|
24
|
+
an omission: bytes handed to Python cannot be wiped. ``bytes`` is immutable, so
|
|
25
|
+
nothing can overwrite it; the interpreter may copy it; and it may reach swap.
|
|
26
|
+
The C ABI does not export such a call, and this wrapper could not add one.
|
|
27
|
+
|
|
28
|
+
:func:`Identity.from_secret` exists for restoring a key you stored elsewhere.
|
|
29
|
+
Whatever you pass it is yours to erase — use a ``bytearray`` and overwrite it,
|
|
30
|
+
because a ``bytes`` cannot be.
|
|
31
|
+
|
|
32
|
+
Better still, the key never has to be in Python at all.
|
|
33
|
+
:func:`Identity.from_key` takes a public key and a function that performs the
|
|
34
|
+
Diffie-Hellman with the private half — a secure element, an HSM, a TPM, reached
|
|
35
|
+
through whatever library talks to it — and FECTP calls that function and never
|
|
36
|
+
sees the key.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import ctypes
|
|
42
|
+
import itertools
|
|
43
|
+
import os
|
|
44
|
+
import sys
|
|
45
|
+
import threading
|
|
46
|
+
from ctypes import POINTER, c_int32, c_size_t, c_ssize_t, c_ubyte, c_uint16, c_uint32, c_void_p
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from typing import Callable
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"FectpError",
|
|
52
|
+
"ProtocolError",
|
|
53
|
+
"BufferTooSmall",
|
|
54
|
+
"KeyUnavailable",
|
|
55
|
+
"Identity",
|
|
56
|
+
"Initiator",
|
|
57
|
+
"Responder",
|
|
58
|
+
"Session",
|
|
59
|
+
"KEY_LEN",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
KEY_LEN = 32
|
|
63
|
+
|
|
64
|
+
_OK = 0
|
|
65
|
+
_ERR_NULL = -1
|
|
66
|
+
_ERR_BUFFER = -2
|
|
67
|
+
_ERR_PROTOCOL = -3
|
|
68
|
+
_ERR_PANIC = -4
|
|
69
|
+
_ERR_TOO_LARGE = -5
|
|
70
|
+
_ERR_KEY = -6
|
|
71
|
+
|
|
72
|
+
# Room for a frame plus the handshake's overhead. The protocol's own limit is
|
|
73
|
+
# negotiated per session; this is the wrapper's scratch size and is generous.
|
|
74
|
+
_SCRATCH = 65535
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class FectpError(Exception):
|
|
78
|
+
"""Something the library refused."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ProtocolError(FectpError):
|
|
82
|
+
"""A frame was malformed, failed to authenticate, or arrived out of turn.
|
|
83
|
+
|
|
84
|
+
Ordinary rather than exceptional: anyone can send bytes to a socket, so a
|
|
85
|
+
frame that does not authenticate is a datagram to discard and not a fault
|
|
86
|
+
in the program. It is an exception here only because Python has no other
|
|
87
|
+
way to say "no".
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class BufferTooSmall(FectpError):
|
|
92
|
+
"""An output buffer was too small. Nothing was written to it."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class KeyUnavailable(FectpError):
|
|
96
|
+
"""The key function given to :func:`Identity.from_key` failed.
|
|
97
|
+
|
|
98
|
+
The device was busy, locked or absent, or the function raised — in which
|
|
99
|
+
case that exception is this one's ``__cause__``. The handshake it happened
|
|
100
|
+
in is over; the identity is not, and may be used again.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _Panic(FectpError):
|
|
105
|
+
"""A panic was caught inside FECTP. That is a bug in FECTP.
|
|
106
|
+
|
|
107
|
+
The handle it happened on is unusable; this is raised rather than returned
|
|
108
|
+
so it cannot be mistaken for a protocol error and retried.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _library_path() -> Path:
|
|
113
|
+
"""Where the shared library is: named, packaged, or built in a checkout."""
|
|
114
|
+
named = os.environ.get("FECTP_LIBRARY")
|
|
115
|
+
if named:
|
|
116
|
+
return Path(named)
|
|
117
|
+
|
|
118
|
+
if sys.platform == "win32":
|
|
119
|
+
name = "fectp.dll"
|
|
120
|
+
elif sys.platform == "darwin":
|
|
121
|
+
name = "libfectp.dylib"
|
|
122
|
+
else:
|
|
123
|
+
name = "libfectp.so"
|
|
124
|
+
|
|
125
|
+
# Inside an installed wheel, beside this file.
|
|
126
|
+
packaged = Path(__file__).resolve().parent / "_native" / name
|
|
127
|
+
if packaged.exists():
|
|
128
|
+
return packaged
|
|
129
|
+
|
|
130
|
+
# In a checkout: bindings/python/fectp/__init__.py, three levels below the
|
|
131
|
+
# workspace root that holds `target`.
|
|
132
|
+
root = Path(__file__).resolve().parents[3]
|
|
133
|
+
for profile in ("release", "debug"):
|
|
134
|
+
candidate = root / "target" / profile / name
|
|
135
|
+
if candidate.exists():
|
|
136
|
+
return candidate
|
|
137
|
+
raise FectpError(
|
|
138
|
+
f"{name} was not found under {root / 'target'}. Build it with "
|
|
139
|
+
"`cargo build -p fectp-ffi --release`, or set FECTP_LIBRARY to its path."
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# The two C functions every key held outside Python goes through: fixed, and
|
|
144
|
+
# alive for the life of the module. A ctypes callback object that is collected
|
|
145
|
+
# while C still holds its address is a crash at some later call, so none is
|
|
146
|
+
# made per key. Each key is a number in `_held_keys` instead, passed to C as
|
|
147
|
+
# its context and back to these.
|
|
148
|
+
_DH_FN = ctypes.CFUNCTYPE(c_int32, c_void_p, POINTER(c_ubyte), POINTER(c_ubyte))
|
|
149
|
+
_RELEASE_FN = ctypes.CFUNCTYPE(None, c_void_p)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _bind() -> ctypes.CDLL:
|
|
153
|
+
lib = ctypes.CDLL(str(_library_path()))
|
|
154
|
+
u8p = POINTER(c_ubyte)
|
|
155
|
+
|
|
156
|
+
# Every signature is declared. Without this ctypes guesses, and guesses
|
|
157
|
+
# wrong on any platform where a pointer is not an int — silently, and only
|
|
158
|
+
# some of the time.
|
|
159
|
+
lib.fectp_identity_generate.restype = c_void_p
|
|
160
|
+
lib.fectp_identity_generate.argtypes = []
|
|
161
|
+
lib.fectp_identity_from_secret.restype = c_void_p
|
|
162
|
+
lib.fectp_identity_from_secret.argtypes = [u8p]
|
|
163
|
+
lib.fectp_identity_public.restype = c_ssize_t
|
|
164
|
+
lib.fectp_identity_public.argtypes = [c_void_p, u8p]
|
|
165
|
+
lib.fectp_identity_free.restype = None
|
|
166
|
+
lib.fectp_identity_free.argtypes = [c_void_p]
|
|
167
|
+
lib.fectp_identity_from_key.restype = c_void_p
|
|
168
|
+
lib.fectp_identity_from_key.argtypes = [u8p, _DH_FN, c_void_p, _RELEASE_FN]
|
|
169
|
+
|
|
170
|
+
lib.fectp_initiator_new.restype = c_void_p
|
|
171
|
+
lib.fectp_initiator_new.argtypes = [c_void_p, u8p, c_uint32, c_uint16]
|
|
172
|
+
lib.fectp_initiator_write_init.restype = c_ssize_t
|
|
173
|
+
lib.fectp_initiator_write_init.argtypes = [c_void_p, u8p, c_size_t, u8p, c_size_t]
|
|
174
|
+
lib.fectp_initiator_read_response.restype = c_ssize_t
|
|
175
|
+
lib.fectp_initiator_read_response.argtypes = [
|
|
176
|
+
POINTER(c_void_p), u8p, c_size_t, u8p, c_size_t, POINTER(c_void_p),
|
|
177
|
+
]
|
|
178
|
+
lib.fectp_initiator_free.restype = None
|
|
179
|
+
lib.fectp_initiator_free.argtypes = [c_void_p]
|
|
180
|
+
|
|
181
|
+
lib.fectp_responder_new.restype = c_void_p
|
|
182
|
+
lib.fectp_responder_new.argtypes = [c_void_p, c_uint16]
|
|
183
|
+
lib.fectp_responder_read_init.restype = c_ssize_t
|
|
184
|
+
lib.fectp_responder_read_init.argtypes = [c_void_p, u8p, c_size_t, u8p, c_size_t]
|
|
185
|
+
lib.fectp_responder_write_response.restype = c_ssize_t
|
|
186
|
+
lib.fectp_responder_write_response.argtypes = [
|
|
187
|
+
POINTER(c_void_p), u8p, c_size_t, u8p, c_size_t, POINTER(c_void_p),
|
|
188
|
+
]
|
|
189
|
+
lib.fectp_responder_free.restype = None
|
|
190
|
+
lib.fectp_responder_free.argtypes = [c_void_p]
|
|
191
|
+
|
|
192
|
+
lib.fectp_session_seal.restype = c_ssize_t
|
|
193
|
+
lib.fectp_session_seal.argtypes = [c_void_p, u8p, c_size_t, u8p, c_size_t]
|
|
194
|
+
lib.fectp_session_open.restype = c_ssize_t
|
|
195
|
+
lib.fectp_session_open.argtypes = [c_void_p, u8p, c_size_t, u8p, c_size_t]
|
|
196
|
+
lib.fectp_session_free.restype = None
|
|
197
|
+
lib.fectp_session_free.argtypes = [c_void_p]
|
|
198
|
+
return lib
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_lib = _bind()
|
|
202
|
+
|
|
203
|
+
# Keys FECTP may still call, by the number it was given as a context. An entry
|
|
204
|
+
# leaves only when FECTP says it is done with that key — after the identity and
|
|
205
|
+
# every handshake begun from it have gone.
|
|
206
|
+
_held_keys: dict[int, Callable[[bytes], bytes]] = {}
|
|
207
|
+
_held_lock = threading.Lock()
|
|
208
|
+
_key_numbers = itertools.count(1)
|
|
209
|
+
|
|
210
|
+
# The exception a key function raised, kept per thread until the call that
|
|
211
|
+
# triggered it turns into `KeyUnavailable`. A Python exception cannot cross C;
|
|
212
|
+
# this is how it gets to the caller anyway.
|
|
213
|
+
_key_failure = threading.local()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@_DH_FN
|
|
217
|
+
def _dh_trampoline(context, peer_public, shared):
|
|
218
|
+
try:
|
|
219
|
+
with _held_lock:
|
|
220
|
+
dh = _held_keys[context]
|
|
221
|
+
result = dh(ctypes.string_at(peer_public, KEY_LEN))
|
|
222
|
+
if len(result) != KEY_LEN:
|
|
223
|
+
raise ValueError(f"a key function must return {KEY_LEN} bytes, not {len(result)}")
|
|
224
|
+
ctypes.memmove(shared, bytes(result), KEY_LEN)
|
|
225
|
+
if isinstance(result, bytearray):
|
|
226
|
+
# The one copy this wrapper can reach. A `bytes` cannot be wiped.
|
|
227
|
+
result[:] = bytes(KEY_LEN)
|
|
228
|
+
return 0
|
|
229
|
+
except BaseException as failure: # noqa: BLE001 - nothing may unwind into C
|
|
230
|
+
_key_failure.error = failure
|
|
231
|
+
return 1
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@_RELEASE_FN
|
|
235
|
+
def _release_trampoline(context):
|
|
236
|
+
with _held_lock:
|
|
237
|
+
_held_keys.pop(context, None)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _buffer(size: int = _SCRATCH):
|
|
241
|
+
return (c_ubyte * size)()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _as_input(data: bytes | bytearray | memoryview | None):
|
|
245
|
+
"""A pointer and a length for `data`, accepting nothing as an empty payload."""
|
|
246
|
+
if not data:
|
|
247
|
+
return (None, 0)
|
|
248
|
+
raw = (c_ubyte * len(data)).from_buffer_copy(bytes(data))
|
|
249
|
+
return (raw, len(raw))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _check(code: int) -> int:
|
|
253
|
+
"""Turns a negative return into the exception it stands for."""
|
|
254
|
+
if code >= 0:
|
|
255
|
+
return code
|
|
256
|
+
if code == _ERR_BUFFER:
|
|
257
|
+
raise BufferTooSmall("the output buffer was too small; nothing was written")
|
|
258
|
+
if code == _ERR_PROTOCOL:
|
|
259
|
+
raise ProtocolError("the frame was rejected: malformed, unauthentic, or out of turn")
|
|
260
|
+
if code == _ERR_NULL:
|
|
261
|
+
raise FectpError("a required argument was missing, or a handle had been consumed")
|
|
262
|
+
if code == _ERR_PANIC:
|
|
263
|
+
raise _Panic("a panic was caught inside FECTP; this handle is unusable")
|
|
264
|
+
if code == _ERR_TOO_LARGE:
|
|
265
|
+
raise FectpError("a length did not fit the platform's word size")
|
|
266
|
+
if code == _ERR_KEY:
|
|
267
|
+
cause = getattr(_key_failure, "error", None)
|
|
268
|
+
_key_failure.error = None
|
|
269
|
+
raise KeyUnavailable("the key function failed; this handshake is over") from cause
|
|
270
|
+
raise FectpError(f"unrecognised error code {code}")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class _Handle:
|
|
274
|
+
"""An owned pointer freed exactly once.
|
|
275
|
+
|
|
276
|
+
Freeing twice is the defect this class exists to make unreachable, and it
|
|
277
|
+
is the one every hand-written binding eventually has. Python's `__del__`
|
|
278
|
+
runs at a time nobody chooses, so the flag rather than the pointer is what
|
|
279
|
+
decides — a pointer set to None by one path and freed by another is the
|
|
280
|
+
same bug wearing a different hat.
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
__slots__ = ("_ptr", "_free")
|
|
284
|
+
|
|
285
|
+
def __init__(self, ptr, free):
|
|
286
|
+
if not ptr:
|
|
287
|
+
raise FectpError("FECTP refused to create the handle")
|
|
288
|
+
self._ptr = c_void_p(ptr)
|
|
289
|
+
self._free = free
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def raw(self) -> c_void_p:
|
|
293
|
+
if self._ptr is None:
|
|
294
|
+
raise FectpError("this handle has already been closed or consumed")
|
|
295
|
+
return self._ptr
|
|
296
|
+
|
|
297
|
+
def take(self) -> c_void_p:
|
|
298
|
+
"""Gives the pointer up, so something else owns it from here."""
|
|
299
|
+
ptr = self.raw
|
|
300
|
+
self._ptr = None
|
|
301
|
+
return ptr
|
|
302
|
+
|
|
303
|
+
def close(self) -> None:
|
|
304
|
+
if self._ptr is not None:
|
|
305
|
+
ptr, self._ptr = self._ptr, None
|
|
306
|
+
self._free(ptr)
|
|
307
|
+
|
|
308
|
+
def __enter__(self):
|
|
309
|
+
return self
|
|
310
|
+
|
|
311
|
+
def __exit__(self, *_exc):
|
|
312
|
+
self.close()
|
|
313
|
+
return False
|
|
314
|
+
|
|
315
|
+
def __del__(self):
|
|
316
|
+
try:
|
|
317
|
+
self.close()
|
|
318
|
+
except Exception:
|
|
319
|
+
# An interpreter shutting down may already have torn down what this
|
|
320
|
+
# needs. Raising here is never useful and hides the real exit.
|
|
321
|
+
pass
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Identity(_Handle):
|
|
325
|
+
"""A long-term X25519 identity.
|
|
326
|
+
|
|
327
|
+
There is no way to read the secret back out. See the module docstring.
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
def __init__(self, ptr):
|
|
331
|
+
super().__init__(ptr, _lib.fectp_identity_free)
|
|
332
|
+
|
|
333
|
+
@classmethod
|
|
334
|
+
def generate(cls) -> "Identity":
|
|
335
|
+
"""A fresh identity from the operating system's randomness."""
|
|
336
|
+
return cls(_lib.fectp_identity_generate())
|
|
337
|
+
|
|
338
|
+
@classmethod
|
|
339
|
+
def from_secret(cls, secret) -> "Identity":
|
|
340
|
+
"""Restores an identity from 32 stored secret bytes.
|
|
341
|
+
|
|
342
|
+
The copy FECTP makes is wiped before this returns. The object you pass
|
|
343
|
+
is yours: use a `bytearray` and overwrite it afterwards, since a
|
|
344
|
+
`bytes` cannot be.
|
|
345
|
+
"""
|
|
346
|
+
if len(secret) != KEY_LEN:
|
|
347
|
+
raise ValueError(f"a secret is {KEY_LEN} bytes, not {len(secret)}")
|
|
348
|
+
raw, _ = _as_input(secret)
|
|
349
|
+
return cls(_lib.fectp_identity_from_secret(raw))
|
|
350
|
+
|
|
351
|
+
@classmethod
|
|
352
|
+
def from_key(cls, public, dh: Callable[[bytes], bytes]) -> "Identity":
|
|
353
|
+
"""An identity whose private key FECTP never sees.
|
|
354
|
+
|
|
355
|
+
``public`` is the key's 32-byte public half. ``dh`` performs X25519 with
|
|
356
|
+
the private half: it is given the peer's 32-byte public key and returns
|
|
357
|
+
the 32-byte shared secret. It is called synchronously, on the thread that
|
|
358
|
+
drives the handshake, twice per handshake on each side.
|
|
359
|
+
|
|
360
|
+
Raising from ``dh``, or returning the wrong length, ends the handshake
|
|
361
|
+
with :class:`KeyUnavailable` carrying the original exception. Return a
|
|
362
|
+
``bytearray`` and this wrapper wipes it after copying; a ``bytes`` it
|
|
363
|
+
cannot.
|
|
364
|
+
|
|
365
|
+
``dh`` is held until FECTP says it is done with it — which may be after
|
|
366
|
+
this identity is closed, if a handshake begun from it is still running.
|
|
367
|
+
"""
|
|
368
|
+
if len(public) != KEY_LEN:
|
|
369
|
+
raise ValueError(f"a public key is {KEY_LEN} bytes, not {len(public)}")
|
|
370
|
+
if not callable(dh):
|
|
371
|
+
raise TypeError("dh must be callable")
|
|
372
|
+
number = next(_key_numbers)
|
|
373
|
+
with _held_lock:
|
|
374
|
+
_held_keys[number] = dh
|
|
375
|
+
raw, _ = _as_input(public)
|
|
376
|
+
ptr = _lib.fectp_identity_from_key(raw, _dh_trampoline, number, _release_trampoline)
|
|
377
|
+
if not ptr:
|
|
378
|
+
# Refused, so FECTP will never release it; that is ours to do.
|
|
379
|
+
with _held_lock:
|
|
380
|
+
_held_keys.pop(number, None)
|
|
381
|
+
return cls(ptr)
|
|
382
|
+
|
|
383
|
+
@property
|
|
384
|
+
def public(self) -> bytes:
|
|
385
|
+
"""The 32-byte public key, which peers need in order to reach you."""
|
|
386
|
+
out = _buffer(KEY_LEN)
|
|
387
|
+
_check(_lib.fectp_identity_public(self.raw, out))
|
|
388
|
+
return bytes(out)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class Session(_Handle):
|
|
392
|
+
"""An established session."""
|
|
393
|
+
|
|
394
|
+
def __init__(self, ptr):
|
|
395
|
+
super().__init__(ptr, _lib.fectp_session_free)
|
|
396
|
+
|
|
397
|
+
def seal(self, payload: bytes) -> bytes:
|
|
398
|
+
"""Encrypts `payload` into a frame to put on the wire."""
|
|
399
|
+
data, length = _as_input(payload)
|
|
400
|
+
out = _buffer()
|
|
401
|
+
n = _check(_lib.fectp_session_seal(self.raw, data, length, out, len(out)))
|
|
402
|
+
return bytes(out[:n])
|
|
403
|
+
|
|
404
|
+
def open(self, frame: bytes) -> bytes:
|
|
405
|
+
"""Decrypts a frame from the wire.
|
|
406
|
+
|
|
407
|
+
Raises :class:`ProtocolError` for a frame that does not authenticate,
|
|
408
|
+
which is a datagram to drop rather than a fault to report.
|
|
409
|
+
"""
|
|
410
|
+
data, length = _as_input(frame)
|
|
411
|
+
out = _buffer()
|
|
412
|
+
n = _check(_lib.fectp_session_open(self.raw, data, length, out, len(out)))
|
|
413
|
+
return bytes(out[:n])
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
class Initiator(_Handle):
|
|
417
|
+
"""The side that starts a handshake."""
|
|
418
|
+
|
|
419
|
+
def __init__(self, identity: Identity, peer_public: bytes, session_id: int, max_frame: int = 1200):
|
|
420
|
+
if len(peer_public) != KEY_LEN:
|
|
421
|
+
raise ValueError(f"a public key is {KEY_LEN} bytes, not {len(peer_public)}")
|
|
422
|
+
peer, _ = _as_input(peer_public)
|
|
423
|
+
super().__init__(
|
|
424
|
+
_lib.fectp_initiator_new(identity.raw, peer, session_id, max_frame),
|
|
425
|
+
_lib.fectp_initiator_free,
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
def write_init(self, payload: bytes = b"") -> bytes:
|
|
429
|
+
"""The opening frame, carrying `payload` inside the handshake."""
|
|
430
|
+
data, length = _as_input(payload)
|
|
431
|
+
out = _buffer()
|
|
432
|
+
n = _check(_lib.fectp_initiator_write_init(self.raw, data, length, out, len(out)))
|
|
433
|
+
return bytes(out[:n])
|
|
434
|
+
|
|
435
|
+
def read_response(self, frame: bytes) -> tuple[Session, bytes]:
|
|
436
|
+
"""Reads the reply, returning the session and any payload it carried.
|
|
437
|
+
|
|
438
|
+
**Consumes this initiator**, whether it succeeds or not: a handshake
|
|
439
|
+
cannot be retried from a half-read state. Using it again raises.
|
|
440
|
+
"""
|
|
441
|
+
slot = c_void_p(self.take().value)
|
|
442
|
+
session = c_void_p()
|
|
443
|
+
data, length = _as_input(frame)
|
|
444
|
+
out = _buffer()
|
|
445
|
+
n = _check(
|
|
446
|
+
_lib.fectp_initiator_read_response(
|
|
447
|
+
ctypes.byref(slot), data, length, out, len(out), ctypes.byref(session)
|
|
448
|
+
)
|
|
449
|
+
)
|
|
450
|
+
return Session(session.value), bytes(out[:n])
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
class Responder(_Handle):
|
|
454
|
+
"""The side that answers a handshake."""
|
|
455
|
+
|
|
456
|
+
def __init__(self, identity: Identity, max_frame: int = 1200):
|
|
457
|
+
super().__init__(
|
|
458
|
+
_lib.fectp_responder_new(identity.raw, max_frame),
|
|
459
|
+
_lib.fectp_responder_free,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
def read_init(self, frame: bytes) -> bytes:
|
|
463
|
+
"""Reads an opening frame, returning any payload it carried."""
|
|
464
|
+
data, length = _as_input(frame)
|
|
465
|
+
out = _buffer()
|
|
466
|
+
n = _check(_lib.fectp_responder_read_init(self.raw, data, length, out, len(out)))
|
|
467
|
+
return bytes(out[:n])
|
|
468
|
+
|
|
469
|
+
def write_response(self, payload: bytes = b"") -> tuple[Session, bytes]:
|
|
470
|
+
"""The reply, returning the session and the frame to send.
|
|
471
|
+
|
|
472
|
+
**Consumes this responder**, as :meth:`Initiator.read_response` does.
|
|
473
|
+
"""
|
|
474
|
+
slot = c_void_p(self.take().value)
|
|
475
|
+
session = c_void_p()
|
|
476
|
+
data, length = _as_input(payload)
|
|
477
|
+
out = _buffer()
|
|
478
|
+
n = _check(
|
|
479
|
+
_lib.fectp_responder_write_response(
|
|
480
|
+
ctypes.byref(slot), data, length, out, len(out), ctypes.byref(session)
|
|
481
|
+
)
|
|
482
|
+
)
|
|
483
|
+
return Session(session.value), bytes(out[:n])
|
fectp/_native/fectp.dll
ADDED
|
Binary file
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fectp
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: FECTP from Python: the sans-IO encrypted session layer, over its C ABI. Not security-audited.
|
|
5
|
+
License-Expression: BSD-3-Clause
|
|
6
|
+
Project-URL: Repository, https://github.com/YounghyeonPark/fectp
|
|
7
|
+
Project-URL: Documentation, https://github.com/YounghyeonPark/fectp/blob/main/bindings/python/README.md
|
|
8
|
+
Keywords: noise-protocol,udp,encryption,transport,x25519
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Security :: Cryptography
|
|
13
|
+
Classifier: Topic :: System :: Networking
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# FECTP from Python
|
|
20
|
+
|
|
21
|
+
The sans-IO session layer, over the C ABI in [`crates/ffi`](https://github.com/YounghyeonPark/fectp/tree/main/crates/ffi).
|
|
22
|
+
Payloads in, frames out, and back again — **you** own the socket, the thread
|
|
23
|
+
and the event loop.
|
|
24
|
+
|
|
25
|
+
**Not audited.** Nothing in this project has been reviewed by someone who
|
|
26
|
+
breaks protocols for a living.
|
|
27
|
+
|
|
28
|
+
## Installing
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install fectp
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Wheels for Windows x64, Linux x64 (glibc 2.28 or newer) and macOS (Apple
|
|
35
|
+
silicon and Intel), each carrying the shared library it needs — no Rust and no
|
|
36
|
+
compiler. Python 3.9 or newer. `ctypes` underneath, so nothing else is pulled
|
|
37
|
+
in.
|
|
38
|
+
|
|
39
|
+
## Running it from a checkout
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cargo build -p fectp-ffi --release
|
|
43
|
+
python3 bindings/python/test_fectp.py
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The shared library cargo just built is found under `target/`, or named through
|
|
47
|
+
`FECTP_LIBRARY`.
|
|
48
|
+
|
|
49
|
+
## What it looks like
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import fectp
|
|
53
|
+
|
|
54
|
+
server = fectp.Identity.generate()
|
|
55
|
+
client = fectp.Identity.generate()
|
|
56
|
+
|
|
57
|
+
initiator = fectp.Initiator(client, server.public, session_id=1)
|
|
58
|
+
responder = fectp.Responder(server)
|
|
59
|
+
|
|
60
|
+
opening = initiator.write_init(b"data sent with the handshake")
|
|
61
|
+
responder.read_init(opening) # -> b"data sent with the handshake"
|
|
62
|
+
|
|
63
|
+
server_session, reply = responder.write_response()
|
|
64
|
+
client_session, _ = initiator.read_response(reply)
|
|
65
|
+
|
|
66
|
+
frame = client_session.seal(b"hello") # put this on a socket
|
|
67
|
+
server_session.open(frame) # -> b"hello"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`Initiator.read_response` and `Responder.write_response` **consume** the handle
|
|
71
|
+
they are called on, success or failure — a handshake cannot be retried from a
|
|
72
|
+
half-read state. Using one again raises rather than corrupting memory, which is
|
|
73
|
+
[what happens](https://github.com/YounghyeonPark/fectp/blob/main/docs/DECISIONS.md) without that check: removing it takes
|
|
74
|
+
this test suite from passing to the interpreter dying.
|
|
75
|
+
|
|
76
|
+
## The secret key
|
|
77
|
+
|
|
78
|
+
**There is no way to read a private key out of an `Identity`,** and the C ABI
|
|
79
|
+
exports no such call for this to wrap.
|
|
80
|
+
|
|
81
|
+
That is the shape of the whole binding rather than an oversight. Bytes handed
|
|
82
|
+
to Python cannot be wiped: `bytes` is immutable so nothing can overwrite it,
|
|
83
|
+
the interpreter copies freely, and the memory may reach swap. Rust wipes its
|
|
84
|
+
copy when the identity is dropped; nothing it does survives the crossing.
|
|
85
|
+
|
|
86
|
+
`Identity.from_secret` restores a key you stored elsewhere, and FECTP wipes the
|
|
87
|
+
copy it makes. What you passed in is yours — use a `bytearray` and overwrite it
|
|
88
|
+
afterwards, because a `bytes` cannot be.
|
|
89
|
+
|
|
90
|
+
### Or never have it here
|
|
91
|
+
|
|
92
|
+
`Identity.from_key` takes a key held by a secure element, an HSM or a TPM, and
|
|
93
|
+
FECTP never sees it:
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
def dh(peer_public: bytes) -> bytes:
|
|
97
|
+
# Ask the device for X25519 with its private key; 32 bytes back.
|
|
98
|
+
return device.derive(peer_public)
|
|
99
|
+
|
|
100
|
+
identity = fectp.Identity.from_key(device.public_key, dh)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`dh` runs synchronously, twice per handshake on each side. If it raises, the
|
|
104
|
+
handshake ends with `KeyUnavailable` and your exception as its `__cause__`;
|
|
105
|
+
the identity can be used again. Return a `bytearray` and the wrapper wipes it
|
|
106
|
+
after copying.
|
|
107
|
+
|
|
108
|
+
## What this does not do
|
|
109
|
+
|
|
110
|
+
The session layer only. **Retransmission, congestion control, fragmentation and
|
|
111
|
+
keep-alive are not here** — they live in the `fectp` crate, above the layer this
|
|
112
|
+
binds. A caller who needs reliable delivery builds it or does without.
|
|
113
|
+
|
|
114
|
+
That trade is why the binding is this shape at all
|
|
115
|
+
([OTHER-LANGUAGES.md](https://github.com/YounghyeonPark/fectp/blob/main/docs/OTHER-LANGUAGES.md)): binding the layer above
|
|
116
|
+
would mean blocking calls to hold the GIL over, threads the library owns, and
|
|
117
|
+
memory crossing the boundary in both directions.
|
|
118
|
+
|
|
119
|
+
One warning worth repeating from D63: the abandonment reporting such a caller
|
|
120
|
+
would rebuild is the logic this project got wrong twice, and §5.5 of the
|
|
121
|
+
specification notes that a conforming receiver cannot observe it — so wire-level
|
|
122
|
+
test vectors cannot catch that class of mistake either.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
fectp/__init__.py,sha256=h_z3j4fcVRTzsFSZhtie7G-NBG8RDBTDSW2xwerxq5Y,18222
|
|
2
|
+
fectp/_native/fectp.dll,sha256=g_ROvF4lPxw-a7rj7Ks35n_k6-W-8tGFvyh1duD6PFc,225280
|
|
3
|
+
fectp-0.2.1.dist-info/licenses/LICENSE,sha256=06BlrmVJAh5WsZrNEZtxJ_FHNsA9QBrtTqUkjMAb2y8,1530
|
|
4
|
+
fectp-0.2.1.dist-info/METADATA,sha256=GvPexdCXZO2KOoZHhwXoSgZad0iCg_yOw6A2nwrpjQM,4841
|
|
5
|
+
fectp-0.2.1.dist-info/WHEEL,sha256=Zx98gwb_dQKckJK3HEOVKnxxD52EfU_PXDG_usMJ2ng,98
|
|
6
|
+
fectp-0.2.1.dist-info/top_level.txt,sha256=S1ifWX41fZ9WIQpcq1ynoK3j1UN1CpedVVf17o9gAn4,6
|
|
7
|
+
fectp-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Younghyeon Park
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fectp
|