Reposted: Java server-side programming security must read

xiaoxiao2021-03-06  46

I. Overview Writing Secure Internet Application is not a light and easy thing: Just look at each professional bulletin board can find a continuous security vulnerability report. How do you guarantee your own Internet app is not like other people's apps? How do you guarantee that your name does not appear in a uncomfortable major security incident report? If you use Java Servlet, JavaServer Pages (JSP), or EJB, many difficult problems have been resolved in advance. Of course, the vulnerability is still possible. Let's take a look at what these vulnerabilities are, and why Java programmers don't have to worry about the problem of some C and Perl programmers must face. C programmers should be familiar with security vulnerabilities, but engineering such as OpenBSD provides security systems that handle such issues. Java language handles this problem with this problem 20 years, but on the other hand, Java is born as a client programming language, and the client's requirements are much more demanding than the server. It means that Java's development has a solid security basis. Java original positioning goals are browser. However, although the Java virtual machine belled in the browser itself is very good, it is not perfect. Sun's "Chronology of Security-Related Bug and Issues" summarizes the vulnerability discovery history of the runtime environment. We know that these vulnerabilities cannot be used as an attack tool when Java is used as a server-side programming language. However, even if Java serves as a client programming language, the number of major security issues has also dropped from 6 in 1996 (three of whom are quite serious) to 1 2000. However, this safety relative increase does not mean that Java is absolutely safe as a server-side programming language, which means that the attack means that the attacker can use is getting more and more restrictions. So, what places are easy to attack, how do other programming languages ​​face similar problems? Second, the cache overflows in the C program, cache overflow is the most common security hazard. The cache overflow appears when the user input exceeds the assigned memory space (exclusive for user input). Cache overflow may become a key factor that caused application coverage. The C procedure is easy to cache, but the Java program is almost impossible to cache. C code read from the input stream input data is usually as follows: CHAR BUFFER [1000]; int Len = read (buffer); due to the size of the cache before reading data, the system is to check if the cache is enough. It is very difficult. The cache overflow enables the user to overwrite the key part of the program data structure, resulting in a secure hidden danger. Experienced attackers can use this to directly insert code and data into the running program. In Java, we generally save user input with a string instead of a character array. Java code equivalent to the front C code is as follows: string buffer = in.readline (); "Cache" size is always identical to the size of the input content. Since the Java string cannot be changed after the creation, the cache overflow is impossible. Take another step, even if you use a character number to replace the string as a cache, Java is not like C, which is easy to produce security vulnerabilities that can be utilized by an attacker. For example, the Java code below will generate overflow: char [] bad = new char [6]; bad [7] = 50; this code always throws a java.lang.Arrayoutofboundsexception exception, and this exception can be self-contained Capture: try {char [] Bad = new char [6]; BAD [7] = 50;} Catch (arrayoutofboundsexception ex) {...} This processing process will never lead to unpredictable behavior.

No matter what method, we always get an ARRAYOUTOFBOUNDSEXCEPTION, while the underlying environment of Java can protect itself from any infringement. In general, when using the Java string type to handle strings, we don't have to worry about the arrayoutofboundsexceptions of strings, so it is a more ideal choice. Java programming mode fundamentally changes the processing method of the user input, avoiding the input cache overflow, so that the Java programmer gets rid of the most dangerous programming vulnerability. Third, the competitive state competition status is Race Condition, which is the most common application security vulnerability in the second class. Creating (Change) resources to modify resources to disable critical moments of resource access, if a process is allowed to access resources, there is a competitive state. The key issue here is that if a task consists of two an indispensable steps, no matter how much you want these two steps, the operating system does not guarantee this. For example, in the database, the transaction mechanism makes two independent events "atomicize". In other words, a process creates a file, then modify the permissions of this file to prohibiting regular access; at the same time, another process without privileges can handle the file, deceive the privileged process incorrectly modify the file, or after the permission setting is completed The original file will continue to be accessed. Generally, in a standard UNIX and NT environment, some high priority processes can insert themselves between the tasks, but such a process does not exist on the Java server; at the same time, use pure Java to write The program is also impossible to modify the license permission of the file. Therefore, most competitive states caused by file access will not appear in Java, but this does not mean that Java completely got rid of this problem, but it is only the problem to enter the virtual machine. Let's take a look at how other development platform handle this problem. In UNIX, we must ensure that the default file creation mode is secure, such as executing "Umask 200" command before the server is started. For more information on umask, perform "Man Umask" view Umask's Man documentation on the command line of the UNIX system. In the NT environment, we must operate the security tag of the ACL (Access Control Table, Access Control List, protect the directory where you want to create the file below. NT new files generally inherit access licenses from its parent directory. See the NT document for more information. Most of the competition in Java appears in the critical code area. For example, in the user login process, the system must generate a unique number as an identifier of the user session. To do this, the system first generates a random number, and then checks if this number has been used by other users in the data structure such as the hash table. If this number is not used by other users, put it in the hash table to prevent other users from being used. The code is like Listing 1: (LISTING 1) / / Save the logged in user IDHASHTABLE HASH; // Random Digital Builder Random Rand; // Generate a Random Digital Integer ID = New Integer (Rand.NextINT ()); while (Hash.Containskey (ID)) {id = new integer (rand.nextint ());} // Prevent the current user to reserve this idhash.put (ID, data); Listing 1 code may bring a serious problem: If there are two threads execute the code of the Listing 1, one of the threads is re-scheduled before the Hash.Put (...) line code. At this time, the same random ID may be used twice. In Java, we have two ways to solve this problem.

