.Net网站架构设计(七)网络安全
谈到网络安全,首先得说一下web网站有哪些最常见漏洞。
非法输入
Unvalidated Input
在数据被输入程序前忽略对数据合法性的检验是一个常见的编程漏洞。随着OWASP对Web应用程序脆弱性的调查,非法输入的问题已成为大多数Web应用程序安全漏洞方面的一个普遍现象。
方案:要在web前端,和服务器端对数据的合法性进行验证
- public class PageValidate
- {
- private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
- private static Regex RegNumber = new Regex("^[0-9]+$");
- private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
- private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
- private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
- private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
- private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
- public PageValidate()
- {
- }
- //数字字符串检查#region 数字字符串检查
- public static bool IsPhone(string inputData)
- {
- Match m = RegPhone.Match(inputData);
- return m.Success;
- }
- /**//// <summary>
- /// 检查Request查询字符串的键值,是否是数字,最大长度限制
- /// </summary>
- /// <param name="req">Request</param>
- /// <param name="inputKey">Request的键值</param>
- /// <param name="maxLen">最大长度</param>
- /// <returns>返回Request查询字符串</returns>
- public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
- {
- string retVal = string.Empty;
- if(inputKey != null && inputKey != string.Empty)
- {
- retVal = req.QueryString[inputKey];
- if(null == retVal)
- retVal = req.Form[inputKey];
- if(null != retVal)
- {
- retVal = SqlText(retVal, maxLen);
- if(!IsNumber(retVal))
- retVal = string.Empty;
- }
- }
- if(retVal == null)
- retVal = string.Empty;
- return retVal;
- }
- /**//// <summary>
- /// 是否数字字符串
- /// </summary>
- /// <param name="inputData">输入字符串</param>
- /// <returns></returns>
- public static bool IsNumber(string inputData)
- {
- Match m = RegNumber.Match(inputData);
- return m.Success;
- }
- /**//// <summary>
- /// 是否数字字符串 可带正负号
- /// </summary>
- /// <param name="inputData">输入字符串</param>
- /// <returns></returns>
- public static bool IsNumberSign(string inputData)
- {
- Match m = RegNumberSign.Match(inputData);
- return m.Success;
- }
- /**//// <summary>
- /// 是否是浮点数
- /// </summary>
- /// <param name="inputData">输入字符串</param>
- /// <returns></returns>
- public static bool IsDecimal(string inputData)
- {
- Match m = RegDecimal.Match(inputData);
- return m.Success;
- }
- /**//// <summary>
- /// 是否是浮点数 可带正负号
- /// </summary>
- /// <param name="inputData">输入字符串</param>
- /// <returns></returns>
- public static bool IsDecimalSign(string inputData)
- {
- Match m = RegDecimalSign.Match(inputData);
- return m.Success;
- }
- #endregion
- //中文检测#region 中文检测
- /**//// <summary>
- /// 检测是否有中文字符
- /// </summary>
- /// <param name="inputData"></param>
- /// <returns></returns>
- public static bool IsHasCHZN(string inputData)
- {
- Match m = RegCHZN.Match(inputData);
- return m.Success;
- }
- #endregion
- //邮件地址#region 邮件地址
- /**//// <summary>
- /// 是否是浮点数 可带正负号
- /// </summary>
- /// <param name="inputData">输入字符串</param>
- /// <returns></returns>
- public static bool IsEmail(string inputData)
- {
- Match m = RegEmail.Match(inputData);
- return m.Success;
- }
- #endregion
- //其他#region 其他
- /**//// <summary>
- /// 检查字符串最大长度,返回指定长度的串
- /// </summary>
- /// <param name="sqlInput">输入字符串</param>
- /// <param name="maxLength">最大长度</param>
- /// <returns></returns>
- public static string SqlText(string sqlInput, int maxLength)
- {
- if(sqlInput != null && sqlInput != string.Empty)
- {
- sqlInput = sqlInput.Trim();
- if(sqlInput.Length > maxLength)//按最大长度截取字符串
- sqlInput = sqlInput.Substring(0, maxLength);
- }
- return sqlInput;
- }
- /**//// <summary>
- /// 字符串编码
- /// </summary>
- /// <param name="inputData"></param>
- /// <returns></returns>
- public static string HtmlEncode(string inputData)
- {
- return HttpUtility.HtmlEncode(inputData);
- }
- /**//// <summary>
- /// 设置Label显示Encode的字符串
- /// </summary>
- /// <param name="lbl"></param>
- /// <param name="txtInput"></param>
- public static void SetLabel(Label lbl, string txtInput)
- {
- lbl.Text = HtmlEncode(txtInput);
- }
- public static void SetLabel(Label lbl, object inputObj)
- {
- SetLabel(lbl, inputObj.ToString());
- }
- //字符串清理
- public static string InputText(string inputString, int maxLength)
- {
- StringBuilder retVal = new StringBuilder();
- // 检查是否为空
- if ((inputString != null) && (inputString != String.Empty))
- {
- inputString = inputString.Trim();
- //检查长度
- if (inputString.Length > maxLength)
- inputString = inputString.Substring(0, maxLength);
- //替换危险字符
- for (int i = 0; i < inputString.Length; i++)
- {
- switch (inputString[i])
- {
- case '"':
- retVal.Append(""");
- break;
- case '<':
- retVal.Append("<");
- break;
- case '>':
- retVal.Append(">");
- break;
- default:
- retVal.Append(inputString[i]);
- break;
- }
- }
- retVal.Replace("'", " ");// 替换单引号
- }
- return retVal.ToString();
- }
- /**//// <summary>
- /// 转换成 HTML code
- /// </summary>
- /// <param name="str">string</param>
- /// <returns>string</returns>
- public static string Encode(string str)
- {
- str = str.Replace("&","&");
- str = str.Replace("'","''");
- str = str.Replace("\"",""");
- str = str.Replace(" "," ");
- str = str.Replace("<","<");
- str = str.Replace(">",">");
- str = str.Replace("\n","<br>");
- return str;
- }
- /**//// <summary>
- ///解析html成 普通文本
- /// </summary>
- /// <param name="str">string</param>
- /// <returns>string</returns>
- public static string Decode(string str)
- {
- str = str.Replace("<br>","\n");
- str = str.Replace(">",">");
- str = str.Replace("<","<");
- str = str.Replace(" "," ");
- str = str.Replace(""","\"");
- return str;
- }
- public static string SqlTextClear(string sqlText)
- {
- if (sqlText == null)
- {
- return null;
- }
- if (sqlText == "")
- {
- return "";
- }
- sqlText = sqlText.Replace(",", "");//去除,
- sqlText = sqlText.Replace("<", "");//去除<
- sqlText = sqlText.Replace(">", "");//去除>
- sqlText = sqlText.Replace("--", "");//去除--
- sqlText = sqlText.Replace("'", "");//去除'
- sqlText = sqlText.Replace("\"", "");//去除"
- sqlText = sqlText.Replace("=", "");//去除=
- sqlText = sqlText.Replace("%", "");//去除%
- sqlText = sqlText.Replace(" ", "");//去除空格
- return sqlText;
- }
- #endregion
- //是否由特定字符组成#region 是否由特定字符组成
- public static bool isContainSameChar(string strInput)
- {
- string charInput = string.Empty;
- if (!string.IsNullOrEmpty(strInput))
- {
- charInput = strInput.Substring(0, 1);
- }
- return isContainSameChar(strInput, charInput, strInput.Length);
- }
- public static bool isContainSameChar(string strInput, string charInput, int lenInput)
- {
- if (string.IsNullOrEmpty(charInput))
- {
- return false;
- }
- else
- {
- Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
- //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
- Match m = RegNumber.Match(strInput);
- return m.Success;
- }
- }
- #endregion
- //检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查#region 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
- /**//// <summary>
- /// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
- /// </summary>
- public static bool isContainSpecChar(string strInput)
- {
- string[] list = new string[] { "123456", "654321" };
- bool result = new bool();
- for (int i = 0; i < list.Length; i++)
- {
- if (strInput == list[i])
- {
- result = true;
- break;
- }
- }
- return result;
- }
- #endregion
- }
失效的访问控制
Broken Access Control
大部分企业都非常关注对已经建立的连接进行控制,但是,允许一个特定的字符串输入可以让攻击行为绕过企业的控制。
解决方案:
采用Atho2的方式对用户身份进行验证;将AccessToken 保存到Cookie里面;设置Cookie失效策略;
当然在分布架构下面;需要用户集中式Redis集群管理用户Session,而在应用级是无状态的。
失效的账户和线程管理
Broken Authentication and Session Management
有良好的访问控制并不意味着万事大吉,企业还应该保护用户的密码、会话令牌、账户列表及其它任何可为攻击者提供有利信息、能帮助他们攻击企业网络的内容。
跨站点脚本攻击
Cross Site Scripting Flaws
这是一种常见的攻击,当攻击脚本被嵌入企业的Web页面或其它可以访问的Web资源中,没有保护能力的台式机访问这个页面或资源时,脚本就会被启动,这种攻击可以影响企业内成百上千员工的终端电脑。
解决方案:要在可能的输入项中过滤所有
缓存溢出问题
Buffer Overflows
这个问题一般出现在用较早的编程语言、如C语言编写的程序中,这种编程错误其实也是由于没有很好地确定输入内容在内存中的位置所致。
注入式攻击
Injection Flaws
如果没有成功地阻止带有语法含义的输入内容,有可能导致对数据库信息的非法访问,在Web表单中输入的内容应该保持简单,并且不应包含可被执行的代码。
解决方案:
1、要使用服务端的可能带来的服务SQL注入的地方进行验证;
2、涉及SQL语句查询是使用SQL变量(强烈推荐)
3、用通用的方法检验是否存在特殊字符
- namespace YQSH.EIMS
- {
- using System;
- public class SqlPourInto
- {
- private System.Collections.Specialized.NameValueCollection Param;
- public SqlPourInto(System.Collections.Specialized.NameValueCollection param)
- {
- this.Param = param;
- }
- public bool HandleParam()
- {
- if (Param.Count == 0)
- return true;
- for (int i = 0; i < Param.Count; i++)
- if (!IsSafeString(Param[i].ToString()))
- return false;
- return true ;
- }
- public bool IsSafeString(string strText)
- {
- bool bResult = true;
- strText = System.Text.RegularExpressions.Regex.Replace(strText, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
- string[] UnSafeArray = new string[23];
- UnSafeArray[0] = "'";
- UnSafeArray[1] = "xp_cmdshell ";
- UnSafeArray[2] = "declare ";
- UnSafeArray[3] = "netlocalgroupadministrators ";
- UnSafeArray[4] = "delete ";
- UnSafeArray[5] = "truncate ";
- UnSafeArray[6] = "netuser ";
- UnSafeArray[7] = "add ";
- UnSafeArray[8] = "drop ";
- UnSafeArray[9] = "update ";
- UnSafeArray[10] = "select ";
- UnSafeArray[11] = "union ";
- UnSafeArray[12] = "exec ";
- UnSafeArray[13] = "create ";
- UnSafeArray[14] = "insertinto ";
- UnSafeArray[15] = "sp_ ";
- UnSafeArray[16] = "exec ";
- UnSafeArray[17] = "create ";
- UnSafeArray[18] = "insert ";
- UnSafeArray[19] = "masterdbo ";
- UnSafeArray[20] = "sp_ ";
- UnSafeArray[21] = ";-- ";
- UnSafeArray[22] = "1= ";
- foreach (string strValue in UnSafeArray)
- {
- if (strText.ToLower().IndexOf(strValue) > -1)
- {
- bResult = false;
- break;
- }
- }
- return bResult;
- }
- }
- }
异常错误处理
Improper Error Handling
当错误发生时,向用户提交错误提示是很正常的事情,但是如果提交的错误提示中包含了太多的内容,就有可能会被攻击者分析出网络环境的结构或配置。
解决方案:Web.config,中将错误配置:
- <customErrors mode="RemoteOnly">
- <error statusCode="403" redirect="NoAccess.htm" />
- <error statusCode="404" redirect="FileNotFound.htm" />
- </customErrors>
不安全的存储
Insecure Storage
对于Web应用程序来说,妥善保存密码、用户名及其他与身份验证有关的信息是非常重要的工作,对这些信息进行加密则是非常有效的方式,但是一些企业会采用那些未经实践验证的加密解决方案,其中就可能存在安全漏洞。
解决方案:对于密码可以采用2次的MD5加密,并验证密码得复杂程度。
程序拒绝服务攻击
Application Denial of Service
与拒绝服务攻击 (DoS)类似,应用程序的DoS攻击会利用大量非法用户抢占应用程序资源,导致合法用户无法使用该Web应用程序。
解决方案
代码解决方案:
- 解决方案:
- 1、避免XSS的方法之一主要是将用户所提供的内容输入输出进行过滤。ASP.NET的Server.HtmlEncode()或功能更强的Microsoft Anti-Cross Site Scripting Library。
- 2、整体网站的过滤处理,下面是通用处理方法。
- public class safe_process
- {
- private const string StrRegex = @"<[^>]+?style=[\w]+?:expression\(|\b(alert|confirm|prompt)\b|^\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|<\s*img\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
- public static bool PostData()
- {
- bool result = false;
- for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
- {
- result = CheckData(HttpContext.Current.Request.Form[i].ToString());
- if (result)
- {
- break;
- }
- }
- return result;
- }
- public static bool GetData()
- {
- bool result = false;
- for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
- {
- result = CheckData(HttpContext.Current.Request.QueryString[i].ToString());
- if (result)
- {
- break;
- }
- }
- return result;
- }
- public static bool CookieData()
- {
- bool result = false;
- for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
- {
- result = CheckData(HttpContext.Current.Request.Cookies[i].Value.ToLower());
- if (result)
- {
- break;
- }
- }
- return result;
- }
- public static bool referer()
- {
- bool result = false;
- return result = CheckData(HttpContext.Current.Request.UrlReferrer.ToString());
- }
- public static bool CheckData(string inputData)
- {
- if (Regex.IsMatch(inputData, StrRegex))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- 在Global.asax中的Application_BeginRequest中调用上面的方法进行处理,代码如下:
- protected void Application_BeginRequest(Object sender, EventArgs e)
- {
- string q = "<div style='position:fixed;top:0px;width:100%;height:100%;background-color:white;color:green;font-weight:bold;border-bottom:5px solid #999;'><br>您的提交带有不合法参数!</div>";
- if (Request.Cookies != null)
- {
- if (SteelMachining.Common.safe_360.CookieData())
- {
- Response.Write(q);
- Response.End();
- }
- }
- if (Request.UrlReferrer != null)
- {
- if (SteelMachining.Common.safe_360.referer())
- {
- Response.Write(q);
- Response.End();
- }
- }
- if (Request.RequestType.ToUpper() == "POST")
- {
- if (SteelMachining.Common.safe_360.PostData())
- {
- Response.Write(q);
- Response.End();
- }
- }
- if (Request.RequestType.ToUpper() == "GET")
- {
- if (SteelMachining.Common.safe_360.GetData())
- {
- Response.Write(q);
- Response.End();
- }
- }
- }
不安全的配置管理
Insecure Configuration Management
有效的配置管理过程可以为Web应用程序和企业的网络架构提供良好的保护。
不安全的网络传输
解决方案:对敏感数据进行加密
采用安全的传输通道(专网,或者VPN)
采取加密协议如Https
网络数据伪造
采取数据加密认证
网络篡改
采取数据认证