-
Notifications
You must be signed in to change notification settings - Fork 4
/
jwtverify.lua
254 lines (216 loc) · 7.29 KB
/
jwtverify.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
--
-- JWT Validation implementation for HAProxy Lua host
--
-- Copyright (c) 2019. Adis Nezirovic <[email protected]>
-- Copyright (c) 2019. Baptiste Assmann <[email protected]>
-- Copyright (c) 2019. Nick Ramirez <[email protected]>
-- Copyright (c) 2019. HAProxy Technologies LLC
--
-- Copyright (c) 2020. Łukasz Budnik <[email protected]>
-- Changes made to the original haproxy script:
-- * added step 8 to support Keycloak realm roles.
--
-- 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,
issuer = nil,
audience = nil,
hmacSecret = nil
}
end
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
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('Authorization header: ' .. authorizationHeader)
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, publicKey)
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
local function audienceIsValid(token, expectedAudience)
return token.payloaddecoded.aud == expectedAudience
end
function jwtverify(txn)
local pem = config.publicKey
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
-- 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, pem) == 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
-- 7. Add scopes to variable
if token.payloaddecoded.scope ~= nil then
txn.set_var(txn, "txn.oauth_scopes", token.payloaddecoded.scope)
else
txn.set_var(txn, "txn.oauth_scopes", "")
end
-- 8. Add roles to variable
if token.payloaddecoded.realm_access ~= nil then
-- Keycloak returns list of roles, need to convert Lua table to string
roles = table.concat(token.payloaddecoded.realm_access.roles, ",")
log("Setting roles: " .. roles)
txn.set_var(txn, "txn.roles", roles)
else
txn.set_var(txn, "txn.roles", "")
end
-- 9. Set authorized variable
log("txn.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("txn.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 an RS256 signature
local publicKeyPath = os.getenv("OAUTH_PUBKEY_PATH")
local pem = readAll(publicKeyPath)
config.publicKey = pem
-- when using an HS256 or HS512 signature
config.hmacSecret = os.getenv("OAUTH_HMAC_SECRET")
log("PublicKeyPath: " .. publicKeyPath)
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)