First, the code of Listing 1 can be rewritten into the form of Listing 2, ensuring that only one thread can perform critical code segments to prevent threads from re-scheduled, avoiding the appearance of competitive states. Second, if the previous code is part of the EJB server, we'd better have a unique ID service using the EJB server thread control mechanism. (Listing 2) Synchronized (Hash) {// Generates a unique random number integer ID = new integer ()); while (hash.containskey (id)) {id = new integer () );} // Reserve the idhash.put (ID, data);} four, string interpretation execution In some programming languages, enter a special function in the input string, and the deceived server makes it performed. Excessive action. The following Perl code is an example: $ data = "mail body"; system ("/ usr / sbin / sendmail -t $ 1 <$ data"); Obviously, these code can be used as part of the CGI program, or from command Conditioning. Typically, it can be called as follows: Perl script.pl honest@true.com It will send a message (ie "mail body") to the user honest@true.com. This example is simple, but we can attack as follows: Perl script.pl honest@true.com; mailcheat@liarandthief.com

For example, the following code is possible to generate such problems: method m = bean.getClass (). GetMethod (action, new class [] {}); M.Invoke (bean, new object [] {}); if " The value of an action allows the user to change, here should pay special attention. Note that this phenomenon may appear in some strange places - perhaps the most strange place is JSP. Most JSP engines use the image API implementation: This bean's SET method should pay special attention because all of these methods can be called remotely. For example, for the JSP page for Listing 3 bean and Listing 4: (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 () {returnpass;} private string name; private string pass;} (listing 4) <% @ Page Import = "Example"%> bean example </ title> </ head > <body> <form> <input type = "text" name = "name" size = "30"> <input type = "submit" value = "submit"> </ form> </ html> on the surface These code only allow users to access the name of the Example Bean. However, understanding the system can access "http://whereever.com/example.jsp?name=fred& password = Hack" URL. This URL changes both the Name property and change the Password password property. Of course, this should not be the intent of the page writer, the author's intent is to design a page that only allows the user to access the name property. Therefore, in use <JSP: setProperty Property = "*" ... />. > When you are very careful, the problem that the string is explained will be performed in any environment that allows the embedded script code. For example, such issues may appear in Xalan (also known as LotusxSL), of course, this means that the system settings are not strict, vulnerable to attack. Xalan's script supports (and this is the default settings of Xalan), and close script support in sensitive applications is a wise choice.</p> <p>When you need to use the DOM to handle the XML document, you must also take into account another point: DOM guarantees that all texts have been properly proposed to prevent illegal tags from being inserted into the script. LotusxSL lacks this feature, but this is not a bug. Support scripts are a feature of LotusxSL and it is in turn off the default. The XSL W3C specification does not specify the ability to support scripts. Now let's take a look at how the string interpretation will affect SQL and JDBC. Suppose we have to search for users in the database with user names and passwords, and the servlet code of Listing 5 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 WHEREusername =" user "AND password =" pass; Statement Stmt = con.createstatement (query); ResultSet RS = con?executeQuery (query); if (rs.next ()) {// Success INT ID = rs.getint (1); ...} else {// Login failed ...} If the user name is inquiry, the user name is equal to "fred", the password is equal to "Something", the query executed is actually: select id from users whereusername = 'fred' and password = 'Something 'This query checks the user's name and password correctly. However, if the user entered in the query condition, the name is equal to "Fred 'and (' a '=' b", the password is equal to "Blah ') or' a '=' a", at which time the query executed by the system becomes: Select id from userSwhere username = 'fred' and ('a' = 'b' and password = 'black') or 'A' = 'a' It can be seen that this query cannot be checked by the username and password correctly. The code of Listing 6 is much safe. It fundamentally prevents the user from modifying the SQL command escape check. (Listing 6) String user = request.getAttribute ( "username"); String pass = request.getAttribute ( "password"); String query = "SELECT id FROM usersWHERE username = AND password =??"; PreparedStatement stmt = con. PrepareStatement (query); Stmt.setString (1, user); Stmt.setString (2, pass); ResultSet RS = stmt.executeQuery (); ... All access to file system is a string may be interpreted local. When accessing a file system with Java, we should pay attention to the name of the file. Listing 7 is an example that may bring danger.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-78479.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="78479" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.061</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'cnww46Us519wPdWei4cyT3J9ADr3Ljok_2B_2BRDZTLRyAee6dMhYwf8uVyIafDM2GA4vSjr0GgsXBhYzTsH'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>