#!/usr/bin/env python3 # © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE. """La cassaforte da riga di comando (F747): un segreto arriva solo col sì della persona.""" from __future__ import annotations import base64 import hashlib import hmac import json import os import re import shlex import subprocess import sys import time import urllib.error import urllib.parse import urllib.request QUI = os.path.dirname(os.path.abspath(__file__)) CMD = 'delminio cassaforte' ATTESA_S = int(os.environ.get('DELMINIO_CASSAFORTE_ATTESA', '100')) INFO = b'delminio-cassaforte-v1' FIRMA = b'delminio-cassaforte-firma-v1:' FIRMA_DEPOSITO = 'delminio-cassaforte-deposito-v1:' FIRMA_PASSAGGIO = 'delminio-cassaforte-passaggio-v1:' NOME_RE = re.compile('^[A-Z][A-Z0-9_]{0,63}$') NOMI_VIETATI = frozenset({'PATH', 'HOME', 'SHELL', 'IFS', 'ENV', 'BASH_ENV', 'CDPATH', 'PS4', 'PROMPT_COMMAND', 'SHELLOPTS', 'BASHOPTS', 'GLOBIGNORE', 'NODE_OPTIONS', 'NODE_PATH', 'PERL5OPT', 'PERL5LIB', 'PERLLIB', 'RUBYOPT', 'RUBYLIB', 'JAVA_TOOL_OPTIONS', '_JAVA_OPTIONS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_EXEC_PATH', 'GIT_ASKPASS', 'SSH_ASKPASS', 'EDITOR', 'VISUAL', 'PAGER', 'BROWSER', 'TMPDIR', 'GIT_PROXY_COMMAND', 'GIT_TEMPLATE_DIR', 'ZDOTDIR', 'GCONV_PATH', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'}) PREFISSI_VIETATI = ('LD_', 'DYLD_', 'PYTHON', 'BASH_FUNC_', 'GIT_CONFIG', 'LUA_') FRASI = { "aiuto": " {cmd} list the secrets you can request (names and notes, never values; \u201ctime-bound\u201d = opens with a single approval)\n {cmd} NAME[,NAME\u2026] \"\" -- command [arguments\u2026]\n requests the secrets from the administrator, with the why: the request reaches their phone.\n Granted, the command starts with the secrets in its environment variables (NAME=value).\n If an open time-bound access covers them all, it starts at once, without asking.\n The command reads the variables: to use them in arguments, go through a shell \u2014\n -- bash -c 'curl -u \"admin:$NAME\" \u2026'\n {cmd} open NAME[,NAME\u2026]|--larghe \"\"\n time-bound access: a single approval for the secrets marked \u201ctime-bound\u201d (--larghe: all of them), for the time the app says.\n {cmd} windows | close the time-bound access opened from here \xb7 close it all\n {cmd} propose NAME \"\"\n proposes a secret that is not there yet: the administrator approves it by entering the value.\n {cmd} deposit NAME[,NAME\u2026] \"\" [--larga] [--dal-file FILE]\n puts a value in the vault without showing it: from stdin (one name) or from a NAME=value file.\n It becomes a secret when the administrator accepts it in the app.", "non_collegato": "\u274c this repository isn't connected to Delminio (.claude/delminio.sh): run the connection again.", "non_risponde": "\u274c Delminio is not responding ({url}): {errore}", "nessun_segreto": "This space's vault is empty: the admin adds secrets from the app (Vault). If you need one, propose it by name.", "nessuna_cassaforte": "This space has no vault: the admin creates it from the app (Vault).", "uso_chiedi": "usage: {cmd} NAME[,NAME\u2026] \"\" -- command [arguments\u2026]", "chiesta": "\U0001f511 Request sent to the admin: {nomi}. Tell them in the chat too: they grant it from the app, on their phone.", "aspetto": " Waiting for approval (up to {secondi} s)\u2026", "ancora_niente": "\u23f3 Not granted yet. When the admin decides, the decision reaches you on the channel: then run the same command again, identical, and it picks up this request.", "negata": "\u270b Denied by {chi}{parole}. The command didn't start.", "scaduta": "\u231b The request expired before anyone approved it: the command didn't start. If it's still needed, run it again and the request starts over.", "consegna_rotta": "\u274c What arrived can't be opened (encrypted data altered, or it wasn't for this request): the command didn't start.", "firma_falsa": "\u274c What arrived doesn't carry the vault's signature: it wasn't sent by an admin's device. The command didn't start; tell the admin.", "firma_cambiata": "\u274c The vault's signing key isn't the one seen the first time ({file}): the command didn't start. If the admin really did recreate the vault, delete that file.", "nomi_diversi": "\u274c Names different from the ones requested arrived: the command didn't start; tell the admin.", "nome_vietato": "\u274c {nome} is a variable that changes what a command runs: it can't be requested from the vault.", "impronta": " Request fingerprint: {impronta} \u2014 in the app the admin sees the same one.", "concessa": "\u2705 Granted by {chi}: the command starts.", "comando_mancante": "\u274c the command after \u201c--\u201d is missing", "uso_proponi": "usage: {cmd} proponi NAME \"\"", "proposta": "\U0001f4dd Proposed {nome}: the admin sees it in the app and, if they approve it, adds the value. Tell them in chat too.", "segno_larga": " \xb7 time-bound", "finestra_chiesta": "\U0001f511 Time-bound access requested from the administrator for {n} secrets ({minuti} minutes from approval). Tell them in chat too: they approve it in the app, on their phone.", "finestra_aperta": "\u2705 Time-bound access opened by {chi} until {ora}: {nomi}. Commands with these secrets start without asking.", "finestra_usata": "\U0001f511 From the open time-bound access (until {ora}): the command starts.", "finestra_finita": "\u231b A time-bound access opened from here is gone (closed or ended).", "finestre_nessuna": "No time-bound access opened from here.", "finestra_riga": " until {ora} {nomi}", "finestre_chiuse": "\U0001f512 Time-bound access closed: {n}.", "nessuna_larga": "No secret is marked \u201ctime-bound\u201d: the administrator marks them in the app, one by one.", "uso_apri": "usage: {cmd} open NAME[,NAME\u2026]|--larghe \"\"", "uso_deposita": "usage: {cmd} deposit NAME[,NAME\u2026] \"\" [--larga] [--dal-file FILE] (one name only: the value from stdin)", "deposito_senza_chiave": "The vault has no deposit key yet: the app creates it when the administrator opens the vault from their device. Tell them, then run it again.", "deposito_firma": "\u274c The deposit key does not carry the vault's signature: I encrypt nothing for it. Warn the administrator.", "deposito_vuoto": "\u274c {nome}: no value (empty stdin, or not in the file). Nothing deposited.", "deposito_stdin": "\u274c With several names the value does not come from stdin: use --dal-file FILE.", "depositato": "\U0001f4e5 Deposited {nome}, encrypted for the vault: it becomes a secret when the administrator accepts it in the app. Tell them in chat too.", "non_concessa": "\u274c The secrets did not arrive (denied, expired or not granted yet): nothing to do.", "chiesta_tua": "\U0001f511 Request sent to the user's phone: {nomi}. It's their secret: they grant it from the app, on their phone. Tell them in the chat too.", "finestra_chiesta_tua": "\U0001f511 Time-bound access requested from the user for {n} of their secrets ({minuti} minutes from approval): they approve it in the app, on their phone. Tell them in chat too.", "impronta_tua": " Request fingerprint: {impronta} \u2014 in the app, on their phone, the user sees the same one." } def F(chiave: str, **sost) -> str: t = FRASI.get(chiave, chiave) for k, v in sost.items(): t = t.replace('{' + k + '}', str(v)) return t class Rifiuto(Exception): def __init__(self, messaggio: str, stato: int=0): super().__init__(messaggio) self.stato = stato _P = 2 ** 255 - 19 _A24 = 121665 def x25519(k: bytes, u: bytes) -> bytes: kk = bytearray(k) kk[0] &= 248 kk[31] &= 127 kk[31] |= 64 n = int.from_bytes(bytes(kk), 'little') x1 = int.from_bytes(u, 'little') & (1 << 255) - 1 x2, z2, x3, z3 = (1, 0, x1, 1) swap = 0 for t in reversed(range(255)): kt = n >> t & 1 if swap ^ kt: x2, x3, z2, z3 = (x3, x2, z3, z2) swap = kt a, b = ((x2 + z2) % _P, (x2 - z2) % _P) aa, bb = (a * a % _P, b * b % _P) e = (aa - bb) % _P c, d = ((x3 + z3) % _P, (x3 - z3) % _P) da, cb = (d * a % _P, c * b % _P) x3, z3 = ((da + cb) ** 2 % _P, x1 * (da - cb) ** 2 % _P) x2, z2 = (aa * bb % _P, e * (aa + _A24 * e) % _P) if swap: x2, z2 = (x3, z3) return (x2 * pow(z2, _P - 2, _P) % _P).to_bytes(32, 'little') _Q = 115792089210356248762697446949407573530086143415290314195533631308867097853951 _B = 41058363725152142129326129780047268409114441015993725554835256314039467401291 _N = 115792089210356248762697446949407573529996955224135760342422259061068512044369 _G = (48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109) def _somma(p1, p2): if p1 is None: return p2 if p2 is None: return p1 if p1[0] == p2[0] and (p1[1] + p2[1]) % _Q == 0: return None if p1 == p2: m = 3 * (p1[0] * p1[0] - 1) * pow(2 * p1[1], _Q - 2, _Q) % _Q else: m = (p2[1] - p1[1]) * pow(p2[0] - p1[0], _Q - 2, _Q) % _Q x = (m * m - p1[0] - p2[0]) % _Q return (x, (m * (p1[0] - x) - p1[1]) % _Q) def _per(k: int, p): r = None while k: if k & 1: r = _somma(r, p) p = _somma(p, p) k >>= 1 return r def verifica_firma(pub: bytes, messaggio: bytes, firma: bytes) -> bool: if len(pub) != 65 or pub[0] != 4 or len(firma) != 64: return False x, y = (int.from_bytes(pub[1:33], 'big'), int.from_bytes(pub[33:], 'big')) if not (x < _Q and y < _Q) or (y * y - x * x * x + 3 * x - _B) % _Q: return False r, s = (int.from_bytes(firma[:32], 'big'), int.from_bytes(firma[32:], 'big')) if not (0 < r < _N and 0 < s < _N): return False z = int.from_bytes(hashlib.sha256(messaggio).digest(), 'big') w = pow(s, _N - 2, _N) punto = _somma(_per(z * w % _N, _G), _per(r * w % _N, (x, y))) return punto is not None and punto[0] % _N == r def pubblica(privata: bytes) -> bytes: return x25519(privata, 9 .to_bytes(32, 'little')) def hkdf(chiave: bytes, sale: bytes, info: bytes, lunghezza: int) -> bytes: prk = hmac.new(sale, chiave, hashlib.sha256).digest() out, blocco, i = (b'', b'', 1) while len(out) < lunghezza: blocco = hmac.new(prk, blocco + info + bytes([i]), hashlib.sha256).digest() out += blocco i += 1 return out[:lunghezza] def flusso(chiave: bytes, n: int) -> bytes: out = b'' i = 0 while len(out) < n: out += hmac.new(chiave, i.to_bytes(8, 'big'), hashlib.sha256).digest() i += 1 return out[:n] def chiavi(condiviso: bytes, pub_client: bytes, eph: bytes, rid: str) -> tuple[bytes, bytes]: k = hkdf(condiviso, pub_client + eph, INFO + b':' + rid.encode(), 64) return (k[:32], k[32:]) def apri(privata: bytes, pub_client: bytes, rid: str, consegna: dict, firma_pub: bytes, nomi: list[str]) -> dict: eph, ct, tag, firma = (_b64d(consegna.get(x, '')) for x in ('eph', 'ct', 'tag', 'firma')) if len(eph) != 32 or len(tag) != 32: raise Rifiuto(F('consegna_rotta')) if not verifica_firma(firma_pub, FIRMA + rid.encode() + pub_client + eph + ct + tag, firma): raise Rifiuto(F('firma_falsa')) condiviso = x25519(privata, eph) if condiviso == bytes(32): raise Rifiuto(F('consegna_rotta')) k_cifra, k_tag = chiavi(condiviso, pub_client, eph, rid) if not hmac.compare_digest(hmac.new(k_tag, eph + ct, hashlib.sha256).digest(), tag): raise Rifiuto(F('consegna_rotta')) chiaro = bytes((a ^ b for a, b in zip(ct, flusso(k_cifra, len(ct))))) try: valori = json.loads(chiaro.decode('utf-8')) except (UnicodeDecodeError, ValueError): raise Rifiuto(F('consegna_rotta')) from None if not isinstance(valori, dict) or not all((isinstance(v, str) for v in valori.values())): raise Rifiuto(F('consegna_rotta')) if set(valori) != set(nomi): raise Rifiuto(F('nomi_diversi')) return valori def vietato(nome: str) -> bool: return not NOME_RE.match(nome) or nome in NOMI_VIETATI or nome.startswith(PREFISSI_VIETATI) def _firme() -> tuple[str, dict]: percorso = os.path.join(_sospese(), 'firme.json') try: with open(percorso, encoding='utf-8') as f: return (percorso, json.load(f)) except (OSError, ValueError): return (percorso, {}) def _di_chi() -> str: return hashlib.sha256(TOKEN.encode()).hexdigest()[:16] def _spazio() -> str: try: pezzo = TOKEN.split('.')[1] cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or '' except (IndexError, ValueError, AttributeError): cli = '' return URL if cli in ('', 'unico') else f'{URL}#{cli}' def _segue_la_catena(da: str, a: str, passaggi) -> bool: passaggi = [x for x in passaggi or [] if isinstance(x, dict)] adesso = da for _ in range(len(passaggi)): p = next((x for x in passaggi if x.get('da') == adesso), None) try: if p is None or not verifica_firma(_b64d(adesso), (FIRMA_PASSAGGIO + str(p.get('a'))).encode(), _b64d(str(p.get('firma') or ''))): return False except (ValueError, TypeError): return False adesso = str(p['a']) if adesso == a: return True return False def firma_ricordata(pub_b64: str, passaggi=None) -> bytes: percorso, note = _firme() if not pub_b64: raise Rifiuto(F('firma_falsa')) vista = note.get(_spazio()) if vista and vista != pub_b64 and (not _segue_la_catena(vista, pub_b64, passaggi)): raise Rifiuto(F('firma_cambiata', file=percorso)) return _b64d(pub_b64) def ricorda_firma(pub_b64: str) -> None: percorso, note = _firme() if note.get(_spazio()) == pub_b64: return note[_spazio()] = pub_b64 fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384) with os.fdopen(fd, 'w', encoding='utf-8') as f: json.dump(note, f) def impronta_richiesta(pub: bytes) -> str: h = hashlib.sha256(pub).hexdigest()[:8].upper() return h[:4] + '-' + h[4:] def _b64(b: bytes) -> str: return base64.b64encode(b).decode() def _b64d(s: str) -> bytes: try: return base64.b64decode(s.replace('-', '+').replace('_', '/') + '=' * (-len(s) % 4)) except (ValueError, TypeError): return b'' def _ambiente() -> tuple[str, str, str]: try: out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines() except (OSError, subprocess.TimeoutExpired): out = [] url, file_token, sessione = (out + ['', '', ''])[:3] try: with open(file_token, encoding='utf-8') as f: token = f.read().strip() except OSError: token = '' if not url or not token: raise Rifiuto(F('non_collegato')) return (url.rstrip('/'), token, sessione) URL, TOKEN, SESSIONE = ('', '', '') def _http(metodo: str, percorso: str, corpo: dict | None=None) -> dict: dati = json.dumps(corpo).encode() if corpo is not None else None req = urllib.request.Request(f'{URL}/api/cassaforte{percorso}', data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'}) try: with urllib.request.urlopen(req, timeout=30) as r: return json.loads(r.read().decode()) except urllib.error.HTTPError as e: raw = e.read().decode() try: msg = json.loads(raw).get('error', raw) except ValueError: msg = raw raise Rifiuto(f'❌ {msg}', e.code) from None except (urllib.error.URLError, OSError) as e: raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None def _sospese() -> str: d = os.path.join(os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache'), 'delminio-cassaforte') os.makedirs(d, mode=448, exist_ok=True) os.chmod(d, 448) return d def _impronta(nomi: list[str], perche: str, comando: list[str]) -> str: return hashlib.sha256(json.dumps([URL, nomi, perche, comando]).encode()).hexdigest()[:32] def _riprendi(chiave: str) -> dict | None: try: with open(os.path.join(_sospese(), chiave), encoding='utf-8') as f: return json.load(f) except (OSError, ValueError): return None def _metti_da_parte(chiave: str, dati: dict) -> None: percorso = os.path.join(_sospese(), chiave) fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384) with os.fdopen(fd, 'w', encoding='utf-8') as f: json.dump(dati, f) def _dimentica(chiave: str) -> None: try: os.remove(os.path.join(_sospese(), chiave)) except OSError: pass def _finestre_dir() -> str: run = os.environ.get('XDG_RUNTIME_DIR') or '' d = os.path.join(run, 'delminio-cassaforte') if run and os.path.isdir(run) else os.path.join(_sospese(), 'finestre') os.makedirs(d, mode=448, exist_ok=True) os.chmod(d, 448) return d def _ora(iso: str) -> str: try: from datetime import datetime return datetime.fromisoformat(iso).astimezone().strftime('%H:%M') except (TypeError, ValueError): return '?' def _finestre() -> list[dict]: from datetime import datetime, timezone adesso = datetime.now(timezone.utc) vive = [] cartella = _finestre_dir() for nome in sorted(os.listdir(cartella)): percorso = os.path.join(cartella, nome) try: with open(percorso, encoding='utf-8') as f: w = json.load(f) finita = datetime.fromisoformat(w['scade']) <= adesso except (OSError, ValueError, KeyError, TypeError): finita = True w = {} if finita: try: os.remove(percorso) except OSError: pass elif w.get('spazio') == _spazio() and w.get('token') == _di_chi(): w['_file'] = percorso vive.append(w) return vive def _togli_finestra(w: dict) -> None: try: os.remove(w['_file']) except (OSError, KeyError): pass def _dalla_finestra(nomi: list[str], comando: str) -> dict | None: for w in _finestre(): if not set(nomi) <= set(w['nomi']): continue try: r = _http('GET', '/richiesta/' + urllib.parse.quote(w['id']) + '?comando=' + urllib.parse.quote(comando[:500])) except Rifiuto as e: if e.stato != 404: raise continue if not r.get('consegna'): _togli_finestra(w) print(F('finestra_finita'), file=sys.stderr) continue firma_pub = r.get('firma_pub') or '' valori = apri(_b64d(w['privata']), _b64d(w['pub']), w['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), w['nomi']) print(F('finestra_usata', ora=_ora(w['scade'])), file=sys.stderr) return {n: valori[n] for n in nomi} return None def elenco() -> int: d = _http('GET', '/elenco') if not d.get('esiste'): print(F('nessuna_cassaforte')) return 0 if not d.get('segreti'): print(F('nessun_segreto')) return 0 for s in d['segreti']: print(f" {s['nome']}" + (F('segno_larga') if s.get('larga') else '') + (f" — {s['nota']}" if s.get('nota') else '')) return 0 def proponi(argomenti: list[str]) -> int: if len(argomenti) < 2: raise Rifiuto(F('uso_proponi', cmd=CMD)) nome = argomenti[0].strip() if vietato(nome): raise Rifiuto(F('nome_vietato', nome=nome)) _http('POST', '/proponi', {'nome': nome, 'nota': ' '.join(argomenti[1:]), 'sessione': SESSIONE}) print(F('proposta', nome=nome)) return 0 def _nomi(testo: str) -> list[str]: nomi = list(dict.fromkeys((n for n in testo.replace(' ', ',').split(',') if n))) for n in nomi: if vietato(n): raise Rifiuto(F('nome_vietato', nome=n)) return nomi def _attendi(nomi: list[str], perche: str, comando: list[str], finestra: bool): chiave = _impronta(nomi, perche, (['--finestra'] if finestra else []) + comando) sospesa = _riprendi(chiave) gia = None if sospesa is not None: try: gia = _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id'])) except Rifiuto as e: if e.stato != 404: raise _dimentica(chiave) sospesa = None if sospesa is not None and (not gia.get('consegna')) and (gia.get('stato') in ('scaduta', 'ritirata', 'chiusa')): _dimentica(chiave) sospesa, gia = (None, None) if sospesa is None: privata = os.urandom(32) pub = pubblica(privata) r = _http('POST', '/chiedi', {'nomi': nomi, 'perche': perche, 'comando': shlex.join(comando), 'sessione': SESSIONE, 'pub': _b64(pub), 'finestra': finestra}) sospesa = {'id': r['id'], 'privata': _b64(privata), 'pub': _b64(pub), 'tua': r.get('decide') == 'tu'} _metti_da_parte(chiave, sospesa) tua = sospesa['tua'] minuti = (r.get('finestra_s') or 0) // 60 if finestra: print(F('finestra_chiesta_tua', n=len(nomi), minuti=minuti) if tua else F('finestra_chiesta', n=len(nomi), minuti=minuti), file=sys.stderr) else: print(F('chiesta_tua', nomi=', '.join(nomi)) if tua else F('chiesta', nomi=', '.join(nomi)), file=sys.stderr) imp = impronta_richiesta(_b64d(sospesa['pub'])) print(F('impronta_tua', impronta=imp) if sospesa.get('tua') else F('impronta', impronta=imp), file=sys.stderr) print(F('aspetto', secondi=ATTESA_S), file=sys.stderr) fine = time.monotonic() + ATTESA_S while True: r = gia if gia is not None else _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id'])) gia = None stato = r.get('stato') if r.get('consegna'): _dimentica(chiave) firma_pub = r.get('firma_pub') or '' valori = apri(_b64d(sospesa['privata']), _b64d(sospesa['pub']), sospesa['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), nomi) ricorda_firma(firma_pub) return (sospesa, r, valori) if stato == 'negata': _dimentica(chiave) parole = r.get('parole') or '' print(F('negata', chi=r.get('deciso_da') or '?', parole=f': «{parole}»' if parole else ''), file=sys.stderr) return 3 if stato in ('scaduta', 'ritirata', 'chiusa'): _dimentica(chiave) print(F('scaduta'), file=sys.stderr) return 3 if time.monotonic() > fine: print(F('ancora_niente'), file=sys.stderr) return 4 time.sleep(2) def valori(nomi: list[str], perche: str, comando: str) -> dict: global URL, TOKEN, SESSIONE if not URL: URL, TOKEN, SESSIONE = _ambiente() nomi = _nomi(','.join(nomi)) dalla = _dalla_finestra(nomi, comando) if dalla is not None: return dalla esito = _attendi(nomi, perche, shlex.split(comando) or [comando], False) if isinstance(esito, int): raise Rifiuto(F('non_concessa'), esito) print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr) return esito[2] def chiedi(argomenti: list[str]) -> int: if '--' not in argomenti or argomenti.index('--') < 2: raise Rifiuto(F('uso_chiedi', cmd=CMD)) i = argomenti.index('--') nomi = _nomi(argomenti[0]) perche = ' '.join(argomenti[1:i]) comando = argomenti[i + 1:] if not comando: raise Rifiuto(F('comando_mancante')) dati = _dalla_finestra(nomi, shlex.join(comando)) if dati is None: esito = _attendi(nomi, perche, comando, False) if isinstance(esito, int): return esito print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr) dati = esito[2] sys.stderr.flush() os.execvpe(comando[0], comando, dict(os.environ, **dati)) def apri_finestra(argomenti: list[str]) -> int: if len(argomenti) < 2: raise Rifiuto(F('uso_apri', cmd=CMD)) if argomenti[0] == '--larghe': nomi = [s['nome'] for s in _http('GET', '/elenco').get('segreti', []) if s.get('larga')] if not nomi: raise Rifiuto(F('nessuna_larga')) else: nomi = _nomi(argomenti[0]) esito = _attendi(nomi, ' '.join(argomenti[1:]), [], True) if isinstance(esito, int): return esito sospesa, r, _ = esito scade = r.get('scade') or '' percorso = os.path.join(_finestre_dir(), 'finestra-' + hashlib.sha256(_spazio().encode()).hexdigest()[:8] + '-' + re.sub('[^A-Za-z0-9_-]', '', sospesa['id']) + '.json') fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384) with os.fdopen(fd, 'w', encoding='utf-8') as f: json.dump({**sospesa, 'nomi': nomi, 'scade': scade, 'spazio': _spazio(), 'token': _di_chi()}, f) print(F('finestra_aperta', chi=r.get('deciso_da') or '?', ora=_ora(scade), nomi=', '.join(nomi)), file=sys.stderr) return 0 def finestre() -> int: vive = _finestre() if not vive: print(F('finestre_nessuna')) for w in vive: print(F('finestra_riga', ora=_ora(w['scade']), nomi=', '.join(w['nomi']))) return 0 def chiudi() -> int: n = 0 for w in _finestre(): try: _http('POST', '/richiesta/' + urllib.parse.quote(w['id']) + '/chiudi', {}) except Rifiuto as e: if e.stato != 404: raise _togli_finestra(w) n += 1 print(F('finestre_chiuse', n=n)) return 0 def _da_file(percorso: str, nomi: list[str]) -> dict: trovati = {} with open(percorso, encoding='utf-8') as f: for riga in f: riga = riga.strip() k, uguale, v = riga.partition('=') if uguale and k.strip() in nomi: trovati[k.strip()] = v.strip().strip('\'"') return trovati def cifra_deposito(pub: bytes, nome: str, valore: str) -> dict: privata = os.urandom(32) eph = pubblica(privata) condiviso = x25519(privata, pub) if condiviso == bytes(32): raise Rifiuto(F('deposito_firma')) k = hkdf(condiviso, pub + eph, INFO + b':deposito:' + nome.encode(), 64) dati = valore.encode('utf-8') ct = bytes((a ^ b for a, b in zip(dati, flusso(k[:32], len(dati))))) tag = hmac.new(k[32:], eph + ct, hashlib.sha256).digest() return {'eph': _b64(eph), 'ct': _b64(ct), 'tag': _b64(tag)} def deposita(argomenti: list[str]) -> int: larga = '--larga' in argomenti argomenti = [a for a in argomenti if a != '--larga'] file = None if '--dal-file' in argomenti: i = argomenti.index('--dal-file') if i + 1 >= len(argomenti): raise Rifiuto(F('uso_deposita', cmd=CMD)) file = argomenti[i + 1] argomenti = argomenti[:i] + argomenti[i + 2:] if len(argomenti) < 2: raise Rifiuto(F('uso_deposita', cmd=CMD)) nomi, nota = (_nomi(argomenti[0]), ' '.join(argomenti[1:])) d = _http('GET', '/elenco') if not d.get('esiste'): raise Rifiuto(F('nessuna_cassaforte')) dep = d.get('deposito') or {} if not dep.get('pub'): raise Rifiuto(F('deposito_senza_chiave')) fp = firma_ricordata(dep.get('firma_pub') or '', dep.get('passaggi')) if not verifica_firma(fp, (FIRMA_DEPOSITO + dep['pub']).encode(), _b64d(dep.get('firma') or '')): raise Rifiuto(F('deposito_firma')) ricorda_firma(dep['firma_pub']) if file: trovati = _da_file(file, nomi) elif len(nomi) == 1: trovati = {nomi[0]: sys.stdin.read().rstrip('\n')} else: raise Rifiuto(F('deposito_stdin')) for n in nomi: if not trovati.get(n): raise Rifiuto(F('deposito_vuoto', nome=n)) pub = _b64d(dep['pub']) for n in nomi: _http('POST', '/proponi', {'nome': n, 'nota': nota, 'sessione': SESSIONE, 'larga': larga, 'deposito': cifra_deposito(pub, n, trovati[n]), 'per': dep['pub']}) print(F('depositato', nome=n)) return 0 def main(argv: list[str]) -> int: global URL, TOKEN, SESSIONE if not argv or argv[0] in ('aiuto', 'help', '-h', '--help'): print(F('aiuto', cmd=CMD)) return 0 try: URL, TOKEN, SESSIONE = _ambiente() gesti = {'elenco': lambda: elenco(), 'proponi': lambda: proponi(argv[1:]), 'apri': lambda: apri_finestra(argv[1:]), 'finestre': lambda: finestre(), 'chiudi': lambda: chiudi(), 'deposita': lambda: deposita(argv[1:])} if argv[0] in gesti: return gesti[argv[0]]() return chiedi(argv) except Rifiuto as e: print(str(e), file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))