-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathjwtverify.lua
More file actions
341 lines (286 loc) · 9.99 KB
/
jwtverify.lua
File metadata and controls
341 lines (286 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
--
-- JWT Validation implementation for HAProxy Lua host
--
-- Copyright (c) 2019. Adis Nezirovic <anezirovic@haproxy.com>
-- Copyright (c) 2019. Baptiste Assmann <bassmann@haproxy.com>
-- Copyright (c) 2019. Nick Ramirez <nramirez@haproxy.com>
-- Copyright (c) 2019. HAProxy Technologies LLC
--
-- Licensed 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.
--
-- Use HAProxy 'lua-load' to load optional configuration file which
-- should contain config table.
-- Default/fallback config
if not config then
config = {
debug = true,
publicKey = nil,
kid = nil,
issuer = nil,
audience = nil,
hmacSecret = nil
}
end
-- search these paths for *.lua and *.so files on CentOS/RHEL
package.path = package.path .. ';/usr/local/share/lua/5.4/?.lua'
package.cpath = package.cpath .. ';/usr/local/lib/lua/5.4/?.so;/usr/local/lib/lua/5.4/?/?.so'
local json = require 'json'
local base64 = require 'base64'
local openssl = {
pkey = require 'openssl.pkey',
digest = require 'openssl.digest',
x509 = require 'openssl.x509',
hmac = require 'openssl.hmac'
}
local function log(msg)
if config.debug then
core.Debug(tostring(msg))
end
end
local function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-- Loops through array to find the given string.
-- items: array of strings
-- test_str: string to search for
local function contains(items, test_str)
for _,item in pairs(items) do
-- strip whitespace
item = item:gsub("%s+", "")
test_str = test_str:gsub("%s+", "")
if item == test_str then
return true
end
end
return false
end
local function readAll(file)
log("Reading file " .. file)
local f = assert(io.open(file, "rb"))
local content = f:read("*all")
f:close()
return content
end
local function decodeJwt(authorizationHeader)
local headerFields = core.tokenize(authorizationHeader, " .")
if #headerFields ~= 4 then
log("Improperly formated Authorization header. Should be 'Bearer' followed by 3 token sections.")
return nil
end
if headerFields[1] ~= 'Bearer' then
log("Improperly formated Authorization header. Missing 'Bearer' property.")
return nil
end
local token = {}
token.header = headerFields[2]
token.headerdecoded = json.decode(base64.decode(token.header))
token.payload = headerFields[3]
token.payloaddecoded = json.decode(base64.decode(token.payload))
token.signature = headerFields[4]
token.signaturedecoded = base64.decode(token.signature)
log('Decoded JWT header: ' .. dump(token.headerdecoded))
log('Decoded JWT payload: ' .. dump(token.payloaddecoded))
return token
end
local function algorithmIsValid(token)
if token.headerdecoded.alg == nil then
log("No 'alg' provided in JWT header.")
return false
elseif token.headerdecoded.alg ~= 'HS256' and token.headerdecoded.alg ~= 'HS512' and token.headerdecoded.alg ~= 'RS256' then
log("HS256, HS512 and RS256 supported. Incorrect alg in JWT: " .. token.headerdecoded.alg)
return false
end
return true
end
local function rs256SignatureIsValid(token, keys, kids)
-- Check if a kid if provided, if so verify it exists in the kids array
local token_kid = token.headerdecoded.kid
local publicKey
if kids ~= nil then
if not contains(kids, token_kid) then
log("The kid provided in the token (" .. token_kid .. ") does not match the kid provided in the configuration.")
return false
end
-- get the key from the keys list at the index of the correct kid
publicKey = keys[token_kid]
else
-- if no kid is provided, use the first key in the list
publicKey = keys[next(keys)]
end
local digest = openssl.digest.new('SHA256')
digest:update(token.header .. '.' .. token.payload)
local vkey = openssl.pkey.new(publicKey)
local isVerified = vkey:verify(token.signaturedecoded, digest)
return isVerified
end
local function hs256SignatureIsValid(token, secret)
local hmac = openssl.hmac.new(secret, 'SHA256')
local checksum = hmac:final(token.header .. '.' .. token.payload)
return checksum == token.signaturedecoded
end
local function hs512SignatureIsValid(token, secret)
local hmac = openssl.hmac.new(secret, 'SHA512')
local checksum = hmac:final(token.header .. '.' .. token.payload)
return checksum == token.signaturedecoded
end
local function expirationIsValid(token)
return os.difftime(token.payloaddecoded.exp, core.now().sec) > 0
end
local function issuerIsValid(token, expectedIssuer)
return token.payloaddecoded.iss == expectedIssuer
end
-- Checks if the audience in the token is listed in the
-- OAUTH_AUDIENCE environment variable. Both the token audience
-- and the environment variable can contain multiple audience values,
-- separated by commas. Each value will be checked.
local function audienceIsValid(token, expectedAudienceParam)
-- Convert OAUTH_AUDIENCE environment variable to a table,
-- even if it contains only one value
local expectedAudiences = expectedAudienceParam
if type(expectedAudiences) == "string" then
-- split multiple values using a space as the delimiter
expectedAudiences = core.tokenize(expectedAudienceParam, " ")
end
local receivedAudiences = token.payloaddecoded.aud
-- Check if 'aud' exists and handle cases where it's missing
if receivedAudiences == nil then
return false
end
-- Convert 'aud' claim to a table, even if it contains only one value
if type(token.payloaddecoded.aud) == "string" then
receivedAudiences ={}
receivedAudiences[1] = token.payloaddecoded.aud
end
for _, receivedAudience in ipairs(receivedAudiences) do
if contains(expectedAudiences, receivedAudience) then
return true
end
end
return false
end
local function setVariablesFromPayload(txn, decodedPayload)
for key, value in pairs(decodedPayload) do
txn:set_var("txn.oauth." .. key, dump(value))
end
end
local function jwtverify(txn)
local keys = config.publicKeys
local kid = config.kid
local issuer = config.issuer
local audience = config.audience
local hmacSecret = config.hmacSecret
-- 1. Decode and parse the JWT
local token = decodeJwt(txn.sf:req_hdr("Authorization"))
if token == nil then
log("Token could not be decoded.")
goto out
end
-- Set an HAProxy variable for each field in the token payload
setVariablesFromPayload(txn, token.payloaddecoded)
-- 2. Verify the signature algorithm is supported (HS256, HS512, RS256)
if algorithmIsValid(token) == false then
log("Algorithm not valid.")
goto out
end
-- 3. Verify the signature with the certificate
if token.headerdecoded.alg == 'RS256' then
if rs256SignatureIsValid(token, keys, kid) == false then
log("Signature not valid.")
goto out
end
elseif token.headerdecoded.alg == 'HS256' then
if hs256SignatureIsValid(token, hmacSecret) == false then
log("Signature not valid.")
goto out
end
elseif token.headerdecoded.alg == 'HS512' then
if hs512SignatureIsValid(token, hmacSecret) == false then
log("Signature not valid.")
goto out
end
end
-- 4. Verify that the token is not expired
if expirationIsValid(token) == false then
log("Token is expired.")
goto out
end
-- 5. Verify the issuer
if issuer ~= nil and issuerIsValid(token, issuer) == false then
log("Issuer not valid.")
goto out
end
-- 6. Verify the audience
if audience ~= nil and audienceIsValid(token, audience) == false then
log("Audience not valid.")
goto out
end
-- 8. Set authorized variable
log("req.authorized = true")
txn.set_var(txn, "txn.authorized", true)
-- exit
do return end
-- way out. Display a message when running in debug mode
::out::
log("req.authorized = false")
txn.set_var(txn, "txn.authorized", false)
end
-- Called after the configuration is parsed.
-- Loads the OAuth public key for validating the JWT signature.
core.register_init(function()
config.issuer = os.getenv("OAUTH_ISSUER")
config.audience = os.getenv("OAUTH_AUDIENCE")
-- when using multiple keys, parse the kid list
local kid = os.getenv("OAUTH_KID")
if kid ~= nil then
config.kid = core.tokenize(kid, " ")
end
-- when using an RS256 signature
local publicKeyPath = os.getenv("OAUTH_PUBKEY_PATH")
if publicKeyPath ~= nil then
-- tokenize the path in case multiple keys are provided
keyPaths = core.tokenize(publicKeyPath, " ")
-- Check if there is more than one file path then we must have kid identifiers
if #keyPaths > 1 and config.kid == nil then
log("Multiple public keys provided but no key identifiers.")
return
end
-- Make sure that the kid size matches the keyPaths size
if config.kid ~= nil and #config.kid ~= #keyPaths then
log("The number of keys does not match the number of key identifiers.")
return
end
-- Read all the keys and store them in the config
config.publicKeys = {}
for i, keyPath in ipairs(keyPaths) do
local pem = readAll(keyPath)
config.publicKeys[config.kid[i]] = pem
end
end
-- when using an HS256 or HS512 signature
config.hmacSecret = os.getenv("OAUTH_HMAC_SECRET")
log("PublicKeyPath: " .. (publicKeyPath or "<none>"))
log("KeyIdentifiers: " .. (kid or "<none>"))
log("Issuer: " .. (config.issuer or "<none>"))
log("Audience: " .. (config.audience or "<none>"))
end)
-- Called on a request.
core.register_action('jwtverify', {'http-req'}, jwtverify, 0)