Log Injection in Fiber
How Log Injection Manifests in Fiber
Log injection in Fiber applications occurs when user-controlled data is written directly to log files without proper sanitization, allowing attackers to manipulate log content, inject malicious commands, or create misleading audit trails. This vulnerability is particularly concerning in Go applications using Fiber's logging middleware.
The most common manifestation appears when request parameters, headers, or body content are logged verbatim. Consider this typical Fiber pattern:
app := fiber.New()
app.Use(middleware.Logger())
app.Post("/api/data", func(c *fiber.Ctx) error {
data := c.FormValue("data")
log.Println("Received data:", data) // Vulnerable to injection
return c.SendString("OK")
})An attacker can craft requests with newline characters and log levels to manipulate the log file:
curl -X POST "http://localhost:3000/api/data" \
-d "data=INFO 2024/01/01 12:00:00 Server started: ALL YOUR BASE ARE BELONG TO US"This injects fake log entries that appear as legitimate log messages, potentially triggering false alerts or hiding malicious activity. The vulnerability extends to structured logging where JSON objects are constructed from user input:
logEntry := fmt.Sprintf(`{"timestamp":"%s","user":"%s","action":"%s"}`,
time.Now().Format(time.RFC3339), userID, action)
log.Println(logEntry)If userID contains special characters, it can break the JSON structure or inject additional fields. Fiber's default logging middleware compounds this by logging request details including headers, which may contain CRLF sequences:
// Default Fiber logger logs request details
app.Use(middleware.Logger())
// Attacker can inject via User-Agent header
curl -H "User-Agent: Mozilla/5.0
ERROR 2024/01/01 12:00:00 Injection detected" ...Multi-line log injection is particularly dangerous in centralized logging systems where injected entries can trigger automated alerts, skew analytics, or provide cover for actual attacks. The injected content may contain SQL injection attempts, XSS payloads, or references to sensitive data that appear in audit logs.
Fiber-Specific Detection
Detecting log injection in Fiber applications requires both static analysis and runtime monitoring. Static analysis should examine all logging statements for direct interpolation of request data:
// Vulnerable patterns to search for
glog.Infof("User %s accessed %s", c.Query("user"), c.Path())
log.Printf("Data: %s", c.Body())
logger.Println("Request:", c.Body())middleBrick's black-box scanning can detect log injection vulnerabilities by analyzing API endpoints and identifying patterns where user input flows to logging mechanisms. The scanner tests for newline injection by sending payloads containing CRLF sequences and monitoring log outputs for manipulation.
Runtime detection in Fiber can be implemented using middleware that sanitizes log entries:
func sanitizeLogMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
// Sanitize request parameters before logging
c.Locals("sanitizedParams", sanitizeInput(c.Params()))
return c.Next()
}
}
func sanitizeInput(input string) string {
// Remove control characters that could break log format
return strings.ReplaceAll(input, "\n", " ")
.ReplaceAll(input, "\r", " ")
.ReplaceAll(input, "%0a", " ")
.ReplaceAll(input, "%0d", " ")
}middleBrick's OpenAPI analysis can identify endpoints that accept user input and cross-reference this with logging patterns in the codebase. The scanner specifically looks for:
- Direct interpolation of request parameters in log statements
- Missing input validation before logging
- Structured logging that constructs JSON from user input
- Logging of headers that may contain malicious content
- Debug logging enabled in production environments
Continuous monitoring with middleBrick's Pro plan can alert you when new endpoints are deployed that may introduce log injection vulnerabilities, providing severity ratings and remediation guidance based on the potential impact of the vulnerability.
Fiber-Specific Remediation
Remediating log injection in Fiber requires a defense-in-depth approach. The first layer is input sanitization before logging:
func safeLog(message string, args ...interface{}) {
sanitized := make([]interface{}, len(args))
for i, arg := range args {
switch v := arg.(type) {
case string:
sanitized[i] = sanitizeForLog(v)
default:
sanitized[i] = arg
}
}
log.Printf(sanitizeForLog(message), sanitized...)
}
func sanitizeForLog(input string) string {
// Remove or encode control characters
input = strings.ReplaceAll(input, "\n", " ")
input = strings.ReplaceAll(input, "\r", " ")
// Escape quotes and special characters
input = strings.ReplaceAll(input, "\"", "'")
// Truncate overly long inputs
if len(input) > 1000 {
input = input[:997] + "..."
}
return input
}
// Usage in Fiber app
app.Post("/api/data", func(c *fiber.Ctx) error {
data := c.FormValue("data")
safeLog("Received data: %s", data)
return c.SendString("OK")
})For structured logging, use proper serialization instead of string interpolation:
type LogEntry struct {
Timestamp string `json:"timestamp"`
User string `json:"user"`
Action string `json:"action"`
Data string `json:"data,omitempty"`
}
// Safe structured logging
entry := LogEntry{
Timestamp: time.Now().Format(time.RFC3339),
User: sanitizeForLog(userID),
Action: sanitizeForLog(action),
}
// Use proper JSON marshaling
jsonData, _ := json.Marshal(entry)
log.Println(string(jsonData))Implement a custom logging middleware in Fiber that filters sensitive information:
func secureLogger() fiber.Handler {
return func(c *fiber.Ctx) error {
// Create sanitized request copy for logging
reqCopy := c.Copy()
// Remove sensitive headers
reqCopy.Request().Header.Del("Authorization")
reqCopy.Request().Header.Del("Cookie")
// Sanitize query parameters
params := reqCopy.Params()
for key := range params {
params[key] = sanitizeForLog(params[key])
}
// Log sanitized request
log.Printf("Request: %s %s %v",
c.Method(), c.OriginalURL(), params)
return c.Next()
}
}
// Use in Fiber app
app.Use(secureLogger())middleBrick's scanning can verify your remediation by testing endpoints with malicious log injection payloads and confirming they're properly sanitized. The scanner provides specific findings with severity levels and exact code locations where vulnerabilities exist, allowing you to prioritize fixes based on the potential impact to your application's security and compliance posture.