-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfernet.lua
More file actions
480 lines (435 loc) · 16.2 KB
/
Copy pathfernet.lua
File metadata and controls
480 lines (435 loc) · 16.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
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
-- fernet.lua — Implémentation GLua/Fernet 0x80 (AES-128-CBC + HMAC-SHA256 + Base64URL)
-- Usage rapide :
-- if SERVER then AddCSLuaFile() end
-- local fernet = include("fernet.lua")
-- local key = fernet.generate_key() -- clé base64url (32 octets internes : 16 sign + 16 enc)
-- local token = fernet.encrypt(key, "coucou le monde")
-- local plain = assert(fernet.decrypt(token, key, 60)) -- TTL 60 s (optionnel)
local fernet = {}
local bit = bit or require("bit")
local bor, band, bxor, lshift, rshift = bit.bor, bit.band, bit.bxor, bit.lshift, bit.rshift
----------------------------------------------------------------------
-- Utils : chaînes/bytes
----------------------------------------------------------------------
local function tobytes_hex(hex)
-- "a0b1..." -> string binaire
local out = {}
for i = 1, #hex, 2 do
out[#out+1] = string.char(tonumber(hex:sub(i, i+1), 16))
end
return table.concat(out)
end
local function bytes_xor_str(a, b) -- xor deux strings binaires de même taille
local out, la = {}, #a
for i = 1, la do
out[i] = string.char(bxor(a:byte(i), b:byte(i)))
end
return table.concat(out)
end
local function pad_pkcs7(s, block)
local pad = block - (#s % block)
if pad == 0 then pad = block end
return s .. string.rep(string.char(pad), pad)
end
local function unpad_pkcs7(s, block)
local n = #s
if n == 0 then return nil, "plain vide" end
local pad = s:byte(n)
if pad < 1 or pad > block or pad > n then return nil, "padding PKCS#7 invalide" end
for i = n - pad + 1, n do
if s:byte(i) ~= pad then return nil, "padding PKCS#7 invalide" end
end
return s:sub(1, n - pad)
end
local function consttime_eq(a, b)
if #a ~= #b then return false end
local acc = 0
for i = 1, #a do
acc = bor(acc, bxor(a:byte(i), b:byte(i)))
end
return acc == 0
end
local function pack_uint64_be(sec)
-- 64-bit big-endian ; on n’utilise que 32 bits hauts à 0 (sec <= 0xFFFFFFFF)
local s = {}
s[1],s[2],s[3],s[4] = 0,0,0,0
s[5] = band(rshift(sec, 24), 0xFF)
s[6] = band(rshift(sec, 16), 0xFF)
s[7] = band(rshift(sec, 8), 0xFF)
s[8] = band(sec, 0xFF)
return string.char(s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8])
end
----------------------------------------------------------------------
-- Base64URL (util.* si dispo, sinon fallback pur Lua)
----------------------------------------------------------------------
local B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function b64_encode_pure(data)
local t, pad = {}, ''
for i = 1, #data, 3 do
local a = data:byte(i) or 0
local b = data:byte(i+1) or 0
local c = data:byte(i+2) or 0
local n = a*65536 + b*256 + c
local c1 = math.floor(n / 262144) % 64 + 1
local c2 = math.floor(n / 4096) % 64 + 1
local c3 = math.floor(n / 64) % 64 + 1
local c4 = n % 64 + 1
if i+1 > #data then c3, c4, pad = 65, 65, '==' -- 65 will be '=' placeholder
elseif i+2 > #data then c4, pad = 65, '=' -- 65 will be '=' placeholder
end
t[#t+1] = B64:sub(c1,c1) .. B64:sub(c2,c2) ..
(c3==65 and '=' or B64:sub(c3,c3)) ..
(c4==65 and '=' or B64:sub(c4,c4))
end
return table.concat(t)
end
local B64_INV = {}
for i = 1, #B64 do B64_INV[B64:byte(i)] = i - 1 end
B64_INV[string.byte('=')] = 0
local function b64_decode_pure(s)
s = s:gsub("%s", "")
local t = {}
for i = 1, #s, 4 do
local a = B64_INV[s:byte(i)] or 0
local b = B64_INV[s:byte(i+1)] or 0
local c = B64_INV[s:byte(i+2)] or 0
local d = B64_INV[s:byte(i+3)] or 0
local n = a*262144 + b*4096 + c*64 + d
local x = string.char(math.floor(n/65536)%256, math.floor(n/256)%256, n%256)
if s:sub(i+2, i+2) == '=' then x = x:sub(1,1)
elseif s:sub(i+3, i+3) == '=' then x = x:sub(1,2) end
t[#t+1] = x
end
return table.concat(t)
end
local function b64url_encode(data)
local enc
if util and util.Base64Encode then
enc = util.Base64Encode(data)
else
enc = b64_encode_pure(data)
end
enc = enc:gsub('+','-'):gsub('/','_'):gsub('=','')
return enc
end
local function b64url_decode(s)
local std = s:gsub('-','+'):gsub('_','/')
local pad = #std % 4
if pad == 2 then std = std .. '=='
elseif pad == 3 then std = std .. '='
elseif pad ~= 0 then
-- pad 1 est impossible en base64url ; on peut lever une erreur
error("Base64URL invalide")
end
if util and util.Base64Decode then
return util.Base64Decode(std)
else
return b64_decode_pure(std)
end
end
----------------------------------------------------------------------
-- HMAC-SHA256 via util.SHA256 (renvoie hex) -> converti en binaire
----------------------------------------------------------------------
local function sha256_hex(s)
if not util or not util.SHA256 then
error("util.SHA256 indisponible : nécessaire pour HMAC-SHA256 dans GMod")
end
return util.SHA256(s)
end
local function hmac_sha256(key, data)
local block = 64
if #key > block then
key = tobytes_hex(sha256_hex(key))
end
if #key < block then
key = key .. string.rep('\0', block - #key)
end
local o_key_pad, i_key_pad = {}, {}
for i = 1, block do
local kb = key:byte(i)
o_key_pad[i] = string.char(bxor(kb, 0x5c))
i_key_pad[i] = string.char(bxor(kb, 0x36))
end
o_key_pad = table.concat(o_key_pad)
i_key_pad = table.concat(i_key_pad)
local inner_hex = sha256_hex(i_key_pad .. data)
local inner_bin = tobytes_hex(inner_hex)
local outer_hex = sha256_hex(o_key_pad .. inner_bin)
return tobytes_hex(outer_hex) -- 32 octets binaires
end
----------------------------------------------------------------------
-- AES-128 (pur Lua) — SubBytes, ShiftRows, MixColumns, KeyExpansion
----------------------------------------------------------------------
local S = {
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0xa0,0xe0,0x3b,0x52,0x9b,0xd6,
0xB,0x29,0xE3,0x2F,0x84,0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,
0x39,0x4A,0x4C,0x58,0xCF,0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,
0x7F,0x50,0x3C,0x9F,0xA8,0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,
0x21,0x10,0xFF,0xF3,0xD2,0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,
0x3D,0x64,0x5D,0x19,0x73,0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,
0x14,0xDE,0x5E,0x0B,0xDB,0xE0-1,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,
0x62,0x91,0x95,0xE4,0x79,0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,
0xEA,0x65,0x7A,0xAE,0x08,0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,
0x1F,0x4B,0xBD,0x8B,0x8A,0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,
0xB9,0x86,0xC1,0x1D,0x9E,0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,
0xE9,0xCE,0x55,0x28,0xDF,0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,
0x0F,0xB0,0x54,0xBB,0x16
}
-- Corrige une coquille (0xE0-1->0xDF) si le rendu Markdown a cassé la ligne au dessus :
S[106] = 0xDF
local Si = { -- inverse S-box
0x52,0x09,0x6A,0xD5,0x30,0x36,0xA5,0x38,0xBF,0x40,0xA3,0x9E,0x81,0xF3,0xD7,0xFB,
0x7C,0xE3,0x39,0x82,0x9B,0x2F,0xFF,0x87,0x34,0x8E,0x43,0x44,0xC4,0xDE,0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,0x69,0x14,0x63,0x55,0x21,0x0C,0x7D
}
local Rcon = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1B,0x36}
local function xtime(a)
a = band(lshift(a,1),0xFF)
return band(a,0xFF)
end
local function gf_mul(a, b)
local p = 0
for _ = 1, 8 do
if band(b,1) ~= 0 then p = bxor(p,a) end
local hi = band(a,0x80)
a = band(lshift(a,1),0xFF)
if hi ~= 0 then a = bxor(a,0x1B) end
b = rshift(b,1)
end
return band(p,0xFF)
end
local function sub_word(word) -- 4 bytes table
return { S[word[1]+1], S[word[2]+1], S[word[3]+1], S[word[4]+1] }
end
local function rot_word(word)
return { word[2], word[3], word[4], word[1] }
end
local function key_expansion(key16)
local w = {} -- 44 words of 4 bytes
for i=1,4 do
local b = { key16:byte(4*(i-1)+1, 4*i) }
w[i] = { b[1], b[2], b[3], b[4] }
end
for i=5,44 do
local temp = { w[i-1][1], w[i-1][2], w[i-1][3], w[i-1][4] }
if (i-1) % 4 == 0 then
temp = sub_word(rot_word(temp))
temp[1] = bxor(temp[1], Rcon[(i-1)//4])
end
local prev = w[i-4]
w[i] = {
bxor(prev[1], temp[1]),
bxor(prev[2], temp[2]),
bxor(prev[3], temp[3]),
bxor(prev[4], temp[4]),
}
end
-- Round keys : 11 * 16 bytes
local rks = {}
for r=0,10 do
local idx = 4*r + 1
local words = { w[idx], w[idx+1], w[idx+2], w[idx+3] }
local bytes = {}
for j=1,4 do
bytes[#bytes+1] = words[j][1]
bytes[#bytes+1] = words[j][2]
bytes[#bytes+1] = words[j][3]
bytes[#bytes+1] = words[j][4]
end
rks[r+1] = bytes -- table of 16 bytes
end
return rks
end
local function add_round_key(s, rk)
for i=1,16 do s[i] = bxor(s[i], rk[i]) end
end
local function sub_bytes(s)
for i=1,16 do s[i] = S[s[i]+1] end
end
local function inv_sub_bytes(s)
for i=1,16 do s[i] = Si[s[i]+1] end
end
local function shift_rows(s)
-- s indexation : col-major ; lignes (1-based):
-- L0: 1,5,9,13 (inchangé)
-- L1: 2,6,10,14 -> rotation gauche 1
local t = s[2]; s[2]=s[6]; s[6]=s[10]; s[10]=s[14]; s[14]=t
-- L2: 3,7,11,15 -> rotation gauche 2
t=s[3]; local u=s[7]; s[3]=s[11]; s[7]=s[15]; s[11]=t; s[15]=u
-- L3: 4,8,12,16 -> rotation gauche 3 (droite 1)
t=s[16]; s[16]=s[12]; s[12]=s[8]; s[8]=s[4]; s[4]=t
end
local function inv_shift_rows(s)
-- inverse des rotations
local t = s[14]; s[14]=s[10]; s[10]=s[6]; s[6]=s[2]; s[2]=t
t=s[11]; local u=s[15]; s[11]=s[3]; s[15]=s[7]; s[3]=t; s[7]=u
t=s[4]; s[4]=s[8]; s[8]=s[12]; s[12]=s[16]; s[16]=t
end
local function mix_columns(s)
for c=0,3 do
local i = 4*c + 1
local a0,a1,a2,a3 = s[i],s[i+1],s[i+2],s[i+3]
local r0 = bxor(gf_mul(a0,2), gf_mul(a1,3), a2, a3)
local r1 = bxor(a0, gf_mul(a1,2), gf_mul(a2,3), a3)
local r2 = bxor(a0, a1, gf_mul(a2,2), gf_mul(a3,3))
local r3 = bxor(gf_mul(a0,3), a1, a2, gf_mul(a3,2))
s[i],s[i+1],s[i+2],s[i+3] = r0,r1,r2,r3
end
end
local function inv_mix_columns(s)
for c=0,3 do
local i = 4*c + 1
local a0,a1,a2,a3 = s[i],s[i+1],s[i+2],s[i+3]
local r0 = bxor(gf_mul(a0,14), gf_mul(a1,11), gf_mul(a2,13), gf_mul(a3,9))
local r1 = bxor(gf_mul(a0,9), gf_mul(a1,14), gf_mul(a2,11), gf_mul(a3,13))
local r2 = bxor(gf_mul(a0,13), gf_mul(a1,9), gf_mul(a2,14), gf_mul(a3,11))
local r3 = bxor(gf_mul(a0,11), gf_mul(a1,13), gf_mul(a2,9), gf_mul(a3,14))
s[i],s[i+1],s[i+2],s[i+3] = r0,r1,r2,r3
end
end
local function aes_encrypt_block(block16, rks)
local s = { block16:byte(1,16) }
add_round_key(s, rks[1])
for r=2,10 do
sub_bytes(s); shift_rows(s)
if r ~= 11 then mix_columns(s) end
add_round_key(s, rks[r])
end
return string.char(unpack(s))
end
local function aes_decrypt_block(block16, rks)
local s = { block16:byte(1,16) }
add_round_key(s, rks[11])
for r=10,2,-1 do
inv_shift_rows(s); inv_sub_bytes(s)
add_round_key(s, rks[r])
if r ~= 2 then inv_mix_columns(s) end
end
return string.char(unpack(s))
end
local function aes_cbc_encrypt(key16, iv16, plain)
local rks = key_expansion(key16)
local out, prev = {}, iv16
local data = pad_pkcs7(plain, 16)
for i=1, #data, 16 do
local block = data:sub(i, i+15)
local x = bytes_xor_str(block, prev)
local e = aes_encrypt_block(x, rks)
out[#out+1] = e
prev = e
end
return table.concat(out)
end
local function aes_cbc_decrypt(key16, iv16, ciph)
local rks = key_expansion(key16)
local out, prev = {}, iv16
for i=1, #ciph, 16 do
local block = ciph:sub(i, i+15)
local d = aes_decrypt_block(block, rks)
out[#out+1] = bytes_xor_str(d, prev)
prev = block
end
return table.concat(out)
end
----------------------------------------------------------------------
-- RNG (faible par défaut) + injection CSPRNG
----------------------------------------------------------------------
local _rng_state = tostring(os.time()) .. tostring(math.random()) .. (SysTime and tostring(SysTime()) or "")
for i=1,8 do _rng_state = util and util.SHA256 and util.SHA256(_rng_state) or (_rng_state .. tostring(math.random())) end
local function weak_random_bytes(n)
local out = {}
for i=1,n do
-- mélange pauvre ; remplacez par une vraie source d’aléa si possible
local h = util and util.SHA256 and util.SHA256(_rng_state .. tostring(i) .. tostring(SysTime and SysTime() or os.clock())) or (_rng_state .. i)
_rng_state = h
local b = 0
if util and util.SHA256 then b = tonumber(h:sub((i%60)+1, (i%60)+2), 16) or math.random(0,255)
else b = math.random(0,255) end
out[i] = string.char(band(b,0xFF))
end
return table.concat(out)
end
local random_bytes = weak_random_bytes
function fernet.set_random(fn)
assert(type(fn) == "function", "set_random attend une fonction n -> string binaire")
random_bytes = fn
end
----------------------------------------------------------------------
-- API FERNET
----------------------------------------------------------------------
function fernet.generate_key()
-- spec : clé = base64url( signing_key(16) || encryption_key(16) )
local signing = random_bytes(16)
local enc = random_bytes(16)
return b64url_encode(signing .. enc)
end
local function derive_keys(key_b64url)
local raw = b64url_decode(key_b64url)
assert(#raw == 32, "Clé Fernet invalide (doit être base64url de 32 octets)")
local signing_key = raw:sub(1,16)
local enc_key = raw:sub(17,32)
return signing_key, enc_key
end
function fernet.encrypt(key_b64url, plaintext, now)
assert(type(plaintext) == "string", "plaintext doit être une string")
local signing_key, enc_key = derive_keys(key_b64url)
local version = string.char(0x80) -- version 0x80
local ts = pack_uint64_be(now or os.time())
local iv = random_bytes(16)
local ciphertext = aes_cbc_encrypt(enc_key, iv, plaintext)
local mac_input = version .. ts .. iv .. ciphertext
local mac = hmac_sha256(signing_key, mac_input)
local token = b64url_encode(mac_input .. mac)
return token
end
function fernet.decrypt(token_b64url, key_b64url, ttl_sec, now)
local signing_key, enc_key = derive_keys(key_b64url)
local blob = b64url_decode(token_b64url)
if #blob < 1+8+16+16+32 then
return nil, "Token trop court"
end
local version = blob:byte(1)
if version ~= 0x80 and version ~= 0x81 then
return nil, "Version inconnue"
end
local ts_bytes = blob:sub(2,9)
local iv = blob:sub(10,25)
local mac = blob:sub(#blob-32+1, #blob)
local ciphertext = blob:sub(26, #blob-32)
-- TTL
if ttl_sec and ttl_sec > 0 then
local s5,s6,s7,s8 = ts_bytes:byte(5,8) -- seconds (32-bit) position
local ts = (s5*16777216) + (s6*65536) + (s7*256) + s8
local now_s = now or os.time()
if now_s - ts > ttl_sec then
return nil, "Token expiré"
end
end
-- vérif HMAC (constant-time)
local mac_input = string.char(version) .. ts_bytes .. iv .. ciphertext
local expected = hmac_sha256(signing_key, mac_input)
if not consttime_eq(mac, expected) then
return nil, "HMAC invalide"
end
local plain = aes_cbc_decrypt(enc_key, iv, ciphertext)
local unp, err = unpad_pkcs7(plain, 16)
if not unp then return nil, err end
return unp
end
return fernet