#include "SecurityExtra.hpp" #include #include #include #include namespace molo::example::fw { namespace { const char* kHex = "0123456789abcdef"; inline std::uint32_t rotr(std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } const std::uint32_t kK[64] = { 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}; } // namespace std::string to_hex(const std::string& raw) { std::string out; out.reserve(raw.size() * 2); for (unsigned char c : raw) { out += kHex[c >> 4]; out += kHex[c & 15]; } return out; } bool from_hex(const std::string& hex, std::string& raw) { raw.clear(); if (hex.size() % 2 != 0) return false; auto val = [](char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; }; for (std::size_t i = 0; i < hex.size(); i += 2) { int a = val(hex[i]), b = val(hex[i + 1]); if (a < 0 || b < 0) return false; raw += static_cast(a * 16 + b); } return true; } bool constant_time_equal(const std::string& a, const std::string& b) { unsigned char diff = a.size() == b.size() ? 0 : 1; std::size_t n = std::min(a.size(), b.size()); for (std::size_t i = 0; i < n; ++i) diff |= static_cast(a[i] ^ b[i]); return diff == 0; } std::string Sha256::digest(const std::string& data) { std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; std::string msg = data; std::uint64_t bits = static_cast(data.size()) * 8; msg += static_cast(0x80); while (msg.size() % 64 != 56) msg += '\0'; for (int i = 7; i >= 0; --i) msg += static_cast((bits >> (i * 8)) & 0xff); for (std::size_t off = 0; off < msg.size(); off += 64) { std::uint32_t w[64]; for (int i = 0; i < 16; ++i) { const unsigned char* p = reinterpret_cast(msg.data()) + off + i * 4; w[i] = (std::uint32_t(p[0]) << 24) | (std::uint32_t(p[1]) << 16) | (std::uint32_t(p[2]) << 8) | p[3]; } for (int i = 16; i < 64; ++i) { std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; for (int i = 0; i < 64; ++i) { std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); std::uint32_t ch = (e & f) ^ (~e & g); std::uint32_t t1 = hh + S1 + ch + kK[i] + w[i]; std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); std::uint32_t mj = (a & b) ^ (a & c) ^ (b & c); std::uint32_t t2 = S0 + mj; hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; } std::string out; for (int i = 0; i < 8; ++i) for (int s = 24; s >= 0; s -= 8) out += static_cast((h[i] >> s) & 0xff); return out; } std::string Sha256::hex(const std::string& data) { return to_hex(digest(data)); } std::string Hmac::sha256(const std::string& key, const std::string& data) { std::string k = key.size() > 64 ? Sha256::digest(key) : key; k.resize(64, '\0'); std::string ipad(64, '\0'), opad(64, '\0'); for (int i = 0; i < 64; ++i) { ipad[i] = static_cast(k[i] ^ 0x36); opad[i] = static_cast(k[i] ^ 0x5c); } return Sha256::digest(opad + Sha256::digest(ipad + data)); } std::string SecureRandom::bytes(std::size_t n) { n = std::min(n, secaps::kMaxRandomBytes); std::string out(n, '\0'); std::FILE* f = std::fopen("/dev/urandom", "rb"); if (!f) throw std::runtime_error("no secure random source"); std::size_t got = std::fread(out.data(), 1, n, f); std::fclose(f); if (got != n) throw std::runtime_error("short read from urandom"); return out; } std::string SecureRandom::token_hex(std::size_t n) { return to_hex(bytes(n)); } namespace { std::string pbkdf2(const std::string& pw, const std::string& salt, int rounds) { std::string u = Hmac::sha256(pw, salt + std::string("\0\0\0\1", 4)); std::string t = u; for (int i = 1; i < rounds; ++i) { u = Hmac::sha256(pw, u); for (std::size_t j = 0; j < t.size(); ++j) t[j] = static_cast(t[j] ^ u[j]); } return t; } } // namespace std::string PasswordHasher::hash(const std::string& password) { std::string salt = SecureRandom::bytes(16); return "pbkdf2-demo$" + std::to_string(secaps::kDemoPbkdf2Rounds) + "$" + to_hex(salt) + "$" + to_hex(pbkdf2(password, salt, secaps::kDemoPbkdf2Rounds)); } bool PasswordHasher::verify(const std::string& password, const std::string& stored) { std::vector parts; std::size_t pos = 0; while (true) { std::size_t d = stored.find('$', pos); parts.push_back(stored.substr(pos, d == std::string::npos ? d : d - pos)); if (d == std::string::npos) break; pos = d + 1; } if (parts.size() != 4 || parts[0] != "pbkdf2-demo") return false; int rounds = 0; try { rounds = std::stoi(parts[1]); } catch (...) { return false; } if (rounds < 1 || rounds > 100000) return false; std::string salt; if (!from_hex(parts[2], salt)) return false; return constant_time_equal(to_hex(pbkdf2(password, salt, rounds)), parts[3]); } void DenialSink::record(const std::string& guard, const std::string& reason) { std::lock_guard lock(mu_); ++total_; if (ring_.size() >= secaps::kMaxDenials) ring_.erase(ring_.begin()); ring_.push_back({guard, reason}); } std::vector DenialSink::list() const { std::lock_guard lock(mu_); return ring_; } std::size_t DenialSink::total() const { std::lock_guard lock(mu_); return total_; } std::string CsrfGuard::issue() const { std::string nonce = SecureRandom::token_hex(16); return nonce + "." + to_hex(Hmac::sha256(secret_, nonce)); } bool CsrfGuard::verify(const std::string& token) const { std::size_t dot = token.find('.'); if (dot == std::string::npos || dot == 0 || token.size() > 200) return false; std::string nonce = token.substr(0, dot); return constant_time_equal(token.substr(dot + 1), to_hex(Hmac::sha256(secret_, nonce))); } bool CorsPolicy::allowed(const std::string& origin) const { return !origin.empty() && origins_.count(origin) > 0; } bool CorsPolicy::apply_preflight(const Request& req, Response& res) const { std::string origin = req.headers.get("Origin"); if (!allowed(origin)) return false; res.headers.set("Access-Control-Allow-Origin", origin); res.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization"); res.headers.set("Access-Control-Max-Age", "600"); res.headers.set("Vary", "Origin"); return true; } bool RateLimiter::hit(const std::string& key, int& retry_after, int& remaining) { std::lock_guard lock(mu_); auto now = std::chrono::steady_clock::now(); auto win = std::chrono::seconds(window_); if (slots_.size() >= secaps::kMaxRateKeys && !slots_.count(key)) { for (auto it = slots_.begin(); it != slots_.end();) it = (now - it->second.start >= win) ? slots_.erase(it) : std::next(it); if (slots_.size() >= secaps::kMaxRateKeys) { // floor: refuse new keys retry_after = window_; remaining = 0; return false; } } Slot& s = slots_[key]; if (s.count == 0 || now - s.start >= win) { s.start = now; s.count = 0; } if (s.count >= limit_) { auto left = std::chrono::duration_cast(win - (now - s.start)); retry_after = std::max(1, static_cast(left.count()) + 1); remaining = 0; return false; } ++s.count; retry_after = 0; remaining = limit_ - s.count; return true; } std::vector> SecurityHeaders::defaults() { return {{"X-Content-Type-Options", "nosniff"}, {"X-Frame-Options", "DENY"}, {"Referrer-Policy", "no-referrer"}, {"Strict-Transport-Security", "max-age=31536000; includeSubDomains"}, {"Cross-Origin-Opener-Policy", "same-origin"}, {"Permissions-Policy", "camera=(), microphone=(), geolocation=()"}}; } void SecurityHeaders::apply(Response& res) { for (const auto& [k, v] : defaults()) res.headers.set(k, v); } CspBuilder::CspBuilder() { directives_["default-src"] = "'none'"; directives_["script-src"] = "'self'"; directives_["style-src"] = "'self'"; directives_["img-src"] = "'self'"; directives_["frame-ancestors"] = "'none'"; } CspBuilder& CspBuilder::script_nonce(const std::string& nonce) { directives_["script-src"] = "'self' 'nonce-" + nonce + "'"; return *this; } CspBuilder& CspBuilder::report_uri(const std::string& uri) { directives_["report-uri"] = uri; return *this; } CspBuilder& CspBuilder::enforce() { report_only_ = false; return *this; } std::string CspBuilder::header_name() const { return report_only_ ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy"; } std::string CspBuilder::build() const { std::string out; for (const auto& [k, v] : directives_) out += (out.empty() ? "" : "; ") + k + " " + v; return out; } bool CspReportStore::add(const std::string& body) { if (body.empty() || body.size() > 4096) return false; std::lock_guard lock(mu_); ++total_; if (reports_.size() >= secaps::kMaxCspReports) reports_.erase(reports_.begin()); reports_.push_back(body); return true; } std::vector CspReportStore::list() const { std::lock_guard lock(mu_); return reports_; } std::size_t CspReportStore::total() const { std::lock_guard lock(mu_); return total_; } PermissionGuard::PermissionGuard() { token_role_ = {{"viewer-token", "viewer"}, {"editor-token", "editor"}, {"admin-token", "admin"}}; role_perms_["viewer"] = {"doc:read"}; role_perms_["editor"] = {"doc:read", "doc:write"}; role_perms_["admin"] = {"doc:read", "doc:write", "admin:manage"}; } PermissionGuard::Verdict PermissionGuard::check(const std::string& authorization, const std::string& permission, std::string& role) const { role.clear(); const std::string prefix = "Bearer "; if (authorization.compare(0, prefix.size(), prefix) != 0) return Verdict::Unauthenticated; auto it = token_role_.find(authorization.substr(prefix.size())); if (it == token_role_.end()) return Verdict::Unauthenticated; role = it->second; return role_perms_.at(role).count(permission) ? Verdict::Allow : Verdict::Forbidden; } std::vector PermissionGuard::permissions(const std::string& role) const { auto it = role_perms_.find(role); if (it == role_perms_.end()) return {}; return {it->second.begin(), it->second.end()}; } SecretsProvider::SecretsProvider() { values_ = {{"DB_PASSWORD", "demo-db-password-1234"}, {"API_KEY", "demo-api-key-abcdef"}, {"SIGNING_KEY", "demo-signing-key-zz"}}; } std::vector SecretsProvider::names() const { std::vector out; for (const auto& [k, v] : values_) out.push_back(k); return out; } bool SecretsProvider::masked(const std::string& name, std::string& out) const { auto it = values_.find(name); if (it == values_.end()) return false; const std::string& v = it->second; out = v.substr(0, 2) + std::string(v.size() - 4, '*') + v.substr(v.size() - 2); return true; } namespace { std::string lower(std::string s) { for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); return s; } } // namespace std::string SqlSafety::check(const std::string& value) { std::string v = lower(value); for (const char* bad : {"--", ";", "/*", "' or ", "\" or ", "union select", "drop table", "xp_"}) if (v.find(bad) != std::string::npos) return std::string("SQL metacharacter or keyword rejected: ") + bad; return ""; } std::string PathGuard::check(const std::string& value) { std::string v = lower(value); if (v.find('\0') != std::string::npos) return "NUL byte rejected"; if (!v.empty() && v[0] == '/') return "absolute path rejected"; for (const char* bad : {"..", "%2e", "\\"}) if (v.find(bad) != std::string::npos) return std::string("traversal sequence rejected: ") + bad; return ""; } std::string UploadValidator::check(const std::string& filename, const std::string& bytes) { if (filename.empty() || filename.size() > 255) return "file name length must be 1 to 255"; if (filename.find('/') != std::string::npos || filename.find('\\') != std::string::npos || filename.find("..") != std::string::npos) return "file name must not contain path parts"; std::size_t dot = filename.rfind('.'); if (dot == std::string::npos) return "extension not allowed (use pdf, png, txt)"; std::string ext = lower(filename.substr(dot + 1)); if (ext != "pdf" && ext != "png" && ext != "txt") return "extension not allowed (use pdf, png, txt)"; if (bytes.size() > kMaxFileBytes) return "file too large (max 1024 bytes)"; if (bytes.empty()) return "file is empty"; if (ext == "pdf" && bytes.compare(0, 5, "%PDF-") != 0) return "content does not match pdf magic bytes"; if (ext == "png" && bytes.compare(0, 4, "\x89PNG") != 0) return "content does not match png magic bytes"; if (ext == "txt") for (unsigned char c : bytes) if (c < 9 || (c > 13 && c < 32) || c == 127) return "txt content contains binary bytes"; return ""; } } // namespace molo::example::fw