-- Повторная подпись 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 { [""] = "" }, вне репозитория ---------------------------------------------------------------- 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 }