如何修复VB.NET应用中的CRLF注入漏洞?附涉事代码
Hey there! Let's fix those CRLF injection vulnerabilities in your VB.NET app. I've looked at your code, and here's what's going on and how to fix it:
问题根源
CRLF injection happens when user-controllable input (like your strFileName here) contains newline characters (\r or \n). If an attacker manipulates the filename to include these characters, they can inject additional HTTP headers into the response—this is exactly what your security scan is flagging.
Looking at your original code:
Dim strFileName As String = Path.GetFileName(FName).Replace(" ", "%20")
Response.AddHeader("Content-Disposition", ("attachment; filename=" + strFileName))
If strFileName included something like malicious.txt\r\nX-Malicious-Header: hacked, the response would end up with an extra, attacker-controlled header. The scan also flagged Response.ContentType likely because it's part of the header chain where injection could occur, even though it's hardcoded here.
修复步骤
Here are the key fixes to eliminate the risk:
- Remove newline characters entirely: This cuts off the injection at the source—no
\ror\nmeans no way to split HTTP headers. - URL-encode the filename: Ensures special characters (like spaces, quotes, or weird symbols) are properly escaped and won't be misinterpreted as header syntax.
- Wrap the filename in quotes: Prevents the server from parsing any remaining special characters in the filename as header parameter separators.
修改后的完整代码
Imports System.IO Imports System.Web ' 后台.vb中的修复后代码片段 Dim originalFileName As String = Path.GetFileName(FName) ' 过滤所有换行符,彻底消除CRLF注入可能 Dim cleanedFileName As String = originalFileName.Replace(vbCr, "").Replace(vbLf, "") ' URL编码文件名,处理特殊字符(替换+为%20保持空格的标准编码) Dim encodedFileName As String = HttpUtility.UrlEncode(cleanedFileName).Replace("+", "%20") Response.ContentType = "application/octet-stream" ' 用双引号包裹编码后的文件名,避免解析歧义 Response.AddHeader("Content-Disposition", $"attachment; filename=""{encodedFileName}""") Response.WriteFile(FName) Response.End()
额外说明
- The
Response.ContentTypeline was likely a false positive from the scanner, since it's hardcoded and not using any user input. You can confirm this with your scan tool's documentation. - Make sure
FNameitself comes from a trusted source (like your server's storage, not direct user input) to avoid other risks like path traversal attacks.
内容的提问来源于stack exchange,提问作者ssuhas76

