You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复VB.NET应用中的CRLF注入漏洞?附涉事代码

修复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 \r or \n means 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.ContentType line 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 FName itself 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:35