Quantcast
Channel: Roy Abu Bakar » Pentesting
Viewing all articles
Browse latest Browse all 2

Cross-site Scripting (XSS) attacks

$
0
0

Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it. The malicious script can access any cookies, session tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page.

I am using same web application and database that I used to previously to demonstrate this XSS attack.

Create table guestbook in webapp database.

CREATE TABLE `webapp`.`guestbook` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL,
    `comments` VARCHAR(300) NOT NULL
) ENGINE = InnoDB;

INSERT INTO `webapp`.`guestbook` VALUES (null, 'roy', 'test 1');

guestbook.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Guest Book</title>
        <style type="text/css">
            div#guestbook_comments {
                width: 45%;
                background-color: #f8fafa;
                border-width: 1px;
                border-style: solid;
                border-color: #C0C0C0;
                padding: 5px 10px 5px 10px;
                margin-bottom: 5px;
            }
            div.input_comments {
                background-color: #f8fafa;
                border-width: 1px;
                border-style: solid;
                border-color: #000000;
                padding: 10px 20px 10px 20px;
                margin-bottom: 20px;
            }
        </style>
        <script type="text/javascript" src="jquery.js"></script>
        <script>
            $(document).on('submit', '.guestform', function(e) {
                $.ajax({
                    url: $(this).attr('action'),
                    type: $(this).attr('method'),
                    data: $(this).serialize(),
                    success: function(html) {
                        $("#name").val('');
                        $("#comments").val('');
                    }
                });
                e.preventDefault();
            });

        </script>    
        <script>
            function validate_required(field,alerttxt)
            {
                with (field) {
                    if (value==null||value=="") {
                        alert(alerttxt);return false;
                    }
                    else {
                        return true;
                    }
                }
            }
            function validate_form(thisform) {
                with (thisform) {

                    if (validate_required(name,"Name can not be empty.")==false)
                    {name.focus();return false;}

                    if (validate_required(comments,"Comments can not be empty.")==false)
                    {message.focus();return false;}

                }
            }

        </script>
    </head>
    <body>

        <h1>Please leave your name and comments</h1>
        <div class="input_comments">
            <form method="post" name="guestform" action="guestform" class="guestform" onsubmit="return validate_form(this)">
                <table width="550" border="0" cellpadding="2" cellspacing="1">
                    <tr>
                        <td width="100">Name *</td> 
                        <td>
                            <input id="name" name="name" type="text" size="30" id="name" maxlength="10">
                        </td>
                    </tr>
                    <tr>
                        <td width="100">Message *</td>
                        <td>
                            <textarea id="comments" name="comments" cols="50" rows="3" maxlength="50"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td width="100">&nbsp;</td>
                        <td>
                            <input name="submit" type="submit" value="Submit">
                        </td>
                    </tr>
                </table>
            </form>
        </div>
        <br />

        <%@page import="java.sql.*" %>
        <%
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp", "root", "passw0rd");

                Statement st = conn.createStatement();
                String sql = "SELECT name, comments FROM guestbook";
                System.out.println(sql);
                ResultSet rs = st.executeQuery(sql);

                while (rs.next()) {
                    String name = rs.getString("name");
                    String comments = rs.getString("comments");
                    out.println("<div id='guestbook_comments'>");
                    out.println("Name: ");
                    out.println(name);
                    out.println("<br/>");
                    out.println("Comments: ");
                    out.println(comments);
                    out.println("<br/>");
                    out.println("</div>");
                }
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        %>
    </body>
</html>

guestform.java

@WebServlet(name = "guestform", urlPatterns = {"/guestform"})
public class guestform extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String name = request.getParameter("name");
            String comments = request.getParameter("comments");

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webapp", "root", "passw0rd");

                conn.setAutoCommit(false);
                String sql = "INSERT into guestbook (name, comments) VALUES (?, ?)";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, name);
                ps.setString(2, comments);
                ps.executeUpdate();
                conn.commit();
                System.out.println(sql);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            out.close();
        }
    }

Let’s test the application for XSS vulnerabilities.

Note: I am using Firefox and Chrome browsers for this test. I am using Firefox for logged in user and Chrome for the guests (non authenticated user).

First, we enter normal input to the form.

normal

The first test, we will input the form like this

test_1

Once we submitted the form, the javascript alert is displayed. Every time a user comes to this website, this XSS exploit will be displayed.

test_1_result

The second test, we will input the form like this

test_2

Once we submitted the form, my website is displayed under test 2 message. This is dangerous because the attacker could use malicious website and place it here.

test_2_result

The 3rd test, we will input the form like this

test_3

Below is the cookie/session that a webserver establishes with the current browser session. Session cookies are the cookies used to perform session management for web applications. This cookies hold the reference to the session identifier for a given user.

Imagine if you are logged-in in a merchandise website to purchase a goods, and someone know information about your session cookies, he could use this cookies to gain access to the website using your account, without even need to authenticate.

test_3_result

Now, I will open chrome browser, and modify the cookies. Please notice that I am not log-in yet to the website, so I cannot access search page.

test_3_modify_cookie

Once I modify and submit cookie changes, I got access to search page!

test_3_session_hijacked

We stole the cookies and Mission Accomplished :)

Countermeasures

Preventing XSS requires separation of untrusted data from active browser content.

  1. The preferred option is to properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL) that the data will be placed into.
  2. Positive or “whitelist” input validation is also recommended as it helps protect against XSS, but is not a complete defense as many applications require special characters in their input. Such validation should, as much as possible, validate the length, characters, format, and business rules on that data before accepting the input.
  3. For rich content, consider auto-sanitization libraries like OWASP’s AntiSamy or the Java HTML Sanitizer Project.
  4. Consider Content Security Policy (CSP) to defend against XSS across your entire site.

In addition, in Java web application we can enable HttpOnly flag in META-INF/context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context useHttpOnly="false" antiJARLocking="true" path="/webapp"/>

The End.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images