Analysis of web Security

Source: Internet
Author: User
Tags sql injection attack least privilege

1.1 System Security 1.1.1 Client Script security

(1) Cross-site scripting attacks (XSS):

XSS attacks, often referred to as hackers through "HTML injection" tampered with the Web page, inserted a malicious script, so that when users browse the Web page, control the user browser an attack.

The most common XSS attack is to initiate a "cookie hijacking" by reading the browser's cookie object, and the current user's login credentials are stored in the server's session, which is stored as a cookie in the browser, and after the cookie is hijacked, means that an attacker could log on directly to the system without a password. We can also enter the script Javascript:alert (Document.cookie) directly in the browser to get the current cookie value.

The current method of preventing "cookie hijacking" is broadly: a. Input check, use filter to filter sensitive keywords; b. Bind the cookie to the user's IP address, c. Implant the HttpOnly logo for the cookie.

This system uses the 3rd way: To insert the HttpOnly logo for the cookie. Once this httponly is set, you will not see the cookie in the browser's document object, and the browser will not be affected when browsing, because the cookie is placed in the browser header (including Ajax), Applications also generally do not operate these sensitive cookies in JS, for some sensitive cookies we use HttpOnly, for some need in the application of JS operation of cookies We do not set, so that the security of the cookie information is guaranteed to ensure the application.

Specific code implementation: in the Web server Tomcat configuration file Server.xml add:

<context docbase= "E:\tomcat\apache-tomcat-6.0.24/webapps/netcredit" path= "/netcredit" reloadable= "false" Usehttponly= "true"/>

or the Web. XML configuration of the project is as follows:

<session-config>         <cookie-config>            

Figure 1-1 Browser Cookie

(2) Cross-site request forgery (CSRF):

The system adopts the most effective defense method against CSRF: verification code.

1.1.2 Server-Side Application security

Server-side security is significantly more important than the client, because a security vulnerability on the server side can be a fatal risk. Therefore, we are more cautious and attention to server-side security.

(1) SQL injection attack:

SQL injection of two key conditions: The first is the user to control input, the second is the original program to execute code, splicing the user input data.

Based on the two key conditions above, the system uses the following methods to prevent SQL injection:

First: Using precompiled statements, which is the most effective way to protect against SQL injection, completely rejects the danger of direct splicing of code.

