-
-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathopenidc.lua
1938 lines (1644 loc) · 61.2 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) 2017-2023 ZmartZone Holding B.V.
Copyright (C) 2015-2017 Ping Identity Corporation
All rights reserved.
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 - [email protected]
--]]
local require = require
local cjson = require("cjson")
local cjson_s = require("cjson.safe")
local http = require("resty.http")
local r_session = require("resty.session")
local string = string
local table = table
local ipairs = ipairs
local pairs = pairs
local type = type
local ngx = ngx
local b64 = ngx.encode_base64
local b64url = require("ngx.base64").encode_base64url
local unb64url = require("ngx.base64").decode_base64url
local log = ngx.log
local DEBUG = ngx.DEBUG
local ERROR = ngx.ERR
local WARN = ngx.WARN
local function token_auth_method_precondition(method, required_field)
return function(opts)
if not opts[required_field] then
log(DEBUG, "Can't use " .. method .. " without opts." .. required_field)
return false
end
return true
end
end
local supported_token_auth_methods = {
client_secret_basic = true,
client_secret_post = true,
private_key_jwt = token_auth_method_precondition('private_key_jwt', 'client_rsa_private_key'),
client_secret_jwt = token_auth_method_precondition('client_secret_jwt', 'client_secret')
}
local openidc = {
_VERSION = "1.8.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
local function is_session(o)
return o ~= nil and o.save and type(o.save) == "function"
end
local function is_session_present(session)
return session ~= nil and next(session:get_data()) ~= nil
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)
log(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 log(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
log(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")
openidc_cache_invalidate("jwt_verification")
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
log(ERROR, "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
log(ERROR, "no \"sub\" claim found in id_token")
return false
end
-- check nonce
if nonce and nonce ~= id_token.nonce then
log(ERROR, "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
log(ERROR, "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
log(ERROR, "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
log(ERROR, "no \"exp\" claim found in id_token")
return false
end
if (id_token.exp + slack) < ngx.time() then
log(ERROR, "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
log(ERROR, "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
log(ERROR, "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
log(ERROR, "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(table_or_string)
local res = table_or_string
if table_or_string and type(table_or_string) == 'table' then
res = table_or_string[1]
end
return res
end
local function get_first_header(headers, header_name)
local header = headers[header_name]
return get_first(header)
end
local function get_first_header_and_strip_whitespace(headers, header_name)
local header = get_first_header(headers, header_name)
return header and header:gsub('%s', '')
end
local function get_forwarded_parameter(headers, param_name)
local forwarded = get_first_header(headers, '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(headers)
return get_forwarded_parameter(headers, 'proto')
or get_first_header_and_strip_whitespace(headers, 'X-Forwarded-Proto')
or ngx.var.scheme
end
local function get_host_name_from_x_header(headers)
local header = get_first_header_and_strip_whitespace(headers, 'X-Forwarded-Host')
return header and header:gsub('^([^,]+),?.*$', '%1')
end
local function get_host_name(headers)
return get_forwarded_parameter(headers, 'host')
or get_host_name_from_x_header(headers)
or ngx.var.http_host
end
-- assemble the redirect_uri
local function openidc_get_redirect_uri(opts, session)
local path = opts.redirect_uri_path
if opts.redirect_uri then
if opts.redirect_uri:sub(1, 1) == '/' then
path = opts.redirect_uri
else
return opts.redirect_uri
end
end
local headers = ngx.req.get_headers()
local scheme = opts.redirect_uri_scheme or get_scheme(headers)
local host = get_host_name(headers)
if not host then
-- possibly HTTP 1.0 and no Host header
if session then session:close() end
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
return scheme .. "://" .. host .. path
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
local function decorate_request(http_request_decorator, req)
return http_request_decorator and http_request_decorator(req) or req
end
local sha256 = (require 'resty.sha256'):new()
local function openidc_s256(verifier)
sha256:update(verifier)
local s256 = b64url(sha256:final())
sha256:reset()
return s256
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")
local err
-- generate state and nonce
local state = resty_string.to_hex(resty_random.bytes(16))
local nonce = (opts.use_nonce == nil or opts.use_nonce)
and resty_string.to_hex(resty_random.bytes(16))
local code_verifier = opts.use_pkce and b64url(resty_random.bytes(32))
-- 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, session),
state = state,
}
if nonce then
params.nonce = nonce
end
if prompt then
params.prompt = prompt
end
if opts.display then
params.display = opts.display
end
if code_verifier then
params.code_challenge_method = 'S256'
params.code_challenge = openidc_s256(code_verifier)
end
if opts.response_mode then
params.response_mode = opts.response_mode
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:set("original_url", target_url)
session:set("state", state)
session:set("nonce", nonce)
session:set("code_verifier", code_verifier)
session:set("last_authenticated", ngx.time())
if opts.lifecycle and opts.lifecycle.on_created then
err = opts.lifecycle.on_created(session, params)
if err then
log(WARN, "failed in `on_created` handler: " .. err)
return err
end
end
local res
res, err = session:save()
if err then
log(WARN, "unable to save session: " .. err)
end
-- 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, ignore_body_on_success)
local ignore_body_on_success = ignore_body_on_success or false
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
if ignore_body_on_success then
return nil, nil
end
-- 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
log(DEBUG, "openidc_configure_proxy : use http proxy")
httpc:set_proxy_options(proxy_opts)
else
log(DEBUG, "openidc_configure_proxy : don't use http proxy")
end
end
-- make a call to the token endpoint
function openidc.call_token_endpoint(opts, endpoint, body, auth, endpoint_name, ignore_body_on_success)
local ignore_body_on_success = ignore_body_on_success or false
local ep_name = endpoint_name or 'token'
if not endpoint then
return nil, 'no endpoint URI for ' .. ep_name
end
local headers = {
["Content-Type"] = "application/x-www-form-urlencoded"
}
if auth then
if auth == "client_secret_basic" then
if opts.client_secret then
headers.Authorization = "Basic " .. b64(ngx.escape_uri(opts.client_id) .. ":" .. ngx.escape_uri(opts.client_secret))
else
-- client_secret must not be set if Windows Integrated Authentication (WIA) is used with
-- Active Directory Federation Services (AD FS) 4.0 (or newer) on Windows Server 2016 (or newer)
headers.Authorization = "Basic " .. b64(ngx.escape_uri(opts.client_id) .. ":")
end
log(DEBUG, "client_secret_basic: authorization header '" .. headers.Authorization .. "'")
elseif auth == "client_secret_post" then
body.client_id = opts.client_id
if opts.client_secret then
body.client_secret = opts.client_secret
end
log(DEBUG, "client_secret_post: client_id and client_secret being sent in POST body")
elseif auth == "private_key_jwt" or auth == "client_secret_jwt" then
local key = auth == "private_key_jwt" and opts.client_rsa_private_key or opts.client_secret
if not key then
return nil, "Can't use " .. auth .. " without a key."
end
body.client_id = opts.client_id
body.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
local now = ngx.time()
local assertion = {
header = {
typ = "JWT",
alg = auth == "private_key_jwt" and "RS256" or "HS256",
},
payload = {
iss = opts.client_id,
sub = opts.client_id,
aud = endpoint,
jti = ngx.var.request_id,
exp = now + (opts.client_jwt_assertion_expires_in and opts.client_jwt_assertion_expires_in or 60),
iat = now
}
}
if auth == "private_key_jwt" then
assertion.header.kid = opts.client_rsa_private_key_id
end
local r_jwt = require("resty.jwt")
body.client_assertion = r_jwt:sign(key, assertion)
log(DEBUG, auth .. ": client_id, client_assertion_type and client_assertion 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
log(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, decorate_request(opts.http_request_decorator, {
method = "POST",
body = ngx.encode_args(body),
headers = headers,
ssl_verify = (opts.ssl_verify ~= "no"),
keepalive = (opts.keepalive ~= "no")
}))
if not res then
err = "accessing " .. ep_name .. " endpoint (" .. endpoint .. ") failed: " .. err
log(ERROR, err)
return nil, err
end
log(DEBUG, ep_name .. " endpoint response: ", res.body)
return openidc_parse_json_response(res, ignore_body_on_success)
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(unb64url(enc_hdr))
local payload = cjson_s.decode(unb64url(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, keepalive, timeout, exptime, proxy_opts, http_request_decorator)
log(DEBUG, "openidc_discover: URL is: " .. url)
local json, err
local v = openidc_cache_get("discovery", url)
if not v then
log(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, decorate_request(http_request_decorator, {
ssl_verify = (ssl_verify ~= "no"),
keepalive = (keepalive ~= "no")
}))
if not res then
err = "accessing discovery url (" .. url .. ") failed: " .. error
log(ERROR, err)
else
log(DEBUG, "response data: " .. res.body)
json, err = openidc_parse_json_response(res)
if json then
openidc_cache_set("discovery", url, cjson.encode(json), exptime or 24 * 60 * 60)
else
err = "could not decode JSON from Discovery data" .. (err and (": " .. err) or '')
log(ERROR, 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
local discovery
discovery, err = openidc_discover(opts.discovery, opts.ssl_verify, opts.keepalive, opts.timeout, opts.discovery_expires_in, opts.proxy_opts,
opts.http_request_decorator)
if not err then
opts.discovery = discovery
end
end
return err
end
-- make a call to the userinfo endpoint
function openidc.call_userinfo_endpoint(opts, access_token)
local err = openidc_ensure_discovered_data(opts)
if err then
return nil, err
end
if not (opts and opts.discovery and opts.discovery.userinfo_endpoint) then
log(DEBUG, "no userinfo endpoint supplied")
return nil, nil
end
local headers = {
["Authorization"] = "Bearer " .. access_token,
}
log(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,
decorate_request(opts.http_request_decorator, {
headers = headers,
ssl_verify = (opts.ssl_verify ~= "no"),
keepalive = (opts.keepalive ~= "no")
}))
if not res then
err = "accessing (" .. opts.discovery.userinfo_endpoint .. ") failed: " .. err
return nil, err
end
log(DEBUG, "userinfo response: ", res.body)
-- handle if the response type is a jwt/signed payload
local responseType = string.lower(res.headers["Content-Type"])
if string.find(responseType, "application/jwt") then
local json, err = openidc.jwt_verify(res.body, opts)
if err then
err = "userinfo jwt could not be verified: " .. err
return nil, err
end
return json
end
-- parse the response from the user info endpoint
return openidc_parse_json_response(res)
end
local function can_use_token_auth_method(method, opts)
local supported = supported_token_auth_methods[method]
return supported and (type(supported) ~= 'function' or supported(opts))
end
-- get the token endpoint authentication method
local function openidc_get_token_auth_method(opts)
if opts.token_endpoint_auth_method ~= nil and not can_use_token_auth_method(opts.token_endpoint_auth_method, opts) then
log(ERROR, "configured value for token_endpoint_auth_method (" .. opts.token_endpoint_auth_method .. ") is not supported, ignoring it")
opts.token_endpoint_auth_method = nil
end
local result
if opts.discovery.token_endpoint_auth_methods_supported ~= nil then
-- if set check to make sure the discovery data includes the selected client auth method
if opts.token_endpoint_auth_method ~= nil then
for index, value in ipairs(opts.discovery.token_endpoint_auth_methods_supported) do
log(DEBUG, index .. " => " .. value)
if value == opts.token_endpoint_auth_method then
log(DEBUG, "configured value for token_endpoint_auth_method (" .. opts.token_endpoint_auth_method .. ") found in token_endpoint_auth_methods_supported in metadata")
result = opts.token_endpoint_auth_method
break
end
end
if result == nil then
log(ERROR, "configured value for token_endpoint_auth_method (" .. opts.token_endpoint_auth_method .. ") NOT found in token_endpoint_auth_methods_supported in metadata")
return nil
end
else
for index, value in ipairs(opts.discovery.token_endpoint_auth_methods_supported) do
log(DEBUG, index .. " => " .. value)
if can_use_token_auth_method(value, opts) then
result = value
log(DEBUG, "no configuration setting for option so select the first supported method specified by the OP: " .. result)
break
end
end
end
else
result = opts.token_endpoint_auth_method
end
-- set a sane default if auto-configuration failed
if result == nil then
result = "client_secret_basic"
end
log(DEBUG, "token_endpoint_auth_method result set to " .. result)
return result
end
-- ensure that discovery and token auth configuration is available in opts
local function ensure_config(opts)
local err
err = openidc_ensure_discovered_data(opts)
if err then
return err
end
-- set the authentication method for the token endpoint
opts.token_endpoint_auth_method = openidc_get_token_auth_method(opts)
end
-- query for discovery endpoint data
function openidc.get_discovery_doc(opts)
local err = openidc_ensure_discovered_data(opts)
if err then
log(ERROR, "error getting endpoints definition using discovery endpoint")
end
return opts.discovery, err
end
local function openidc_jwks(url, force, ssl_verify, keepalive, timeout, exptime, proxy_opts, http_request_decorator)
log(DEBUG, "openidc_jwks: URL is: " .. url .. " (force=" .. force .. ") (decorator=" .. (http_request_decorator and type(http_request_decorator) or "nil"))
local json, err, v
if force == 0 then
v = openidc_cache_get("jwks", url)
end
if not v then
log(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, decorate_request(http_request_decorator, {
ssl_verify = (ssl_verify ~= "no"),
keepalive = (keepalive ~= "no")
}))
if not res then
err = "accessing jwks url (" .. url .. ") failed: " .. error
log(ERROR, err)
else
log(DEBUG, "response data: " .. res.body)
json, err = openidc_parse_json_response(res)
if json then
openidc_cache_set("jwks", url, cjson.encode(json), exptime or 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
log(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, typ)
typ = typ:upper() or "CERTIFICATE"
data = b64(data)
return string.format(envelope, typ, data:gsub(wrap, '%0\n', (#data - 1) / 64), typ)
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 encode_bit_string(array)
local s = "\0" .. array -- first octet holds the number of unused bits
return "\3" .. encode_length(#s) .. s
end
local function openidc_pem_from_x5c(x5c)
log(DEBUG, "Found x5c, getting PEM public key from x5c entry of json public key")
local chunks = split_by_chunk(x5c[1], 64)
local pem = "-----BEGIN CERTIFICATE-----\n" ..
table.concat(chunks, "\n") ..
"\n-----END CERTIFICATE-----"
log(DEBUG, "Generated PEM key from x5c:", pem)
return pem
end
local function openidc_pem_from_rsa_n_and_e(n, e)
log(DEBUG, "getting PEM public key from n and e parameters of json public key")
local der_key = {
unb64url(n), unb64url(e)
}
local encoded_key = encode_sequence_of_integer(der_key)
local pem = der2pem(encode_sequence({
encode_sequence({
"\6\9\42\134\72\134\247\13\1\1\1" -- OID :rsaEncryption
.. "\5\0" -- ASN.1 NULL of length 0
}),
encode_bit_string(encoded_key)
}), "PUBLIC KEY")
log(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.keepalive, opts.timeout, opts.jwk_expires_in, opts.proxy_opts,
opts.http_request_decorator)
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 x5c = jwk.x5c
if x5c and type(x5c) ~= 'table' then
log(WARN, "Found invalid JWK with x5c claim not being an array but a " .. type(x5c))
x5c = nil
end
if x5c and #(jwk.x5c) == 0 then
log(WARN, "Found invalid JWK with empty x5c array, ignoring x5c claim")
x5c = nil
end
local pem
if x5c then
pem = openidc_pem_from_x5c(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(jwk)
end
openidc_cache_set("jwks", cache_id, pem, opts.jwk_expires_in or 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
return expected_algs == jwt_header.alg
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 r_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
log(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 = r_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"