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
|
-- The guests' egress policy, for nginx (OpenResty), see default.nix.
--
-- Per VM: whose a guest is, egress_guests.lua says by its address (which
-- the bridge makes sure of, see default.nix), and which tap it's on,
-- ADDR/ADDRESS and ADDR/TAP, as long as they agree. VMS/TAP has
-- the name of the VM's list, RULES/USER/LIST its rules, one per line, both
-- read on every connection and request:
-- https://example.com example.com and its subdomains, passed
-- through without decrypting
-- https://example.com/foo/ only requests whose path starts with /foo/,
-- decrypted to check that
-- https://example.com/foo only /foo itself and paths below it (/foo/...;
-- not /foo-bar), with any query,
-- decrypted to check that
-- (tcp:// and udp:// rules are for nftables, see default.nix.)
-- A domain with any whole-domain rule is passed through, whatever path
-- rules it has. Everything else gets denied.
--
-- Upstream is always port 443 of the server name (SNI), as resolved by
-- the host, never the address the guest connected to.
local _M = {}
local RULES = os.getenv("RIG_EGRESS_RULES") -- RULES/USER/LIST
local VMS = os.getenv("RIG_EGRESS_VMS") -- VMS/TAP: LIST
local STATE = os.getenv("RIG_EGRESS_STATE") -- ca.key, ca.pem
local RUN = os.getenv("RIG_EGRESS_RUN") -- RUN/decrypt-TAP.sock: the http server
local ADDR = os.getenv("RIG_EGRESS_ADDR") -- ADDR/TAP: ADDRESS, ADDR/ADDRESS: TAP
local HOSTS = os.getenv("RIG_EGRESS_HOSTS") -- HOSTS/TAP: ADDRESS NAME, the tap's rules' names
-- { addresses = { [ADDRESS] = USER }, taps = { [TAP] = USER },
-- deny = { ADDRESS/PREFIXLEN, ... } }
local owners = require("egress_guests")
local by_tap = {}
for tap, user in pairs(owners.taps) do
by_tap[tap] = { tap = tap, user = user }
end
local function first_line(path)
local f = io.open(path)
local s = f and f:read("*l")
if f then
f:close()
end
return s
end
-- The guest at an address: { tap, user }, or nil.
local function guest_at(address)
local user = owners.addresses[address]
local tap = user and first_line(ADDR .. "/" .. address)
local guest = tap and by_tap[tap]
if guest and guest.user == user and first_line(ADDR .. "/" .. tap) == address then
return guest
end
end
local function valid_name(s)
return s ~= nil and s:match("^[a-z0-9-]+[a-z0-9.-]*$") ~= nil
and not s:find("%.%.") and s:sub(-1) ~= "."
end
-- The name of the guest's list, nil if none (or a bad one), and its
-- description for the log: USER TAP LIST.
local function list(guest)
local f = io.open(VMS .. "/" .. guest.tap)
local name = f and f:read(256)
if f then
f:close()
end
name = name and name:match("^([A-Za-z0-9_-]+)\n?$")
return name, guest.user .. " " .. guest.tap .. " " .. (name or "-")
end
local function rules(guest, name)
local domains, paths = {}, {}
local f = name and io.open(RULES .. "/" .. guest.user .. "/" .. name)
if not f then
return domains, paths
end
-- Only the first 64k, so a huge file can't slow down everyone's egress.
local text = f:read(65536) or ""
f:close()
for line in text:gmatch("[^\n]+") do
local domain, path = line:match("^%s*https://([^/%s]+)(/?%S*)%s*$")
if valid_name(domain) then
if path == "" then
domains[domain] = true
else
paths[domain] = paths[domain] or {}
table.insert(paths[domain], path)
end
end
end
return domains, paths
end
-- nil (deny), "pass", or the list of allowed path prefixes
local function policy(host, guest, name)
host = host and host:lower()
if not guest or not name or not valid_name(host) then
return nil
end
local domains, paths = rules(guest, name)
local prefixes = {}
local suffix = host
while suffix do
if domains[suffix] then
return "pass"
end
for _, p in ipairs(paths[suffix] or {}) do
table.insert(prefixes, p)
end
suffix = suffix:match("^[^.]*%.(.+)$")
end
if #prefixes > 0 then
return prefixes
end
end
-- Whether a (percent-decoded) path is allowed by the path rules: no "." or
-- ".." segments, and a rule's path itself or one below it, whole segments
-- only: /search/issues allows /search/issues and /search/issues/..., not
-- /search/issuesx; a rule ending in "/" allows what starts with it.
local function path_allowed(path, prefixes)
for segment in path:gmatch("[^/]+") do
if segment == "." or segment == ".." then
return false
end
end
for _, p in ipairs(prefixes) do
if path:sub(1, #p) == p and
(#path == #p or p:sub(-1) == "/" or path:sub(#p + 1, #p + 1) == "/") then
return true
end
end
return false
end
-- stream, preread: pass through, decrypt, or close
function _M.preread()
local sni = ngx.var.ssl_preread_server_name
local guest = guest_at(ngx.var.remote_addr)
local name, who
if guest then
name, who = list(guest)
end
local p = policy(sni, guest, name)
who = who or "- - -"
if p == "pass" then
ngx.var.egress_upstream = sni:lower() .. ":443"
ngx.var.egress_log = "ALLOW " .. who .. " https://" .. sni:lower()
elseif p then
ngx.var.egress_upstream = "unix:" .. RUN .. "/decrypt-" .. guest.tap .. ".sock"
else
ngx.var.egress_log = "DENY " .. who .. " " .. (sni ~= "" and "https://" .. sni or "-")
return ngx.exit(403)
end
end
-- http, ssl_certificate: a certificate for the server name, from our CA
local ca_cert, ca_key, leaf_key, leaf_key_der
local certs = {} -- server name -> parsed certificate chain
local function read(path)
local f = assert(io.open(path))
local s = f:read("*a")
f:close()
return s
end
local function make_cert(name)
local x509 = require("resty.openssl.x509")
local pkey = require("resty.openssl.pkey")
local bn = require("resty.openssl.bn")
local x509_name = require("resty.openssl.x509.name")
local altname = require("resty.openssl.x509.altname")
local extension = require("resty.openssl.x509.extension")
if not ca_cert then
ca_cert = assert(x509.new(read(STATE .. "/ca.pem")))
ca_key = assert(pkey.new(read(STATE .. "/ca.key")))
leaf_key = assert(pkey.new({ type = "EC", curve = "prime256v1" }))
leaf_key_der = assert(leaf_key:tostring("private", "DER"))
end
local serial = require("resty.string").to_hex(require("resty.random").bytes(16))
local now = ngx.time()
local cert = x509.new()
assert(cert:set_version(3))
assert(cert:set_serial_number(assert(bn.new(serial, 16))))
assert(cert:set_not_before(now - 3600))
assert(cert:set_not_after(now + 30 * 86400))
assert(cert:set_subject_name(assert(x509_name.new():add("CN", name))))
assert(cert:set_issuer_name(ca_cert:get_subject_name()))
assert(cert:set_pubkey(leaf_key))
assert(cert:set_subject_alt_name(assert(altname.new():add("DNS", name))))
assert(cert:set_basic_constraints({ CA = false }))
assert(cert:add_extension(assert(extension.new("extendedKeyUsage", "serverAuth"))))
assert(cert:sign(ca_key))
return assert(require("ngx.ssl").parse_pem_cert(cert:to_PEM()))
end
-- Whose the connection is isn't known here; but only connections that
-- some VM's path rules allow get here (see preread), and each request
-- gets checked in access.
function _M.certificate()
local ssl = require("ngx.ssl")
local name = ssl.server_name()
if not valid_name(name and name:lower()) then
return ngx.exit(ngx.ERROR)
end
name = name:lower()
local chain = certs[name]
if not chain then
chain = make_cert(name)
certs[name] = chain
end
assert(ssl.clear_certs())
assert(ssl.set_cert(chain))
assert(ssl.set_der_priv_key(leaf_key_der))
end
-- http, access: check host and path of decrypted requests
function _M.access()
local guest = by_tap[(ngx.var.server_addr or ""):match("decrypt%-(.+)%.sock$")]
local name, who
if guest then
name, who = list(guest)
end
ngx.var.egress_guest = who or "- - -"
local sni = (ngx.var.ssl_server_name or ""):lower()
local host = (ngx.var.host or ""):lower()
local path = ngx.unescape_uri((ngx.var.request_uri or ""):match("^[^?]*"))
local p = policy(sni, guest, name)
local ok = type(p) == "table" and host == sni and path:sub(1, 1) == "/" and
path_allowed(path, p)
ngx.var.egress_verdict = ok and "ALLOW" or "DENY"
if not ok then
return ngx.exit(403)
end
end
-- For the guests' checks: addresses, as numbers (IPv4) or eight 16-bit
-- groups (IPv6), and whether an address is in a prefix.
local bit = require("bit")
local function v4(s)
local a, b, c, d = (s or ""):match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
if not a then
return nil
end
local n = 0
for _, x in ipairs({ a, b, c, d }) do
x = tonumber(x)
if x > 255 then
return nil
end
n = n * 256 + x
end
return n
end
local function v6(s)
s = s or ""
if not s:match("^[%x:]+$") or s:find(":::") then
return nil
end
local head, tail = s:match("^(.-)::(.*)$")
local function groups(t)
local g = {}
for x in t:gmatch("[^:]+") do
if #x > 4 then
return nil
end
table.insert(g, tonumber(x, 16))
end
return g
end
local g
if head then
local h, t = groups(head), groups(tail)
if not h or not t or #h + #t > 7 then
return nil
end
g = h
for _ = 1, 8 - #h - #t do
table.insert(g, 0)
end
for _, x in ipairs(t) do
table.insert(g, x)
end
else
g = groups(s)
if not g or #g ~= 8 then
return nil
end
end
return g
end
-- { family = 4, n = NUMBER } or { family = 6, g = GROUPS }, or nil
local function address(s)
local n = v4(s)
if n then
return { family = 4, n = n }
end
local g = v6(s)
if g then
return { family = 6, g = g }
end
end
-- Whether address a is in ADDRESS[/PREFIXLEN].
local function within(a, prefix)
local p, len = prefix:match("^(.-)/(%d+)$")
p = address(p or prefix)
if not p or p.family ~= a.family then
return false
end
len = tonumber(len) or (a.family == 4 and 32 or 128)
if a.family == 4 then
if len > 32 then
return false
end
if len == 0 then
return true
end
local mask = bit.lshift(-1, 32 - len)
return bit.band(bit.tobit(a.n), mask) == bit.band(bit.tobit(p.n), mask)
end
if len > 128 then
return false
end
for i = 1, 8 do
local bits = math.min(math.max(len - (i - 1) * 16, 0), 16)
if bits == 0 then
break
end
local mask = bit.band(bit.lshift(0xffff, 16 - bits), 0xffff)
if bit.band(a.g[i], mask) ~= bit.band(p.g[i], mask) then
return false
end
end
return true
end
-- The guest's tcp:// and udp:// rules: { proto, host, from, to }, host an
-- ADDRESS[/PREFIXLEN] or a name, as rig-firewall takes them.
local function port_rules(guest, name)
local list = {}
local f = name and io.open(RULES .. "/" .. guest.user .. "/" .. name)
if not f then
return list
end
local text = f:read(65536) or ""
f:close()
for line in text:gmatch("[^\n]+") do
local proto, host, from, to = line:match("^%s*(%a+)://(.+):(%d+)%-?(%d*)%s*$")
if proto == "tcp" or proto == "udp" then
host = host:match("^%[(.+)%]$") or host
table.insert(list, { proto = proto, host = host:lower(),
from = tonumber(from), to = tonumber(to) or tonumber(from) })
end
end
return list
end
-- What the tap's guest gets for names in rules (rig-firewall's hosts
-- file for the tap): { [NAME] = { ADDRESS, ... } }; any other name, the
-- guest gets 172.16.0.1.
local function hosts(guest)
local map = {}
local f = io.open(HOSTS .. "/" .. guest.tap)
if not f then
return map
end
for line in (f:read(65536) or ""):gmatch("[^\n]+") do
local a, n = line:match("^(%S+)%s+(%S+)")
if a then
n = n:lower()
map[n] = map[n] or {}
table.insert(map[n], a)
end
end
f:close()
return map
end
-- Whether the guest can connect to tcp:// or udp://HOST:PORT, as the
-- firewall decides: an address that a rule allows (by address or prefix,
-- or by name, as resolved for the tap), but not in denyDestinations, and
-- not tcp port 443, which goes to the proxy (IPv4) or nowhere (IPv6).
local function port_ok(guest, name, proto, host, port)
if proto == "tcp" and port == 443 then
return false
end
local resolved = hosts(guest)
local candidates
if address(host) then
candidates = { host }
else
candidates = resolved[host:lower()] or {}
end
local list = port_rules(guest, name)
for _, c in ipairs(candidates) do
local a = address(c)
local denied = not a
for _, d in ipairs(owners.deny) do
if a and within(a, d) then
denied = true
end
end
if not denied then
for _, r in ipairs(list) do
if r.proto == proto and port >= r.from and port <= r.to then
if address(r.host:match("^[^/]+")) then
if within(a, r.host) then
return true
end
else
for _, ra in ipairs(resolved[r.host] or {}) do
local b = address(ra)
if b and b.family == a.family and within(a, ra) then
return true
end
end
end
end
end
end
end
return false
end
-- Whether the guest's egress allows a URI: https://HOST[:443][/PATH]
-- (with path rules, the path matters), or tcp:// and udp://HOST:PORT.
local function allowed(guest, name, uri)
local scheme, rest = uri:match("^(%a+)://(.*)$")
scheme = scheme and scheme:lower()
if scheme == "https" then
local authority, path = rest:match("^([^/?#]*)([^?#]*)")
local host, port = authority:match("^(.-):(%d+)$")
host = host or authority
if port and port ~= "443" then
return false
end
local p = policy(host, guest, name)
if p == "pass" then
return true
end
if type(p) ~= "table" then
return false
end
return path_allowed(ngx.unescape_uri(path ~= "" and path or "/"), p)
elseif scheme == "tcp" or scheme == "udp" then
local host, port = rest:match("^(.+):(%d+)$")
if not host then
return false
end
host = host:match("^%[(.+)%]$") or host
return port_ok(guest, name, scheme, host, tonumber(port))
end
return false
end
-- http, content: the guest's checks, one URI per line, one true or false
-- per line back, in the same order.
local MAX_CHECKS = 100
function _M.check()
local guest = guest_at(ngx.var.remote_addr)
local name = guest and list(guest)
ngx.req.read_body()
local body = ngx.req.get_body_data() or ""
-- The body's last newline ends the last URI, it doesn't start another.
body = body:gsub("\r?\n$", "")
local lines = {}
if body ~= "" then
for line in (body .. "\n"):gmatch("([^\n]*)\n") do
table.insert(lines, (line:gsub("\r$", ""):match("^%s*(.-)%s*$")))
end
end
if #lines > MAX_CHECKS then
ngx.status = 413
ngx.say("at most " .. MAX_CHECKS .. " URIs")
return ngx.exit(413)
end
local out = {}
for _, line in ipairs(lines) do
table.insert(out, (guest and name and allowed(guest, name, line)) and "true" or "false")
end
ngx.header.content_type = "text/plain"
ngx.print(table.concat(out, "\n") .. (#out > 0 and "\n" or ""))
end
return _M
|