Example analysis of security problems in JSP application development

Source: Internet
Author: User
Tags array command line execution garbage collection html form html tags variables versions
js| Safety | procedure | Question one, overview
When the network programming becomes more and more convenient, the system function is more and more powerful, the security refers to several times drops. This is probably the tragedy and sadness of network programming. A variety of dynamic content generation environment has prospered www, their design goal is to give developers more power to the end users more convenient. Because of this, system designers and developers must explicitly consider security issues as a consideration, and hindsight is hard to work with.

From a security perspective, the vulnerabilities of server-side WWW applications come from a wide range of interactive capabilities and transmission channels. They are tools that attackers can use directly to influence the system. When attackers look for and exploit system security vulnerabilities, they always put pressure on system security. The common defense strategy against all of these attacks is the so-called input validation.

At the same level, there are two main types of design errors that cause security problems:

· Poor access control.

· Make implicit assumptions about the deployment environment.

In the literature on security, there are many in-depth analyses on the problem of access control. Here we will discuss security management issues on the underlying implementation (code and configuration), and the environment under discussion is JSP. Alternatively, we will discuss the malicious user input masquerading itself and the various methods of changing the application of predetermined behavior, considering how to validate input legality and reduce the unwelcome detection of information and application interfaces.

Second, JSP overview

JSP technology allows Java code logic to be embedded within HTML and XML documents, facilitating the creation and management of dynamic www content. JSP pages are processed by the JSP engine and converted to a Java Servlet, and then if a request for a JSP page appears, the Web server responds with the corresponding Servlet output.

While JSP and servlet are functionally equivalent, the JSP's dynamic content generation approach is the opposite of a servlet: JSP embeds Java code into a document rather than embedding it in a Java application. To access external functionality and reusable objects, JSP provides additional markup for interacting with JavaBean components, which are similar in syntax to HTML tags.

It is worth noting that HTML syntax is a subset of the JSP syntax (a pure HTML document is a valid JSP page), but the converse is not necessarily correct. Specifically, to facilitate the dynamic generation of content and formatting, JSP allows other tags to be embedded within the tag. For example, the following is a legitimate JSP code:


<a HREF = "<%= request.getremoteuser ()%>" >


As you can see later in this article, this structure increases the complexity of security issues.

Compared to CGI, JSPs have better performance and session-state persistence mechanisms. This is done primarily by using a Java thread within the same process to handle multiple servlet implementations, while CGI generally requires that a process be created and dismantled separately for each request.

III. Security Issues

Because access to server resources is completely open, unsafe servlet conversions from JSP pages can threaten either the server, the network on which the server resides, any one or all of the clients accessing the page, even through DDoS or worm distributed attacks, and may affect the entire Internet.

It is often assumed that Java, as a type-safe language with garbage collection capabilities, has a sandbox (Sandbox) mechanism that can magically guarantee software security. And in fact, many low-level security issues that exist in other languages, such as buffering or heap overflows, rarely harm Java programs.

However, this does not mean that it is difficult to write unsafe Java programs, especially for a servlet. Validating input and controlling access to resources is an issue that must always be a concern. In addition, the architecture of the JSP is quite complex, which contains many subsystems that collaborate with each other. The interactions between these subsystems are often the source of security risks.

In addition, although all JSP implementations now revolve around Java, the JSP specification allows almost all other languages to play the role. In this way, the security of these alternative languages must also be considered.

In short, there are quite a few opportunities to create security vulnerabilities in JSP systems. Here we will discuss the most common part of them.

General problems of non-confidence user input

The non-confidence user input (untrusted user input) actually contains all the user input. User input comes from the client and can be reached at the server side in many different ways, sometimes even disguised. The user input provided for the JSP server includes, but is not limited to:

· The parameter portion of the request URL;

· Data submitted by a post or GET request from an HTML form;

· Data that is temporarily stored on the client (i.e. cookies);

· database query;

· Environment variables set by other processes;

The problem with user input is that they are interpreted by the server-side application, so attackers can modify the input data to achieve the purpose of controlling the vulnerable part of the server. The vulnerable parts of the server often appear as data access points that are identified by the user-supplied qualifier or by executing an external program.

The JSP can invoke local code (via JNI) that is saved in the library and execute external commands. Class Runtime provides an exec () method. The exec () method treats its first argument as a command line that needs to be executed in a separate process. If portions of this command string must be entered from user input, user input must be filtered to ensure that the system executes commands and their parameters are expected.

