Skip to content

Commit 9956719

Browse files
committed
Example
0 parents  commit 9956719

File tree

6 files changed

+463
-0
lines changed

6 files changed

+463
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.venv
2+
.idea

README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Envoy Lua ASN.1 Example
2+
3+
This is an example of how to validate a request based on an ECDSA ASN.1 signature in Envoy’s lua engine. Please note this is only an example and is missing additional checks on the token that you might want in a production environment.
4+
5+
Starting server:
6+
```
7+
$ docker run -p 18000:18000 --mount type=bind,source="$(pwd)"/envoy-config,target=/envoy-config,readonly -it envoyproxy/envoy:v1.21.0 --config-path /envoy-config/envoy.yaml
8+
9+
[2022-02-17 22:19:44.229][29][info][lua] [source/extensions/filters/http/lua/lua_filter.cc:796] script log: filter beginning
10+
[2022-02-17 22:19:44.230][29][info][lua] [source/extensions/filters/http/lua/lua_filter.cc:796] script log: x-amzn-oidc-data: eyJhbGciOiAiRVMyNTYiLCAidHlwIjogIkpXVCIsICJraWQiOiAiMTIzNCIsICJzaWduZXIiOiAiYXJuOmF3czplbGFzdGljbG9hZGJhbGFuY2luZzp1cy1lYXN0LTI6MTIzNDU2Nzg5MDpsb2FkYmFsYW5jZXIvYXBwL2Zvb2JhciJ9.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsICJuYW1lIjogIlNsYXZhIiwgImVtYWlsIjogInNsYXZhQGV4YW1wbGUuY29tIn0=.quspn70308gCjLs3slvbuH5svek1wDBoeasFexzcrHPe_eFajgSt4x4q06IdgsYvKkxaT2WQiOOSber_2KGJxg==
11+
[2022-02-17 22:19:44.230][29][info][lua] [source/extensions/filters/http/lua/lua_filter.cc:796] script log: checking signature against key
12+
[2022-02-17 22:19:44.230][29][info][lua] [source/extensions/filters/http/lua/lua_filter.cc:796] script log: signature valid
13+
```
14+
15+
Running the client:
16+
```
17+
$ pip install -r requirements.txt
18+
$ python client.py
19+
20+
public key =
21+
-----BEGIN PUBLIC KEY-----
22+
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmyuuRixAItd2StXgNOv7qfc/rMs1
23+
dqLR7jaF3D+hEt/l9RPjsfqOFHwrOzOl6QpdoCVAPszYPocHp5FaI59ByQ==
24+
-----END PUBLIC KEY-----
25+
26+
request headers: {'x-amzn-oidc-data': 'eyJhbGciOiAiRVMyNTYiLCAidHlwIjogIkpXVCIsICJraWQiOiAiMTIzNCIsICJzaWduZXIiOiAiYXJuOmF3czplbGFzdGljbG9hZGJhbGFuY2luZzp1cy1lYXN0LTI6MTIzNDU2Nzg5MDpsb2FkYmFsYW5jZXIvYXBwL2Zvb2JhciJ9.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsICJuYW1lIjogIlNsYXZhIiwgImVtYWlsIjogInNsYXZhQGV4YW1wbGUuY29tIn0=.quspn70308gCjLs3slvbuH5svek1wDBoeasFexzcrHPe_eFajgSt4x4q06IdgsYvKkxaT2WQiOOSber_2KGJxg=='}
27+
response: 200 signature valid
28+
```

