aboutsummaryrefslogtreecommitdiffstats
path: root/egress.lua
blob: a019d7ac1294ce749dec28a03c233e80712a5d7f (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
-- The guests' egress policy, for nginx (OpenResty), see host.nix.
--
-- The rules (one per line, read on every connection and request):
--   example.com           example.com and its subdomains, passed through
--                         without decrypting
--   example.com/foo/      only requests whose path starts with /foo/,
--                         decrypted to check that
-- 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")
local STATE = os.getenv("FC_EGRESS_STATE")  -- ca.key, ca.pem
local DECRYPT = os.getenv("FC_EGRESS_DECRYPT")  -- the http server's socket

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

local function rules()
  local domains, paths = {}, {}
  local f = io.open(RULES)
  if not f then
    return domains, paths
  end
  for line in f:lines() do
    local domain, path = line:match("^%s*([^/%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
  f:close()
  return domains, paths
end

-- nil (deny), "pass", or the list of allowed path prefixes
local function policy(host)
  host = host and host:lower()
  if not valid_name(host) then
    return nil
  end
  local domains, paths = rules()
  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 p = policy(sni)
  if p == "pass" then
    ngx.var.egress_upstream = sni:lower() .. ":443"
    ngx.var.egress_log = "ALLOW " .. sni:lower()
  elseif p then
    ngx.var.egress_upstream = "unix:" .. DECRYPT
  else
    ngx.var.egress_log = "DENY " .. (sni ~= "" and 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

function _M.certificate()
  local ssl = require("ngx.ssl")
  local name = ssl.server_name()
  if type(policy(name)) ~= "table" 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 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)
  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