// Kendi sunucunda webhook imzasını doğrulamak (Webhooks, Pro ve üstü). // Her olayda sunucumuz senin adresine JSON gövdeli bir POST atar ve şu başlıkları ekler: // X-OsProtect-Event: olay türü (ör. tamper.threshold) // X-OsProtect-Signature: sha256= // HMAC anahtarı webhook'u eklerken BİR KEZ gösterilen "whsec_..." gizli anahtarıdır. // Gövdeyi ayrıştırmadan ÖNCE imzayı ham baytlar üzerinde doğrula; tutmazsa isteği reddet. #include #include #include #include #pragma comment(lib, "bcrypt.lib") static std::string HmacSha256Hex(const std::string& key, const std::string& body) { BCRYPT_ALG_HANDLE alg = nullptr; BYTE mac[32] = {}; std::string hex; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, nullptr, BCRYPT_ALG_HANDLE_HMAC_FLAG) != 0) return ""; if (BCryptHash(alg, (PUCHAR)key.data(), (ULONG)key.size(), (PUCHAR)body.data(), (ULONG)body.size(), mac, sizeof(mac)) == 0) { static const char* digits = "0123456789abcdef"; for (BYTE b : mac) { hex += digits[b >> 4]; hex += digits[b & 15]; } } BCryptCloseAlgorithmProvider(alg, 0); return hex; } // Sabit sürede karşılaştırma: imzayı harf harf tahmin etmeye karşı. static bool SafeEquals(const std::string& a, const std::string& b) { if (a.size() != b.size()) return false; unsigned char diff = 0; for (size_t i = 0; i < a.size(); ++i) diff |= (unsigned char)(a[i] ^ b[i]); return diff == 0; } // rawBody: isteğin gövdesi, hiç değiştirilmeden (boşluklar dahil) okunmuş hâli. // signatureHeader: X-OsProtect-Signature başlığının değeri. static bool VerifyWebhook(const std::string& secret, const std::string& rawBody, const std::string& signatureHeader) { const std::string prefix = "sha256="; if (signatureHeader.compare(0, prefix.size(), prefix) != 0) return false; std::string expected = HmacSha256Hex(secret, rawBody); return !expected.empty() && SafeEquals(expected, signatureHeader.substr(prefix.size())); } int main() { // Gizli anahtarı kodun içine değil ortam değişkenine koy. char secret[256] = {}; size_t len = 0; if (getenv_s(&len, secret, sizeof(secret), "OS_WEBHOOK_SECRET") != 0 || len == 0) { printf("OS_WEBHOOK_SECRET ayarlı değil.\n"); return 1; } // Kendi HTTP sunucundan gelen değerler (burada örnek): std::string body = R"({"event":"tamper.threshold","ts":1767225600,"tenant_id":12,"user_note":"","data":{"kind":"tamper.threshold"}})"; std::string header = "sha256=" + HmacSha256Hex(secret, body); // gerçek istekte başlıktan okunur if (!VerifyWebhook(secret, body, header)) { printf("İmza geçersiz: 401 döndür ve isteği yok say.\n"); return 1; } printf("İmza doğru. Olayı işle ve 2xx döndür (8 saniye içinde).\n"); return 0; }