Repository navigation
Expand file tree
/
Copy pathhyper_cipher.py
More file actions
2436 lines (2211 loc) · 118 KB
/
Copy pathhyper_cipher.py
File metadata and controls
2436 lines (2211 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
HYPERCIPHER v5 - 2048-bit hardware-bound rotating stream cipher
===============================================================
MIMARI (4 katman)
-----------------
[L1] MASTER KEY - 2048 bit (256 byte)
master = Argon2id(passphrase || 0x00 || hardware_fingerprint,
salt, time=3, lanes=1, memory_cost=kdf_n KiB)
- KDF: Argon2id (RFC 9106, PHC kazanani) - GPU/ASIC/trade-off direnci
en yuksek parola KDF'si (v4'ten itibaren; once scrypt).
- v5 keyfile (ikinci faktor): passphrase onceli HKDF-SHA512(salt=keyfile,
info="HYPR/keyfile/v1") dogrudan KDF'e degil, KDF'e ORTUKLU girer
(age/sympa modeli) - keyfile yoksa acilamaz.
- Anahtar ASLA koda gomulmez, ASLA diske yazilmaz.
- Her calistirmada canli sistem kimliginden (MachineGuid, MAC,
volume serial, CPU, hostname) + kullanicinin passphrase'inden
sifirdan turetilir. Iki faktorlu: makine + insan (ve v5'te keyfile).
[L2] ROTASYON - her ROTATION_BYTES (varsayilan 1024) byte veride
TAZE bir 2048-bit subkey uretilir ve ZINCIRLENIR:
subkey_i = HKDF-SHA512(master, salt=nonce,
info="HYPR/subkey/" || LE64(rot_no) || prev_sub)
(subkey_{-1} = master; zincirleme = bir subkey kirilirsa geri sarmak
imkansiz, her subkey tum oncelere bagli)
~1 GiB/s throughput'ta bu tam olarak ~0.001 ms'de bir key degisimi
demektir. Data-driven rotasyon: wall-clock senkronizasyon sorunu yok.
[L3] KEYSTREAM - DUAL-FAMILY (iki bagimsiz hash ailesi, defense in depth):
blok = KeyedBLAKE2b-512(key=subkey[:64], msg=subkey[64:] || LE64(blok_no) || b"HYPR1")
XOR
HMAC-SHA512(key=subkey, msg=LE64(blok_no) || b"HYPR2")
Bir ailenin gelecekte (bilinmeyen) bir zayifligi cikarsa diger aile
keystreami sifir geri getirir. ciphertext = plaintext XOR blok
[L4] BUTUNLUK - Encrypt-then-MAC:
tag = HMAC-SHA512(auth_key, header || ciphertext)
auth_key = HKDF-SHA512(master, salt=nonce, info="HYPR/auth")
PAKET FORMATI (104 byte header + ciphertext + 64 byte tag):
version(1) | flags(1) | rotation_bytes(2) | kdf_n(4) | salt(32) |
nonce(24) | SHA-256(salt||fp)(32) | data_len(8)
KASITLI OLARAK MAGIC YOK - paket random veri gibi gorunur.
flags: bit0=donanim bagli, bit1=ISO 7816-4 padding, bit2=keyfile(kullanildi)
Rezevre flag bitleri fail-closed reddedilir (zafiyet raporu [16]).
v4 paketler v5 ile uyumlu acilir (VERSION 4 korundu); v3/v2 degil (KDF degisti).
DURUST LIMITLER (tamami README.md'de):
- Key rotasyonu, master key entropisinin UZERINE guvenlik EKLEMEZ.
- 2048-bit uzayi brute-force: ~2^2048 ~= 3.2e616 deneme.
Saniyede 1e30 deneme (fiziksel olarak imkansiz) ile bile ~1e579 yil.
Bir googol sadece 1e100 yildir.
- Bu bir ogrenme/muhendislik projesidir. Gercek sirlar icin AES-256-GCM kullan.
"""
from __future__ import annotations
import hashlib
import hmac
import math
import os
import platform
import re
import secrets
import stat
import struct
import tempfile
import unicodedata
import uuid
import warnings
from collections import Counter, namedtuple
from typing import Any, Dict, Optional
# v4: Argon2id KDF (RFC 9106, PHC kazanani). cryptography zorunlu bagimlilik;
# scrypt'in aksine GPU/ASIC/trade-off direnci en ust seviyededir.
try:
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
except ImportError as _ie: # pragma: no cover - bagimlilik denetimi
raise SystemExit(
"v4 Argon2id KDF icin 'cryptography' paketi gerekli: "
"pip install cryptography"
) from _ie
# ---------------------------------------------------------------------------
# Sabitler
# ---------------------------------------------------------------------------
VERSION = 4 # 1 byte (v4: Argon2id KDF + HKDF + HMAC keystream + nonce 24)
# v5 OZELLIKLERI (keyfile + gunclu-perde) AYNI VERSION'da:
# yeni FLAG_KEYFILE biti ile geriye-uyumlu eklendi - eski
# v4 paketler (flag yok) aynen acilir, yeni keyfile paketleri
# flag bitiyle ayrisir. VERSION yukseltmek eski paketleri
# KIRARDI; flag yaklasimi %100 geriye uyumlu.
KEY_BYTES = 256 # 2048 bit master key
ROTATION_BYTES = 1024 # subkey basina veri byte'i (~0.001 ms @ 1 GiB/s)
SALT_BYTES = 32
NONCE_BYTES = 24 # XChaCha tarzi random-nonce guvenligi (zafiyet [12])
FP_HASH_BYTES = 32 # SHA-256(makine parmak izi)
TAG_BYTES = 64 # HMAC-SHA512
DEFAULT_KDF_N = 1 << 17 # Argon2id memory_cost KiB: OWASP onerilen uzeri
# (128 MiB, ~0.87s olculdu; RFC 9106 second
# recommendation 64 MiB t=3 uzerinde)
MIN_KDF_N = 1 << 14 # alt sinir: API esnekligi (16 MiB; uretimde 2^17 onerilir)
MAX_KDF_N = 1 << 18 # ust sinir: 256 MiB bellek / ~1s CPU -> siseirilmis
# header KDF DoS karsi (RFC 7914 Sec.14 ZORUNLU
# kiler; libsodium SENSITIVE=2^20/1GiB yalnizca
# KENDI sectigin veri icin, saldirgan header'i
# icin degil. age: encrypt 2^18, decrypt cap 22
# ama acik SetMaxWorkFactor uyarisi. DENETIM 5
# bulgu [7]: 512 MiB -> 256 MiB daraltildi;
# HYPERCIPHER_MAX_KDF_N env ile servis
# operatoru kendi butcesine gore daha da
# daraltabilir (rscrypto Argon2VerifyPolicy).)
KDF_MAX_ENV_CAP = 1 << 19 # ESKI env cap (512 MiB). DENETIM 5 bulgu [9]:
# env artik MAX_KDF_N (256 MiB) ile sinirli -
# bu sabit yalnizca geriye uyum/sozlesme icin
# tutulur, _effective_max_kdf_n onu KULLANMAZ.
def _effective_max_kdf_n() -> int:
"""HYPERCIPHER_MAX_KDF_N env: KDF DoS cap'ini servis butcesine gore daralt.
DENETIM 5 bulgu [7] fix'i: sabit 512 MiB cap servis operatorunun ortamina
gore fazla genis olabilir (tek saldirgan paket ~2s CPU + 512 MiB bellek).
rscrypto Argon2VerifyPolicy deseni: operator max_memory_cost_kib secer,
KDF CALISTIRMADAN once reddedilir. Ayni ilke burada:
- env yoksa -> MAX_KDF_N (256 MiB, C++ tarafi set edemez)
- env gecersiz -> ValueError (fail-closed: sessizce genisletilmez)
- env 2'nin kuvveti degilse -> ValueError (API sozlesmesi)
DENETIM 5 bulgu [9] fix'i: env YALNIZCA daraltabilir - ust sinir MAX_KDF_N
(256 MiB). Eski KDF_MAX_ENV_CAP (512 MiB) genisletme yolu saldirgan
header ile birlikte 2x bellek/CPU amplifikasyonu uretebiliyordu
(dos doc/code uyusmazligi: kod 512'ye izin veriyordu, doc 'sadece
daraltabilir' diyordu). Artik env degerleri asla varsayilani ASAMAZ.
V5.3 zafiyet raporu [4] notu (BILGI): env her KDF cagrisinda yeniden
okunur (parse basina degil). Bu BILINCLIDIR - isletme butce degisikligi
bir sonraki islemde aninda uygulanir; env okuma maliyeti Argon2id'in
(~0.87s) yaninda ihmal edilir. Kaldi ki fail-closed zaten: gecersiz env
sessizce genisletme degil, ValueError uretir.
"""
raw = os.environ.get("HYPERCIPHER_MAX_KDF_N")
if raw is None:
return MAX_KDF_N
try:
value = int(raw, 10)
except ValueError:
raise ValueError(
"HYPERCIPHER_MAX_KDF_N tamsayi olmali (Argon2id memory_cost KiB, "
"2'nin kuvveti)") from None
if value < MIN_KDF_N or value > MAX_KDF_N:
raise ValueError(
f"HYPERCIPHER_MAX_KDF_N {value} sinir disi "
f"[{MIN_KDF_N}..{MAX_KDF_N}] (env yalnizca daraltabilir)")
if value & (value - 1):
raise ValueError(
"HYPERCIPHER_MAX_KDF_N 2'nin kuvveti olmali "
"(Argon2id memory_cost KiB)")
return value
ARGON2_TIME = 3 # Argon2id time_cost (RFC 9106 ikinci onerisi t=3)
ARGON2_LANES = 1 # Argon2id parallelism (OWASP: minimum p=1)
CHUNK = 1 << 20 # 1 MiB dosya okuma parcasi
FLAG_HARDWARE = 0b0000_0001 # flag biti: bit0 = donanim bagli
FLAG_PADDED = 0b0000_0010 # flag biti: bit1 = ISO 7816-4 padding uygulandi
FLAG_KEYFILE = 0b0000_0100 # flag biti: bit2 = v5 keyfile (ikinci faktor) kullanildi.
# age/sympa modeli: passphrase + keyfile(>=32 byte)
# HKDF-SHA512 ile birlestirilir (age/sympa HKDF-SHA256
# kullanir, biz SHA512 - master 2048-bit ailesiyle tutarli);
# keyfile tek basina
# ise yaramaz, passphrase de. Saldirgan ikisini de
# ele gecirmek zorunda - zayif perde artik sorun degil.
KEYFILE_MIN_BYTES = 32 # keyfile alt siniri (sympa: >=32 byte onerisi)
KEYFILE_RECOMMENDED_BYTES = 64 # generate_keyfile() varsayilan boyutu
KEYFILE_MAX_BYTES = 1 << 20 # ust sinir: 1 MiB makul kullanim capi (fazlasi DoS)
KEYFILE_INFO = b"HYPR/keyfile/v1" # HKDF domain separator (SP 800-108 label)
# V5.3 zafiyet raporu [1] (DUSUK) fix'i: deterministic test API'si FAIL-CLOSED.
# _encrypt_deterministic / _encrypt_file_deterministic salt/nonce SABITLER;
# public API'den salt/nonce kaldirildigi (IC[10]) icin kalan tek nonce-reuse
# yolu bu ic API'nin import edilip cagrilmasiydi. Tink felsefesi: nonce
# misuse'a duyarsiz olmayan bir modu KULLANICIYA ACIK birakma - bu fonksiyonlar
# artik varsayilan olarak RuntimeError firlatir; yalnizca acik opt-in
# (conftest.py veya test dosyasi basi: hc._DETERMINISTIC_MODE = True) ile
# calisir. Uretim kodu bu bayraga DOKUNMAMALIDIR.
_DETERMINISTIC_MODE = False
PASSPHRASE_MIN_GUESSES_LOG10 = 14.0 # v5: zxcvbn esigi - 10^14 tahmin ~= 1e4/sn'de
# 781 yil (Argon2id ile gercek hiz 1e4'ten cok
# dusuk oldugundan fiilen milyonlarca yil).
# => alti kalan perde CLI'da REDDEDILIR
# (--allow-weak ile acik riske razi olunur).
_ZXCVBN_AVAILABLE = False # import denemesi asagida yapilir (bagimlilik opsiyonel)
# Header duzeni (104 byte, little-endian). KASITLI OLARAK MAGIC YOK:
# paket random veri gibi gorunur. Dogrulama tamamen keyed HMAC-SHA512
# tag ile yapilir. v3: nonce 16->24 ([12]), iterations -> kdf_n = scrypt N
# ([13]), header 96 -> 104 byte. v4: kdf_n = Argon2id memory_cost KiB
# (RFC 9106), scrypt parametresi yerine. Boyut degismedi (104 byte).
# 0:1 version (1)
# 1:2 flags (1)
# 2:4 rotation_bytes (2, uint16) - 0 = varsayilan (ROTATION_BYTES)
# 4:8 kdf_n (4, uint32) - Argon2id memory_cost KiB (2'nin kuvveti, [13][14])
# 8:40 salt (32)
# 40:64 nonce (24)
# 64:96 fp_hash (32)
# 96:104 data_len (8)
HEADER_BYTES = 1 + 1 + 2 + 4 + SALT_BYTES + NONCE_BYTES + FP_HASH_BYTES + 8
Header = namedtuple(
"Header",
"version flags rotation_bytes kdf_n salt nonce fp_hash data_len payload",
)
class CipherError(Exception):
"""Dogrulama hatasi, kurcalama tespiti veya format hatasi."""
# ---------------------------------------------------------------------------
# L0: Donanim derinligi - makine parmak izi (koda/yere gomulu DEGIL)
# ---------------------------------------------------------------------------
def collect_hardware_fingerprint() -> bytes:
"""Makine kimligi: ikinci key faktoru. Asla saklanmaz, her calistirmada
canli sistemden toplanir.
V4 zafiyet raporu [2] (ENTROPI DEGILDIR - SAHIPLIK FAKTORUDUR): bu
bilesenler yari-kamusal metaveridir - MachineGuid registry'de okunabilir,
MAC/serial/hostname ag uzerinden sizabilir. Kriptografik guc KAYNAGI
DEGILDIR; guc passphrase + keyfile'dan gelir. fp yalnizca (a) master
turetimine makineye-bagli girdi (farkli makinede acilamaz) ve
(b) hash gorunusuyle gorsel kimlik saglar. Bu yuzden fp hicbir zaman
"ekstra entropi" olarak sayilmaz - guclu perde/keyfile zorunlulugu
bu rolden BAGIMSIZDUR.
"""
parts: list[str] = []
# 1) MachineGuid - Windows kurulumu basina sabit, en guclu capa
try:
import winreg
with winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography"
) as k:
mg, _ = winreg.QueryValueEx(k, "MachineGuid")
parts.append(f"mguid:{mg}")
except Exception: # nosec B110
pass # kasitli: fp kaynagi okunamazsa digerleriyle devam
# 2) MAC adresleri (sirali - NIC sirasi onemsiz)
try:
macs = sorted({uuid.getnode()})
parts.append(f"mac:{','.join(hex(m) for m in macs)}")
except Exception: # nosec B110
pass # kasitli: fp kaynagi okunamazsa digerleriyle devam
# 3) Sistem surucusu volume serial
# V5.3 zafiyet raporu [3] fix'i: ctypes.windll (bellekten derlenen,
# argtypes'siz) yerine acik WinDLL + tam imza. Yanlis cagri imzasi
# sessizce veri bozabilir ya da (x64'te) yigin dengesizligi yaratabilir;
# argtypes/restype hatali cagrilari calisma aninda reddeder.
try:
import ctypes
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_GetVolumeInformationW = _k32.GetVolumeInformationW
_GetVolumeInformationW.restype = ctypes.c_int # BOOL
_GetVolumeInformationW.argtypes = (
ctypes.c_wchar_p, # lpRootPathName
ctypes.c_wchar_p, # lpVolumeNameBuffer
ctypes.c_uint32, # nVolumeNameSize
ctypes.POINTER(ctypes.c_uint32), # lpVolumeSerialNumber
ctypes.POINTER(ctypes.c_uint32), # lpMaximumComponentLength
ctypes.POINTER(ctypes.c_uint32), # lpFileSystemFlags
ctypes.c_wchar_p, # lpFileSystemNameBuffer
ctypes.c_uint32, # nFileSystemNameSize
)
vol_name = ctypes.create_unicode_buffer(256)
fs_name = ctypes.create_unicode_buffer(256)
serial = ctypes.c_uint32()
ok = _GetVolumeInformationW(
"C:\\", vol_name, 256, ctypes.byref(serial),
None, None, fs_name, 256,
)
if ok:
parts.append(f"vol:{serial.value:x}")
except Exception: # nosec B110
pass # kasitli: fp kaynagi okunamazsa digerleriyle devam
# 4) CPU + hostname (son care entropisi)
parts.append(f"proc:{platform.processor() or 'unknown'}")
parts.append(f"node:{platform.node()}")
return "|".join(parts).encode("utf-8", errors="replace")
def fingerprint_summary() -> str:
"""`hash` komutu icin insan okunur ozet."""
return collect_hardware_fingerprint().decode("utf-8", errors="replace")
def fingerprint_digest(fp_blob: bytes | None = None,
salt: bytes = b"") -> bytes:
"""Donanim parmak izi ozetinin TEK KAYNAGI (V4 zafiyet raporu [4]).
Eskiden _build_header ICINDE inline `sha256(salt + fp_blob)` yazilirken
bu fonksiyon ayri bir formulle (tuzsuz) cakisiyordu - iki dogruluk
kaynagi, ileride sapma riski. Artik tek formul burada:
digest = SHA-256(salt + fp_blob)
- fp_blob=None (parametresiz cagri): canli makine parmak izi toplanir
(demo.py, test stabilite karsilastirmasi - geriye uyumlu).
- salt=b"" : tuzsuz ozet (eski davranis, yalnizca gorsel/hash amacli).
_build_header de ayni fonksiyonu cagirir; formuller BIRBIRINDEN
SAPAMAZ.
"""
if fp_blob is None:
fp_blob = collect_hardware_fingerprint()
return hashlib.sha256(salt + fp_blob).digest()
# ---------------------------------------------------------------------------
# L1: Master key turetimi
# ---------------------------------------------------------------------------
def _derive_master(passphrase: str, fp_blob: bytes, salt: bytes,
kdf_n: int, keyfile: bytes | None = None) -> bytearray:
"""passphrase [+ keyfile] + donanim parmak izi -> 2048-bit master key.
KDF (v4): scrypt -> Argon2id (RFC 9106, PHC kazanani). Argon2id, scrypt'in
aksine GPU/ASIC/trade-off direnci en yuksek PHC algoritmasidir ve OWASP
2024+ onerisidir. Parametreler:
- memory_cost = kdf_n KiB (OWASP min 19 MiB; default 2^17 = 128 MiB)
- time_cost = ARGON2_TIME (3; RFC 9106 ikinci onerisi t=3)
- parallelism = ARGON2_LANES (1; OWASP minimum)
Salt zaten encrypt tarafinda random uretilir ve header'da saklanir.
v5 KEYFILE KATMANI (age/sympa modeli): keyfile verildiyse passphrase TEK
BASINA anahtar materyali olmaktan cikar:
pre = HKDF-SHA512(ikm=passphrase_bytes, salt=keyfile, info=KEYFILE_INFO)
material = pre || 0x00 || fp_blob -> Argon2id
Boylece saldirgan zayif perdeyi bilse bile keyfile olmadan HICBIR sey
yapamaz; zayif perde sorunu insan hafizasindan keyfile'a TASINIR.
keyfile=None ise eski davranis (passphrase || fp) AYNEN korunur ->
mevcut v4 paketler geriye uyumlu acilir.
RAM hijyeni (zafiyet raporu [5] + DENETIM 5 bulgu [8]): KDF girdi
materyali (passphrase + fp) MUTABLE bytearray olarak insa edilir ve KDF
cagrisindan SONRA sifirlanir. DENETIM 5: pw_bytes ARTIK bytearray
(immutable bytes degil) - boylece passphrase'in UTF-8 kopyasi da wipe
edilir; keyfile=None dalinda bytearray(pw_bytes) kopyasi yerine ayni
buffer kullanilir (ekstra kopya uretilmez). Python'da immutable bytes
silinemez (pyca/cryptography doc: immutable silinemez, mutable buffer
gec); yapilabilecek en guclu sey tum gecici kopyalari mutable tutup wipe
etmektir - boylece heap dump'inda passphrase materyali kalmaz.
Passphrase guvenligi (zafiyet raporu [26][20]):
- Bos/whitespace passphrase REDDEDILIR (kutuphane seviyesi - CLI zaten
reddediyor, API acigi kapatildi) -> ValueError.
- Unicode NFC normalizasyonu (NIST SP 800-63B): ayni gorunen ama farkli
kodlanmis (NFC/NFD) passphrase'ler AYNI key'i uretmeli, yoksa
kullanici kilitli kalir.
"""
if not passphrase.strip():
raise ValueError("passphrase bos olamaz")
# V5.3 zafiyet raporu [2] fix'i: fp_blob NUL byte iceremez. material
# encoding'i pw_bytes || 0x00 || fp_blob'dur; ayrac (0x00) yalnizca tek
# bir konumda aranabilir oldugunda encoding INJECTIVE'dir (NIST SP
# 800-108r1 context encoding ilkesi - belirsizlik yaratan serbest
# icerik reddedilir). Canli parmak izi (mguid:/mac:/vol:/proc:/node:)
# ASCII metin oldugu icin NUL asla uretilmez; kontrol davranisi
# DEGISTIRMEZ, yalnizca KDF girdisinin ayrismasi guvence altina alinir.
if b"\x00" in fp_blob:
raise ValueError(
"fp_blob NUL byte (0x00) iceremez: ayrac tekliligini bozar")
normalized = unicodedata.normalize("NFC", passphrase)
# DENETIM 5 bulgu [8]: pw_bytes MUTABLE bytearray - immutable bytes
# (encode ciktisi) silinemezdi; simdi wipe(material) passphrase
# kopyasini da temizler (immutable normalized/str CPython'in kopyalari,
# hepsini temizlemek mumkun degil - en guclu pratik: mutable buffer).
pw_bytes = bytearray(normalized.encode("utf-8"))
if keyfile is not None:
# v5: passphrase'i keyfile'a ORTUKLE (age/sympa). HKDF ciktisi
# mutable kopyaya tasinir; passphrase'in kendisi KDF'e girmemis olur.
# (pre immutable bytes -> pyca/cryptography siniri, silinemez;
# kopyasi material wipe edilir. asil gizlilik HKDF + Argon2id
# katmanlarinda, passphrase kopyasi pw_bytes ise wipe edilir.)
pre = _hkdf(pw_bytes, salt=keyfile, info=KEYFILE_INFO,
length=KEYFILE_MIN_BYTES)
material = bytearray(pre)
# DENETIM 5 bulgu [10]: keyfile branch'inde pw_bytes ayri bir
# mutable buffer olarak kalir ve material wipe edilse bile PASSphrase
# kopyasi RAM'de kalir. material != pw_bytes oldugunda ikisi de wipe
# edilmelidir (else branch'te material is pw_bytes - cift wipe zararsiz).
wipe_pw = True
else:
material = pw_bytes # kopyasiz: ayni buffer, wipe ile temizlenir
wipe_pw = False
material.append(0) # ayrac
material.extend(fp_blob)
try:
# Argon2id(salt, length, iterations, lanes, memory_cost KiB).
# Argon2id blok boyu 1024 byte -> memory_cost KiB cinsindendir.
# type: ignore[call-arg,arg-type] - rust-backed sinifin py.typed
# stub'i yok; imza calisma aninda dogrulandi (Argon2id(salt, len,
# iterations, lanes, memory_cost) + bytearray kabul ediyor).
kdf = Argon2id(salt, KEY_BYTES, ARGON2_TIME, ARGON2_LANES, kdf_n) # type: ignore[call-arg]
return bytearray(kdf.derive(material)) # type: ignore[arg-type]
finally:
wipe(material)
if wipe_pw:
wipe(pw_bytes)
# ---------------------------------------------------------------------------
# HKDF-SHA512 (RFC 5869) - anahtar ayrimi (zafiyet raporu [15])
# ---------------------------------------------------------------------------
def _hkdf(ikm: bytes | bytearray, salt: bytes, info: bytes,
length: int) -> bytes:
"""HKDF-SHA512: Extract (PRK = HMAC(salt, IKM)) + Expand.
Raw concatenation yerine SP 800-108 uyumlu label tabanli ayrim:
info'ya baglam etiketi girer, counter ile genisletilir.
V4 zafiyet raporu [7]: RFC 5869 counter TEK OKTET'tir (0x01..0xff,
255 blok). SHA-512 blok boyu 64 -> azami cikti 255 * 64 = 16320 byte.
Sessiz truncation/ValueError yerine acik sinir kontrolu: bu capin
uzerinde uzatma ISTENEMEZ (counter 256+ tasardi, iki farkli blok
ayni T(i) ile cakisirdi).
"""
max_len = 255 * hashlib.sha512().digest_size # RFC 5869 tekil oktet
if length < 0 or length > max_len:
raise ValueError(
f"HKDF cikti uzunlugu {length} sinir disi [0..{max_len}] "
f"(RFC 5869 tek oktet counter siniri)")
prk = hmac.new(salt, ikm, hashlib.sha512).digest()
out = bytearray()
t = b""
counter = 1
while len(out) < length:
# T(i) = HMAC(PRK, T(i-1) || info || i)
t = hmac.new(prk, t + info + bytes([counter]),
hashlib.sha512).digest()
out += t
counter += 1
return bytes(out[:length])
# ---------------------------------------------------------------------------
# L2: Subkey rotasyonu - SHA-512 counter DRBG + ZINCIRLEME
# ---------------------------------------------------------------------------
def _derive_subkey(prev_sub: bytes | bytearray, master: bytes | bytearray,
nonce: bytes, rotation_index: int) -> bytes:
"""2048-bit subkey = HKDF-SHA512(master, salt=nonce, info=...).
Zafiyet raporu [15]: raw concatenation (SHA-512(prev||master||...))
SP 800-108 uyumsuzdu. Simdi RFC 5869 HKDF: Extract PRK = HMAC(nonce,
master), Expand ile info label "HYPR/subkey/<rot>" + ZINCIRLEME:
prev_sub info'ya girer, boylece subkey_{i-1} ele gecirilse bile geri
sarmak (rewind) imkansizdir ve her subkey tum onceki rotasyonlara
baglidir.
"""
info = b"HYPR/subkey/" + struct.pack("<Q", rotation_index) + prev_sub
return _hkdf(master, nonce, info, KEY_BYTES)
def _derive_auth_key(master: bytes | bytearray, nonce: bytes) -> bytearray:
"""HMAC-SHA512 auth key = HKDF(master, salt=nonce, info="HYPR/auth").
Zafiyet raporu [15]: SHA-512(master || b"AUTH") yerine SP 800-108
label tabanli ayrim - auth ve subkey ayni master'dan ama farkli
baglamlarda turetilir, cakisamaz.
"""
return bytearray(_hkdf(master, nonce, b"HYPR/auth", 64))
def _keystream_block(subkey: bytes | bytearray, block_idx: int) -> bytes:
"""64 byte dual-family keystream blogu.
Iki bagimsiz kanitli PRF ayni girisle calisip XOR'lanir:
a) keyed BLAKE2b-512 (key = subkey[:64])
b) HMAC-SHA512 (zafiyet raporu [11]: secret-prefix SHA-512 kanitli
PRF DEGILDIR - length extension teorisi; HMAC ile degistirildi)
Bir aile zayif cikarsa digeri keystreami korur.
"""
ctr = struct.pack("<Q", block_idx)
a = hashlib.blake2b(subkey[64:] + ctr + b"HYPR1",
key=subkey[:64], digest_size=64).digest()
b = hmac.new(subkey, ctr + b"HYPR2", hashlib.sha512).digest()
return bytes(x ^ y for x, y in zip(a, b))
# ---------------------------------------------------------------------------
# L3: Keystream uretici (XOR simetrik oldugu icin encrypt/decrypt ortak)
# ---------------------------------------------------------------------------
class _CipherState:
"""Chunk'lara bolunmus veri icin rotasyon + blok sayaci durumu."""
__slots__ = ("master", "nonce", "rotation_bytes",
"offset", "cur_rot", "cur_sub", "block_idx")
def __init__(self, master: bytes | bytearray, nonce: bytes,
rotation_bytes: int):
self.master = master
self.nonce = nonce
self.rotation_bytes = rotation_bytes
self.offset = 0 # islenen toplam veri byte'i
self.cur_rot = -1 # aktif rotasyon indeksi
self.cur_sub = master # aktif 2048-bit subkey (zincirin basi: master)
self.block_idx = 0 # global 64-byte keystream blok sayaci
def process(self, data: bytes) -> bytes:
out = bytearray()
pos = 0
n = len(data)
while pos < n:
rot = self.offset // self.rotation_bytes
if rot != self.cur_rot: # ROTASYON
self.cur_rot = rot
self.cur_sub = _derive_subkey(
self.cur_sub, self.master, self.nonce, rot)
ks = _keystream_block(self.cur_sub, self.block_idx)
take = min(64, n - pos)
for i in range(take):
out.append(data[pos + i] ^ ks[i])
pos += take
self.offset += take
self.block_idx += 1
return bytes(out)
# ---------------------------------------------------------------------------
# Header isleme
# ---------------------------------------------------------------------------
def _build_header(use_hardware: bool, kdf_n: int, salt: bytes,
nonce: bytes, fp_blob: bytes, data_len: int,
rotation_bytes: int = ROTATION_BYTES,
padded: bool = False, keyfile: bool = False) -> bytes:
flags = FLAG_HARDWARE if use_hardware else 0
if padded:
flags |= FLAG_PADDED
if keyfile:
# v5: keyfile kullanildi -> decrypt keyfile'siz acilmamali.
flags |= FLAG_KEYFILE
if use_hardware:
# Zafiyet raporu [19]: fp_hash dogrudan SHA-256(makine kimligi)
# OLSAYDI her pakette AYNI ozet gorunurdu -> calinan dosyalar
# arasi korelasyon + makine atfetme. Simdi dosyaya ozel salt ile
# tuzlanir: her pakette FARKLI gorunur, gizlilik/izleme kapisi
# kapanir. (Kriptografik amac: master turetimine fp zaten giriyor;
# bu alan yalnizca dogrulama-oripli meta-veri idi.)
# V4 zafiyet raporu [4]: fp_hash hesabi fingerprint_digest()'in
# ALTINA GOCERILDI - formullerde sapma imkansiz (tek kaynak).
fp_hash = fingerprint_digest(fp_blob, salt)
else:
fp_hash = b"\x00" * FP_HASH_BYTES
# rotation_bytes header'a gomulur (decrypt'te dogru degerin kullanilmasi
# IÇIN - aksi halde yanlis rotation sessizce bozuk plaintext uretir).
# 0 degeri yalnizca ESKI paketlerde gorunur -> varsayilan.
stored_rot = rotation_bytes
return (
bytes([VERSION, flags]) + struct.pack("<H", stored_rot)
+ struct.pack("<I", kdf_n)
+ salt + nonce + fp_hash
+ struct.pack("<Q", data_len)
)
def _validate_params(kdf_n: int, rotation_bytes: int,
salt: bytes, nonce: bytes) -> None:
"""Encrypt ic API'si icin parametre dogrulamasi (IC[10] sonrasi).
Sessiz bozuk format / crash / uint16 tasmasi ureten degerler sifreleme
ONCESI reddedilir:
- kdf_n sinir disi veya 2'nin kuvveti degil : Argon2id memory_cost
KiB (2^n sozlesmesi) + siseirilmis header KDF DoS karsi ([13][14]).
- rotation_bytes < 64 : rotasyon 64-byte keystream bloklarinda uygulanir,
daha kucuk degerler asla dogru sekilde kullanilamaz -> reddet.
- rotation_bytes > 65535 : uint16 header tasar -> reddet.
- salt/nonce yanlis uzunluk : sessizce bozuk format -> reddet.
NOT: salt/nonce artik PUBLIC API'den gelmez (encrypt()/encrypt_file() her
cagri icin CSPRNG uretir - IC[10]); bu dogrulama yalnizca ic
_encrypt_deterministic()/_encrypt_file_deterministic() test yolunu
korur. Imza zorunlu bytes'tir (None kabul edilmez).
"""
if not MIN_KDF_N <= kdf_n <= _effective_max_kdf_n():
raise ValueError(
f"kdf_n {kdf_n} sinir disi "
f"[{MIN_KDF_N}..{_effective_max_kdf_n()}] (2'nin kuvveti olmali)")
if kdf_n & (kdf_n - 1):
raise ValueError(
f"kdf_n {kdf_n} 2'nin kuvveti olmali (Argon2id memory_cost KiB)")
if not 64 <= rotation_bytes <= 65535:
raise ValueError(
f"rotation_bytes {rotation_bytes} sinir disi [64..65535]")
if rotation_bytes % 64 != 0:
# Zafiyet raporu [17]: keystream 64-byte bloklar halinde uretilir;
# rotation 64'un kati degilse subkey degisimi blok sinirina denk
# gelmez ve dokumante edilen "her X byte'da taze subkey" garantisi
# sessizce ihlal edilir. 64'un kati zorunlu (64, 128, 1024, 65472).
raise ValueError(
f"rotation_bytes {rotation_bytes} 64'un kati olmali "
"(keystream blok siniri ile hizalama)")
if len(salt) != SALT_BYTES:
raise ValueError(f"salt {len(salt)} bayt olmali ({SALT_BYTES})")
if len(nonce) != NONCE_BYTES:
raise ValueError(f"nonce {len(nonce)} bayt olmali ({NONCE_BYTES})")
def _validate_keyfile(keyfile: bytes | bytearray) -> None:
"""v5 keyfile dogrulamasi: >=32 byte (sympa onerisi), ust cap 1 MiB.
Keyfile, HKDF-SHA512'ya salt olarak girer; <32 byte entropi icerigi
ikinci faktorun guvenligini gereksiz yere dusurur (age/sympa ayni
siniri koyar). Ust sinir: cok buyuk keyfile'lar bellek/performans
amplifikasyonu yapmasin (bunlar saldirgan kontrolunde degildir ama
makul kullanim capi yine de sinirli).
V4 zafiyet raporu [6] (ENTROPI SANITY): boyut siniri tek basina
yetersizdir - kullanici keyfile olarak tahmin edilebilir bir dosya
(tumu ayni bayt, kisa donen desen) secerse ikinci faktor ENTROPISIZ
kalir ve "keyfile korumali" izlenimi yanlis olur. Fail-closed:
- <8 farkli bayt -> tahmin edilebilir (tum-ayni / 1-7 bayt donen)
- Shannon entropisi < 3.0 bit/bayt -> duzenli/desenli dosya
Gercek rastgele (generate-keyfile) ve gercek dunya metin dosyalari
(TR/EN, ~4+ bit/bayt) bu esikleri rahat gecer. 'generate-keyfile'
kullanilmasi ONERILIR - elle secilen dosya ikinci faktoru zayiflatir.
"""
if not isinstance(keyfile, (bytes, bytearray)):
raise ValueError("keyfile bytes olmali")
if len(keyfile) < KEYFILE_MIN_BYTES:
raise ValueError(
f"keyfile en az {KEYFILE_MIN_BYTES} byte olmali "
f"(simdi {len(keyfile)}) - yeterli entropi icin "
f"'generate-keyfile' komutunu kullanin")
if len(keyfile) > KEYFILE_MAX_BYTES:
raise ValueError(
f"keyfile en fazla {KEYFILE_MAX_BYTES} byte olmali "
f"(simdi {len(keyfile)})")
# V4 [6]: entropi sanity (fail-closed - tahmin edilebilir keyfile reddi)
counts = Counter(keyfile)
if len(counts) < 8:
raise ValueError(
f"keyfile tahmin edilebilir ({len(counts)} farkli bayt < 8) - "
f"ikinci faktor islevsiz. 'generate-keyfile' ile uretin")
n = len(keyfile)
entropy = -sum((c / n) * math.log2(c / n) for c in counts.values())
if entropy < 3.0:
raise ValueError(
f"keyfile dusuk entropi ({entropy:.1f} bit/bayt < 3.0) - "
f"duzenli/desenli dosya ikinci faktor olarak yetersiz. "
f"'generate-keyfile' ile uretin")
def parse_header(header: bytes) -> Header:
if len(header) != HEADER_BYTES:
raise CipherError("bozuk header uzunlugu")
version = header[0]
if version != VERSION:
raise CipherError(f"desteklenmeyen format surumu: {version}")
flags = header[1]
if flags & ~(FLAG_HARDWARE | FLAG_PADDED | FLAG_KEYFILE):
# Zafiyet raporu [16]: tanimsiz/rezevre flag bitleri fail-open
# olmasin - ileride guvenlikle ilgili bir bit tanimlanirsa eski
# surum yabanci paketi sessizce kabul etmemeli.
raise CipherError("desteklenmeyen flag bitleri (kurcalanmis veya "
"yeni format)")
stored_rot = struct.unpack_from("<H", header, 2)[0]
if stored_rot != 0 and stored_rot < 64:
# 0 = eski varsayilan (legacy); 1..63 = encrypt asla uretmez
# (64 alti rotasyon 64-byte keystream bloklarinda uygulanamaz) ->
# kurcalanmis veya yabanci format.
raise CipherError("supheli rotation_bytes (kurcalanmis veya dogru "
"dosya degil)")
if stored_rot != 0 and stored_rot % 64 != 0:
# Zafiyet raporu [17]: 64'un kati olmayan rotation encrypt ile
# uretilemez (validate zorunlu kirar) -> boyle header kurcalanmis
# veya yabanci formattir, fail-open yerine reddet.
raise CipherError("supheli rotation_bytes (64'un kati degil - "
"kurcalanmis veya dogru dosya degil)")
rotation_bytes = stored_rot if stored_rot != 0 else ROTATION_BYTES
kdf_n = struct.unpack_from("<I", header, 4)[0]
# Zafiyet raporu [14]: kdf_n sinir disi/gecersiz -> KDF CALISTIRMADAN
# reddet (saldirgan 256 MiB bellek / ~1s CPU amplifikasyonu yapamasin).
# DENETIM 5 bulgu [7]: env daraltilmis cap'a da uyulur (servis
# operatorunun HYPERCIPHER_MAX_KDF_N'i header'daki kdf_n'den buyukse
# reddedilir - KDF calismaz).
# Argon2id memory_cost 8'in kati olmali; 2'nin kuvveti kisi gereksizdir
# ancak API sozlesmesi 2^n KiB tutar (test/golden uyumlulugu).
if kdf_n < MIN_KDF_N or kdf_n > _effective_max_kdf_n() or kdf_n & (kdf_n - 1):
raise CipherError("supheli KDF parametresi (kurcalanmis veya dogru "
"dosya degil)")
salt = header[8:8 + SALT_BYTES]
nonce = header[40:40 + NONCE_BYTES]
fp_hash = header[64:64 + FP_HASH_BYTES]
data_len = struct.unpack_from("<Q", header, 96)[0]
return Header(version, flags, rotation_bytes, kdf_n, salt, nonce,
fp_hash, data_len, header[:HEADER_BYTES])
# ---------------------------------------------------------------------------
# RAM hijyeni
# ---------------------------------------------------------------------------
def wipe(buf: bytearray | None) -> None:
"""Anahtar materyali kullanim sonrasi sifirla.
None-safe: _derive_auth_key() gibi bir turetim HATA verirse
`finally: wipe(auth_key)` NameError yerine sorunsuz doner (asil
hata maskelenmez - Pyright reportPossiblyUnboundVariable fix).
V5.3 zafiyet raporu [5] notu (BILGI): Python'da immutable bytes
(ve str) SIFIRLANAMAZ - CPython nesneleri paylasilabilir; pyca/
cryptography resmi dokumantasyonu da "mutable buffer gec" der.
Bu nedenle tum KDF girdileri bytearray'dir ve wipe() ile temizlenir;
immutable kopyalari temizlemek mumkun degildir (tum gecici kopyalari
mutable tutmak en guclu pratik yaklasimdir - _derive_master'da yapilir).
Guc kopyalari ise interpreter siniridir, kod duzeltmesi yoktur.
"""
if buf is None:
return
for i in range(len(buf)):
buf[i] = 0
# ---------------------------------------------------------------------------
# ISO 7816-4 padding (opsiyonel plaintext boyut gizleme - zafiyet raporu [18])
# ---------------------------------------------------------------------------
def _pad_iso7816(data: bytes, block_size: int) -> bytes:
"""data || 0x80 || 0x00... -> uzunluk block_size'in kati.
Her zaman en az 1 byte ekler (0x80): plaintext zaten blok sinirinda
olsa bile TAM bir 0x80 + 0x00* blogu eklenir. Boylece unpad'de
"sondaki ilk 0x80" her zaman padding'e aittir - plaintext'in kendi
icindeki 0x80'lerle karisma imkani yoktur.
"""
pad_len = block_size - (len(data) % block_size)
return data + b"\x80" + b"\x00" * (pad_len - 1)
def _pad_len_for(data_len: int, block_size: int) -> int:
"""data_len boyutlu veriye ISO 7816-4 padding ile eklenecek byte sayisi."""
return block_size - (data_len % block_size)
def _unpad_iso7816(data: bytes) -> bytes:
"""_pad_iso7816'nin tersi. Bozuk/eksik padding -> ValueError.
Blok boyutundan bagimsiz calisir: ISO 7816-4 pad her zaman 0x80 ile
biter ve 0x80'den once yalnizca plaintext vardir; sondaki 0x00'lar
atlanip ilk 0x80 kesilir. Kurcalanmis paket zaten HMAC'te reddedilir;
bu fonksiyon yalnizca dogrulanmis plaintext uzerinde calisir, ama
yine de fail-closed. Pad blok boyutu max 65536 oldugundan bundan
fazla 0x00 siyirmak asla gecerli degildir.
"""
if not data:
raise ValueError("bos veri - padding bekleniyor")
i = len(data) - 1
n_zeros = 0
while i >= 0 and data[i] == 0x00:
i -= 1
n_zeros += 1
if n_zeros > 65536: # [18]: pad_to ust siniri 65536
raise ValueError("asiri uzun padding (bozuk)")
if i < 0 or data[i] != 0x80:
raise ValueError("bozuk padding (0x80 bulunamadi)")
return data[:i]
# ---------------------------------------------------------------------------
# Tek parca API (kucuk veri)
# ---------------------------------------------------------------------------
def encrypt(plaintext: bytes, passphrase: str, *,
use_hardware: bool = True, kdf_n: int = DEFAULT_KDF_N,
rotation_bytes: int = ROTATION_BYTES,
pad_to: int | None = None,
keyfile: bytes | None = None) -> bytes:
"""Duz metni sifreler; header + ciphertext + tag paketi dondurur.
keyfile (v5): ikinci faktor. Verilirse passphrase + keyfile HKDF-SHA512
ile birlestirilir (sympa/age HKDF-SHA256 kullanir, SHA512 master ailesiyle
tutarli) ve paket FLAG_KEYFILE tasir; decrypt ayni keyfile olmadan
acilamaz. zayif perde tek basina artik ise yaramaz.
pad_to (zafiyet raporu [18]): plaintext boyutunu gizlemek icin opsiyonel
ISO 7816-4 padding - ciphertext uzunlugu pad_to'nun kati olur. data_len
header'da PADDING DAHIL uzlunugu tasir; decrypt otomatik kaldirir.
GUVENLIK (IC[10]): salt ve nonce KULLANICIDAN GIZLENIR - her cagri icin
CSPRNG (os.urandom) ile uretilir, API sabit nonce kabul ETMEZ. Nonce
reuse (ayni key+nonce -> ayni keystream -> plaintext XOR sizintisi)
boylece kullanici hatasiyla imkansiz (libsodium secretstream / Tink
misuse-resistant modeli). Deterministik testler ic ic
_encrypt_deterministic() kullanir - PUBLIC API'DE DEGIL.
"""
return _encrypt_core(
plaintext, passphrase, use_hardware=use_hardware,
salt=os.urandom(SALT_BYTES), nonce=os.urandom(NONCE_BYTES),
kdf_n=kdf_n, rotation_bytes=rotation_bytes, pad_to=pad_to,
keyfile=keyfile)
def _encrypt_core(plaintext: bytes, passphrase: str, *,
use_hardware: bool, salt: bytes, nonce: bytes,
kdf_n: int = DEFAULT_KDF_N,
rotation_bytes: int = ROTATION_BYTES,
pad_to: int | None = None,
keyfile: bytes | None = None) -> bytes:
"""IC UYGULAMA CORE - yalnizca encrypt() ve _encrypt_deterministic() cagirir.
DOGRUDAN CAGIRMAYIN: salt/nonce buraya DISARIDAN gelir. encrypt() her
cagri icin CSPRNG ile taze uretir; _encrypt_deterministic (test-only)
V5.3'ten itibaren _DETERMINISTIC_MODE opt-in'i ile korunur. Bu core
guard tasimaz (public API ayni koddan gecer), ama her iki tek giris
noktasi da nonce-reuse'u engeller: public=uretilmis taze, deterministic=
fail-closed kapali.
"""
_validate_params(kdf_n, rotation_bytes, salt, nonce)
if keyfile is not None:
_validate_keyfile(keyfile)
if pad_to is not None:
if not 16 <= pad_to <= 65536:
raise ValueError(f"pad_to {pad_to} sinir disi [16..65536]")
plaintext = _pad_iso7816(plaintext, pad_to)
fp = collect_hardware_fingerprint() if use_hardware else b""
master = _derive_master(passphrase, fp, salt, kdf_n, keyfile)
auth_key = None # _derive_auth_key hata verirse wipe(None) -> guvenli
try:
auth_key = _derive_auth_key(master, nonce)
state = _CipherState(master, nonce, rotation_bytes)
ciphertext = state.process(plaintext)
header = _build_header(use_hardware, kdf_n, salt, nonce, fp,
len(plaintext), rotation_bytes,
padded=pad_to is not None,
keyfile=keyfile is not None)
tag = hmac.new(auth_key, header + ciphertext, hashlib.sha512).digest()
return header + ciphertext + tag
finally:
wipe(master)
wipe(auth_key)
def _encrypt_deterministic(plaintext: bytes, passphrase: str, *,
use_hardware: bool, salt: bytes, nonce: bytes,
kdf_n: int = DEFAULT_KDF_N,
rotation_bytes: int = ROTATION_BYTES,
pad_to: int | None = None,
keyfile: bytes | None = None) -> bytes:
"""SADECE ic/test API: encrypt() ile ayni ama salt/nonce SABITTIR.
PUBLIC API'DE KULLANMAYIN. Ayni (salt, nonce) iki farkli mesaj icin
tekrar kullanilirsa keystream ayni olur ve plaintext XOR ile sizabilir
(IC[10] / zafiyet raporu [12]). encrypt() her cagri icin CSPRNG ile
yeni salt/nonce uretir; bu fonksiyon yalnizca deterministik testler
(keystream determinizmi, STS, avalanche, golden vektor, boyut/uzunluk
dogrulamasi) icindir.
V5.3: _DETERMINISTIC_MODE=False iken RuntimeError (fail-closed).
"""
if not _DETERMINISTIC_MODE:
raise RuntimeError(
"_encrypt_deterministic test-only API kapali: "
"_DETERMINISTIC_MODE=False. Public API icin encrypt() kullan "
"(CSPRNG salt/nonce); test ortaminda conftest.py opt-in yapar.")
return _encrypt_core(
plaintext, passphrase, use_hardware=use_hardware,
salt=salt, nonce=nonce, kdf_n=kdf_n,
rotation_bytes=rotation_bytes, pad_to=pad_to, keyfile=keyfile)
def decrypt(packet: bytes, passphrase: str, *,
keyfile: bytes | None = None) -> bytes:
"""Paketi cozer. Yanlis key / kurcalama / farkli makine -> CipherError.
keyfile (v5): paket FLAG_KEYFILE tasiyorsa keyfile ZORUNLU - verilmezse
ayni hata sinifi (CipherError) ile reddedilir (oracle olusturmaz).
Zafiyet raporu [6]: donanim parmak izi erken ayri olarak KONTROL
EDILMEZ. fp zaten master key turetimine giriyor; farkli makinede
master farkli cikar ve HMAC zaten basarisiz olur. Erken fp kiyasi
yalnizca bir timing/hata-mesaji ORACLE'i uretirdi (PBKDF2 atlanirdi).
Tek tarafsiz hata mesaji: hangi dogrulama basarisiz oldu belli olmaz.
rotation_bytes header'dan okunur - encrypt ile birebir ayni deger
garantilenir (yanlis rotation sessizce bozuk plaintext uretemez).
"""
if len(packet) < HEADER_BYTES + TAG_BYTES:
raise CipherError("paket cok kisa")
h = parse_header(packet[:HEADER_BYTES])
use_hw = bool(h.flags & FLAG_HARDWARE)
use_kf = bool(h.flags & FLAG_KEYFILE)
if use_kf and keyfile is None:
# v5: keyfile'li paket keyfile'siz acilamaz. "keyfile gerekli" ipucu
# bir oracle degildir - flag zaten plaintext header'da gorunur.
raise CipherError("bu paket keyfile (ikinci faktor) ile sifrelenmis - "
"aynı keyfile verilmeden acilamaz")
if keyfile is not None and not use_kf:
# V4 zafiyet raporu [3]: paket keyfile korumali DEGILSE keyfile
# SESSIZCE YOK SAYILMAZ - kullanici "keyfile korumali" sanmasin.
# KDF amplifikasyonu ONCESI net hata (fail-closed). Flag plaintext
# header'da gorundugu icin bu hata oracle degildir.
raise CipherError("bu paket keyfile korumali DEGIL - keyfile "
"verilmesi gerekmez (paket yalnizca passphrase "
"ile sifrelenmis)")
if keyfile is not None:
_validate_keyfile(keyfile)
total = HEADER_BYTES + h.data_len + TAG_BYTES
if len(packet) != total:
raise CipherError("paket uzunlugu hatali (kurcalanmis olabilir)")
fp = collect_hardware_fingerprint() if use_hw else b""
master = _derive_master(passphrase, fp, h.salt, h.kdf_n,
keyfile if use_kf else None)
auth_key = None # _derive_auth_key hata verirse wipe(None) -> guvenli
try:
auth_key = _derive_auth_key(master, h.nonce)
ciphertext = packet[HEADER_BYTES:HEADER_BYTES + h.data_len]
tag = packet[HEADER_BYTES + h.data_len:]
expected = hmac.new(auth_key, h.payload + ciphertext,
hashlib.sha512).digest()
if not hmac.compare_digest(expected, tag):
raise CipherError("dogrulama basarisiz - yanlis passphrase, "
"farkli makine veya kurcalanmis veri")
state = _CipherState(master, h.nonce, h.rotation_bytes)
plaintext = state.process(ciphertext)
if h.flags & FLAG_PADDED:
# Zafiyet raporu [18]: header'da data_len PADDING DAHIL uzunluktur;
# HMAC dogrulandiktan SONRA ISO 7816-4 padding kaldirilir.
try:
plaintext = _unpad_iso7816(plaintext)
except ValueError:
raise CipherError("dogrulama basarisiz - yanlis passphrase, "
"farkli makine veya kurcalanmis veri")
return plaintext
finally:
wipe(master)
wipe(auth_key)
# ---------------------------------------------------------------------------
# Dosya stream API (buyuk veri, chunk tabanli)
# ---------------------------------------------------------------------------
def encrypt_file(in_path: str, out_path: str, passphrase: str, *,
use_hardware: bool = True, kdf_n: int = DEFAULT_KDF_N,
rotation_bytes: int = ROTATION_BYTES,
pad_to: int | None = None,
keyfile: bytes | None = None,
progress=None) -> str:
"""Dosyayi chunk chunk sifreler. progress(done, total) cagrisi opsiyonel.
keyfile (v5): encrypt() ile ayni - ikinci faktor. FLAG_KEYFILE set edilir.
GUVENLIK (IC[10]): encrypt() ile ayni politika - salt/nonce kullanicidan
gizlenir, her cagri icin CSPRNG ile uretilir. API sabit nonce kabul
etmez (nonce reuse -> keystream XOR sizintisi). Deterministik
karsilastirmalar icin ic _encrypt_file_deterministic() vardir.
GUVENLIK (zafiyet raporu [1][2][3][9][10]):
- Gecici dosya mkstemp(O_EXCL, 0600, random isim) ile acilir:
symlink/junction saldirisi ve onceden yerlesim imkansiz ([1][2]).
- TOCTOU: boyut open() SONRASI fstat() ile alinir; islem sirasinda
dosya degisirse done != data_len kontrolu paketi reddeder ([3]).
- Girdi normal DOSYA olmali (FIFO/device/dir -> CipherError) ([10]).
- ATOMIC: fsync + os.replace; hata durumunda gecici dosya silinir,
asla yarim/bozuk cikti birakilmaz ([9]).
"""
return _encrypt_file_core(
in_path, out_path, passphrase, use_hardware=use_hardware,
salt=os.urandom(SALT_BYTES), nonce=os.urandom(NONCE_BYTES),
kdf_n=kdf_n, rotation_bytes=rotation_bytes, pad_to=pad_to,
keyfile=keyfile, progress=progress)
def _encrypt_file_core(in_path: str, out_path: str,
passphrase: str, *, use_hardware: bool,
salt: bytes, nonce: bytes,
kdf_n: int = DEFAULT_KDF_N,
rotation_bytes: int = ROTATION_BYTES,
pad_to: int | None = None,
keyfile: bytes | None = None,
progress=None) -> str:
"""IC UYGULAMA CORE - yalnizca encrypt_file() ve
_encrypt_file_deterministic() cagirir.
DOGRUDAN CAGIRMAYIN: salt/nonce disaridan gelir; encrypt_file() CSPRNG
ile taze uretir, _encrypt_file_deterministic (test-only) V5.3'ten
itibaren _DETERMINISTIC_MODE opt-in'i ile korunur. Iki giris noktasi
da nonce-reuse'u engeller (bkz. _encrypt_core docstring).
"""
_validate_params(kdf_n, rotation_bytes, salt, nonce)
if keyfile is not None:
_validate_keyfile(keyfile)
if pad_to is not None and not 16 <= pad_to <= 65536:
raise ValueError(f"pad_to {pad_to} sinir disi [16..65536]")
fp = collect_hardware_fingerprint() if use_hardware else b""
# BULGU 17 fix (arastirma: "create secrets late, destroy early" + RAII
# wipe-on-all-paths + "zeroize before returning error"): onceki siralamada
# master derive EDILDIKTEN sonra _make_tmp_near try DISINDA cagrilirdi;
# tmp olusturma hata verirse (orn. hedef dizin yok) finally hic calismaz
# ve 256B master wipe edilmeden GC'ye kalirdi (ampirik: ProcessLookupError
# ile kanitlandi). En guclu cozum: once kaynak (tmp) tahsis edilir, master
# ise try ICINDE turetilir - boylece tum hata yollari finally/wipe kapsamina
# girer ve secret mumkun olan EN GEK anda olusturulur (yasam suresi minimum).
fd, tmp_path = _make_tmp_near(out_path)
fout = None