client.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import base64
2+
import hashlib
3+
import json
4+
import requests
5+
6+
from ecdsa import NIST256p, SigningKey
7+
from ecdsa.util import randrange_from_seed__trytryagain
8+
9+
10+
###############################################################################
11+
# Generate signing key
12+
#
13+
# Create a signing key from a known seed to make testing easier. The public
14+
# key (aka verification key) is pasted into the envoy.yaml config.
15+
###############################################################################
16+
17+
def make_key(key_seed: bytes):
18+
secexp = randrange_from_seed__trytryagain(key_seed, NIST256p.order)
19+
return SigningKey.from_secret_exponent(secexp, curve=NIST256p)
20+
21+
22+
seed = b'00000000000000000000000000000001'
23+
private_key = make_key(seed)
24+
public_key_pem = private_key.verifying_key.to_pem().decode('utf8')
25+
26+
print(f'public key = \n{public_key_pem}')
27+
28+
###############################################################################
29+
# Create and sign JWT
30+
###############################################################################
31+
header = {
32+
"alg": "ES256",
33+
"typ": "JWT",
34+
"kid": "1234",
35+
"signer": "arn:aws:elasticloadbalancing:us-east-2:1234567890:loadbalancer/app/foobar"
36+
}
37+
38+
claims = {
39+
"sub": "1234567890",
40+
"name": "Slava",
41+
"email": "slava@example.com"
42+
}
43+
44+
jwt = '{}.{}'.format(
45+
base64.standard_b64encode(json.dumps(header).encode('utf8')).decode('utf8'),
46+
base64.standard_b64encode(json.dumps(claims).encode('utf8')).decode('utf8')
47+
)
48+
49+
signature = private_key.sign(jwt.encode('utf8'), hashfunc=hashlib.sha256)
50+
signature = base64.urlsafe_b64encode(signature).decode('utf8')
51+
jwt = f'{jwt}.{signature}'
52+
53+
###############################################################################
54+
# Make request to Envoy
55+
###############################################################################
56+
headers = {
57+
'x-amzn-oidc-data': jwt
58+
}
59+
60+
print(f'request headers: {headers}')
61+
resp = requests.get(url='http://localhost:18000', headers=headers)
62+
63+
print(f'response: {resp.status_code} {resp.text}')

