Prevention of external XSS attacks

Source: Internet
Author: User
Tags set cookie

Introduction:

This article focuses on how to prevent external XSS attacks.

Practice:

In fact, we can see from the http://www.bkjia.com/Article/201312/264737.html article that the main attack means does not allow attackers to run a section of JS on the machine, this section of js contains a section of document. if you can obtain the correct value for cookie processing, you can use the obtained information to send it to a specified machine of the attacker for theft. Therefore, it is easy to solve the problem by using a mechanism that prevents the malicious js code embedded on the attacker's machine from getting the document. cookie content.

Can this be achieved? after reading the following document, I found that a Cookie has an HttpOnly flag. If I set it to true, therefore, this cookie can only be accessed through the http protocol, but cannot be accessed through javascript scripts or applets. We are thinking that since information theft is a js script to get the document. cookie content, will the problem be solved after the Cookie is set to HttpOnly?

To this end, let's make an experiment and let the Cookie be generated using java code instead of using a certain js section in the connection above (in this case, HttpOnly works, then the js Code for setting the Cookie takes effect)

The code is very simple. We made a Servlet and asked the user to create a Cookie (now hard-coded) when accessing this Servlet: For comparison, let's first do an example of not setting HttpOnly:

The Code is as follows:

Package com. charles. study; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** this Servlet is used to generate a Cookie * @ author charles. wang **/public class CookieServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {buildResponseWithCookie (response );} /*** hard-code a Cookie and write it to the client * @ param response * @ throws IOException */private void buildResponseWithCookie (HttpServletResponse response) throws IOException {response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); Cookie cookie = new Cookie ("charles", "1234567890"); cookie. setMaxAge (24*3600); cookie. setPath ("/"); response. addCookie (cookie); out. println ("Already Written Cookie to Client");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

Then define servlet-mapping (Omitted) in web. xml)

When we access the page, open Firebug and switch to the Cookie Tag:

As you can see, by default, the HttpOnly attribute of this Cookie is not set (column 7 in the table below)

Now, switch to the Console tab and enter document. cookie:

The red part shows that we get the cookie value at this time, that is, js can get the cookie content completely.

Now let's change our code. Add a line of cookie. setHttpOnly (true) at the place where the cookie is created );

/*** Hard-code a Cookie and write it to the client * @ param response * @ throws IOException */private void buildResponseWithCookie (HttpServletResponse response) throws IOException {response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); Cookie cookie = new Cookie ("charles", "1234567890"); cookie. setMaxAge (24*3600); cookie. setPath ("/"); // the following line is specially used to solve the XSS attack problem from outside cookie. setHttpOnly (true); response. addCookie (cookie); out. println ("Already Written Cookie to Client ");}

The others remain unchanged. Then we repeat the experiment above. We open this servlet page, open Firebug, and switch to the Cookie Tag:

At this time, we can find that the HttpOnly attribute of the 7th column is set.

Now, switch to the Console tab and enter document. cookie:

This time, we found that the Cookie no longer displays "charles = 1234567890". Instead, it only displays "" null, which indicates that our HttpOnly attribute works. Our malicious js cannot obtain any valuable information through document. cookie.

Conclusion:

Therefore, from the comparison of the above two experiments, we found that the HttpOnly attribute is a key attribute for solving external XSS attacks. We can also expand it if it does not meet the requirements of the above experiment, in the above experiment, we allow response to directly add a cookie. However, in reality, most examples are through session HttpSession, and then some confidential information is added to its scope, and maintained on the server side. Then the client will also have an id to reference the corresponding session. Can this Session use the HttpOnly attribute? The answer is yes.

If you are using servlet 3.0 +, you can use the following code to configure the HttpOnly attribute in the corresponding web. xml:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>XSSDemo</display-name> <session-config> <cookie-config> 

Note that our xsd is the xsd of servlet 3.0, so we can use the <cookie-config> sub-element in <session-config>, then, the HttpOnly feature is enabled with

Let's make an experiment to prove that we modify CookieServlet so that when we access this Servlet, he will create a Session:

public class CookieServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        HttpSession session= request.getSession();        session.setAttribute("charles_session","9876543210");                                                                                                                                                                                                                                                                                                                                                                                                                    response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        out.println("Session Created");                                                                                                                                                                                                                                                                                                                                                                                                                 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}

Obviously, from the seventh column, we can see that the HttpOnly of the newly created Session Cookie is correctly set.

Summary:

We have done a few experiments to solve the problem of external XSS attacks, mainly by setting the HttpOnly attribute, which can prevent js or applet from operating cookies, besides, it applies not only to general cookies, but also to Session cookies. in fact, its idea is very simple. Since external XSS attacks allow you to take out the information, I strictly keep the customs line, you just need to "burn" any piece of paper through the customs (for example, I am using it), so that no matter what you do, you can get the information from the ashes through malicious code.

In practice, for a general Cookie, you only need to set cookie. setHttpOnly (true) when it is created ).

For Session cookies, if your app container supports the servlet 3.0 specification, you only need to configure <Cookie-config> enable

// Explicitly add HttpOnly String sessionid = request by overwriting the Http Response Header of SET-COOKIE. getSession (). getId (); response. setHeader ("SET-COOKIE", "JSESSIONID =" + sessionid + "; HttpOnly ");

In fact, the mainstream browsers now support HttpOnly well, and it is more difficult for hackers to intrude.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.