-
Notifications
You must be signed in to change notification settings - Fork 5
/
openidc.lua
1473 lines (1243 loc) · 46.4 KB
/
openidc.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
--[[
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
***************************************************************************
Copyright (C) 2015-2017 Ping Identity Corporation
All rights reserved.
For further information please contact:
Ping Identity Corporation
1099 18th St Suite 2950
Denver, CO 80202
303.468.2900
http://www.pingidentity.com
DISCLAIMER OF WARRANTIES:
THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
--]]
local require = require
local cjson = require "cjson"
local cjson_s = require "cjson.safe"
local http = require "resty.http"
local string = string
local ipairs = ipairs
local pairs = pairs
local type = type
local ngx = ngx
local b64 = ngx.encode_base64
local unb64 = ngx.decode_base64
local supported_token_auth_methods = {
client_secret_basic = true,
client_secret_post = true
}
local openidc = {
_VERSION = "1.6.0"
}
openidc.__index = openidc
local function store_in_session(opts, feature)
-- We don't have a whitelist of features to enable
if not opts.session_contents then
return true
end
return opts.session_contents[feature]
end
-- set value in server-wide cache if available
local function openidc_cache_set(type, key, value, exp)
local dict = ngx.shared[type]
if dict and (exp > 0) then
local success, err, forcible = dict:set(key, value, exp)
ngx.log(ngx.DEBUG, "cache set: success=", success, " err=", err, " forcible=", forcible)
end
end
-- retrieve value from server-wide cache if available
local function openidc_cache_get(type, key)
local dict = ngx.shared[type]
local value
if dict then
value = dict:get(key)
if value then ngx.log(ngx.DEBUG, "cache hit: type=", type, " key=", key) end
end
return value
end
-- invalidate values of server-wide cache
local function openidc_cache_invalidate(type)
local dict = ngx.shared[type]
if dict then
ngx.log(ngx.DEBUG, "flushing cache for "..type)
dict.flush_all(dict)
local nbr = dict.flush_expired(dict)
end
end
-- invalidate all server-wide caches
function openidc.invalidate_caches()
openidc_cache_invalidate("discovery")
openidc_cache_invalidate("jwks")
openidc_cache_invalidate("introspection")
end
-- validate the contents of and id_token
local function openidc_validate_id_token(opts, id_token, nonce)
-- check issuer
if opts.discovery.issuer ~= id_token.iss then
ngx.log(ngx.ERR, "issuer \"", id_token.iss, "\" in id_token is not equal to the issuer from the discovery document \"", opts.discovery.issuer, "\"")
return false
end
-- check sub
if not id_token.sub then
ngx.log(ngx.ERR, "no \"sub\" claim found in id_token")
return false
end
-- check nonce
if nonce and nonce ~= id_token.nonce then
ngx.log(ngx.ERR, "nonce \"", id_token.nonce, "\" in id_token is not equal to the nonce that was sent in the request \"", nonce, "\"")
return false
end
-- check issued-at timestamp
if not id_token.iat then
ngx.log(ngx.ERR, "no \"iat\" claim found in id_token")
return false
end
local slack=opts.iat_slack and opts.iat_slack or 120
if id_token.iat > (ngx.time() + slack) then
ngx.log(ngx.ERR, "id_token not yet valid: id_token.iat=", id_token.iat, ", ngx.time()=", ngx.time(), ", slack=", slack)
return false
end
-- check expiry timestamp
if not id_token.exp then
ngx.log(ngx.ERR, "no \"exp\" claim found in id_token")
return false
end
if (id_token.exp + slack) < ngx.time() then
ngx.log(ngx.ERR, "token expired: id_token.exp=", id_token.exp, ", ngx.time()=", ngx.time())
return false
end
-- check audience (array or string)
if not id_token.aud then
ngx.log(ngx.ERR, "no \"aud\" claim found in id_token")
return false
end
if (type(id_token.aud) == "table") then
for _, value in pairs(id_token.aud) do
if value == opts.client_id then
return true
end
end
ngx.log(ngx.ERR, "no match found token audience array: client_id=", opts.client_id )
return false
elseif (type(id_token.aud) == "string") then
if id_token.aud ~= opts.client_id then
ngx.log(ngx.ERR, "token audience does not match: id_token.aud=", id_token.aud, ", client_id=", opts.client_id )
return false
end
end
return true
end
local function get_first_header(header_name)
local header = ngx.req.get_headers()[header_name]
if header and type(header) == 'table' then
header = header[1]
end
return header
end
local function get_first_header_and_strip_whitespace(header_name)
local header = get_first_header(header_name)
return header and header:gsub('%s', '')
end
local function get_forwarded_parameter(param_name)
local forwarded = get_first_header("Forwarded")
local params = {}
if forwarded then
local function parse_parameter(pv)
local name, value = pv:match("^%s*([^=]+)%s*=%s*(.-)%s*$")
if name and value then
if value:sub(1, 1) == '"' then
value = value:sub(2, -2)
end
params[name:lower()] = value
end
end
-- this assumes there is no quoted comma inside the header's value
-- which should be fine as comma is not legal inside a node name,
-- a URI scheme or a host name. The only thing that might bite us
-- are extensions.
local first_part = forwarded
local first_comma = forwarded:find("%s*,%s*")
if first_comma then
first_part = forwarded:sub(1, first_comma - 1)
end
first_part:gsub("[^;]+", parse_parameter)
end
return params[param_name:gsub("^%s*(.-)%s*$", "%1"):lower()]
end
local function get_scheme()
return get_forwarded_parameter("proto")
or get_first_header_and_strip_whitespace('X-Forwarded-Proto')
or ngx.var.scheme
end
local function get_host_name_from_x_header()
local header = get_first_header_and_strip_whitespace('X-Forwarded-Host')
return header and header:gsub('^([^,]+),?.*$', '%1')
end
local function get_host_name()
return get_forwarded_parameter("host")
or get_host_name_from_x_header()
or ngx.var.http_host
end
-- assemble the redirect_uri
local function openidc_get_redirect_uri(opts)
local scheme = opts.redirect_uri_scheme or get_scheme()
local host = get_host_name()
if not host then
-- possibly HTTP 1.0 and no Host header
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
return scheme.."://"..host..opts.redirect_uri_path
end
-- perform base64url decoding
local function openidc_base64_url_decode(input)
local reminder = #input % 4
if reminder > 0 then
local padlen = 4 - reminder
input = input .. string.rep('=', padlen)
end
input = input:gsub('-','+'):gsub('_','/')
return unb64(input)
end
local function openidc_combine_uri(uri, params)
if params == nil or next(params) == nil then
return uri
end
local sep = "?"
if string.find(uri, "?", 1, true) then
sep = "&"
end
return uri .. sep .. ngx.encode_args(params)
end
-- send the browser of to the OP's authorization endpoint
local function openidc_authorize(opts, session, target_url, prompt)
local resty_random = require "resty.random"
local resty_string = require "resty.string"
-- generate state and nonce
local state = resty_string.to_hex(resty_random.bytes(16))
local nonce = resty_string.to_hex(resty_random.bytes(16))
-- assemble the parameters to the authentication request
local params = {
client_id=opts.client_id,
response_type="code",
scope=opts.scope and opts.scope or "openid email profile",
redirect_uri=openidc_get_redirect_uri(opts),
state=state,
nonce=nonce,
}
if prompt then
params.prompt = prompt
end
if opts.display then
params.display = opts.display
end
-- merge any provided extra parameters
if opts.authorization_params then
for k,v in pairs(opts.authorization_params) do params[k] = v end
end
-- store state in the session
session:start()
session.data.original_url = target_url
session.data.state = state
session.data.nonce = nonce
session.data.last_authenticated = ngx.time()
session:save()
-- redirect to the /authorization endpoint
ngx.header["Cache-Control"] = "no-cache, no-store, max-age=0"
return ngx.redirect(openidc_combine_uri(opts.discovery.authorization_endpoint, params))
end
-- parse the JSON result from a call to the OP
local function openidc_parse_json_response(response)
local err
local res
-- check the response from the OP
if response.status ~= 200 then
err = "response indicates failure, status="..response.status..", body="..response.body
else
-- decode the response and extract the JSON object
res = cjson_s.decode(response.body)
if not res then
err = "JSON decoding failed"
end
end
return res, err
end
local function openidc_configure_timeouts(httpc, timeout)
if timeout then
if type(timeout) == "table" then
local r, e = httpc:set_timeouts(timeout.connect or 0, timeout.send or 0, timeout.read or 0)
else
local r, e = httpc:set_timeout(timeout)
end
end
end
-- Set outgoing proxy options
local function openidc_configure_proxy(httpc, proxy_opts)
if httpc and proxy_opts and type(proxy_opts) == "table" then
ngx.log(ngx.DEBUG, "openidc_configure_proxy : use http proxy")
httpc:set_proxy_options(proxy_opts)
else
ngx.log(ngx.DEBUG, "openidc_configure_proxy : don't use http proxy")
end
end
-- make a call to the token endpoint
local function openidc_call_token_endpoint(opts, endpoint, body, auth, endpoint_name)
local ep_name = endpoint_name or 'token'
local headers = {
["Content-Type"] = "application/x-www-form-urlencoded"
}
if auth then
if auth == "client_secret_basic" then
headers.Authorization = "Basic "..b64( opts.client_id..":"..opts.client_secret)
ngx.log(ngx.DEBUG,"client_secret_basic: authorization header '"..headers.Authorization.."'")
end
if auth == "client_secret_post" then
body.client_id=opts.client_id
body.client_secret=opts.client_secret
ngx.log(ngx.DEBUG, "client_secret_post: client_id and client_secret being sent in POST body")
end
end
local pass_cookies = opts.pass_cookies
if pass_cookies then
if ngx.req.get_headers()["Cookie"] then
local t = {}
for cookie_name in string.gmatch(pass_cookies, "%S+") do
local cookie_value = ngx.var["cookie_"..cookie_name]
if cookie_value then
table.insert(t, cookie_name.."="..cookie_value)
end
end
headers.Cookie = table.concat(t, "; ")
end
end
ngx.log(ngx.DEBUG, "request body for "..ep_name.." endpoint call: ", ngx.encode_args(body))
local httpc = http.new()
openidc_configure_timeouts(httpc, opts.timeout)
openidc_configure_proxy(httpc, opts.proxy_opts)
local res, err = httpc:request_uri(endpoint, {
method = "POST",
body = ngx.encode_args(body),
headers = headers,
ssl_verify = (opts.ssl_verify ~= "no")
})
if not res then
err = "accessing "..ep_name.." endpoint ("..endpoint..") failed: "..err
ngx.log(ngx.ERR, err)
return nil, err
end
ngx.log(ngx.DEBUG, ep_name.." endpoint response: ", res.body)
return openidc_parse_json_response(res)
end
-- make a call to the userinfo endpoint
local function openidc_call_userinfo_endpoint(opts, access_token)
if not opts.discovery.userinfo_endpoint then
ngx.log(ngx.DEBUG, "no userinfo endpoint supplied")
return nil, nil
end
local headers = {
["Authorization"] = "Bearer "..access_token,
}
ngx.log(ngx.DEBUG,"authorization header '"..headers.Authorization.."'")
local httpc = http.new()
openidc_configure_timeouts(httpc, opts.timeout)
openidc_configure_proxy(httpc, opts.proxy_opts)
local res, err = httpc:request_uri(opts.discovery.userinfo_endpoint, {
headers = headers,
ssl_verify = (opts.ssl_verify ~= "no")
})
if not res then
err = "accessing ("..opts.discovery.userinfo_endpoint..") failed: "..err
return nil, err
end
ngx.log(ngx.DEBUG, "userinfo response: ", res.body)
-- parse the response from the user info endpoint
return openidc_parse_json_response(res)
end
-- computes access_token expires_in value (in seconds)
local function openidc_access_token_expires_in(opts, expires_in)
return (expires_in or opts.access_token_expires_in or 3600) - 1 - (opts.access_token_expires_leeway or 0)
end
local function openidc_load_jwt_none_alg(enc_hdr, enc_payload)
local header = cjson_s.decode(openidc_base64_url_decode(enc_hdr))
local payload = cjson_s.decode(openidc_base64_url_decode(enc_payload))
if header and payload and header.alg == "none" then
return {
raw_header = enc_hdr,
raw_payload = enc_payload,
header = header,
payload = payload,
signature = ''
}
end
return nil
end
-- get the Discovery metadata from the specified URL
local function openidc_discover(url, ssl_verify, timeout, proxy_opts)
ngx.log(ngx.DEBUG, "openidc_discover: URL is: "..url)
local json, err
local v = openidc_cache_get("discovery", url)
if not v then
ngx.log(ngx.DEBUG, "discovery data not in cache, making call to discovery endpoint")
-- make the call to the discovery endpoint
local httpc = http.new()
openidc_configure_timeouts(httpc, timeout)
openidc_configure_proxy(httpc, proxy_opts)
local res, error = httpc:request_uri(url, {
ssl_verify = (ssl_verify ~= "no")
})
if not res then
err = "accessing discovery url ("..url..") failed: "..error
ngx.log(ngx.ERR, err)
else
ngx.log(ngx.DEBUG, "response data: "..res.body)
json, err = openidc_parse_json_response(res)
if json then
if string.sub(url, 1, string.len(json['issuer'])) == json['issuer'] then
openidc_cache_set("discovery", url, cjson.encode(json), 24 * 60 * 60)
else
err = "issuer field in Discovery data does not match URL"
ngx.log(ngx.ERR, err)
json = nil
end
else
err = "could not decode JSON from Discovery data" .. (err and (": " .. err) or '')
ngx.log(ngx.ERR, err)
end
end
else
json = cjson.decode(v)
end
return json, err
end
-- turn a discovery url set in the opts dictionary into the discovered information
local function openidc_ensure_discovered_data(opts)
local err
if type(opts.discovery) == "string" then
opts.discovery, err = openidc_discover(opts.discovery, opts.ssl_verify, opts.timeout, opts.proxy_opts)
end
return err
end
-- query for discovery endpoint data
function openidc.get_discovery_doc(opts)
local err = openidc_ensure_discovered_data (opts)
if err then
ngx.log(ngx.ERR, "error getting endpoints definition using discovery endpoint")
end
return opts.discovery, err
end
local function openidc_jwks(url, force, ssl_verify, timeout, proxy_opts)
ngx.log(ngx.DEBUG, "openidc_jwks: URL is: "..url.. " (force=" .. force .. ")")
local json, err, v
if force == 0 then
v = openidc_cache_get("jwks", url)
end
if not v then
ngx.log(ngx.DEBUG, "cannot use cached JWKS data; making call to jwks endpoint")
-- make the call to the jwks endpoint
local httpc = http.new()
openidc_configure_timeouts(httpc, timeout)
openidc_configure_proxy(httpc, proxy_opts)
local res, error = httpc:request_uri(url, {
ssl_verify = (ssl_verify ~= "no")
})
if not res then
err = "accessing jwks url ("..url..") failed: "..error
ngx.log(ngx.ERR, err)
else
ngx.log(ngx.DEBUG, "response data: "..res.body)
json, err = openidc_parse_json_response(res)
if json then
openidc_cache_set("jwks", url, cjson.encode(json), 24 * 60 * 60)
end
end
else
json = cjson.decode(v)
end
return json, err
end
local function split_by_chunk(text, chunkSize)
local s = {}
for i=1, #text, chunkSize do
s[#s+1] = text:sub(i,i+chunkSize - 1)
end
return s
end
local function get_jwk (keys, kid)
local rsa_keys = {}
for _, value in pairs(keys) do
if value.kty == "RSA" and (not value.use or value.use == "sig") then
table.insert(rsa_keys, value)
end
end
if kid == nil then
if #rsa_keys == 1 then
ngx.log(ngx.DEBUG, "returning only RSA key of JWKS for keyid-less JWT")
return rsa_keys[1], nil
else
return nil, "JWT doesn't specify kid but the keystore contains multiple RSA keys"
end
end
for _, value in pairs(rsa_keys) do
if value.kid == kid then
return value, nil
end
end
return nil, "RSA key with id " .. kid .. " not found"
end
local wrap = ('.'):rep(64)
local envelope = "-----BEGIN %s-----\n%s\n-----END %s-----\n"
local function der2pem(data, header, typ)
typ = typ:upper() or "CERTIFICATE"
if header == nil then
data = b64(data)
return string.format(envelope, typ, data:gsub(wrap, '%0\n', (#data-1)/64), typ)
else
-- ADDING b64 RSA HEADER WITH OID
data = header .. b64(data)
return string.format(envelope, typ, data:gsub(wrap, '%0\n', (#data-1)/64), typ)
end
end
local function encode_length(length)
if length < 0x80 then
return string.char(length)
elseif length < 0x100 then
return string.char(0x81, length)
elseif length < 0x10000 then
return string.char(0x82, math.floor(length/0x100), length%0x100)
end
error("Can't encode lengths over 65535")
end
local function encode_sequence(array, of)
local encoded_array = array
if of then
encoded_array = {}
for i = 1, #array do
encoded_array[i] = of(array[i])
end
end
encoded_array = table.concat(encoded_array)
return string.char(0x30) .. encode_length(#encoded_array) .. encoded_array
end
local function encode_binary_integer(bytes)
if bytes:byte(1) > 127 then
-- We currenly only use this for unsigned integers,
-- however since the high bit is set here, it would look
-- like a negative signed int, so prefix with zeroes
bytes = "\0" .. bytes
end
return "\2" .. encode_length(#bytes) .. bytes
end
local function encode_sequence_of_integer(array)
return encode_sequence(array,encode_binary_integer)
end
local function openidc_pem_from_x5c(x5c)
-- TODO check x5c length
ngx.log(ngx.DEBUG, "Found x5c, getting PEM public key from x5c entry of json public key")
local chunks = split_by_chunk(b64(openidc_base64_url_decode(x5c[1])), 64)
local pem = "-----BEGIN CERTIFICATE-----\n" ..
table.concat(chunks, "\n") ..
"\n-----END CERTIFICATE-----"
ngx.log(ngx.DEBUG,"Generated PEM key from x5c:", pem)
return pem
end
local function openidc_pem_from_rsa_n_and_e(n, e)
ngx.log(ngx.DEBUG , "getting PEM public key from n and e parameters of json public key")
local der_key = {
openidc_base64_url_decode(n), openidc_base64_url_decode(e)
}
local encoded_key = encode_sequence_of_integer(der_key)
--PEM KEY FROM PUBLIC KEYS, PASSING 64 BIT ENCODED RSA HEADER STRING WHICH IS SAME FOR ALL KEYS
local pem = der2pem(encoded_key,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A","PUBLIC KEY")
ngx.log(ngx.DEBUG, "Generated pem key from n and e: ", pem)
return pem
end
local function openidc_pem_from_jwk(opts, kid)
local err = openidc_ensure_discovered_data(opts)
if err then
return nil, err
end
if not opts.discovery.jwks_uri or not (type(opts.discovery.jwks_uri) == "string") or (opts.discovery.jwks_uri == "") then
return nil, "opts.discovery.jwks_uri is not present or not a string"
end
local cache_id = opts.discovery.jwks_uri .. '#' .. (kid or '')
local v = openidc_cache_get("jwks", cache_id)
if v then
return v
end
local jwk, jwks
for force=0, 1 do
jwks, err = openidc_jwks(opts.discovery.jwks_uri, force, opts.ssl_verify, opts.timeout, opts.proxy_opts)
if err then
return nil, err
end
jwk, err = get_jwk(jwks.keys, kid)
if jwk and not err then
break
end
end
if err then
return nil, err
end
local pem
-- TODO check x5c length
if jwk.x5c then
pem = openidc_pem_from_x5c(jwk.x5c)
elseif jwk.kty == "RSA" and jwk.n and jwk.e then
pem = openidc_pem_from_rsa_n_and_e(jwk.n, jwk.e)
else
return nil, "don't know how to create RSA key/cert for " .. cjson.encode(jwt)
end
openidc_cache_set("jwks", cache_id, pem, 24 * 60 * 60)
return pem
end
-- does lua-resty-jwt and/or we know how to handle the algorithm of the JWT?
local function is_algorithm_supported(jwt_header)
return jwt_header and jwt_header.alg and (
jwt_header.alg == "none"
or string.sub(jwt_header.alg, 1, 2) == "RS"
or string.sub(jwt_header.alg, 1, 2) == "HS"
)
end
-- is the JWT signing algorithm an asymmetric one whose key might be
-- obtained from the discovery endpoint?
local function uses_asymmetric_algorithm(jwt_header)
return string.sub(jwt_header.alg, 1, 2) == "RS"
end
-- is the JWT signing algorithm one that has been expected?
local function is_algorithm_expected(jwt_header, expected_algs)
if expected_algs == nil or not jwt_header or not jwt_header.alg then
return true
end
if type(expected_algs) == 'string' then
expected_algs = { expected_algs }
end
for _, alg in ipairs(expected_algs) do
if alg == jwt_header.alg then
return true
end
end
return false
end
-- parse a JWT and verify its signature (if present)
local function openidc_load_jwt_and_verify_crypto(opts, jwt_string, asymmetric_secret,
symmetric_secret, expected_algs, ...)
local jwt = require "resty.jwt"
local enc_hdr, enc_payload, enc_sign = string.match(jwt_string, '^(.+)%.(.+)%.(.*)$')
if enc_payload and (not enc_sign or enc_sign == "") then
local jwt = openidc_load_jwt_none_alg(enc_hdr, enc_payload)
if jwt then
if opts.accept_none_alg then
ngx.log(ngx.DEBUG, "accept JWT with alg \"none\" and no signature")
return jwt
else
return jwt, "token uses \"none\" alg but accept_none_alg is not enabled"
end
end -- otherwise the JWT is invalid and load_jwt produces an error
end
local jwt_obj = jwt:load_jwt(jwt_string, nil)
if not jwt_obj.valid then
local reason = "invalid jwt"
if jwt_obj.reason then
reason = reason .. ": " .. jwt_obj.reason
end
return nil, reason
end
if not is_algorithm_expected(jwt_obj.header, expected_algs) then
local alg = jwt_obj.header and jwt_obj.header.alg or "no algorithm at all"
return nil, "token is signed by unexpected algorithm \"" .. alg .. "\""
end
local secret
if is_algorithm_supported(jwt_obj.header) then
if uses_asymmetric_algorithm(jwt_obj.header) then
secret = asymmetric_secret
if not secret and opts.discovery then
ngx.log(ngx.DEBUG, "using discovery to find key")
local err
secret, err = openidc_pem_from_jwk(opts, jwt_obj.header.kid)
if secret == nil then
ngx.log(ngx.ERR, err)
return nil, err
end
end
else
secret = symmetric_secret
end
end
if #{...} == 0 then
-- an empty list of claim specs makes lua-resty-jwt add default
-- validators for the exp and nbf claims if they are
-- present. These validators need to know the configured slack
-- value
local jwt_validators = require "resty.jwt-validators"
jwt_validators.set_system_leeway(opts.iat_slack and opts.iat_slack or 120)
end
jwt_obj = jwt:verify_jwt_obj(secret, jwt_obj, ...)
if jwt_obj then
ngx.log(ngx.DEBUG, "jwt: ", cjson.encode(jwt_obj), " ,valid: ", jwt_obj.valid, ", verified: ", jwt_obj.verified)
end
if not jwt_obj.verified then
local reason = "jwt signature verification failed"
if jwt_obj.reason then
reason = reason .. ": " .. jwt_obj.reason
end
return jwt_obj, reason
end
return jwt_obj
end
--
-- Load and validate id token from the id_token properties of the token endpoint response
-- Parameters :
-- - opts the openidc module options
-- - jwt_id_token the id_token from the id_token properties of the token endpoint response
-- - session the current session
-- Return the id_token, nil if valid
-- Return nil, the error if invalid
--
local function openidc_load_and_validate_jwt_id_token(opts, jwt_id_token, session)
local jwt_obj, err = openidc_load_jwt_and_verify_crypto(opts, jwt_id_token, opts.secret, opts.client_secret,
opts.discovery.id_token_signing_alg_values_supported)
if err then
local alg = (jwt_obj and jwt_obj.header and jwt_obj.header.alg) or ''
local is_unsupported_signature_error = jwt_obj and not jwt_obj.verified and not is_algorithm_supported(jwt_obj.header)
if is_unsupported_signature_error then
if opts.accept_unsupported_alg == nil or opts.accept_unsupported_alg then
ngx.log(ngx.WARN, "ignored id_token signature as algorithm '" .. alg .. "' is not supported")
else
err = "token is signed using algorithm \"" .. alg .. "\" which is not supported by lua-resty-jwt"
ngx.log(ngx.ERR, err)
return nil, err
end
else
ngx.log(ngx.ERR, "id_token '" .. alg .. "' signature verification failed")
return nil, err
end
end
local id_token = jwt_obj.payload
ngx.log(ngx.DEBUG, "id_token header: ", cjson.encode(jwt_obj.header))
ngx.log(ngx.DEBUG, "id_token payload: ", cjson.encode(jwt_obj.payload))
-- validate the id_token contents
if openidc_validate_id_token(opts, id_token, session.data.nonce) == false then
err = "id_token validation failed"
ngx.log(ngx.ERR, err)
return nil, err
end
return id_token
end
-- handle a "code" authorization response from the OP
local function openidc_authorization_response(opts, session)
local args = ngx.req.get_uri_args()
local err
if not args.code or not args.state then
err = "unhandled request to the redirect_uri: "..ngx.var.request_uri
ngx.log(ngx.ERR, err)
return nil, err, session.data.original_url, session
end
-- check that the state returned in the response against the session; prevents CSRF
if args.state ~= session.data.state then
err = "state from argument: "..(args.state and args.state or "nil").." does not match state restored from session: "..(session.data.state and session.data.state or "nil")
ngx.log(ngx.ERR, err)
return nil, err, session.data.original_url, session
end
-- check the iss if returned from the OP
if args.iss and args.iss ~= opts.discovery.issuer then
err = "iss from argument: "..args.iss.." does not match expected issuer: "..opts.discovery.issuer
ngx.log(ngx.ERR, err)
return nil, err, session.data.original_url, session
end
-- check the client_id if returned from the OP
if args.client_id and args.client_id ~= opts.client_id then
err = "client_id from argument: "..args.client_id.." does not match expected client_id: "..opts.client_id
ngx.log(ngx.ERR, err)
return nil, err, session.data.original_url, session
end
-- assemble the parameters to the token endpoint
local body = {
grant_type="authorization_code",
code=args.code,
redirect_uri=openidc_get_redirect_uri(opts),
state = session.data.state
}
ngx.log(ngx.DEBUG, "Authentication with OP done -> Calling OP Token Endpoint to obtain tokens")
local current_time = ngx.time()
-- make the call to the token endpoint
local json
json, err = openidc_call_token_endpoint(opts, opts.discovery.token_endpoint, body, opts.token_endpoint_auth_method)
if err then
return nil, err, session.data.original_url, session
end
local id_token, err = openidc_load_and_validate_jwt_id_token(opts, json.id_token, session);
if err then
return nil, err, session.data.original_url, session
end
session:start()
-- mark this sessions as authenticated
session.data.authenticated = true
-- clear state and nonce to protect against potential misuse
session.data.nonce = nil
session.data.state = nil
if store_in_session(opts, 'id_token') then
session.data.id_token = id_token
end
if store_in_session(opts, 'user') then
-- call the user info endpoint
-- TODO: should this error be checked?
local user
user, err = openidc_call_userinfo_endpoint(opts, json.access_token)
if err then
ngx.log(ngx.ERR, "error calling userinfo endpoint: " .. err)
elseif user then
if id_token.sub ~= user.sub then
err = "\"sub\" claim in id_token (\"" .. (id_token.sub or "null") .. "\") is not equal to the \"sub\" claim returned from the userinfo endpoint (\"" .. (user.sub or "null") .. "\")"
ngx.log(ngx.ERR, err)
else
session.data.user = user
end
end
end
if store_in_session(opts, 'enc_id_token') then
session.data.enc_id_token = json.id_token
end
if store_in_session(opts, 'access_token') then
session.data.access_token = json.access_token
session.data.access_token_expiration = current_time
+ openidc_access_token_expires_in(opts, json.expires_in)
if json.refresh_token ~= nil then
session.data.refresh_token = json.refresh_token
end
end
-- save the session with the obtained id_token
session:save()
-- redirect to the URL that was accessed originally
ngx.log(ngx.DEBUG, "OIDC Authorization Code Flow completed -> Redirecting to original URL ("..session.data.original_url..")")
ngx.redirect(session.data.original_url)
return nil, nil, session.data.original_url, session
end
local openidc_transparent_pixel = "\137\080\078\071\013\010\026\010\000\000\000\013\073\072\068\082" ..
"\000\000\000\001\000\000\000\001\008\004\000\000\000\181\028\012" ..
"\002\000\000\000\011\073\068\065\084\120\156\099\250\207\000\000" ..
"\002\007\001\002\154\028\049\113\000\000\000\000\073\069\078\068" ..
"\174\066\096\130"
-- handle logout
local function openidc_logout(opts, session)
local session_token = session.data.enc_id_token
session:destroy()
local headers = ngx.req.get_headers()
local header = headers['Accept']
if header and header:find("image/png") then
ngx.header["Cache-Control"] = "no-cache, no-store"