HAProxy как приватный шлюз к S3 VK Cloud: конфигурация, Lua, тесты, документация
- haproxy.cfg: терминация TLS (самоподписанный сертификат, wildcard), подмена Host/SNI, переписывание Location/Server и тел ответов (s3_rewrite.lua) - s3_resign.lua: проверка подписи SigV4 клиента и повторная подпись под реальный Host - s3gw-snat.nft: SNAT клиентской подсети (nftables) для прямого доступа - tests: автотесты Lua (SHA-256/HMAC/SigV4), сборщик метрик и расчёт сводок нагрузочных тестов - docs: планы и итоги всех итераций, отчёт о пути пакета, сравнительные тесты CPU/RAM (512 МБ, 2 ГБ multipart 5/20/40 потоков, 1 и 4 vCPU), Mermaid-диаграммы, сырые данные замеров - Секреты (hostinfo.txt, hostkey.key, s3_creds.lua) исключены через .gitignore Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
ea1592800a
169 files changed
+5848
No files matched your search
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# Самоподписанный сертификат для client-facing стороны (формат PEM для HAProxy: cert + key).
|
||||
set -euo pipefail
|
||||
OUT=${1:-/etc/haproxy/certs}
|
||||
GW_IP=${GW_IP:-10.140.0.13} # адрес шлюза для SAN (стенд: 172.28.104.1)
|
||||
mkdir -p "$OUT"
|
||||
openssl req -x509 -newkey rsa:3072 -nodes -days 825 \
|
||||
-keyout "$OUT/s3-v.key" -out "$OUT/s3-v.crt" \
|
||||
-subj "/CN=s3-v.myhost.local" \
|
||||
-addext "subjectAltName=DNS:s3-v.myhost.local,DNS:*.s3-v.myhost.local,IP:$GW_IP"
|
||||
cat "$OUT/s3-v.crt" "$OUT/s3-v.key" > "$OUT/s3-v.myhost.local.pem"
|
||||
chmod 600 "$OUT"/s3-v.key "$OUT/s3-v.myhost.local.pem"
|
||||
echo "Передайте $OUT/s3-v.crt клиенту как доверенный сертификат."
|
||||
@@ -0,0 +1,70 @@
|
||||
global
|
||||
log /dev/log local0
|
||||
maxconn 4096
|
||||
lua-prepend-path /etc/haproxy/?.lua
|
||||
lua-load /etc/haproxy/s3_rewrite.lua
|
||||
lua-load /etc/haproxy/s3_resign.lua
|
||||
user haproxy
|
||||
group haproxy
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-bind-ciphersuites TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
# лог: клиент -> шлюз, SNI/Host до и после переписывания, соединение шлюз -> S3, результат проверки подписи
|
||||
log-format "%ci:%cp -> %fi:%fp %ft sni=%[ssl_fc_sni] host_in=%[capture.req.hdr(0)] | %b/%s via %bi:%bp -> %si:%sp host_out=%[var(txn.fwd_host)] auth=%[var(txn.s3_auth)] | %ST %B bytes %Tt ms | %{+Q}r"
|
||||
option dontlognull
|
||||
timeout connect 5s
|
||||
timeout client 300s # большие загрузки/multipart
|
||||
timeout server 300s
|
||||
timeout http-request 30s
|
||||
|
||||
resolvers sys
|
||||
parse-resolv-conf
|
||||
hold valid 30s
|
||||
|
||||
#---------------------------------------------------------------
|
||||
# client-facing: приватный адрес, самоподписанный сертификат
|
||||
#---------------------------------------------------------------
|
||||
frontend fe_s3_client
|
||||
bind 10.140.0.13:443 ssl crt /etc/haproxy/certs/s3-v.myhost.local.pem alpn http/1.1
|
||||
|
||||
# допускаем только клиента из диаграммы
|
||||
tcp-request connection reject if !{ src 10.140.0.1 }
|
||||
|
||||
# принимаем только приватное имя: path-style (s3-v.myhost.local)
|
||||
# и virtual-hosted (<bucket>.s3-v.myhost.local, одна метка = wildcard-сертификат)
|
||||
acl host_priv hdr(host) -i -m reg ^([a-z0-9-]+\.)?s3-v\.myhost\.local(:[0-9]+)?$
|
||||
http-request deny deny_status 421 if !host_priv
|
||||
|
||||
capture request header Host len 64
|
||||
|
||||
default_backend be_s3_public
|
||||
|
||||
#---------------------------------------------------------------
|
||||
# public-facing: новая TLS-сессия к реальному S3
|
||||
#---------------------------------------------------------------
|
||||
backend be_s3_public
|
||||
# просим S3 не сжимать ответ, иначе тело нельзя переписать
|
||||
http-request del-header Accept-Encoding
|
||||
|
||||
# SigV4: проверка подписи клиента под приватный Host и повторная подпись под реальный
|
||||
# (Host входит в подпись, без этого S3 отвечает SignatureDoesNotMatch)
|
||||
http-request lua.s3_resign
|
||||
http-request deny deny_status 403 if { var(txn.s3_auth) -m str fail }
|
||||
|
||||
# подмена FQDN (и bucket-префикса), остальные заголовки сохраняются
|
||||
http-request set-header Host %[req.hdr(host),field(1,:),regsub(s3-v\.myhost\.local$,hb.ru-msk.vkcloud-storage.ru)]
|
||||
http-request set-var(txn.fwd_host) req.hdr(host)
|
||||
|
||||
# обратный трафик: прячем реальное имя в редиректах и служебных заголовках
|
||||
http-response replace-header Location (https?://)([^/]*\.)?hb\.ru-msk\.vkcloud-storage\.ru(.*) \1\2s3-v.myhost.local\3
|
||||
http-response del-header Server
|
||||
|
||||
# тела ответов (XML/JSON/HTML) и presigned-ссылки в них: реальное имя -> приватное
|
||||
filter lua.s3rewrite
|
||||
|
||||
# проверка сертификата VK Cloud обязательна; SNI = реальное имя (с учётом bucket.)
|
||||
server vk hb.ru-msk.vkcloud-storage.ru:443 ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt sni req.hdr(host) resolvers sys resolve-prefer ipv4 check check-ssl check-sni hb.ru-msk.vkcloud-storage.ru inter 10s
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Секреты для повторной подписи SigV4. Файл: /etc/haproxy/s3_creds.lua, права 640 root:haproxy, в репозиторий не коммитить.
|
||||
return {
|
||||
["<AccessKeyId>"] = "<SecretAccessKey>",
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
-- Повторная подпись AWS SigV4 на шлюзе.
|
||||
-- Клиент подписывает запрос под приватный Host (s3-v.myhost.local), а реальный S3
|
||||
-- принимает только свой Host. Действие http-request lua.s3_resign:
|
||||
-- 1) проверяет подпись клиента под приватный Host (секрет по Access Key ID из CREDS);
|
||||
-- 2) подставляет реальный Host и подписывает запрос заново (Authorization или X-Amz-Signature).
|
||||
-- Тело не затрагивается: по TLS клиент использует UNSIGNED-PAYLOAD / unsigned trailer.
|
||||
|
||||
local REAL = "hb.ru-msk.vkcloud-storage.ru"
|
||||
local PRIVATE = "s3-v.myhost.local"
|
||||
local CREDS = "/etc/haproxy/s3_creds.lua" -- return { ["<AccessKeyId>"] = "<Secret>" }, вне репозитория
|
||||
|
||||
---------------------------------------------------------------- SHA-256 / HMAC
|
||||
local M32 = 0xffffffff
|
||||
local K = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
}
|
||||
|
||||
local function rr(x, n) return ((x >> n) | (x << (32 - n))) & M32 end
|
||||
|
||||
local function sha256(msg)
|
||||
local h0, h1, h2, h3 = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a
|
||||
local h4, h5, h6, h7 = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
|
||||
local len = #msg
|
||||
msg = msg .. "\128" .. string.rep("\0", (55 - len) % 64) .. string.pack(">I8", len * 8)
|
||||
for pos = 1, #msg, 64 do
|
||||
local w = { string.unpack(">I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4I4", msg, pos) }
|
||||
for i = 17, 64 do
|
||||
local a, b = w[i - 15], w[i - 2]
|
||||
local s0 = rr(a, 7) ~ rr(a, 18) ~ (a >> 3)
|
||||
local s1 = rr(b, 17) ~ rr(b, 19) ~ (b >> 10)
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & M32
|
||||
end
|
||||
local a, b, c, d, e, f, g, h = h0, h1, h2, h3, h4, h5, h6, h7
|
||||
for i = 1, 64 do
|
||||
local S1 = rr(e, 6) ~ rr(e, 11) ~ rr(e, 25)
|
||||
local ch = (e & f) ~ (~e & g)
|
||||
local t1 = (h + S1 + ch + K[i] + w[i]) & M32
|
||||
local S0 = rr(a, 2) ~ rr(a, 13) ~ rr(a, 22)
|
||||
local maj = (a & b) ~ (a & c) ~ (b & c)
|
||||
local t2 = (S0 + maj) & M32
|
||||
h, g, f, e, d, c, b, a = g, f, e, (d + t1) & M32, c, b, a, (t1 + t2) & M32
|
||||
end
|
||||
h0, h1, h2, h3 = (h0 + a) & M32, (h1 + b) & M32, (h2 + c) & M32, (h3 + d) & M32
|
||||
h4, h5, h6, h7 = (h4 + e) & M32, (h5 + f) & M32, (h6 + g) & M32, (h7 + h) & M32
|
||||
end
|
||||
return string.pack(">I4I4I4I4I4I4I4I4", h0, h1, h2, h3, h4, h5, h6, h7)
|
||||
end
|
||||
|
||||
local function hex(s) return (s:gsub(".", function(c) return string.format("%02x", c:byte()) end)) end
|
||||
|
||||
local function hmac(key, msg)
|
||||
if #key > 64 then key = sha256(key) end
|
||||
key = key .. string.rep("\0", 64 - #key)
|
||||
local ipad = key:gsub(".", function(c) return string.char(c:byte() ~ 0x36) end)
|
||||
local opad = key:gsub(".", function(c) return string.char(c:byte() ~ 0x5c) end)
|
||||
return sha256(opad .. sha256(ipad .. msg))
|
||||
end
|
||||
|
||||
---------------------------------------------------------------- SigV4
|
||||
local function uri_decode(s)
|
||||
return (s:gsub("%%(%x%x)", function(x) return string.char(tonumber(x, 16)) end))
|
||||
end
|
||||
|
||||
local function uri_encode(s)
|
||||
return (s:gsub("[^A-Za-z0-9%-%._~]", function(c) return string.format("%%%02X", c:byte()) end))
|
||||
end
|
||||
|
||||
-- канонический query: пары перекодируются, сортируются; X-Amz-Signature исключается
|
||||
local function canon_query(raw)
|
||||
local items = {}
|
||||
for pair in raw:gmatch("[^&]+") do
|
||||
local k, v = pair:match("^([^=]*)=?(.*)$")
|
||||
k, v = uri_encode(uri_decode(k)), uri_encode(uri_decode(v))
|
||||
if k ~= "X-Amz-Signature" then items[#items + 1] = { k, v } end
|
||||
end
|
||||
table.sort(items, function(a, b)
|
||||
if a[1] ~= b[1] then return a[1] < b[1] end
|
||||
return a[2] < b[2]
|
||||
end)
|
||||
for i, kv in ipairs(items) do items[i] = kv[1] .. "=" .. kv[2] end
|
||||
return table.concat(items, "&")
|
||||
end
|
||||
|
||||
-- p: secret, method, path, query, headers{имя(lower)=значение}, signed("a;b"), payload,
|
||||
-- amzdate, region, service, host (значение заголовка host для подписи)
|
||||
local function signature(p)
|
||||
local lines = {}
|
||||
for name in p.signed:gmatch("[^;]+") do
|
||||
local v = name == "host" and p.host or (p.headers[name] or "")
|
||||
lines[#lines + 1] = name .. ":" .. v:gsub("%s+", " "):match("^%s*(.-)%s*$") .. "\n"
|
||||
end
|
||||
local creq = table.concat({
|
||||
p.method, p.path ~= "" and p.path or "/", canon_query(p.query),
|
||||
table.concat(lines), p.signed, p.payload,
|
||||
}, "\n")
|
||||
local day = p.amzdate:sub(1, 8)
|
||||
local scope = day .. "/" .. p.region .. "/" .. p.service .. "/aws4_request"
|
||||
local sts = "AWS4-HMAC-SHA256\n" .. p.amzdate .. "\n" .. scope .. "\n" .. hex(sha256(creq))
|
||||
local k = hmac("AWS4" .. p.secret, day)
|
||||
k = hmac(k, p.region)
|
||||
k = hmac(k, p.service)
|
||||
k = hmac(k, "aws4_request")
|
||||
return hex(hmac(k, sts))
|
||||
end
|
||||
|
||||
local function equal(a, b)
|
||||
if #a ~= #b then return false end
|
||||
local diff = 0
|
||||
for i = 1, #a do diff = diff | (a:byte(i) ~ b:byte(i)) end
|
||||
return diff == 0
|
||||
end
|
||||
|
||||
---------------------------------------------------------------- действие HAProxy
|
||||
local creds = {}
|
||||
do
|
||||
local ok, t = pcall(dofile, CREDS)
|
||||
if ok and type(t) == "table" then creds = t end
|
||||
end
|
||||
|
||||
local function header(h, name)
|
||||
local t = h[name]
|
||||
if not t then return nil end
|
||||
local out = {}
|
||||
for i = 0, #t do out[#out + 1] = t[i] end
|
||||
return table.concat(out, ",")
|
||||
end
|
||||
|
||||
local function resign(txn)
|
||||
local h = txn.http:req_get_headers()
|
||||
local auth = header(h, "authorization")
|
||||
local query = txn.sf:query() or ""
|
||||
local presigned = query:find("X-Amz-Signature=", 1, true) ~= nil
|
||||
if not auth and not presigned then return end -- анонимный запрос
|
||||
|
||||
local function fail(why)
|
||||
txn:Warning("s3_resign: " .. why)
|
||||
txn:set_var("txn.s3_auth", "fail")
|
||||
end
|
||||
|
||||
local host = header(h, "host")
|
||||
if not host then return fail("no Host header") end
|
||||
|
||||
-- разбор параметров подписи (заголовок или presigned query)
|
||||
local cred, signed, given, amzdate, payload
|
||||
if presigned then
|
||||
local q = {}
|
||||
for pair in query:gmatch("[^&]+") do
|
||||
local k, v = pair:match("^([^=]*)=?(.*)$")
|
||||
q[uri_decode(k)] = uri_decode(v)
|
||||
end
|
||||
cred, signed, given = q["X-Amz-Credential"], q["X-Amz-SignedHeaders"], q["X-Amz-Signature"]
|
||||
amzdate, payload = q["X-Amz-Date"], "UNSIGNED-PAYLOAD"
|
||||
else
|
||||
cred, signed, given = auth:match(
|
||||
"^AWS4%-HMAC%-SHA256%s+Credential=([^,%s]+),%s*SignedHeaders=([^,%s]+),%s*Signature=(%x+)$")
|
||||
amzdate, payload = header(h, "x-amz-date"), header(h, "x-amz-content-sha256")
|
||||
end
|
||||
if not (cred and signed and given and amzdate and payload) then return fail("incomplete signature") end
|
||||
|
||||
local akid, day, region, service = cred:match("^([^/]+)/(%d+)/([^/]+)/([^/]+)/aws4_request$")
|
||||
if not akid then return fail("bad Credential") end
|
||||
local secret = creds[akid]
|
||||
if not secret then return fail("unknown Access Key " .. akid) end
|
||||
|
||||
local hdrs = {}
|
||||
for name in signed:gmatch("[^;]+") do hdrs[name] = header(h, name) end
|
||||
local p = {
|
||||
secret = secret, method = txn.sf:method(), path = txn.sf:path(), query = query,
|
||||
headers = hdrs, signed = signed, payload = payload, amzdate = amzdate,
|
||||
region = region, service = service, host = host,
|
||||
}
|
||||
|
||||
-- 1) подпись клиента под приватный Host
|
||||
if not equal(signature(p), given:lower()) then return fail("client signature mismatch") end
|
||||
|
||||
-- 2) подпись под реальный Host
|
||||
p.host = (host:match("^[^:]+"):gsub(PRIVATE:gsub("%p", "%%%0") .. "$", REAL))
|
||||
local new = signature(p)
|
||||
txn.http:req_set_header("host", p.host)
|
||||
if presigned then
|
||||
txn.http:req_set_query((query:gsub("X%-Amz%-Signature=%x+", "X-Amz-Signature=" .. new)))
|
||||
else
|
||||
txn.http:req_set_header("authorization", string.format(
|
||||
"AWS4-HMAC-SHA256 Credential=%s, SignedHeaders=%s, Signature=%s", cred, signed, new))
|
||||
end
|
||||
txn:set_var("txn.s3_auth", "ok")
|
||||
end
|
||||
|
||||
if core then core.register_action("s3_resign", { "http-req" }, resign) end
|
||||
|
||||
-- для автономных тестов (вне HAProxy)
|
||||
return { sha256 = sha256, hmac = hmac, hex = hex, signature = signature, canon_query = canon_query }
|
||||
@@ -0,0 +1,92 @@
|
||||
-- Переписывание реального FQDN S3 на приватный в текстовых телах ответов
|
||||
-- (XML, JSON, HTML, text), в том числе внутри presigned-ссылок.
|
||||
-- Бинарные объекты не затрагиваются: фильтр включается только по Content-Type.
|
||||
|
||||
local REAL = "hb.ru-msk.vkcloud-storage.ru"
|
||||
local PRIVATE = "s3-v.myhost.local"
|
||||
local TYPES = { "xml", "json", "html", "text/" }
|
||||
|
||||
-- plain-замена без regexp: имя содержит спецсимволы Lua-паттернов
|
||||
local function replace_all(s, from, to)
|
||||
local out, pos = {}, 1
|
||||
while true do
|
||||
local a, b = s:find(from, pos, true)
|
||||
if not a then break end
|
||||
out[#out + 1] = s:sub(pos, a - 1)
|
||||
out[#out + 1] = to
|
||||
pos = b + 1
|
||||
end
|
||||
out[#out + 1] = s:sub(pos)
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
-- Потоковая обработка. Имя может быть разрезано границей порций, поэтому
|
||||
-- последние (#REAL - 1) байт удерживаются до следующей порции или конца тела.
|
||||
local Stream = {}
|
||||
Stream.__index = Stream
|
||||
|
||||
function Stream.new()
|
||||
return setmetatable({ carry = "" }, Stream)
|
||||
end
|
||||
|
||||
function Stream:process(data, eom)
|
||||
local s = replace_all(self.carry .. data, REAL, PRIVATE)
|
||||
if eom then
|
||||
self.carry = ""
|
||||
return s
|
||||
end
|
||||
local keep = math.min(#REAL - 1, #s)
|
||||
self.carry = s:sub(#s - keep + 1)
|
||||
return s:sub(1, #s - keep)
|
||||
end
|
||||
|
||||
-- Подключение к HAProxy (filter lua.s3rewrite)
|
||||
local Filter = {}
|
||||
Filter.id = "s3rewrite"
|
||||
Filter.flags = filter.FLT_CFG_FL_HTX
|
||||
Filter.__index = Filter
|
||||
|
||||
function Filter:new()
|
||||
return setmetatable({ active = false, stream = Stream.new() }, Filter)
|
||||
end
|
||||
|
||||
local function is_text(ctype)
|
||||
ctype = (ctype or ""):lower()
|
||||
for _, t in ipairs(TYPES) do
|
||||
if ctype:find(t, 1, true) then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function Filter:http_headers(txn, http_msg)
|
||||
if not http_msg:is_resp() then return filter.CONTINUE end
|
||||
|
||||
local code = tonumber(http_msg:get_stline().code)
|
||||
local headers = http_msg:get_headers()
|
||||
local ctype = headers["content-type"] and headers["content-type"][0]
|
||||
local enc = headers["content-encoding"] and headers["content-encoding"][0]
|
||||
local no_body = code < 200 or code == 204 or code == 304 or txn.sf:method() == "HEAD"
|
||||
|
||||
if no_body or not is_text(ctype) or (enc and enc ~= "identity") then
|
||||
return filter.CONTINUE
|
||||
end
|
||||
|
||||
self.active = true
|
||||
-- длина тела меняется: Content-Length заменяем на chunked
|
||||
http_msg:set_body_len("chunked")
|
||||
filter.register_data_filter(self, http_msg.channel)
|
||||
return filter.CONTINUE
|
||||
end
|
||||
|
||||
function Filter:http_payload(txn, http_msg)
|
||||
if not self.active then return end
|
||||
local data = http_msg:body(0, -1) or ""
|
||||
http_msg:remove(0, #data)
|
||||
local out = self.stream:process(data, http_msg:eom())
|
||||
if #out > 0 then http_msg:send(out) end
|
||||
end
|
||||
|
||||
core.register_filter("s3rewrite", Filter, function(flt) return flt end)
|
||||
|
||||
-- для автономных тестов (вне HAProxy)
|
||||
return { Stream = Stream, replace_all = replace_all }
|
||||
@@ -0,0 +1,9 @@
|
||||
# SNAT клиентской подсети в сторону S3 (Egress Node). Отдельная таблица: чужие правила не затрагиваются.
|
||||
add table ip s3gw_nat
|
||||
flush table ip s3gw_nat
|
||||
table ip s3gw_nat {
|
||||
chain postrouting {
|
||||
type nat hook postrouting priority srcnat; policy accept;
|
||||
ip saddr 172.28.104.0/24 oifname "eth0" counter snat to 138.16.200.95
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user