Repository navigation
Expand file tree
/
Copy pathencryption_engine.py
More file actions
257 lines (218 loc) · 11.2 KB
/
Copy pathencryption_engine.py
File metadata and controls
257 lines (218 loc) · 11.2 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
import os
import time
import json
import pandas as pd
from status_manager import StatusManager
try:
import oqs
except ImportError:
oqs = None
try:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidTag
CRYPTO_OK = True
except ImportError:
CRYPTO_OK = False
try:
from scapy.all import rdpcap
from feature_extraction import get_payload
except ImportError:
rdpcap = None
try:
import psutil
except ImportError:
psutil = None
# Newer liboqs uses the "ML-KEM-xxx" names; older ones only know "Kyber xxx".
KEM_NAMES = {"HYBRID_1024": ["ML-KEM-1024", "Kyber1024"],
"HYBRID_768": ["ML-KEM-768", "Kyber768"]}
KEY_LEN = {"AES-256-GCM": 32, "AES-128-GCM": 16, "ChaCha20-Poly1305": 32}
SELF_CHECK_PACKETS = 20 # how many packets get the decrypt + tamper test
def _pq_secret(kex):
"""Real ML-KEM key agreement via liboqs. Both sides are simulated in this one program."""
if oqs is None:
raise RuntimeError("liboqs-python (oqs) not installed -- needed for ML-KEM")
last = None
for name in KEM_NAMES[kex]:
try:
with oqs.KeyEncapsulation(name) as kem:
public_key = kem.generate_keypair()
ciphertext, ss_sender = kem.encap_secret(public_key)
ss_receiver = kem.decap_secret(ciphertext)
if ss_sender != ss_receiver:
raise RuntimeError("ML-KEM secrets do not match")
return ss_sender, name
except Exception as e:
last = e
raise RuntimeError(f"ML-KEM not available in this liboqs build: {last}")
def establish_session(kex, cipher_name, flow_id):
"""
Key agreement for ONE conversation, then HKDF (RFC 5869) to make the real key.
X25519 : normal (classical) key exchange
HYBRID_xxx : X25519 secret + ML-KEM secret joined, then HKDF (hybrid)
Returns (key, handshake_ms, label)
"""
t0 = time.perf_counter()
a, b = X25519PrivateKey.generate(), X25519PrivateKey.generate()
ss_classic = a.exchange(b.public_key())
if ss_classic != b.exchange(a.public_key()):
raise RuntimeError("X25519 secrets do not match")
ikm, label = ss_classic, "X25519"
if kex.startswith("HYBRID"):
ss_pq, kem_name = _pq_secret(kex)
ikm = ss_classic + ss_pq
label = f"X25519+{kem_name}"
info = f"APQCrypt-v1|{flow_id}|{cipher_name}".encode()
key = HKDF(algorithm=hashes.SHA256(), length=KEY_LEN[cipher_name], salt=None, info=info).derive(ikm)
return key, (time.perf_counter() - t0) * 1000, label
class FlowSession:
__slots__ = ("aead", "cipher_name", "key", "handshake_ms", "label")
def __init__(self, key, cipher_name, handshake_ms, label):
self.key = key
self.cipher_name = cipher_name
self.handshake_ms = handshake_ms
self.label = label
self.aead = AESGCM(key) if cipher_name.startswith("AES") else ChaCha20Poly1305(key)
def encrypt_payload(session, plaintext, aad=b""):
"""AEAD encryption (also detects tampering). Returns (nonce+ciphertext+tag, microseconds)."""
t0 = time.perf_counter_ns()
nonce = os.urandom(12)
ct = nonce + session.aead.encrypt(nonce, plaintext, aad)
return ct, (time.perf_counter_ns() - t0) / 1000
def decrypt_payload(session, blob, aad=b""):
return session.aead.decrypt(blob[:12], blob[12:], aad)
def get_flow_id(rec):
if rec.get("Flow_ID") and str(rec.get("Flow_ID")) != "NA":
return str(rec["Flow_ID"])
a = (str(rec.get("Source_IP", "")), int(rec.get("Source_Port", 0) or 0))
b = (str(rec.get("Destination_IP", "")), int(rec.get("Dest_Port", 0) or 0))
return str(tuple(sorted([a, b])))
class EncryptionEngine:
def __init__(self, output_file="data/encrypted_results.csv"):
self.output_file = output_file
self.start_time = None
self.last_stats = {}
def encrypt_traffic(self, policy_file, pcap_file):
try:
if not os.path.exists(policy_file):
StatusManager.update_status("Encryption", f"Error: Policy file not found: {policy_file}")
return None
if not os.path.exists(pcap_file):
StatusManager.update_status("Encryption", f"Error: PCAP file not found: {pcap_file}")
return None
if rdpcap is None:
StatusManager.update_status("Encryption", "Error: Scapy not available")
return None
if not CRYPTO_OK:
StatusManager.update_status("Encryption", "Error: cryptography library not available")
return None
self.start_time = time.time()
StatusManager.update_status("Encryption", "Loading policy decisions and packet payloads...", 99)
df = pd.read_csv(policy_file)
if len(df) == 0:
StatusManager.update_status("Encryption", "Error: Policy file is empty")
return None
packets = rdpcap(pcap_file)
records = df.to_dict("records")
n = len(records)
# Timing starts HERE, after the file is loaded, so the numbers measure
# key exchange + encryption only (reading the pcap is the same for every mode).
wall0, cpu0 = time.perf_counter(), time.process_time()
sessions = {}
ct_len, enc_us, hs_ms, new_hs, flow_ids, kex_used, pay_len = ([None] * n for _ in range(7))
new_hs = [False] * n
flow_first = {} # flow -> (sensitivity, label)
checks = {"roundtrip_ok": 0, "roundtrip_fail": 0, "tamper_detected": 0, "tamper_missed": 0}
checked = 0
for i, rec in enumerate(records):
pkt_idx = int(rec["Pkt_Index"]) if rec.get("Pkt_Index") is not None and pd.notna(rec.get("Pkt_Index")) else i
pkt = packets[pkt_idx] if 0 <= pkt_idx < len(packets) else None # match by packet number
flow_id = get_flow_id(rec)
flow_ids[i] = flow_id
cipher_name = str(rec.get("Symmetric_Cipher", "AES-256-GCM"))
kex = str(rec.get("Key_Exchange", "")) or ("HYBRID_1024" if rec.get("PQC_Handshake_Used") else "X25519")
if kex not in ("X25519", "HYBRID_768", "HYBRID_1024"):
kex = "HYBRID_1024" if rec.get("PQC_Handshake_Used") else "X25519"
if flow_id not in sessions:
key, hms, label = establish_session(kex, cipher_name, flow_id)
sessions[flow_id] = FlowSession(key, cipher_name, hms, label)
hs_ms[i] = round(hms, 4)
new_hs[i] = True
flow_first[flow_id] = (str(rec.get("Sensitivity", "")), label)
session = sessions[flow_id]
kex_used[i] = session.label
payload = get_payload(pkt) if pkt is not None else b""
pay_len[i] = len(payload)
if not payload:
ct_len[i], enc_us[i] = 0, 0.0
continue
aad = flow_id.encode()
ct, us = encrypt_payload(session, payload, aad)
ct_len[i], enc_us[i] = len(ct), round(us, 2)
# ---- self-checks on a small sample: decrypt must match, tampering must be caught ----
if checked < SELF_CHECK_PACKETS:
checked += 1
try:
checks["roundtrip_ok" if decrypt_payload(session, ct, aad) == payload else "roundtrip_fail"] += 1
except Exception:
checks["roundtrip_fail"] += 1
bad = ct[:-1] + bytes([ct[-1] ^ 0x01])
try:
decrypt_payload(session, bad, aad)
checks["tamper_missed"] += 1
except InvalidTag:
checks["tamper_detected"] += 1
if i % 200 == 0:
StatusManager.update_status("Encryption", f"Encrypting... {i}/{n} packets ({len(sessions)} flows)", 99)
out = df.copy()
out["Flow_Key"] = flow_ids
out["New_Flow_Handshake"] = new_hs
out["Handshake_Time_ms"] = hs_ms
out["Key_Exchange_Used"] = kex_used
out["Payload_Length"] = pay_len
out["Ciphertext_Length"] = ct_len
out["Encrypt_Time_us"] = enc_us
tmp = self.output_file + ".tmp"
out.to_csv(tmp, index=False)
os.replace(tmp, self.output_file)
high_flows = [f for f, (s, _l) in flow_first.items() if s == "HIGH"]
high_pq = [f for f in high_flows if "ML-KEM" in flow_first[f][1] or "Kyber" in flow_first[f][1]]
pq_flows = [f for f, (_s, l) in flow_first.items() if "ML-KEM" in l or "Kyber" in l]
total_hs = sum(h for h in hs_ms if h)
total_enc_us = sum(e for e in enc_us if e)
payload_total = sum(p for p in pay_len if p)
ct_total = sum(c for c in ct_len if c)
self.last_stats = {
"wall_s": round(time.perf_counter() - wall0, 4),
"cpu_s": round(time.process_time() - cpu0, 4),
"mem_mb": round(psutil.Process().memory_info().rss / 1e6, 1) if psutil else None,
"packets": n, "flows": len(sessions),
"pq_flows": len(pq_flows),
"pq_flow_share": round(len(pq_flows) / max(1, len(sessions)), 3),
"high_flows": len(high_flows), "high_flows_pq": len(high_pq),
"high_pq_coverage": round(len(high_pq) / len(high_flows), 3) if high_flows else None,
"handshake_ms_total": round(total_hs, 3),
"encrypt_ms_total": round(total_enc_us / 1000, 3),
"overhead_bytes": int(ct_total - payload_total),
"checks": checks,
}
try:
with open("data/encryption_checks.json", "w") as f:
json.dump({"checks": checks, **{k: v for k, v in self.last_stats.items() if k != "checks"}}, f, indent=2)
except Exception:
pass
StatusManager.record_module_timing("Encryption Engine", time.time() - self.start_time)
msg = (f"✓ Encryption Complete | {n} packets | {len(sessions)} flows | {len(pq_flows)} quantum-safe (hybrid) flows | "
f"Handshake total: {round(total_hs, 2)}ms | Encrypt total: {round(total_enc_us / 1000, 2)}ms | "
f"Decrypt checks OK: {checks['roundtrip_ok']} | Tamper caught: {checks['tamper_detected']}/"
f"{checks['tamper_detected'] + checks['tamper_missed']} | File: {self.output_file}")
print(f"[DEBUG] {msg}")
StatusManager.update_status("Encryption", msg, 100)
return self.output_file
except Exception as e:
import traceback
print(f"[DEBUG] Encryption engine error:\n{traceback.format_exc()}")
StatusManager.update_status("Encryption", f"Error: {str(e)}")
return None