Even if the command string has nothing to do with user input, the necessary checks must still be performed when the external command is executed. In some cases, an attacker could modify the server's environment variables to affect the execution of external commands. For example, modify the PATH environment variable to point to a malicious program that masquerades as the name of the program called EXEC ().

To avoid this danger, it is a good practice to explicitly set the environment variables before any external calls are made. The specific setting method is to use an array of environment variables as the second argument in the exec () call, and the elements in the array must be in name=value format.

Similar problems can occur when a user enters an arbitrary type of input/output stream that identifies a program open. You should not rely on untested user input when accessing files, databases, or other network connections. In addition, after opening a stream, it is not safe to send user input directly to it.

This is especially true for SQL queries. The following section of the JSP code that accesses the JDBC API is unsafe because an attacker can embed the character of a separate command in the input he submits to achieve the purpose of executing a dangerous command:

<%@ page import= "java.sql.*"%>
<!--here plus some open SQL
Server-connected Code-->
<% Statement stmt = Connection.getstatement ();
String query =
"SELECT * from user_records WHERE USER ="
+ Request.getparameter ("username");
ResultSet result =
Statement.executequery (query);
%>


If username contains a semicolon, for example:

Http://server/db.jsp? Username=joe;
Select%20*%20from%20system_records


Some versions of SQL Server ignore the entire query, but there are a few versions of SQL Server that will execute two commands. In the latter case, an attacker can access a database resource that is not otherwise eligible for access (assuming the Web server has access), and an appropriate input test can prevent such problems from appearing.

V. Input INSPECTION

From a security standpoint, input validation includes syntax checking of data from an external data source (an unsecured data source, see previous description), and sometimes semantic checking. Depending on the critical level of application and other factors, actions taken as input test results may be one or more of the following:

· Ignoring grammatical and unsafe ingredients;

· Replace the unsafe parts with safe code;

· Abort the use of the affected code;

· Report Errors;

· Activation of an intrusion detection system;

Input validation can be done in one of the following two modes: enumerating unsafe characters and rejecting them, defining a set of safe characters, and then excluding and rejecting unsafe characters. These two modes are referred to as forward and reverse input filtering respectively. In general, forward input filtering is simpler and more secure, because many times it is not easy to enumerate the characters that may be misunderstood by server-side applications, client browsers, Web servers, and operating systems.

Six, get requests, and sensitive data in cookies

As defined in the CGI protocol, the easiest way to transfer request data from the client to the server side is the GET request method. When you use the GET request method, the input data is appended to the request URL and is formatted as follows:

