Common security vulnerabilities in web development and ways to avoid them

Source: Internet
Author: User
Tags httpcontext md5 encryption md5 hash throw exception xml attribute

1. Security attacks

1, SQL, HTML, JS, os command injection

2, XSS Cross-site scripting attacks, using trusted users in the site, insert malicious script code on the Web page

3. CSRF Cross-site request forgery, leveraging trusted Web sites by disguising requests from trusted users.

4. Directory Traversal Vulnerability

5. Parameter tampering

6. Session Hijacking

2. Summary of measures to prevent attacks

1) Perform a thorough security check or filter on the data entered by the user, paying particular attention to checking for the inclusion of SQL or XSS special characters.

Validating user-entered data, including values, types, scopes, and so on, validation with validation controls RequiredFieldValidator RangeValidator RegularExpressionValidator

These checks or filters must be performed on the server-side client. Client service side to verify, the client in order to improve the user experience, the server can effectively prevent threats

2) do not use a database connection with administrator privileges, do not use dynamic stitching SQL

3) Confidential information is encrypted and cannot be used in clear text

4) When each page is loaded, judge the legality of the user.

5) sensitive information in the session after login needs to be encrypted to avoid storing sensitive information in permanent cookies, and important cookies are marked as HTTP only

6) Use SSL, post when sending sensitive information, use new Web HSTs security protocol as far as possible

7) Do not throw the details of the exception directly to the user, return the friendly page unexpectedly, prevent the user from seeing sensitive information

8) Configure the firewall at the interface between the server and the network to block the scanning and detection of the server by the outside user.

9) Restrict the background access to the website, such as: Prohibit public IP access to the background, prohibit the waiter to use weak password.

10) Turn off the Windows 8.3 format feature. The command mode under the DOS system is 8.3 format, that is, the file name is not more than 8 characters and the extension is not more than 3 characters. Shape:???. Exe.

The Windows System file name is now up to 255 characters long.

11) Restrict access to sensitive pages or directories.

12) Use vulnerability scanning software, such as IBM Appscan,uniswebscanner, to evaluate security before the project is released.

Security Vulnerabilities and Prevention:

1. SQL Injection Vulnerability
1, in the framework of the harmful statements and symbols built into the filter, such as Insert ' Update, filter in the base class, this kind of class will not care to avoid these common attacks

 <summary>///filter The injection script in the SQL statement string///</summary>//<param name= "source" > Incoming characters        Strings </param>////<returns> filtered strings </returns> public static string Sqlfilter (string source) {if (string.            IsNullOrEmpty (source)) {return ""; }//single quotation mark replaced with two single quotes Source = source.            Replace ("'", "" "); Source = source.            Replace ("\" "," "); Source = source.            Replace ("&", "&amp"); Source = source.            Replace ("<", "&lt"); Source = source.            Replace (">", "&gt"); Source = source.            Replace ("delete", ""); Source = source.            Replace ("Update", ""); Source = source.            Replace ("Insert", ""); The half-width number is replaced with the full-width number, which prevents multiple statements from executing Source = source.            Replace (";", ";"); The half-width bracket is replaced by the full-width bracket Source = source.            Replace ("(", "("); Source = source.            Replace (")", ")"); ///////////To replace with regular expressions, prevent the case of letters//////////////////////Remove the command keyword that executes the stored procedure Source = source.            Replace ("Exec", ""); Source = source.            Replace ("Execute", ""); Remove the system stored procedure or the extended stored procedure keyword Source = source.            Replace ("Xp_", "x P_"); Source = source.            Replace ("sp_", "s P_"); Prevents 16-binary injection of Source = source.            Replace ("0x", "0 x");        return source; }


     2, persist in parameterized assignment
     3, do not directly throw exception details to the user, return friendly pages unexpectedly, prevent users from seeing the details of the database, When you close the customerrors of Web. config, you may not see it.
         <system.web>
              <compilat Ion debug= "true" targetframework= "4.0"/>
        &NBSP;</SYSTEM.WEB>
2, XSS is also called Css--cross site script cross-site scripting attack
     1, clean user input, filter JS code, filter special characters
          [1] <> (angle brackets)     [5]; (semicolon)
          [2] "(quotation marks)     &NBS P     [6] () (brackets)
          [3] ' (single quote)         [7] & (& symbol) br>          [4]% (percent sign) [8] + (plus)
    &NBSP;2, Use the methods in the Httpuitility and Antixsslibrary class libraries to manipulate HTML code

Assignment does not bounce box This.lblName.Text = Encoder.htmlencode ("<script>alert (' OK ');</script>");

Coding method Usage Scenarios
HtmlEncode (String) Untrusted HTML code.
Htmlattributeencode (String) Untrusted HTML Properties
Javascriptencode (String) Untrusted input is used in JavaScript
UrlEncode (String) Untrusted URLs
Visualbasicscriptencode (String) Untrusted input is used in VBScript
Xmlencode (String) Untrusted input FOR XML output
Xmlattributeencode (String) Untrusted input as an XML attribute


3, user information with MD5 encryption

       #region MD5 Encryption///<summary>//Get MD5 hash value///</summary>//<param name=  "Text" > String </param>//&LT;RETURNS&GT;MD5 hash </returns> public static string Getmd5hash (string Text) {MD5 MD5 = MD5.            Create ();            byte[] data = Md5.computehash (Encoding.Default.GetBytes (Text));            StringBuilder builder = new StringBuilder (); for (int i = 0; i < data. Length; i++) {Builder. Append (Data[i].            ToString ("X2")); } return builder.        ToString (); }///<summary>//Verify MD5 hash value///</summary>//<param name= "Text" > String </p aram>//<param name= "Texthash" > Hash value </param>//<returns> same return True, different return False</return s> public static bool Verifymd5hash (string Text, String texthash) {string hash = Getmd5hash (T            EXT); StringcompareR comparer = Stringcomparer.ordinalignorecase;            if (0 = = Comparer.compare (hash, Texthash)) {return true;            } else {return false; }} #endregion

  

4, when the page load to determine whether the user is logged in, if not logged on to the login interface, each page inherits the base class Basecontrol

  protected override void OnActionExecuting (ActionExecutingContext filtercontext)        {            //authentication            if ( CurrentUser = = null)            {                string request = System.Web.HttpContext.Current.Request.Headers.Get (" X-requested-with ");                if (string. Compare (Request, "XMLHttpRequest", true) = = 0)                {                    Filtercontext.result = new Jsonresult {Data = "login timeout, please refresh the page!" " };                    FilterContext.HttpContext.Response.ContentType = "Text/plain;charset=utf-8";                    FilterContext.HttpContext.Response.Status = "403 Internal Server Error";                    FilterContext.HttpContext.Response.StatusCode = 403;                }                else                {                    Filtercontext.result = new Redirectresult ("~/login/sessionouttime");                }            }        }

  

See:

Web vulnerability: Various injections, attacks

Several common vulnerability resolution methods for Web development

Common Security issues in PHP development and solutions (e.g. SQL injection, CSRF, XSS, CC, etc.)

Common security vulnerabilities in web development and ways to avoid them

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.