Public list<t> findbypage (final String hql, final object[] values, final int offset,           final int pageSize) {       L ist<t> list = Gethibernatetemplate (). Executefind (New Hibernatecallback () {public           Object doinhibernate ( Session session)              throws Hibernateexception, sqlexception{              Query query=session.createquery (HQL);              for (int i = 0; i < values.length; i++) {                  query.setparameter (i, values[i]);              }              if (! ( Offset==0 && pagesize==0) {                  query.setfirstresult (offset). Setmaxresults (pageSize);              }              list<t> result = Query.list ();              return result;           }       );    return list;    }

Second: Turn off the error echo feature of the Web server, which can prevent an attacker from attacking the system and making adjustments to the attacker's content by echoing the detailed error message, providing great convenience to the attacker. We add the following sample code to the project's Web. xml file:

    <error-page>        <error-code>400</error-code>        <location>/error400.jsp</location > </error-page> .....    

Third: The database itself uses the principle of least privilege, the system program does not use the highest-privileged root to connect to the database, but the use of the minimum rights to meet the system requirements of the database connection, and the use of different accounts between the multiple databases, to ensure that each database has a separate corresponding account.

(2) File Upload vulnerability:

File upload vulnerability refers to the user uploading an executable script file and the ability to execute server-side commands through a script file, which can lead to serious consequences. And this system involves a lot of picture format file upload, so the handling of uploading problem is very cautious, and as far as possible to achieve security standards.

This system mainly through the upload file detailed format verification:

The first step: The file format is simply judged by the suffix name.

public static Boolean ispicture (String pinput) throws exception{      //Get file suffix      String tmpname = pinput.substring ( Pinput.lastindexof (".") + 1,                                  pinput.length ());      Declare picture suffix an array group      String Imgearray [] = {"JPG", "PNG", "JPEG"};      Iterate over the name array      for (int i = 0; i

The second step: by reading the first two characters of the file to compare, for example, the PNG format picture's first two characters are 8950, and the JPG format picture first two characters is Ffd8.

public static String bytestohexstring (byte[] src) {        StringBuilder StringBuilder = new StringBuilder ();        if (src = = NULL | | src.length <= 0) {            return null;        }        for (int i = 0; i < Src.length, i++) {            int v = src[i] & 0xff;//byte to int            String HV = integer.tohexstring ( v);            if (Hv.length () < 2) {                stringbuilder.append (0);            }            Stringbuilder.append (HV);        }        return stringbuilder.tostring ();    }  

The third step: if the upload is a picture, then get the corresponding height and width, if there is a corresponding width and height can be considered to upload a picture.

public static Boolean isimage (File imagefile) {        if (!imagefile.exists ()) {            return false;        }        Image img = null;        try {            img = imageio.read (imagefile);            if (img = = NULL | | img.getwidth (NULL) <= 0 | | img.getheight (NULL) <= 0) {                return false;            }            return true;        } catch (Exception e) {            return false;        } finally {            img = null;        }   }

If the above verification is successful, the system will rename the file name when storing the files, and set the corresponding Web server, the directory is not displayed by default. Because file uploads require the user to be able to access the file if the code needs to be executed, overwriting the file name with a random number will greatly increase the cost of the attack and even fail to successfully implement the attack at all.

Rename the name of the file StringBuilder sb = new StringBuilder (). Append (New Date (). GetTime ()). Append ("."). Append (filemsg[1]);

(3) Certification Session Management:

Authentication is actually a process of verifying credentials, so we have strict rules for login passwords: Passwords require more than 8 digits in length and contain letters, numbers, and symbols in more than two combinations. and encrypt the password before storing the database. In order to prevent some violent cracking means, but also for the user experience, the system uses the user to log on by default does not carry out the verification code input, but the password three times the input failure needs to verify the code input, five consecutive input errors, the user's IP address will be sealed, Can be automatically unpacked after a period of time or the background administrator to manually unpack. Related to the operation of the system funds, such as bidding, we also need the user set up and provide payment password, and withdrawals and other operations we also equipped with SMS verification code function. To enhance the reliability of the verification.

When the user login is completed, a new session is created on the server side, the user's status and related information is stored in the session, the server maintains the session of all the online users, and the browser is SessionID encrypted and stored in the cookie. Here comes the "cookie hijacking" issue mentioned earlier, which was successfully resolved by embedding HttpOnly in cookies. The system also set a valid time to the session, to ensure that the session will be automatically destroyed after the effective time, in order to prevent the session long connection to the security risks. Add the following code to the Web. xml file:

<session-config>     <session-timeout>30</session-timeout></session-config>

(4) Access control:

Access control is actually to establish the corresponding relationship between users and permissions, the system uses "role-based access control", according to the corresponding function module division of the corresponding permissions, and assign the appropriate permissions to different roles, and then assign the role to the user, the user has the role of the rights held. For specific design and implementation analysis See 1.2 annotation and Struts2 interceptors for role-based vertical rights management.

1.2 Annotation and Struts2 interceptors implement role-based vertical rights Management 1.2.1 Module design

The following is the physical model design of the system's vertical Rights Management module:

Figure 1-2 Physical model of the Rights Management module

There is a many-to-many relationship between the administrator and the role, so that one administrator can be assigned multiple roles for management, and the roles and permissions are many-to-many relationships, and the permissions are divided according to the function module, so that the role can be fine-grained permission assignment.

Code implementation of the 4.3.2 module

First, the annotation class is declared, and the annotation class is customized, and the corresponding annotations are defined according to the functionality of the implementation that we need, so that the corresponding annotations are used for the method that needs to be commented upon, and the code is as follows:

@Retention (retentionpolicy.runtime)//annotations survive, the entire runtime is Alive @Target (Elementtype.method)//This annotation indicates that only the method has     Effect public @interface Permission {/** module name **/String model ();    /** Permission value **/String privilegevalue (); /* To distinguish whether the current page is dialog or navtab*/String targetType ();} Then define the appropriate interceptor class, and in the Struts2 configuration file struts.xml The interceptor configuration, for the corresponding required classes for interception verification, the definition of the interceptor part of the core code is as follows:/** * Checksum control on the method of interception/@SuppressWarn           Ings ("Unchecked") public Boolean validate (admin admin, actioninvocation Invocation, list<role> rolelist,                                  Map session) {String methodname= "execute";       Defines the default access method Currentmethod = null;                MethodName = Invocation.getproxy (). GetMethod (); By Actionproxy, get the currently executing method name try {//Take advantage of reflection, get concrete method by method Name Currentmethod = Invocation.getproxy (). GE       Taction (). GetClass (). GetMethod (MethodName, new class[] {});       } catch (Exception e) {e.printstacktrace (); } if (CURrentmethod! = null && currentmethod.isannotationpresent (Permission.class)) {//Get Permission annotations on method           Permission Permission = currentmethod.getannotation (Permission.class); The system permissions are constructed through permission annotations systemprivilege privilege = new Systemprivilege (New Systemprivilegeid (permission.privile           Gevalue (), Permission.model ()));           Session.put ("TargetType", Permission.targettype ()); Iterates over the specific permissions that the user has, if included, returns True for (Role role:rolelist) {Roleprivilege Roleprivileg              E = new Roleprivilege (privilege, role);              if (Role.getroleprivileges (). Contains (Roleprivilege)) {return true;       }} return false; } return true;

The system needs to add the corresponding function module to the permission table, in order to have a relatively fine granularity, the module will be divided according to the function, and the permission is subdivided according to the button:

Figure 1-3 Database

After defining the appropriate permissions, we need to comment on the corresponding execution method body, which allows the interceptor to obtain the module and permission type of the executing method body according to the comment when it intercepts the validation:

@Permission (model= "Recharge", privilegevalue= "recharge", targettype= "dialog")
Implementation of the 4.3.3 module

First add the appropriate employee:

Then add the appropriate role, fill in the Role name and check the appropriate permissions:

Then add the appropriate user, tick the corresponding role of the user, you can select multiple roles, and select the appropriate user corresponding employees:

Analysis of web Security

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.