Url[?name=value[&name=value[& ...]]


Obviously, this encoding is not appropriate for transmitting sensitive data, as the entire URL and request string are normally passed through the communication channel in plaintext. All routing devices can log this information as well as the server. If you want to transmit sensitive data in a customer request, we should use the Post method plus an appropriate encryption mechanism (for example, through SSL). From the point of view of the JSP engine, to a large extent, which transport method is used is irrelevant, because the two are handled the same way.

During the development of WWW, Netscape introduced the concept of cookie. A cookie is a small amount of information that the server saves to the client and the server extracts the information to maintain session state or to track the activity of the client browser. JSP provides a Addcookie () method for response suppressed objects to set cookies on the client, and provides a GetCookie () method of the request () object to extract the contents of the cookie.

A cookie is an instance of a Javax.servlet.http.Cookie class. For two reasons, if you save sensitive data to cookies, security is compromised: first, the entire contents of the cookie are visible to the client; second, although browsers generally do not provide the ability to fake cookies, But nothing can prevent users from answering servers with completely bogus cookies. In general, no information submitted by any client browser can be assumed to be absolutely secure.

Attacks implemented through embedded markup

CERT advisory ca-2000-02 describes a problem in which a customer embeds a malicious HTML tag in a request. This problem is commonly referred to as the "Cross site scripting" problem, but its name is somewhat improper because it is not just about the script, but it has nothing to do with "crossing the Site" (Cross site). However, when the name appeared, the problem was not widely known.

This attack usually contains a sick script submitted by the user, or contains malicious HTML (or XML) tags that the JSP engine introduces to the dynamically generated page. This attack may be done for other users or for the server, but the latter is less common.

Typical examples of "Cross site scripting" attacks can be seen on the forum server because these servers allow users to embed formatting tags in their submitted articles. Often, the abused tags are those that can embed code into the page, such as:

<SCRIPT>, <OBJECT>, <APPLET> and <EMBED>.


There are also some signs that can be dangerous and, in particular, may be used to deceive visitors into exposing sensitive information. The following is an example of a request string containing a malicious token:

Http://server/jsp_script.jsp?poster
=evilhacker& message=
<SCRIPT>evil_code</SCRIPT>


To prevent this problem, you must rely on input checking and output filtering. Such checks must be done on the server side and should not be dependent on client script (such as JavaScript) because nothing can prevent the user from escaping the client-side validation process. The following code fragment demonstrates how to check for embedded markup on the server side:

<!--HTML code end-->
<% 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 (' + ', ' _ ');
%>
<p>


The message you submitted is:

</tt><!--add additional HTML code below-->


Since it is difficult to enumerate all the illegal characters, a more secure approach is to forward filtering, which is to discard (or convert) all other characters except those that are actually allowed to appear (for example, [a-za-z0-9]).

Viii. notes on the JavaBean

JSP quickly and easily accesses reusable components (Java objects) in JSP pages in accordance with a series of conventions described in the JavaBean specification. Each JavaBean component encapsulates data and functionality that can be used independently of the calling environment. The bean contains data members (properties) and implements a standard API for accessing these properties through the get and set methods.

To quickly initialize all the properties of the specified bean, the JSP provides a shortcut that provides a name=value pair in the query string and matches the name of the target attribute. Consider the following example of using a bean (shown in XML format):

<jsp:usebean id= "Mybasket"
class= "Basketbean" >
<jsp:setproperty name= "Mybasket"
property= "*"/> <jsp:useBean>
<body> <p> You have put the product:
<jsp::getproperty name= "Mybasket"
property= "NewItem"/> added to the shopping basket
<br/> amount is $ <jsp::getproperty
Name= "Mybasket" property= "balance"/>
Prepare <a href= "checkout.jsp" > Payment </a>


Note the wildcard symbol "*" used in the SetProperty method call. This symbol indicates that the JSP sets the value of all the properties specified in the query string. As intended, the script is invoked in the following way:

http://server/addToBasket.jsp?newItem=ITEM0105342


Normally, this is the form of a query string constructed by an HTML form. But the problem is that nothing prevents users from setting the Balance property:

Http://server/addToBasket.jsp?
Newitem=item0105342&balance=0


When processing the markup for a page, the JSP container maps This parameter to the Balance property with the same name in the bean and attempts to set the property to 0.

To avoid this problem, the JSP developer must implement some kind of security measure in the Bean's set and get methods (the bean must enforce the access control on the attribute), and should also be cautious when using wildcard characters.

IX. implementation vulnerabilities and source code security

Regardless of which JSP implementations, at some stage, some versions of them can pose a dangerous security risk to the system, even if the JSP developer complies with the security programming practices. For example, in a version of JRun in Allaire, if the request URL contains the string ". Jsp%00" as part of the JSP script extension, the server does not ignore null bytes, and it treats the page as a static, non-JSP page, and so on.

In this way, the server requests the operating system to open the page, while null bytes are ignored and the result is provided to the user with the source code of the JSP page instead of the results of the page execution.

Similarly, one version of Tomcat also has a security risk. As long as the request class is in the following format, it allows an attacker to see the source code for the JSP page:

http://server/page.js%2570


The trick here is that%25 is the URL-encoded "%" and 70 is the hexadecimal value of "P". The Web server does not invoke the JSP processor (because the URL does not end with ". JSP"), but the static file processor manages to map the URL to the correct file name (again decoding the URL).

In addition, many Web servers and JSP implementations have demonstration scripts that often contain security vulnerabilities. It is safe to disable access to all of these scripts before deploying the server to a rogue environment, the Internet.

In short, the JSP developer should be clear about what security risks are currently on the platform they are developing. Subscribing to Bugtraq and mailing lists from all vendors is a good way to track this type of information.

Conclusion

JSP is the same as any other powerful technology. If you want to ensure the security and reliability of your deployed systems, you must be cautious when applying JSP. In this article, we briefly discuss code and configuration-level security issues that often occur in JSP scripts, and offer suggestions to reduce the security risks associated with them.


http://server/page.js%2570


The trick here is that%25 is the URL-encoded "%" and 70 is the hexadecimal value of "P". The Web server does not invoke the JSP processor (because the URL does not end with ". JSP"), but the static file processor manages to map the URL to the correct file name (again decoding the URL).

In addition, many Web servers and JSP implementations have demonstration scripts that often contain security vulnerabilities. It is safe to disable access to all of these scripts before deploying the server to a rogue environment, the Internet.

In short, the JSP developer should be clear about what security risks are currently on the platform they are developing. Subscribing to Bugtraq and mailing lists from all vendors is a good way to track this type of information.



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.