vault-handoff 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.
@@ -0,0 +1,63 @@
1
+ """vault-handoff: a password-unlocked server vault with forward-secret,
2
+ end-to-end encrypted password hand-off between logged-in browsers.
3
+
4
+ See SPEC.md in the repository for the protocol and the threat model.
5
+ """
6
+
7
+ from .alerts import (
8
+ SECURITY_EVENT_TEXT,
9
+ AlertSink,
10
+ SecurityEvent,
11
+ alerts_from_env,
12
+ format_security_alert,
13
+ markdown_code_span,
14
+ mattermost_bot_alerts,
15
+ mattermost_webhook_alerts,
16
+ peekaboo_alerts,
17
+ )
18
+ from .attestation import (
19
+ AttestationError,
20
+ HiveAttestation,
21
+ verify_key_attestation,
22
+ )
23
+ from .http import NO_STORE_HEADERS, handle_request
24
+ from .kdf import DEFAULT_KDF, KdfParams, check_verifier, derive_keys, make_verifier
25
+ from .policy import DEFAULT_POLICY, HandoffPolicy, approval_for, parse_handoff_policy
26
+ from .protocol import Principal, VaultError
27
+ from .seal import handoff_code
28
+ from .vault import AuditEvent, StorageAdapter, Vault, WrongKeyError
29
+
30
+ __all__ = [
31
+ "DEFAULT_KDF",
32
+ "DEFAULT_POLICY",
33
+ "NO_STORE_HEADERS",
34
+ "SECURITY_EVENT_TEXT",
35
+ "AlertSink",
36
+ "AttestationError",
37
+ "AuditEvent",
38
+ "HandoffPolicy",
39
+ "HiveAttestation",
40
+ "KdfParams",
41
+ "Principal",
42
+ "SecurityEvent",
43
+ "StorageAdapter",
44
+ "Vault",
45
+ "VaultError",
46
+ "WrongKeyError",
47
+ "alerts_from_env",
48
+ "approval_for",
49
+ "check_verifier",
50
+ "derive_keys",
51
+ "format_security_alert",
52
+ "handle_request",
53
+ "handoff_code",
54
+ "make_verifier",
55
+ "markdown_code_span",
56
+ "mattermost_bot_alerts",
57
+ "mattermost_webhook_alerts",
58
+ "parse_handoff_policy",
59
+ "peekaboo_alerts",
60
+ "verify_key_attestation",
61
+ ]
62
+
63
+ __version__ = "0.1.0"
@@ -0,0 +1,462 @@
1
+ """Security alerts (SPEC section 10): attempts to guess the password over the
2
+ network, tamper with the protocol, or talk a colleague's browser into handing
3
+ the password over raise a loud event in a staff channel.
4
+
5
+ On by default: with no ``alerts`` argument the destination comes from the
6
+ environment (:func:`alerts_from_env`), the same settings every app (and the
7
+ npm package) reads. ``alerts=False`` or ``VAULT_HANDOFF_ALERTS=off`` opts
8
+ out. Every event is also logged.
9
+
10
+ Sinks run on one background thread, so a request never waits for Mattermost.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import logging
17
+ import os
18
+ import queue
19
+ import re
20
+ import ssl
21
+ import threading
22
+ import urllib.parse
23
+ import urllib.request
24
+ from collections.abc import Callable, Mapping, Sequence
25
+ from dataclasses import dataclass, replace
26
+ from datetime import datetime, timezone
27
+ from typing import Any, Literal
28
+
29
+ from .protocol import Principal
30
+
31
+ log = logging.getLogger("vault_handoff")
32
+
33
+ SecurityEventKind = Literal[
34
+ "password_guessing",
35
+ "tampered_message",
36
+ "challenge_misuse",
37
+ "handoff_denied",
38
+ "handoff_declined",
39
+ "handoff_flood",
40
+ "handoff_probe",
41
+ "unauthorized_action",
42
+ "unknown_route",
43
+ "attestation_failed",
44
+ ]
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class SecurityEvent:
49
+ kind: str
50
+ app_id: str
51
+ at: int
52
+ #: What happened. May hold attacker-chosen text: format it safely.
53
+ detail: str
54
+ #: The suspect (for ``handoff_declined``, the requester).
55
+ user_id: str | None = None
56
+ username: str | None = None
57
+ name: str | None = None
58
+ ip: str | None = None
59
+ #: Alerts dropped by the flood guard since the last one sent.
60
+ suppressed: int = 0
61
+
62
+
63
+ AlertSink = Callable[[SecurityEvent], None]
64
+ AlertsOption = Literal[False] | AlertSink | Sequence[AlertSink]
65
+
66
+ SECURITY_EVENT_TEXT: dict[str, tuple[str, str]] = {
67
+ "password_guessing": (
68
+ "DB password guessing",
69
+ "Repeated wrong DB passwords from one login: the rate limit kicked in.",
70
+ ),
71
+ "tampered_message": (
72
+ "Tampered message",
73
+ (
74
+ "A sealed message or request body didn't come from the real client "
75
+ "(it failed to decrypt or was malformed)."
76
+ ),
77
+ ),
78
+ "challenge_misuse": (
79
+ "Challenge misuse",
80
+ (
81
+ "A sealed password named a challenge of another login or purpose, or one "
82
+ "this server never issued (a replay?)."
83
+ ),
84
+ ),
85
+ "handoff_denied": (
86
+ "Banned login asked for the password",
87
+ "A login the hand-off policy denies asked colleagues for the DB password.",
88
+ ),
89
+ "handoff_declined": (
90
+ "Password request declined",
91
+ (
92
+ "A colleague refused to hand the DB password to this login. "
93
+ "Check who made the request."
94
+ ),
95
+ ),
96
+ "handoff_flood": (
97
+ "Password request flood",
98
+ (
99
+ "One login keeps asking colleagues for the DB password "
100
+ "(trying to get someone to click approve?)."
101
+ ),
102
+ ),
103
+ "handoff_probe": (
104
+ "Hand-off probing",
105
+ (
106
+ "A login poked at a hand-off it has no part in "
107
+ "(another login's request, or its own as a donor)."
108
+ ),
109
+ ),
110
+ "unauthorized_action": (
111
+ "Unauthorized vault action",
112
+ (
113
+ "A login without the DB password (or the right to share it) tried an "
114
+ "action the app never offers it."
115
+ ),
116
+ ),
117
+ "unknown_route": (
118
+ "Vault API probing",
119
+ "A request to a vault API route that doesn't exist.",
120
+ ),
121
+ "attestation_failed": (
122
+ "Hive didn't vouch for a requester",
123
+ (
124
+ "Hive refused to attest the key of a login asking for the DB password, "
125
+ "or its attestation didn't check out."
126
+ ),
127
+ ),
128
+ }
129
+
130
+
131
+ def markdown_code_span(text: str) -> str:
132
+ """``text`` as one inline code span it can't break out of (the detail is
133
+ the attacker's own input): a fence longer than any backtick run inside
134
+ never closes early, and Mattermost doesn't notify mentions inside code."""
135
+ flat = re.sub(r"\s*[\r\n]+\s*", " ", text) or "-"
136
+ longest = max((len(run) for run in re.findall(r"`+", flat)), default=0)
137
+ fence = "`" * (longest + 1)
138
+ pad = " " if flat.startswith("`") or flat.endswith("`") else ""
139
+ return f"{fence}{pad}{flat}{pad}{fence}"
140
+
141
+
142
+ def format_security_alert(e: SecurityEvent) -> str:
143
+ title, description = SECURITY_EVENT_TEXT[e.kind]
144
+ if e.user_id:
145
+ parts = [markdown_code_span(e.name)] if e.name else []
146
+ if e.username:
147
+ parts.append(f"username {markdown_code_span(e.username)}")
148
+ parts.append(f"user id {markdown_code_span(e.user_id)}")
149
+ who = ", ".join(parts)
150
+ else:
151
+ who = "not logged in"
152
+ at = datetime.fromtimestamp(e.at / 1000, timezone.utc)
153
+ lines = [
154
+ (
155
+ f":rotating_light: **Security alert ({markdown_code_span(e.app_id)}): "
156
+ f"{title}**"
157
+ ),
158
+ description,
159
+ f"Who: {who}",
160
+ f"Network address: {markdown_code_span(e.ip) if e.ip else 'unknown'}",
161
+ f"Details: {markdown_code_span(e.detail)}",
162
+ f"Time: {at.isoformat(timespec='milliseconds').replace('+00:00', 'Z')}",
163
+ ]
164
+ if e.suppressed:
165
+ lines.append(f"({e.suppressed} more alerts were held back by the flood guard)")
166
+ return "\n".join(lines)
167
+
168
+
169
+ # --- sinks ---------------------------------------------------------------------------
170
+
171
+ Poster = Callable[[str, dict[str, str], bytes | None, str], tuple[int, bytes]]
172
+
173
+
174
+ def _context(verify: bool | ssl.SSLContext) -> ssl.SSLContext:
175
+ if isinstance(verify, ssl.SSLContext):
176
+ return verify
177
+ ctx = ssl.create_default_context()
178
+ if not verify:
179
+ ctx.check_hostname = False
180
+ ctx.verify_mode = ssl.CERT_NONE
181
+ return ctx
182
+
183
+
184
+ def _http(verify: bool | ssl.SSLContext, timeout: float = 10) -> Poster:
185
+ def send(
186
+ url: str, headers: dict[str, str], body: bytes | None, method: str
187
+ ) -> tuple[int, bytes]:
188
+ if not url.startswith(("https://", "http://")):
189
+ raise ValueError(f"not an http(s) URL: {url!r}")
190
+ request = urllib.request.Request(url, body, headers, method=method)
191
+ try:
192
+ with urllib.request.urlopen( # scheme checked above
193
+ request, timeout=timeout, context=_context(verify)
194
+ ) as response:
195
+ return response.status, response.read()
196
+ except urllib.error.HTTPError as error:
197
+ return error.code, error.read()
198
+
199
+ return send
200
+
201
+
202
+ def _expect_ok(status: int, body: bytes, what: str) -> None:
203
+ if not 200 <= status < 300:
204
+ raise RuntimeError(f"{what} failed (HTTP {status}): {body[:200]!r}")
205
+
206
+
207
+ def mattermost_webhook_alerts(
208
+ url: str,
209
+ *,
210
+ verify: bool | ssl.SSLContext = True,
211
+ format: Callable[[SecurityEvent], str] = format_security_alert,
212
+ poster: Poster | None = None,
213
+ ) -> AlertSink:
214
+ """Posts to a Mattermost incoming webhook."""
215
+ send = poster or _http(verify)
216
+
217
+ def sink(event: SecurityEvent) -> None:
218
+ body = json.dumps({"text": format(event)}).encode()
219
+ status, raw = send(url, {"Content-Type": "application/json"}, body, "POST")
220
+ _expect_ok(status, raw, "Mattermost webhook")
221
+
222
+ return sink
223
+
224
+
225
+ _CHANNEL_ID = re.compile(r"[a-z0-9]{26}")
226
+
227
+
228
+ def mattermost_bot_alerts(
229
+ *,
230
+ server_url: str,
231
+ token: str,
232
+ channel: str,
233
+ verify: bool | ssl.SSLContext = True,
234
+ format: Callable[[SecurityEvent], str] = format_security_alert,
235
+ poster: Poster | None = None,
236
+ ) -> AlertSink:
237
+ """Posts as a Mattermost bot. ``channel`` is a channel URL
238
+ (``https://chat/<team>/channels/<name>``, looked up once) or a channel id."""
239
+ send = poster or _http(verify)
240
+ base = server_url.rstrip("/")
241
+ auth = {"Authorization": f"Bearer {token}"}
242
+ resolved: list[str] = (
243
+ [channel.strip()] if _CHANNEL_ID.fullmatch(channel.strip()) else []
244
+ )
245
+
246
+ def channel_id() -> str:
247
+ if resolved:
248
+ return resolved[0]
249
+ parts = [p for p in urllib.parse.urlparse(channel.strip()).path.split("/") if p]
250
+ if len(parts) < 3 or parts[-2] != "channels":
251
+ raise ValueError(f"{channel!r} is not a Mattermost channel URL")
252
+ team, name = (urllib.parse.unquote(parts[-3]), urllib.parse.unquote(parts[-1]))
253
+ url = (
254
+ f"{base}/api/v4/teams/name/{urllib.parse.quote(team, safe='')}"
255
+ f"/channels/name/{urllib.parse.quote(name, safe='')}"
256
+ )
257
+ status, raw = send(url, auth, None, "GET")
258
+ _expect_ok(status, raw, "Mattermost channel lookup")
259
+ resolved.append(json.loads(raw)["id"])
260
+ return resolved[0]
261
+
262
+ def sink(event: SecurityEvent) -> None:
263
+ body = json.dumps({"channel_id": channel_id(), "message": format(event)})
264
+ status, raw = send(
265
+ f"{base}/api/v4/posts",
266
+ {**auth, "Content-Type": "application/json"},
267
+ body.encode(),
268
+ "POST",
269
+ )
270
+ _expect_ok(status, raw, "Mattermost post")
271
+
272
+ return sink
273
+
274
+
275
+ def peekaboo_alerts(
276
+ *,
277
+ url: str,
278
+ get_access_token: Callable[[], str],
279
+ commander: str = "vault-handoff",
280
+ verify: bool | ssl.SSLContext = True,
281
+ format: Callable[[SecurityEvent], str] = format_security_alert,
282
+ poster: Poster | None = None,
283
+ ) -> AlertSink:
284
+ """Tweets through Peek-a-Boo's staff tweet channel, as Bluz does
285
+ (``POST <url>/api/tweet/student`` with a Hive bearer token)."""
286
+ send = poster or _http(verify)
287
+ endpoint = f"{url.rstrip('/')}/api/tweet/student"
288
+
289
+ def sink(event: SecurityEvent) -> None:
290
+ body = json.dumps({"commander": commander, "message": format(event)})
291
+ status, raw = send(
292
+ endpoint,
293
+ {
294
+ "Authorization": f"Bearer {get_access_token()}",
295
+ "Content-Type": "application/json",
296
+ },
297
+ body.encode(),
298
+ "POST",
299
+ )
300
+ try:
301
+ ok = 200 <= status < 300 and json.loads(raw).get("status") == 0
302
+ except ValueError:
303
+ ok = False
304
+ if not ok:
305
+ raise RuntimeError(f"Peek-a-Boo tweet failed (HTTP {status})")
306
+
307
+ return sink
308
+
309
+
310
+ _OFF = re.compile(r"(0|off|false|no|disabled?)", re.IGNORECASE)
311
+
312
+
313
+ def alerts_from_env(env: Mapping[str, str] | None = None) -> list[AlertSink] | None:
314
+ """The destinations every app shares, from the environment. None when
315
+ ``VAULT_HANDOFF_ALERTS`` is off; an empty list when nothing is set.
316
+
317
+ - ``VAULT_HANDOFF_ALERT_WEBHOOK``: a Mattermost incoming-webhook URL, or
318
+ - ``MATTERMOST_URL`` + ``MATTERMOST_ACCESS_TOKEN`` +
319
+ ``VAULT_HANDOFF_ALERT_CHANNEL`` (falls back to ``TWEET_CHANNEL_URL``).
320
+ """
321
+ env = os.environ if env is None else env
322
+
323
+ def get(key: str) -> str:
324
+ return env.get(key, "").strip()
325
+
326
+ if _OFF.fullmatch(get("VAULT_HANDOFF_ALERTS")):
327
+ return None
328
+ if get("VAULT_HANDOFF_ALERT_WEBHOOK"):
329
+ return [mattermost_webhook_alerts(get("VAULT_HANDOFF_ALERT_WEBHOOK"))]
330
+ channel = get("VAULT_HANDOFF_ALERT_CHANNEL") or get("TWEET_CHANNEL_URL")
331
+ if get("MATTERMOST_URL") and get("MATTERMOST_ACCESS_TOKEN") and channel:
332
+ return [
333
+ mattermost_bot_alerts(
334
+ server_url=get("MATTERMOST_URL"),
335
+ token=get("MATTERMOST_ACCESS_TOKEN"),
336
+ channel=channel,
337
+ )
338
+ ]
339
+ return []
340
+
341
+
342
+ # --- the alerter ----------------------------------------------------------------------
343
+
344
+ THROTTLE_MS = 5 * 60_000
345
+ GLOBAL_WINDOW_MS = 10 * 60_000
346
+ GLOBAL_MAX = 30
347
+ MAX_DETAIL = 300
348
+
349
+
350
+ class Alerter:
351
+ """Logs every event and sends it to the sinks, unless the same kind about
352
+ the same login went out in the last 5 minutes or 30 alerts went out in the
353
+ last 10 (so an attacker can't flood the channel). Never raises.
354
+
355
+ ``background=False`` runs sinks inline (tests)."""
356
+
357
+ def __init__(
358
+ self,
359
+ app_id: str,
360
+ option: AlertsOption | None,
361
+ now: Callable[[], int],
362
+ env: Mapping[str, str] | None = None,
363
+ *,
364
+ background: bool = True,
365
+ ) -> None:
366
+ self._app_id = app_id
367
+ self._now = now
368
+ if option is False:
369
+ self._sinks: Sequence[AlertSink] = []
370
+ elif callable(option):
371
+ self._sinks = [option]
372
+ elif option is not None:
373
+ self._sinks = list(option)
374
+ else:
375
+ from_env = alerts_from_env(env)
376
+ self._sinks = from_env or []
377
+ if from_env is not None and not from_env:
378
+ log.warning(
379
+ "%s: security alerts have no destination. Set "
380
+ "VAULT_HANDOFF_ALERT_WEBHOOK, or MATTERMOST_URL + "
381
+ "MATTERMOST_ACCESS_TOKEN + VAULT_HANDOFF_ALERT_CHANNEL; "
382
+ "VAULT_HANDOFF_ALERTS=off turns them off.",
383
+ app_id,
384
+ )
385
+ self._lock = threading.Lock()
386
+ self._last: dict[str, int] = {}
387
+ self._window_start = 0
388
+ self._sent_in_window = 0
389
+ self._suppressed = 0
390
+ self._background = background
391
+ self._queue: queue.Queue[SecurityEvent] | None = None
392
+
393
+ def __call__(self, kind: str, who: Principal | Any | None, detail: str) -> None:
394
+ t = self._now()
395
+ if len(detail) > MAX_DETAIL:
396
+ detail = detail[:MAX_DETAIL] + "…"
397
+ event = SecurityEvent(
398
+ kind=kind,
399
+ app_id=self._app_id,
400
+ at=t,
401
+ detail=detail,
402
+ user_id=getattr(who, "user_id", None) or None,
403
+ username=getattr(who, "username", None) or None,
404
+ name=getattr(who, "name", None) or None,
405
+ ip=getattr(who, "ip", None) or None,
406
+ )
407
+ log.warning(
408
+ "SECURITY %s %s user=%s ip=%s %s",
409
+ self._app_id,
410
+ kind,
411
+ json.dumps(event.user_id),
412
+ json.dumps(event.ip),
413
+ json.dumps(event.detail, ensure_ascii=False),
414
+ )
415
+ if not self._sinks:
416
+ return
417
+ with self._lock:
418
+ key = f"{kind}\0{event.user_id or event.ip or '-'}"
419
+ last = self._last.get(key)
420
+ if last is not None and t - last < THROTTLE_MS:
421
+ return
422
+ if t - self._window_start >= GLOBAL_WINDOW_MS:
423
+ self._window_start = t
424
+ self._sent_in_window = 0
425
+ if self._sent_in_window >= GLOBAL_MAX:
426
+ self._suppressed += 1
427
+ return
428
+ self._sent_in_window += 1
429
+ if len(self._last) > 1000:
430
+ self._last.clear()
431
+ self._last[key] = t
432
+ if self._suppressed:
433
+ event = replace(event, suppressed=self._suppressed)
434
+ self._suppressed = 0
435
+ if self._background:
436
+ self._enqueue(event)
437
+ else:
438
+ self._deliver(event)
439
+
440
+ def _deliver(self, event: SecurityEvent) -> None:
441
+ for sink in self._sinks:
442
+ try:
443
+ sink(event)
444
+ except Exception as error: # noqa: BLE001 (an alert must never break a request)
445
+ log.error("security alert failed to send: %s", error)
446
+
447
+ def _enqueue(self, event: SecurityEvent) -> None:
448
+ with self._lock:
449
+ if self._queue is None:
450
+ self._queue = queue.Queue(maxsize=200)
451
+ threading.Thread(
452
+ target=self._worker, name="vault-handoff-alerts", daemon=True
453
+ ).start()
454
+ try:
455
+ self._queue.put_nowait(event)
456
+ except queue.Full:
457
+ log.error("security alert queue is full; dropped %s", event.kind)
458
+
459
+ def _worker(self) -> None:
460
+ assert self._queue is not None
461
+ while True:
462
+ self._deliver(self._queue.get())