Fix Insecure Webhooks in Gin
Webhooks are essentially unauthenticated POST requests by default. If you don't verify the origin, you're inviting attackers to spoof events, manipulate state, or trigger sensitive workflows. In the Gin framework, the standard fix is implementing HMAC-SHA256 signature verification via middleware to ensure the payload hasn't been tampered with and actually originated from a trusted provider.
The Vulnerable Pattern
func SetupRouter() *gin.Engine {
r := gin.Default()
r.POST("/webhook", func(c *gin.Context) {
var payload map[string]interface{}
// VULNERABILITY: Blindly trusting the JSON body without verification
if err := c.ShouldBindJSON(&payload); err == nil {
processBusinessLogic(payload)
c.Status(200)
}
})
return r
}
The Secure Implementation
To secure the endpoint, we implement three critical steps: 1. Extract the raw request body (c.Request.Body) before it is parsed. 2. Compute the HMAC-SHA256 hash using a shared secret key. 3. Use hmac.Equal for constant-time comparison. This prevents timing attacks where an attacker could guess the signature byte-by-byte based on server response latency. We also re-populate the request body using io.NopCloser so subsequent Gin handlers can still bind the JSON data.
func VerifyWebhookSignature(secret []byte) gin.HandlerFunc { return func(c *gin.Context) { body, _ := io.ReadAll(c.Request.Body) c.Request.Body = io.NopCloser(bytes.NewBuffer(body)) signature := c.GetHeader("X-Hub-Signature-256")mac := hmac.New(sha256.New, secret) mac.Write(body) expectedMAC := "sha256=" + hex.EncodeToString(mac.Sum(nil)) if signature == "" || !hmac.Equal([]byte(signature), []byte(expectedMAC)) { c.AbortWithStatusJSON(401, gin.H{"error": "Invalid signature"}) return } c.Next() }}
// Usage: // r.POST(“/webhook”, VerifyWebhookSignature([]byte(os.Getenv(“WEBHOOK_SECRET”))), handler)
Your Gin API
might be exposed to Insecure Webhooks
74% of Gin apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.