aboutsummaryrefslogtreecommitdiffstats
path: root/modules/host/egress.lua
blob: d276e05bc7246fbff0ec400a65641ab4213c6325 (plain)
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
-- 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
-- (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("FC_EGRESS_RULES")  -- RULES/USER/LIST
local VMS = os.getenv("FC_EGRESS_VMS")  -- VMS/TAP: LIST
local STATE = os.getenv("FC_EGRESS_STATE")  -- ca.key, ca.pem
local RUN = os.getenv("FC_EGRESS_RUN")  -- RUN/decrypt-TAP.sock: the http server
local ADDR = os.getenv("FC_EGRESS_ADDR")  -- ADDR/TAP: ADDRESS, ADDR/ADDRESS: TAP
-- { addresses = { [ADDRESS] = USER }, taps = { [TAP] = USER } }
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

-- 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) == "/"
  if ok then
    for segment in path:gmatch("[^/]+") do
      if segment == "." or segment == ".." then
        ok = false
      end
    end
  end
  if ok then
    ok = false
    for _, prefix in ipairs(p) do
      if path:sub(1, #prefix) == prefix then
        ok = true
      end
    end
  end
  ngx.var.egress_verdict = ok and "ALLOW" or "DENY"
  if not ok then
    return ngx.exit(403)
  end
end

return _M