-
Notifications
You must be signed in to change notification settings - Fork 111
/
session.lua
2839 lines (2324 loc) · 79.7 KB
/
session.lua
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
---
-- Session library.
--
-- Session library provides HTTP session management capabilities for OpenResty based
-- applications, libraries and proxies.
--
-- @module resty.session
local require = require
local table_new = require "table.new"
local isempty = require "table.isempty"
local buffer = require "string.buffer"
local utils = require "resty.session.utils"
local clear_request_header = ngx.req.clear_header
local set_request_header = ngx.req.set_header
local setmetatable = setmetatable
local http_time = ngx.http_time
local tonumber = tonumber
local select = select
local assert = assert
local remove = table.remove
local header = ngx.header
local error = error
local floor = math.ceil
local time = ngx.time
local byte = string.byte
local type = type
local sub = string.sub
local fmt = string.format
local var = ngx.var
local log = ngx.log
local max = math.max
local min = math.min
local derive_aes_gcm_256_key_and_iv = utils.derive_aes_gcm_256_key_and_iv
local derive_hmac_sha256_key = utils.derive_hmac_sha256_key
local encrypt_aes_256_gcm = utils.encrypt_aes_256_gcm
local decrypt_aes_256_gcm = utils.decrypt_aes_256_gcm
local encode_base64url = utils.encode_base64url
local decode_base64url = utils.decode_base64url
local load_storage = utils.load_storage
local encode_json = utils.encode_json
local decode_json = utils.decode_json
local base64_size = utils.base64_size
local hmac_sha256 = utils.hmac_sha256
local rand_bytes = utils.rand_bytes
local unset_flag = utils.unset_flag
local set_flag = utils.set_flag
local has_flag = utils.has_flag
local inflate = utils.inflate
local deflate = utils.deflate
local bunpack = utils.bunpack
local errmsg = utils.errmsg
local sha256 = utils.sha256
local bpack = utils.bpack
local trim = utils.trim
local NOTICE = ngx.NOTICE
local WARN = ngx.WARN
local KEY_SIZE = 32
--[ HEADER ----------------------------------------------------------------------------------------------------] || [ PAYLOAD --]
--[ Type || Flags || Session ID || Creation Time || Rolling Offset || Data Size || Tag || Idling Offset || Mac ] || [ Data ]
--[ 1B || 2B || 32B || 5B || 4B || 3B || 16B || 3B || 16B ] || [ *B ]
local COOKIE_TYPE_SIZE = 1 -- 1
local FLAGS_SIZE = 2 -- 3
local SID_SIZE = 32 -- 35
local CREATION_TIME_SIZE = 5 -- 40
local ROLLING_OFFSET_SIZE = 4 -- 44
local DATA_SIZE = 3 -- 47
local TAG_SIZE = 16 -- 63
local IDLING_OFFSET_SIZE = 3 -- 66
local MAC_SIZE = 16 -- 82
local HEADER_TAG_SIZE = COOKIE_TYPE_SIZE + FLAGS_SIZE + SID_SIZE + CREATION_TIME_SIZE + ROLLING_OFFSET_SIZE + DATA_SIZE
local HEADER_TOUCH_SIZE = HEADER_TAG_SIZE + TAG_SIZE
local HEADER_MAC_SIZE = HEADER_TOUCH_SIZE + IDLING_OFFSET_SIZE
local HEADER_SIZE = HEADER_MAC_SIZE + MAC_SIZE
local HEADER_ENCODED_SIZE = base64_size(HEADER_SIZE)
local COOKIE_TYPE = bpack(COOKIE_TYPE_SIZE, 1)
local MAX_COOKIE_SIZE = 4096
local MAX_COOKIES = 9
local MAX_COOKIES_SIZE = MAX_COOKIES * MAX_COOKIE_SIZE -- 36864 bytes
local MAX_CREATION_TIME = 2 ^ (CREATION_TIME_SIZE * 8) - 1 -- ~34789 years
local MAX_ROLLING_OFFSET = 2 ^ (ROLLING_OFFSET_SIZE * 8) - 1 -- ~136 years
local MAX_IDLING_OFFSET = 2 ^ (IDLING_OFFSET_SIZE * 8) - 1 -- ~194 days
local MAX_DATA_SIZE = 2 ^ (DATA_SIZE * 8) - 1 -- 16777215 bytes
local MAX_TTL = 34560000 -- 400 days
-- see: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-11#section-4.1.2.1
local FLAGS_NONE = 0x0000
local FLAG_STORAGE = 0x0001
local FLAG_FORGET = 0x0002
local FLAG_DEFLATE = 0x0010
local DEFAULT_AUDIENCE = "default"
local DEFAULT_SUBJECT
local DEFAULT_ENFORCE_SAME_SUBJECT = false
local DEFAULT_META = {}
local DEFAULT_IKM
local DEFAULT_IKM_FALLBACKS
local DEFAULT_HASH_STORAGE_KEY = false
local DEFAULT_HASH_SUBJECT = false
local DEFAULT_STORE_METADATA = false
local DEFAULT_TOUCH_THRESHOLD = 60 -- 1 minute
local DEFAULT_COMPRESSION_THRESHOLD = 1024 -- 1 kB
local DEFAULT_REQUEST_HEADERS
local DEFAULT_RESPONSE_HEADERS
local DEFAULT_COOKIE_NAME = "session"
local DEFAULT_COOKIE_PATH = "/"
local DEFAULT_COOKIE_SAME_SITE = "Lax"
local DEFAULT_COOKIE_SAME_PARTY
local DEFAULT_COOKIE_PRIORITY
local DEFAULT_COOKIE_PARTITIONED
local DEFAULT_COOKIE_HTTP_ONLY = true
local DEFAULT_COOKIE_PREFIX
local DEFAULT_COOKIE_DOMAIN
local DEFAULT_COOKIE_SECURE
local DEFAULT_REMEMBER_COOKIE_NAME = "remember"
local DEFAULT_REMEMBER_SAFETY = "Medium"
local DEFAULT_REMEMBER_META = false
local DEFAULT_REMEMBER = false
local DEFAULT_STALE_TTL = 10 -- 10 seconds
local DEFAULT_IDLING_TIMEOUT = 900 -- 15 minutes
local DEFAULT_ROLLING_TIMEOUT = 3600 -- 1 hour
local DEFAULT_ABSOLUTE_TIMEOUT = 86400 -- 1 day
local DEFAULT_REMEMBER_ROLLING_TIMEOUT = 604800 -- 1 week
local DEFAULT_REMEMBER_ABSOLUTE_TIMEOUT = 2592000 -- 30 days
local DEFAULT_STORAGE
local STATE_NEW = "new"
local STATE_OPEN = "open"
local STATE_CLOSED = "closed"
local AT_BYTE = byte("@")
local EQUALS_BYTE = byte("=")
local SEMICOLON_BYTE = byte(";")
local COOKIE_EXPIRE_FLAGS = "; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0"
local HEADER_BUFFER = buffer.new(HEADER_SIZE)
local FLAGS_BUFFER = buffer.new(128)
local DATA_BUFFER = buffer.new(MAX_COOKIES_SIZE)
local HIDE_BUFFER = buffer.new(256)
local DATA = table_new(2, 0)
local HEADERS = {
id = "Session-Id",
audience = "Session-Audience",
subject = "Session-Subject",
timeout = "Session-Timeout",
idling_timeout = "Session-Idling-Timeout",
["idling-timeout"] = "Session-Idling-Timeout",
rolling_timeout = "Session-Rolling-Timeout",
["rolling-timeout"] = "Session-Rolling-Timeout",
absolute_timeout = "Session-Absolute-Timeout",
["absolute-timeout"] = "Session-Absolute-Timeout",
}
local function set_response_header(name, value)
header[name] = value
end
local function sha256_storage_key(sid)
local key, err = sha256(sid)
if not key then
return nil, errmsg(err, "unable to sha256 hash session id")
end
if SID_SIZE ~= 32 then
key = sub(key, 1, SID_SIZE)
end
key, err = encode_base64url(key)
if not key then
return nil, errmsg(err, "unable to base64url encode session id")
end
return key
end
local function sha256_subject(subject)
local hashed_subject, err = sha256(subject)
if not hashed_subject then
return nil, errmsg(err, "unable to sha256 hash subject")
end
hashed_subject, err = encode_base64url(sub(hashed_subject, 1, 16))
if not hashed_subject then
return nil, errmsg(err, "unable to base64url encode subject")
end
return hashed_subject
end
local function calculate_mac(ikm, nonce, msg)
local mac_key, err = derive_hmac_sha256_key(ikm, nonce)
if not mac_key then
return nil, errmsg(err, "unable to derive session message authentication key")
end
local mac, err = hmac_sha256(mac_key, msg)
if not mac then
return nil, errmsg(err, "unable to calculate session message authentication code")
end
if MAC_SIZE ~= 32 then
return sub(mac, 1, MAC_SIZE)
end
return mac
end
local function calculate_cookie_chunks(cookie_name_size, data_size)
local space_needed = cookie_name_size + 1 + HEADER_ENCODED_SIZE + data_size
if space_needed > MAX_COOKIES_SIZE then
return nil, "cookie size limit exceeded"
end
if space_needed <= MAX_COOKIE_SIZE then
return 1
end
for i = 2, MAX_COOKIES do
space_needed = space_needed + cookie_name_size + 2
if space_needed > MAX_COOKIES_SIZE then
return nil, "cookie size limit exceeded"
elseif space_needed <= (MAX_COOKIE_SIZE * i) then
return i
end
end
return nil, "cookie size limit exceeded"
end
local function merge_cookies(cookies, cookie_name_size, cookie_name, cookie_data)
if not cookies then
return cookie_data
end
if type(cookies) == "string" then
if byte(cookies, cookie_name_size + 1) == EQUALS_BYTE and
sub(cookies, 1, cookie_name_size) == cookie_name
then
return cookie_data
end
return { cookies, cookie_data }
end
if type(cookies) ~= "table" then
return nil, "unable to merge session cookies with response cookies"
end
local count = #cookies
for i = 1, count do
if byte(cookies[i], cookie_name_size + 1) == EQUALS_BYTE and
sub(cookies[i], 1, cookie_name_size) == cookie_name
then
cookies[i] = cookie_data
return cookies
end
if i == count then
cookies[i+1] = cookie_data
return cookies
end
end
end
local function get_store_metadata(self)
if not self.store_metadata then
return
end
local data = self.data
local count = #data
if count == 1 then
local audience = data[1][2]
local subject = data[1][3]
if audience and subject then
audience = encode_base64url(audience)
subject = self.hash_subject(subject)
return {
audiences = { audience },
subjects = { subject },
}
end
return
end
local audiences
local subjects
local index = 0
for i = 1, count do
local audience = data[i][2]
local subject = data[i][3]
if audience and subject then
audience = encode_base64url(audience)
self.hash_subject(subject)
if not audiences then
audiences = table_new(count, 0)
subjects = table_new(count, 0)
end
index = index + 1
audiences[index] = audience
subjects[index] = subject
end
end
if not audiences then
return
end
return {
audiences = audiences,
subjects = subjects,
}
end
local function get_property(self, name)
if name == "id" then
local sid = self.meta.sid
if not sid then
return
end
return encode_base64url(sid)
elseif name == "nonce" then
return self.meta.sid
elseif name == "audience" then
return self.data[self.data_index][2]
elseif name == "subject" then
return self.data[self.data_index][3]
elseif name == "timeout" then
local timeout
local meta = self.meta
if self.idling_timeout > 0 then
timeout = self.idling_timeout - (meta.timestamp - meta.creation_time - meta.rolling_offset - meta.idling_offset)
end
if self.rolling_timeout > 0 then
local t = self.rolling_timeout - (meta.timestamp - meta.creation_time - meta.rolling_offset)
timeout = timeout and min(t, timeout) or t
end
if self.absolute_timeout > 0 then
local t = self.absolute_timeout - (meta.timestamp - meta.creation_time)
timeout = timeout and min(t, timeout) or t
end
return timeout
elseif name == "idling-timeout" or name == "idling_timeout" then
local idling_timeout = self.idling_timeout
if idling_timeout == 0 then
return
end
local meta = self.meta
return idling_timeout - (meta.timestamp - meta.creation_time - meta.rolling_offset - meta.idling_offset)
elseif name == "rolling-timeout" or name == "rolling_timeout" then
local rolling_timeout = self.rolling_timeout
if rolling_timeout == 0 then
return
end
local meta = self.meta
return rolling_timeout - (meta.timestamp - meta.creation_time - meta.rolling_offset)
elseif name == "absolute-timeout" or name == "absolute_timeout" then
local absolute_timeout = self.absolute_timeout
if absolute_timeout == 0 then
return
end
local meta = self.meta
return absolute_timeout - (meta.timestamp - meta.creation_time)
else
return self.meta[name]
end
end
local function open(self, remember, meta_only)
local storage = self.storage
local current_time = time()
local cookie_name
if remember then
cookie_name = self.remember_cookie_name
else
cookie_name = self.cookie_name
end
local cookie = var["cookie_" .. cookie_name]
if not cookie then
return nil, "missing session cookie"
end
local header_decoded do
header_decoded = sub(cookie, 1, HEADER_ENCODED_SIZE)
if #header_decoded ~= HEADER_ENCODED_SIZE then
return nil, "invalid session header"
end
local err
header_decoded, err = decode_base64url(header_decoded)
if not header_decoded then
return nil, errmsg(err, "unable to base64url decode session header")
end
end
HEADER_BUFFER:set(header_decoded)
local cookie_type do
cookie_type = HEADER_BUFFER:get(COOKIE_TYPE_SIZE)
if #cookie_type ~= COOKIE_TYPE_SIZE then
return nil, "invalid session cookie type"
end
if cookie_type ~= COOKIE_TYPE then
return nil, "invalid session cookie type"
end
end
local flags do
flags = HEADER_BUFFER:get(FLAGS_SIZE)
if #flags ~= FLAGS_SIZE then
return nil, "invalid session flags"
end
flags = bunpack(FLAGS_SIZE, flags)
if storage then
if not has_flag(flags, FLAG_STORAGE) then
return nil, "invalid session flags"
end
elseif has_flag(flags, FLAG_STORAGE) then
return nil, "invalid session flags"
end
end
local sid do
sid = HEADER_BUFFER:get(SID_SIZE)
if #sid ~= SID_SIZE then
return nil, "invalid session id"
end
end
local creation_time do
creation_time = HEADER_BUFFER:get(CREATION_TIME_SIZE)
if #creation_time ~= CREATION_TIME_SIZE then
return nil, "invalid session creation time"
end
creation_time = bunpack(CREATION_TIME_SIZE, creation_time)
if not creation_time or creation_time < 0 or creation_time > MAX_CREATION_TIME then
return nil, "invalid session creation time"
end
local absolute_elapsed = current_time - creation_time
if absolute_elapsed > MAX_ROLLING_OFFSET then
return nil, "session lifetime exceeded"
end
if remember then
local remember_absolute_timeout = self.remember_absolute_timeout
if remember_absolute_timeout ~= 0 then
if absolute_elapsed > remember_absolute_timeout then
return nil, "session remember absolute timeout exceeded"
end
end
else
local absolute_timeout = self.absolute_timeout
if absolute_timeout ~= 0 then
if absolute_elapsed > absolute_timeout then
return nil, "session absolute timeout exceeded"
end
end
end
end
local rolling_offset do
rolling_offset = HEADER_BUFFER:get(ROLLING_OFFSET_SIZE)
if #rolling_offset ~= ROLLING_OFFSET_SIZE then
return nil, "invalid session rolling offset"
end
rolling_offset = bunpack(ROLLING_OFFSET_SIZE, rolling_offset)
if not rolling_offset or rolling_offset < 0 or rolling_offset > MAX_ROLLING_OFFSET then
return nil, "invalid session rolling offset"
end
local rolling_elapsed = current_time - creation_time - rolling_offset
if remember then
local remember_rolling_timeout = self.remember_rolling_timeout
if remember_rolling_timeout ~= 0 then
if rolling_elapsed > remember_rolling_timeout then
return nil, "session remember rolling timeout exceeded"
end
end
else
local rolling_timeout = self.rolling_timeout
if rolling_timeout ~= 0 then
if rolling_elapsed > rolling_timeout then
return nil, "session rolling timeout exceeded"
end
end
end
end
local data_size do
data_size = HEADER_BUFFER:get(DATA_SIZE)
if #data_size ~= DATA_SIZE then
return nil, "invalid session data size"
end
data_size = bunpack(DATA_SIZE, data_size)
if not data_size or data_size < 0 or data_size > MAX_DATA_SIZE then
return nil, "invalid session data size"
end
end
local tag do
tag = HEADER_BUFFER:get(TAG_SIZE)
if #tag ~= TAG_SIZE then
return nil, "invalid session tag"
end
end
local idling_offset do
idling_offset = HEADER_BUFFER:get(IDLING_OFFSET_SIZE)
if #idling_offset ~= IDLING_OFFSET_SIZE then
return nil, "invalid session idling offset"
end
idling_offset = bunpack(IDLING_OFFSET_SIZE, idling_offset)
if not idling_offset or idling_offset < 0 or idling_offset > MAX_IDLING_OFFSET then
return nil, "invalid session idling offset"
end
if remember then
if idling_offset ~= 0 then
return nil, "invalid session idling offset"
end
else
local idling_timeout = self.idling_timeout
if idling_timeout ~= 0 then
local idling_elapsed = current_time - creation_time - rolling_offset - idling_offset
if idling_elapsed > idling_timeout then
return nil, "session idling timeout exceeded"
end
end
end
end
local ikm do
ikm = self.ikm
local mac = HEADER_BUFFER:get(MAC_SIZE)
if #mac ~= MAC_SIZE then
return nil, "invalid session message authentication code"
end
local msg = sub(header_decoded, 1, HEADER_MAC_SIZE)
local expected_mac, err = calculate_mac(ikm, sid, msg)
if mac ~= expected_mac then
local fallback_keys = self.ikm_fallbacks
if fallback_keys then
local count = #fallback_keys
if count > 0 then
for i = 1, count do
ikm = fallback_keys[i]
expected_mac, err = calculate_mac(ikm, sid, msg)
if mac == expected_mac then
break
end
if i == count then
return nil, errmsg(err, "invalid session message authentication code")
end
end
else
return nil, errmsg(err, "invalid session message authentication code")
end
else
return nil, errmsg(err, "invalid session message authentication code")
end
end
end
local data_index = self.data_index
local audience = self.data[data_index][2]
local initial_chunk, ciphertext, ciphertext_encoded, info_data do
if storage then
local key, err = self.hash_storage_key(sid)
if not key then
return nil, err
end
local data, err = storage:get(cookie_name, key, current_time)
if not data then
return nil, errmsg(err, "unable to load session")
end
data, err = decode_json(data)
if not data then
return nil, errmsg(err, "unable to json decode session")
end
ciphertext = data[1]
ciphertext_encoded = ciphertext
info_data = data[2]
if info_data then
info_data, err = decode_base64url(info_data)
if not info_data then
return nil, errmsg(err, "unable to base64url decode session info")
end
info_data, err = decode_json(info_data)
if not info_data then
return nil, errmsg(err, "unable to json decode session info")
end
if not info_data[audience] then
info_data[audience] = self.info.data and self.info.data[audience] or nil
end
end
else
local cookie_chunks, err = calculate_cookie_chunks(#cookie_name, data_size)
if not cookie_chunks then
return nil, err
end
if cookie_chunks == 1 then
initial_chunk = sub(cookie, -data_size)
ciphertext = initial_chunk
else
initial_chunk = sub(cookie, HEADER_ENCODED_SIZE + 1)
DATA_BUFFER:reset():put(initial_chunk)
for i = 2, cookie_chunks do
local chunk = var["cookie_" .. cookie_name .. i]
if not chunk then
return nil, errmsg(err, "missing session cookie chunk")
end
DATA_BUFFER:put(chunk)
end
ciphertext = DATA_BUFFER:get()
end
end
if #ciphertext ~= data_size then
return nil, "invalid session payload"
end
local err
ciphertext, err = decode_base64url(ciphertext)
if not ciphertext then
return nil, errmsg(err, "unable to base64url decode session data")
end
end
if remember then
self.remember_meta = {
timestamp = current_time,
flags = flags,
sid = sid,
creation_time = creation_time,
rolling_offset = rolling_offset,
data_size = data_size,
idling_offset = idling_offset,
ikm = ikm,
header = header_decoded,
initial_chunk = initial_chunk,
ciphertext = ciphertext_encoded,
}
else
self.meta = {
timestamp = current_time,
flags = flags,
sid = sid,
creation_time = creation_time,
rolling_offset = rolling_offset,
data_size = data_size,
idling_offset = idling_offset,
ikm = ikm,
header = header_decoded,
initial_chunk = initial_chunk,
ciphertext = ciphertext_encoded,
}
end
if meta_only then
return true
end
local aes_key, err, iv
if remember then
aes_key, err, iv = derive_aes_gcm_256_key_and_iv(ikm, sid, self.remember_safety)
else
aes_key, err, iv = derive_aes_gcm_256_key_and_iv(ikm, sid)
end
if not aes_key then
return nil, errmsg(err, "unable to derive session decryption key")
end
local aad = sub(header_decoded, 1, HEADER_TAG_SIZE)
local plaintext, err = decrypt_aes_256_gcm(aes_key, iv, ciphertext, aad, tag)
if not plaintext then
return nil, errmsg(err, "unable to decrypt session data")
end
local data do
if has_flag(flags, FLAG_DEFLATE) then
plaintext, err = inflate(plaintext)
if not plaintext then
return nil, errmsg(err, "unable to inflate session data")
end
end
data, err = decode_json(plaintext)
if not data then
return nil, errmsg(err, "unable to json decode session data")
end
end
if storage then
self.info.data = info_data
end
local audience_index
local count = #data
for i = 1, count do
if data[i][2] == audience then
audience_index = i
break
end
end
if not audience_index then
data[count + 1] = self.data[data_index]
self.state = STATE_NEW
self.data = data
self.data_index = count + 1
return nil, "missing session audience", true
end
self.state = STATE_OPEN
self.data = data
self.data_index = audience_index
return true
end
local function save(self, state, remember)
local cookie_name
local meta
if remember then
cookie_name = self.remember_cookie_name
meta = self.remember_meta or {}
else
cookie_name = self.cookie_name
meta = self.meta
end
local cookie_name_size = #cookie_name
local storage = self.storage
local flags = self.flags
if storage then
flags = set_flag(flags, FLAG_STORAGE)
else
flags = unset_flag(flags, FLAG_STORAGE)
end
local sid, err = rand_bytes(SID_SIZE)
if not sid then
return nil, errmsg(err, "unable to generate session id")
end
local current_time = time()
local rolling_offset
local creation_time = meta.creation_time
if creation_time then
rolling_offset = current_time - creation_time
if rolling_offset > MAX_ROLLING_OFFSET then
return nil, "session maximum rolling offset exceeded"
end
else
creation_time = current_time
rolling_offset = 0
end
if creation_time > MAX_CREATION_TIME then
-- this should only happen at around year 36759 (most likely a clock problem)
return nil, "session maximum creation time exceeded"
end
do
local meta_flags = meta.flags
if meta_flags and has_flag(meta_flags, FLAG_FORGET) then
flags = set_flag(flags, FLAG_FORGET)
end
end
local data, data_size, cookie_chunks do
data = self.data
if self.enforce_same_subject then
local count = #data
if count > 1 then
local subject = data[self.data_index][3]
for i = count, 1, -1 do
if data[i][3] ~= subject then
remove(data, i)
end
end
end
end
data, err = encode_json(data)
if not data then
return nil, errmsg(err, "unable to json encode session data")
end
data_size = #data
local compression_threshold = self.compression_threshold
if compression_threshold ~= 0 and data_size > compression_threshold then
local deflated_data, err = deflate(data)
if not deflated_data then
log(NOTICE, "[session] unable to deflate session data (", err , ")")
else
if deflated_data then
local deflated_size = #deflated_data
if deflated_size < data_size then
flags = set_flag(flags, FLAG_DEFLATE)
data = deflated_data
data_size = deflated_size
end
end
end
end
data_size = base64_size(data_size)
if storage then
if data_size > MAX_DATA_SIZE then
return nil, "session maximum data size exceeded"
end
cookie_chunks = 1
else
cookie_chunks, err = calculate_cookie_chunks(cookie_name_size, data_size)
if not cookie_chunks then
return nil, err
end
end
end
local idling_offset = 0
local packed_flags = bpack(FLAGS_SIZE, flags)
local packed_data_size = bpack(DATA_SIZE, data_size)
local packed_creation_time = bpack(CREATION_TIME_SIZE, creation_time)
local packed_rolling_offset = bpack(ROLLING_OFFSET_SIZE, rolling_offset)
local packed_idling_offset = bpack(IDLING_OFFSET_SIZE, idling_offset)
HEADER_BUFFER:reset()
HEADER_BUFFER:put(COOKIE_TYPE, packed_flags, sid, packed_creation_time, packed_rolling_offset, packed_data_size)
local ikm = self.ikm
local aes_key, iv
if remember then
aes_key, err, iv = derive_aes_gcm_256_key_and_iv(ikm, sid, self.remember_safety)
else
aes_key, err, iv = derive_aes_gcm_256_key_and_iv(ikm, sid)
end
if not aes_key then
return nil, errmsg(err, "unable to derive session encryption key")
end
local ciphertext, err, tag = encrypt_aes_256_gcm(aes_key, iv, data, HEADER_BUFFER:tostring())
if not ciphertext then
return nil, errmsg(err, "unable to encrypt session data")
end
HEADER_BUFFER:put(tag, packed_idling_offset)
local mac, err = calculate_mac(ikm, sid, HEADER_BUFFER:tostring())
if not mac then
return nil, err
end
local header_decoded = HEADER_BUFFER:put(mac):get()
local header_encoded, err = encode_base64url(header_decoded)
if not header_encoded then
return nil, errmsg(err, "unable to base64url encode session header")
end
local payload, err = encode_base64url(ciphertext)
if not payload then
return nil, errmsg(err, "unable to base64url encode session data")
end
local cookies = header["Set-Cookie"]
local cookie_flags = self.cookie_flags
local initial_chunk
local ciphertext_encoded
local remember_flags
if remember then
local max_age = self.remember_rolling_timeout
if max_age == 0 or max_age > MAX_TTL then
max_age = MAX_TTL
end
local expires = http_time(creation_time + max_age)
remember_flags = fmt("; Expires=%s; Max-Age=%d", expires, max_age)
end
if cookie_chunks == 1 then
local cookie_data
if storage then
ciphertext_encoded = payload
if remember then
cookie_data = fmt("%s=%s%s%s", cookie_name, header_encoded, cookie_flags, remember_flags)
else
cookie_data = fmt("%s=%s%s", cookie_name, header_encoded, cookie_flags)
end
else
initial_chunk = payload
if remember then
cookie_data = fmt("%s=%s%s%s%s", cookie_name, header_encoded, payload, cookie_flags, remember_flags)