Application security of JSP

Time:2022-5-13

1、 Overview
When network programming becomes more and more convenient, the system function becomes more and more powerful, but the security decreases exponentially. I’m afraid this is the misfortune and sadness of network programming. Various dynamic content generation environments have prospered www. their design goal is to give developers more power and end users more convenience. Because of this, system designers and developers must clearly consider the security issue as a consideration, and it is difficult to regret afterwards.   
From the perspective of security, the weakness of server-side WWW applications comes from a variety of interaction capabilities and transmission channels. They are tools that attackers can use to directly affect the system. When attackers look for and exploit system security vulnerabilities, they always bring pressure to system security. The common defense strategy against all these attacks is called input verification.   
From the same perspective, there are two main design errors that lead to safety problems:
·Poor access control, and
·Make implicit assumptions about the deployment environment.   
In the literature on security, there are many in-depth analyses on access control. Here we want to discuss the security management of the underlying implementation (code and configuration), and the environment we discuss is JSP. In other words, we will discuss various methods for malicious user input to disguise itself and change the predetermined behavior of the application, and consider how to verify the legitimacy of the input and reduce the undesirable detection of information and application interfaces.   
2、 JSP overview
JSP technology allows java code logic to be embedded into HTML and XML documents, which brings convenience to create and manage dynamic www content. JSP pages are pre processed by the JSP engine and converted into Java servlets. After that, if there is a request for JSP pages, the web server will respond with the corresponding servlet output results. Although JSP and servlet are functionally equivalent, compared with servlet, the dynamic content generation method of JSP is just the opposite: JSP embeds java code into documents rather than documents into Java applications. The syntax of these JSP components is similar to that of the external markup, which provides additional access to these JSP components. It is worth noting that HTML syntax belongs to a subset of JSP syntax (a pure HTML document is a legal JSP page), but the reverse is not necessarily correct. In particular, in order to facilitate the dynamic generation of content and format, JSP allows other tags to be embedded in tags. For example, the following is a legal JSP code:
<A HREF = “<%= request.getRemoteUser() %>”>  
As can be seen from the later part of this paper, this structure increases the complexity of security problems.   
Compared with CGI, JSP has better performance and session management (i.e. session state persistence) mechanism. This is mainly realized by using java threads to process multiple servlets in the same process, while CGI generally requires to create and dismantle a process for each request.   
3、 Security issues
The worm may not access the entire Internet server or the whole server through the open JSP, which may even affect the security of the entire server or server. People often assume that Java, as a type safe, garbage collection capable language with sandbox mechanism, can miraculously ensure software security. In fact, many low-level security problems in other languages, such as buffer or heap overflow, rarely harm Java programs. However, this does not mean that it is difficult to write unsafe Java programs, especially for writing servlets. Verifying input and controlling access to resources is always a concern. In addition, the architecture of JSP is quite complex, including many cooperative subsystems. The interaction between these subsystems is often the root of security risks. In addition, although all JSP implementations now revolve around Java, the JSP specification allows almost all other languages to play this role. In this way, the security of these alternative languages must also be considered.   
In short, there are many opportunities for security vulnerabilities in JSP system. Below we will discuss the most common parts of them.   
4、 General problems of untrusted user input
Untrusted user input actually contains all user input. User input comes from the client and can reach the server through many different ways, sometimes even disguised. The user input provided for the JSP server includes (but is not limited to):
·The parameter part of the request URL
·Data submitted by HTML form through post or get request
·Data temporarily saved 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 control the vulnerable part of the server by modifying the input data. The vulnerable part of the server is often represented by some data access points, which are identified by the qualifier provided by the user or obtained by executing external programs.   
JSP can call the local code stored in the library (through JNI) and execute external commands. The runtime class provides an exec () method. The exec () method treats its first parameter as a command line that needs to be executed in a separate process. If some parts of the command string must be obtained from user input, the user input must be filtered to ensure that the commands executed by the system 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 executing external commands. In some cases, an attacker may modify the environment variables of the server to affect the execution of external commands. For example, modify the path environment variable to point to a malicious program disguised as the name of the program called by exec (). To avoid this danger, it is a good practice to explicitly set environment variables before making any external calls. The specific setting method is: in the exec () call, take an array of environment variables as the second parameter, and the elements in the array must be in the format of name = value.   
A similar problem occurs when the user enters any type of input / output stream used to identify the program open. Access to files, databases, or other network connections should not rely on unauthenticated user input. 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 JSP code fragment accessing the JDBC API is very unsafe, because an attacker can embed characters separating commands in the input he submits, so as to achieve the purpose of executing dangerous commands:
<%@ page import=”java.sql.*” %> <!– Add some code to open SQL Server connection — > <% 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 will ignore the entire query, but some versions of SQL server will execute two commands. If it is the latter, the attacker can access the database resources that he is not authorized to access (assuming that the web server has access rights).   
Proper input verification can prevent such problems.   
5、 Input verification
From a security point of view, input verification includes syntax checking and sometimes semantic checking of data from external data sources (untrusted data sources, see the previous description). Depending on the criticality of the application and other factors, the actions taken as input inspection results may be one or more of the following:
·Ignore grammatical insecurity
·Replace the unsafe part with safe code
·Abort the use of the affected code
·Report errors
·Activate an intrusion detection system.   
Input verification can be carried out according to one of the following two modes: listing unsafe characters and rejecting them; Define a set of safe characters, and then exclude and reject unsafe characters. These two modes are called forward and reverse input filtering respectively. In general, forward input filtering is simpler and safer, because many times, it is not easy to list characters that may be misunderstood by server-side applications, client browsers, web servers and operating systems.   
Please refer to the example of input verification in the “attack through embedded tags” section below this article, which demonstrates how to avoid misunderstandings of maliciously submitted input.   
6、 Sensitive data in get requests and cookies
As defined by CGI protocol, the simplest way to transfer request data from client to server is get request method. When using the get request method, after the input data is attached to the request URL, the format is as follows:
URL[?name=value[&name=value[&…]]]
Obviously, this encoding method is not appropriate for transmitting sensitive data, because usually, the whole URL and request string pass through the communication channel in clear text. All routing devices can record this information like the server. If we want to transmit sensitive data in customer requests, we should use the post method, plus an appropriate encryption mechanism (for example, through SSL connection). From the perspective of JSP engine, to a large extent, it doesn’t matter which transmission method to use, because they are handled in the same way.   
In the development of WWW, Netscape introduced the concept of cookie. Cookies are a small amount of information saved by the server to the client. The server extracts this information to maintain the session state or track the activity of the client browser. JSP provides an addcookie () method of response implicit object, which is used to set cookies on the client; A getcookie () method of the request () object is provided to extract the contents of the cookie. Cookies are javax servlet. http. An instance of the cookie class. For two reasons, if sensitive data is saved to a cookie, the security is threatened: first, all the contents of the cookie are visible to the client; Second, although browsers generally do not provide the ability to forge cookies, nothing can prevent users from answering the server with completely forged cookies.   
Generally speaking, the information submitted by any client browser cannot be assumed to be absolutely safe.   
7、 Attacks via embedded Tags
CERT advisory ca-2000-02 describes the problem of customers embedding malicious HTML tags in requests. This problem is generally referred to as “cross site scripting”, but its name is misused because it is not only related to scripts, but also has nothing special to do with “cross site”. However, when the name appeared, the problem was not widely understood.   
This attack usually contains a sick script submitted by the user, or contains malicious HTML (or XML) tags, which will be introduced into the dynamically generated page by the JSP engine. This attack may be directed against other users or against servers, but the latter is less common. Typical examples of “cross site scripting” attacks can be seen on forum servers, which allow users to embed formatting tags in their submitted articles. Generally, the abused tags are those that can embed code into the page, such as < script >, < Object >, < applet > and < embed >. In addition, some tags can also pose risks. In particular, < form > may be used to deceive browsers to expose sensitive information. The following is an example of a request string containing a malicious tag:
http://server/jsp_script.jsp?poster=evilhacker& message=<SCRIPT>evil_code</SCRIPT>
To prevent this problem, of course, it depends on input inspection and output filtering. Such checks must be performed on the server side and should not rely on client-side scripts (such as JavaScript), because nothing can prevent users from evading the client-side verification process.   
The following code snippet demonstrates how to check embedded tags on the server side:
<!– End of HTML code — > <% 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: < HR / > < TT > <% = message% > < / TT > < / HR / > < / P >! — add other HTML codes below — >
Since it is difficult to list all illegal characters, a safer way is to forward filter, that is, discard (or convert) all characters except those that are actually allowed to appear (such as [a-za-z0-9]).   
8、 Description of JavaBean
According to a series of conventions described in JavaBean specification, JSP can quickly and easily access reusable components (Java objects) in JSP pages. Each JavaBean component encapsulates some data and functions that can be used independently of the calling environment. Beans contain data members (properties) and implement standard APIs for accessing these properties through get and set methods.   
To quickly initialize all the attributes of the specified bean, JSP provides a shortcut, that is, provide the name = value pair in the query string and make it match the name of the target attribute. Consider the following example of using beans (shown in XML format):
< jsp: usebean id = “mybasket” class = “basketbean” / > < jsp: setproperty name = “mybasket” property = “*” / > < jsp: usebean > < HTML > < head > < title > your shopping basket < / Title > < / head > < body > < p > you have added the goods: < jsp:: getproperty name = “mybasket” property = “newitem” / > to the shopping basket < br / > the amount is $< jsp:: getproperty name = “mybasket” property = “balance” / > prepare < a href = “checkout. JSP” > payment</a>
Note the wildcard “*” used in the setproperty method call. This symbol instructs the JSP to set the values of all properties specified in the query string. According to the original intention, the script is called as follows:
http://server/addToBasket.jsp?newItem=ITEM0105342
Normally, the query string constructed by HTML form is in this form. The problem is that nothing prevents users from setting the balance attribute:
http://server/addToBasket.jsp? newItem=ITEM0105342&balance=0
When processing the < jsp: setproperty > tag of the page, the JSP container will map this parameter to the balance property with the same name in the bean and try to set the property to 0.   
In order to avoid this problem, JSP developers must implement some security measures in the set and get methods of the bean (the bean must enforce access control on the property). At the same time, they should also be careful when using the wildcard of < jsp: setproperty >.   
9、 Implementation vulnerabilities and source code security
No matter what kind of JSP implementation, at a certain stage, some versions of them will bring dangerous security risks to the system. Even if JSP developers follow safe programming practices, it will not help. For example, in a version of jrun of Allaire, if the request URL contains the string “. JSP% 00” as part of the JSP script extension, the server will not ignore null bytes, and it will treat the page as a static non JSP page. In this way, the server will request the operating system to open the page, but at this time, the null byte is ignored. The result is provided to the user with the source code of the JSP page rather than the execution result of the page.   
Similarly, a version of Tomcat has a security risk. As long as the request class is in the following format, it will let the attacker see the source code of the JSP page:
http://server/page.js%2570
The trick here is that% 25 is the “%” of the URL code and 70 is the hexadecimal value of “P”. The web server will not call the JSP processor (because the URL does not end with “. JSP”), but the static file processor will try to map the URL to the correct file name (decode the URL again).   
In addition, many web servers and JSP implementations come with demonstration scripts, which often contain security risks. Barring access to all these scripts is good for security until the server is deployed to a malicious environment (i.e. the Internet).   
In short, JSP developers should be clear about the current security risks on the platform they are developing. Subscribing to bugtraq and mailing lists from all vendors is a good way to track this information.   
Concluding remarks
JSP is like any other powerful technology. If you want to ensure the security and reliability of the deployed system, you must be careful when applying JSP. In this article, we briefly discuss the common code and configuration level security problems in JSP scripts, and put forward some suggestions to reduce the security risks.   

Recommended Today

Unveil the mystery of HTML 5 working draft

The World Wide Web Consortium (W3C) released a draft specification for HTML 5, the first major revision of HTML 4 since it was released more than a decade ago During this period, as developers gradually transplant their applications to the web, it has developed from a major static media to an interactive application with rich […]