sanitizeUserAgentSuffix sanitizes the user agent suffix
(value string)
| 72 | |
| 73 | // sanitizeUserAgentSuffix sanitizes the user agent suffix |
| 74 | func sanitizeUserAgentSuffix(value string) string { |
| 75 | // Security constraints for HTTP User-Agent header: |
| 76 | // 1. Max length to prevent server buffer overflow (Tomcat default: 8KB total headers) |
| 77 | // 2. Only allow safe characters to prevent header injection |
| 78 | // 3. Remove control characters and newlines |
| 79 | |
| 80 | // Remove control characters, CR, LF, and other dangerous characters |
| 81 | value = strings.ReplaceAll(value, "\r", "") |
| 82 | value = strings.ReplaceAll(value, "\n", "") |
| 83 | value = strings.ReplaceAll(value, "\t", " ") |
| 84 | |
| 85 | // Only allow ASCII characters, spaces, hyphens, dots, underscores, and alphanumeric |
| 86 | // This prevents header injection attacks |
| 87 | invalidChars := regexp.MustCompile(`[^a-zA-Z0-9 .\-_]`) |
| 88 | value = invalidChars.ReplaceAllString(value, "") |
| 89 | |
| 90 | // Remove sequences that could be interpreted as header separators |
| 91 | value = strings.ReplaceAll(value, ":", "") |
| 92 | value = strings.ReplaceAll(value, ";", "") |
| 93 | |
| 94 | // Trim whitespace and limit length |
| 95 | value = strings.TrimSpace(value) |
| 96 | if len(value) > maxSuffixLength { |
| 97 | value = value[:maxSuffixLength] |
| 98 | value = strings.TrimSpace(value) // Trim again in case we cut in the middle of whitespace |
| 99 | } |
| 100 | |
| 101 | return value |
| 102 | } |