. Net website architecture design (7) Network Security

Source: Internet
Author: User
Tags encode string

. Net website architecture design (7) Network Security
. Net website architecture (7) network security when it comes to network security, you must first talk about the most common web site vulnerabilities. Illegal Input


Unvalidated Input

Ignoring the test of Data legitimacy before data is input into a program is a common programming vulnerability. With OWASP's investigation of Web application vulnerabilities, illegal input has become a common phenomenon in most Web application security vulnerabilities.

Solution: Check the validity of data on the web Front-end and on the server.

 

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] + $ "); // equivalent to ^ [+-]? \ D + [.]? \ D + $ private static Regex RegEmail = new Regex ("^ [\ w-] + @ [\ w-] + \\. (com | net | org | edu | mil | TV | biz | info) $ "); // a string of w English letters or numbers, like the [a-zA-Z0-9] syntax, private static Regex RegCHZN = new Regex ("[\ u4e00-\ u9fa5]"); public PageValidate () {} // number string check # region number string check public static bool IsPhone (string inputData) {Match m = RegPhone. match (inputData); return m. success ;}/**/////// Check whether the key value of the Request string is a number and the maximum length is limited //////Request ///Request key ///Maximum length ///
 
  
Returns the Request query string.
 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 ;}/**/////// Whether it is a numeric string //////Input string ///
 Public static bool IsNumber (string inputData) {Match m = RegNumber. Match (inputData); return m. Success ;}/**/////// Whether a numeric string can contain positive and negative numbers //////Input string ///
 Public static bool IsNumberSign (string inputData) {Match m = RegNumberSign. Match (inputData); return m. Success ;}/**/////// Whether it is a floating point number //////Input string ///
 Public static bool IsDecimal (string inputData) {Match m = RegDecimal. Match (inputData); return m. Success ;}/**/////// Whether the floating point can contain positive and negative numbers //////Input string ///
 Public static bool IsDecimalSign (string inputData) {Match m = RegDecimalSign. match (inputData); return m. success;} # endregion // Chinese detection # region Chinese detection /**/////// Check whether there are any Chinese characters /////////
 Public static bool IsHasCHZN (string inputData) {Match m = RegCHZN. match (inputData); return m. success;} # endregion // email address # region email address /**/////// Whether the floating point can contain positive and negative numbers //////Input string ///
 Public static bool IsEmail (string inputData) {Match m = RegEmail. Match (inputData); return m. Success;} # endregion/others # other region /**/////// Check the maximum length of a string and return the string of the specified length //////Input string ///Maximum length ///
 Public static string SqlText (string sqlInput, int maxLength) {if (sqlInput! = Null & sqlInput! = String. empty) {sqlInput = sqlInput. trim (); if (sqlInput. length> maxLength) // extract the string sqlInput = sqlInput by the maximum Length. substring (0, maxLength);} return sqlInput ;}/**/////// String encoding /////////
 Public static string HtmlEncode (string inputData) {return HttpUtility. HtmlEncode (inputData );}/**/////// Set the Label to display the Encode string /////////Public static void SetLabel (Label lbl, string txtInput) {lbl. text = HtmlEncode (txtInput);} public static void SetLabel (Label lbl, object inputObj) {SetLabel (lbl, inputObj. toString ();} // clear the public static string InputText (string inputString, int maxLength) {StringBuilder retVal = new StringBuilder (); // check whether it is null if (inputString! = Null) & (inputString! = String. empty) {inputString = inputString. trim (); // check the length if (inputString. length> maxLength) inputString = inputString. substring (0, maxLength); // Replace the dangerous character 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 ("'", ""); // Replace single quotes} return retVal. toString ();}/**/////// Convert to HTML code //////String ///
 
  
String
 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", ""); return str ;}/**/////// Parse html into plain text //////String ///
 
  
String
 Public static string Decode (string str) {str = str. replace ("", "\ 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 (",", ""); // remove, sqlText = sqlText. replace ("<", ""); // remove <SqlText = sqlText. replace (">", ""); // remove> sqlText = sqlText. replace ("--", ""); // remove -- sqlText = sqlText. replace ("'", ""); // remove 'sqltext = sqlText. replace ("\" "," "); // remove" sqlText = sqlText. replace ("=", ""); // remove = sqlText. replace ("%", ""); // remove % sqlText = sqlText. replace ("", ""); // remove space return sqlText;} # endregion // whether it is composed of specific characters # Whether region is composed of specific characters public static bool isContainSameChar (string strIn Put) {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 // check whether the input parameter is a special character defined: this method is currently used for security check of password input # region check whether the input parameter is a special character defined: This method is currently used for security check of Password Input /**/////// Check whether the input parameter has some defined special characters: This method is currently used for Password Input security check ///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}


 

Invalid Access Control


Broken Access Control

Most enterprises are very concerned about controlling established connections. However, allowing a specific string input can bypass the control of the enterprise.

Solution:

Use the Atho2 method to verify the user's identity; Save the AccessToken to the Cookie; set the Cookie failure policy;

Of course, in the distributed architecture, users need to manage user sessions in a centralized Redis cluster, but they are stateless at the application level.

Invalid account and thread management


Broken Authentication and Session Management

Good access control does not mean everything is fine. Enterprises should also protect users' passwords, session tokens, account lists, and any other information that can provide attackers with favorable information and help them attack the enterprise network.
 

Cross-Site Scripting


Cross Site Scripting Flaws

This is a common attack. When an Attack Script is embedded into an enterprise's Web page or other Web resources that can be accessed, a desktop without protection can access this page or resource, the script will be started. This attack can affect the terminal computers of hundreds of employees in the enterprise.
Solution: filter all possible input items

Cache Overflow


Buffer Overflows

This problem usually occurs in programs written in earlier programming languages, such as C language. This programming error is also caused by the lack of a good determination of the location of the input content in the memory.
 

Injection attacks


Injection Flaws

If the input content with syntax meanings is not successfully blocked, it may lead to illegal access to the database information. The content entered in the Web form should be kept simple, and should not contain executable code.
Solution:

1. Verify the possible service SQL Injection locations on the server;

2. SQL variables are used for SQL statement queries (highly recommended)

3. Use a common method to check whether special characters exist.

 

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");    //            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;        }    }}


 

Exception Handling


Improper Error Handling

When an error occurs, it is normal to submit the error message to the user. However, if the submitted error prompt contains too much content, attackers may analyze the structure or configuration of the network environment.
Solution: Web. config, which contains the following error configurations:

 

      
       
   
  
 


 

Insecure storage


Insecure Storage

For Web applications, it is very important to properly store passwords, user names, and other information related to identity authentication. encryption of such information is very effective, however, some enterprises will adopt unverified encryption solutions, which may have security vulnerabilities.
Solution: use MD5 encryption twice for the password and verify the complexity of the password.

Program Denial of Service Attack


Application Denial of Service

Similar to DoS attacks, DoS attacks take advantage of a large number of illegal users to seize application resources, so that legal users cannot use the Web application.

Code solution:

Solution: 1. One of the methods to avoid XSS is to filter the content input and output provided by users. Server. HtmlEncode () of ASP. NET or a more powerful Microsoft Anti-Cross Site Scripting Library. 2. The following is a general method for filtering the overall website. 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 ;}} at Global. the Application_BeginRequest in asax calls the above method for processing. The Code is as follows: protected void Application_BeginRequest (Object sender, EventArgs e) {string q ="

Your submission has invalid parameters! "; 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


Insecure Configuration Management

Effective configuration management can provide good protection for Web applications and enterprise network architecture.

Insecure network transmission

Solution: Encrypt Sensitive data

Use a secure transmission channel (private network, or VPN)

Adopt encryption protocols such as Https

Network Data forgery

Adopt data encryption authentication

Network tampering

Data Authentication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.