C#中Row.Cells[2].Text的额外字符串校验问题(Checkmarx检测未通过)
解决Checkmarx检测字符串未校验/未清理的问题
首先,你的代码里存在一个正则表达式语法错误,这是导致校验逻辑失效、Checkmarx报错的核心原因:
你写的@"\w{1-35}"中,量词的正确语法是{min,max}(逗号分隔),而非减号。这个错误会让正则无法正确匹配1到35位的字母数字下划线,等于没有做有效校验。
修复步骤与替代校验方案
1. 修复正则表达式并关联校验与变量使用
把正则修正为@"\w{1,35}",并且确保校验后使用的是经过校验的变量(即使值相同,也能帮助Checkmarx识别校验逻辑的关联):
string qry = "SELECT * from table_name " + "WHERE column_name = @variable"; var cmd = new SqlCommand(qry, con); cmd.CommandTimeout = 500; cmd.CommandType = CommandType.Text; // 先提取输入值,统一校验 string input = Row.Cells[2].Text; // 修正正则的量词语法,加上锚点确保全匹配 if (!Regex.IsMatch(input, @"^\w{1,35}$")) throw new ArgumentException("Invalid string"); // 使用经过校验的input变量,而非再次读取Row.Cells[2].Text cmd.Parameters.AddWithValue("@variable", input); cmd.ExecuteNonQuery();
2. 替代的校验/清理方法
如果正则还是无法被Checkmarx识别,可以尝试更直白的校验逻辑:
长度+字符白名单校验
string input = Row.Cells[2].Text; // 检查长度范围 if (input.Length < 1 || input.Length > 35) throw new ArgumentException("Invalid string length"); // 检查所有字符是否在允许的范围内 var allowedChars = new HashSet<char>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"); foreach (char c in input) { if (!allowedChars.Contains(c)) throw new ArgumentException("Invalid character in string"); } cmd.Parameters.AddWithValue("@variable", input);
主动清理(过滤非法字符)
如果允许清理而非直接报错,可以移除所有非法字符后再校验长度:
string input = Row.Cells[2].Text; var allowedChars = new HashSet<char>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"); // 过滤非法字符 string cleanedInput = new string(input.Where(c => allowedChars.Contains(c)).ToArray()); // 检查清理后的长度是否符合要求 if (cleanedInput.Length < 1 || cleanedInput.Length > 35) throw new ArgumentException("Invalid string after cleaning"); cmd.Parameters.AddWithValue("@variable", cleanedInput);
关于Checkmarx检测的说明
你的代码已经使用了参数化查询,这本身是防止SQL注入的最佳实践,理论上不存在注入风险。Checkmarx的报错是因为静态分析没有识别到你的有效校验逻辑(尤其是原正则的语法错误导致校验失效),按照上述方法修正后,应该能通过检测。
内容的提问来源于stack exchange,提问作者Lia Lucindia
相关产品推荐
相关产品推荐

