using System;
using System.Linq;
namespace CSFramework.DB.Common
{
///
/// 代码安全检查工具类-ver:20210820
///
public static class CodeSafeHelper
{
///
/// 检查SQL语句Where条件是否存在单引号
///
public static bool IsCheckSQM { get; set; } = false;
///
/// 检查SQL语句是否存在注入攻击字符
///
public static bool IsCheckInjection { get; set; } = false;
///
/// 防止命令注入,Process.Start()
///
///
///
public static string GetSafeCmd(string content)
{
if (string.IsNullOrWhiteSpace(content))
{
return string.Empty;
}
else
{
//防止命令注入的方法如下:
//过滤可能引起命令注入的危险字符,如:; ,[ ,] ,| ,< ,> ,\。
var cs = new char[] { ';', '[', ']', '|', '<', '>' };
foreach (var c in cs)
content = content.Replace(c.ToString(), "");
return content.Trim();
}
}
///
/// 防止路径遍历
///
///
///
public static string GetSafePath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return string.Empty;
}
else
{
//防止路径遍历, 过滤..和/字符
var fileName = path.Replace("..", "").Replace("/", "");
return fileName;
}
}
///
/// 获取安全的SQL脚本
///
/// SQL脚本
/// 替换可能造成SQL注入攻击的字符
///
public static string GetSafeSQL(string sql,
bool replaceInjectionChar = false)
{
if (string.IsNullOrWhiteSpace(sql))
{
return string.Empty;
}
else
{
//检测单引号,防止注入攻击
if (IsCheckSQM && sql.IndexOf("'") > 0) sql = CheckSQM(sql);
//防止SQL注入的方法如下:
//过滤可能引起SQL注入的危险字符, 注意MySQL的注释:[-- ]后面有空格
if (replaceInjectionChar || IsCheckInjection)
{
var cs = new string[] { "#", "--", "-- ", "/*", "*/" };
foreach (var c in cs)
sql = sql.Replace(c, "");
}
return sql.Trim();
}
}
///
/// 检查SQL语法单引号,若不正常抛出异常。
/// 单引号SQM:Single Quotation Mark
///
/// SQL语句
/// 若检测不通过抛出异常
private static string CheckSQM(string sql)
{
if (string.IsNullOrWhiteSpace(sql)) return string.Empty;
//SQL没有单引号不处理
if (sql.IndexOf("'") < 0) return sql;
//找出单引号数量
var count = sql.Count(a => a == '\'');
//奇数,单引号不配对!
if (count % 2 == 1)
throw new Exception($"SQL语法不正确!\r\nSQL:{sql}\r\n请检查单引号是否配对。");
//检查where语句后面是否存在单引号
var w = sql.ToLower().IndexOf("where");
if (w > 0)
{
var where = sql.ToLower().Substring(w, sql.Length - w);
if (where.IndexOf("'") >= 0)
throw new Exception(
$"SQL语句WHERE条件不允许任何单引号\"'\"拼接,请使用SQL参数传值!\r\n" + where);
}
return sql;
}
}
}