envoy-config/base64.lua

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
--[[
2+
base64 -- v1.5.3 public domain Lua base64 encoder/decoder
3+
no warranty implied; use at your own risk
4+
Needs bit32.extract function. If not present it's implemented using BitOp
5+
or Lua 5.3 native bit operators. For Lua 5.1 fallbacks to pure Lua
6+
implementation inspired by Rici Lake's post:
7+
http://ricilake.blogspot.co.uk/2007/10/iterating-bits-in-lua.html
8+
author: Ilya Kolbin (iskolbin@gmail.com)
9+
url: github.com/iskolbin/lbase64
10+
COMPATIBILITY
11+
Lua 5.1+, LuaJIT
12+
LICENSE
13+
See end of file for license information.
14+
--]]
15+
16+
17+
local base64 = {}
18+
19+
local extract = _G.bit32 and _G.bit32.extract -- Lua 5.2/Lua 5.3 in compatibility mode
20+
if not extract then
21+
if _G.bit then -- LuaJIT
22+
local shl, shr, band = _G.bit.lshift, _G.bit.rshift, _G.bit.band
23+
extract = function( v, from, width )
24+
return band( shr( v, from ), shl( 1, width ) - 1 )
25+
end
26+
elseif _G._VERSION == "Lua 5.1" then
27+
extract = function( v, from, width )
28+
local w = 0
29+
local flag = 2^from
30+
for i = 0, width-1 do
31+
local flag2 = flag + flag
32+
if v % flag2 >= flag then
33+
w = w + 2^i
34+
end
35+
flag = flag2
36+
end
37+
return w
38+
end
39+
else -- Lua 5.3+
40+
extract = load[[return function( v, from, width )
41+
return ( v >> from ) & ((1 << width) - 1)
42+
end]]()
43+
end
44+
end
45+
46+
47+
function base64.makeencoder( s62, s63, spad )
48+
local encoder = {}
49+
for b64code, char in pairs{[0]='A','B','C','D','E','F','G','H','I','J',
50+
'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y',
51+
'Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
52+
'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2',
53+
'3','4','5','6','7','8','9',s62 or '+',s63 or'/',spad or'='} do
54+
encoder[b64code] = char:byte()
55+
end
56+
return encoder
57+
end
58+
59+
function base64.makedecoder( s62, s63, spad )
60+
local decoder = {}
61+
for b64code, charcode in pairs( base64.makeencoder( s62, s63, spad )) do
62+
decoder[charcode] = b64code
63+
end
64+
return decoder
65+
end
66+
67+
local DEFAULT_ENCODER = base64.makeencoder()
68+
local DEFAULT_DECODER = base64.makedecoder()
69+
70+
local char, concat = string.char, table.concat
71+
72+
function base64.encode( str, encoder, usecaching )
73+
encoder = encoder or DEFAULT_ENCODER
74+
local t, k, n = {}, 1, #str
75+
local lastn = n % 3
76+
local cache = {}
77+
for i = 1, n-lastn, 3 do
78+
local a, b, c = str:byte( i, i+2 )
79+
local v = a*0x10000 + b*0x100 + c
80+
local s
81+
if usecaching then
82+
s = cache[v]
83+
if not s then
84+
s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
85+
cache[v] = s
86+
end
87+
else
88+
s = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[extract(v,0,6)])
89+
end
90+
t[k] = s
91+
k = k + 1
92+
end
93+
if lastn == 2 then
94+
local a, b = str:byte( n-1, n )
95+
local v = a*0x10000 + b*0x100
96+
t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[extract(v,6,6)], encoder[64])
97+
elseif lastn == 1 then
98+
local v = str:byte( n )*0x10000
99+
t[k] = char(encoder[extract(v,18,6)], encoder[extract(v,12,6)], encoder[64], encoder[64])
100+
end
101+
return concat( t )
102+
end
103+
104+
function base64.decode( b64, decoder, usecaching )
105+
decoder = decoder or DEFAULT_DECODER
106+
local pattern = '[^%w%+%/%=]'
107+
if decoder then
108+
local s62, s63
109+
for charcode, b64code in pairs( decoder ) do
110+
if b64code == 62 then s62 = charcode
111+
elseif b64code == 63 then s63 = charcode
112+
end
113+
end
114+
pattern = ('[^%%w%%%s%%%s%%=]'):format( char(s62), char(s63) )
115+
end
116+
b64 = b64:gsub( pattern, '' )
117+
local cache = usecaching and {}
118+
local t, k = {}, 1
119+
local n = #b64
120+
local padding = b64:sub(-2) == '==' and 2 or b64:sub(-1) == '=' and 1 or 0
121+
for i = 1, padding > 0 and n-4 or n, 4 do
122+
local a, b, c, d = b64:byte( i, i+3 )
123+
local s
124+
if usecaching then
125+
local v0 = a*0x1000000 + b*0x10000 + c*0x100 + d
126+
s = cache[v0]
127+
if not s then
128+
local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
129+
s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
130+
cache[v0] = s
131+
end
132+
else
133+
local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40 + decoder[d]
134+
s = char( extract(v,16,8), extract(v,8,8), extract(v,0,8))
135+
end
136+
t[k] = s
137+
k = k + 1
138+
end
139+
if padding == 1 then
140+
local a, b, c = b64:byte( n-3, n-1 )
141+
local v = decoder[a]*0x40000 + decoder[b]*0x1000 + decoder[c]*0x40
142+
t[k] = char( extract(v,16,8), extract(v,8,8))
143+
elseif padding == 2 then
144+
local a, b = b64:byte( n-3, n-2 )
145+
local v = decoder[a]*0x40000 + decoder[b]*0x1000
146+
t[k] = char( extract(v,16,8))
147+
end
148+
return concat( t )
149+
end
150+
151+
return base64
152+
153+
--[[
154+
------------------------------------------------------------------------------
155+
This software is available under 2 licenses -- choose whichever you prefer.
156+
------------------------------------------------------------------------------
157+
ALTERNATIVE A - MIT License
158+
Copyright (c) 2018 Ilya Kolbin
159+
Permission is hereby granted, free of charge, to any person obtaining a copy of
160+
this software and associated documentation files (the "Software"), to deal in
161+
the Software without restriction, including without limitation the rights to
162+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
163+
of the Software, and to permit persons to whom the Software is furnished to do
164+
so, subject to the following conditions:
165+
The above copyright notice and this permission notice shall be included in all
166+
copies or substantial portions of the Software.
167+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
168+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
169+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
170+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
171+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
172+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
173+
SOFTWARE.
174+
------------------------------------------------------------------------------
175+
ALTERNATIVE B - Public Domain (www.unlicense.org)
176+
This is free and unencumbered software released into the public domain.
177+
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
178+
software, either in source code form or as a compiled binary, for any purpose,
179+
commercial or non-commercial, and by any means.
180+
In jurisdictions that recognize copyright laws, the author or authors of this
181+
software dedicate any and all copyright interest in the software to the public
182+
domain. We make this dedication for the benefit of the public at large and to
183+
the detriment of our heirs and successors. We intend this dedication to be an
184+
overt act of relinquishment in perpetuity of all present and future rights to
185+
this software under copyright law.
186+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
187+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
188+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
189+
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
190+
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
191+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
192+
------------------------------------------------------------------------------
193+
--]]

0 commit comments

Comments
 (0)