Sunday, July 20, 2014

Top 10 OWASP 2013 attacks A3: Cross-Site Scripting (XSS)


Cross-site scripting (XSS) is a code injection attack.

WikiPedia: “XSS enables attackers to inject client-side script into Web pages viewed by other users.”

This means the attacker does not directly target a victim but targets a web site. To anyone using the  website,  a malicious code appears to be the part of the webpage and the code is executed. These codes perform some unintentional action. can happen every time when a  the web page includes user input in its pages, because the attacker can then insert a string that will be treated as code by the victim's browser.

An Example: 

A user is allowed to comment in a page. The input is directly displayed in the page.

In this example I will create a simple jsp page that displays a table, and allow users to comment. I will then try to perform XSS to see if I can force the page to do something malicious.

My page looked sth like:
Project Code can be found here.



HTML of comment Section
<div> 
           Comments:<br>  
           <table>  
                <tbody><tr><td><b>Seldon</b></td><td>Lenord Cheated</td></tr>  
                <tr>  
                     <td valign="top" align="top">Insert new comment</td>  
                     <td></td>  
                </tr>  
                <tr>  
                     <td valign="top">Name</td>  
                     <td><form action="save" method="post">  
                               <input type="text" name="name"><br>   
                               <textarea name="com"></textarea><br>  
                               <input type="submit">  
                          </form></td>  
                </tr>  
           </tbody></table>  
      </div>  

Note that the comments are saved in database.

Not for the next comment  let me insert some Java Script.
<script type="text/javascript">
alert("If this appears, I can use XSS to change the contents");
</script>




The result of the such is Statement is

 Comments:  
           Raj:<script type="text/javascript">  
      alert("If this appears, I can use XSS to change the contents");  
 </script>  

This will show a "alert" every time someone visits the page.

Lets try this:
 <script type="text/javascript">
                var v = document.getElementsByClassName('divCell');
for (var i = 0; i < v.length; i++) {
v[i].innerHTML = 0;
}
</script>

This will set all table values to 0. A web visitor may not know that the site has been compromised.

Why is XSS so disastrous?

XSS attack only have affect a web page because JavaScript actions are only limited to browser, So it can't be very disastrous. But consider these:

  • JavaScript can make arbitrary modifications to the HTML and DOM.
    • The implications:
      • JavaScript can redirect you to a phishing site.
      • JavaScript has access to some of the user's sensitive information, such as cookies.This is a step towards identity theft, and session fixation.
      • JavaScript can send HTTP requests with arbitrary destinations by Ajax. This mean sensitive information in the wrong part.
To make thing even worse, victims may remain unaware of the attacks and every one who visits the XSS compromised page is a victim.

Some prevention Rules suggested by owasp.org:

  • Never Insert Untrusted Data
  •  HTML Escape Before Inserting Untrusted Data into HTML Content
  • JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values
  • HTML escape JSON values
  • Sanitize HTML.
All these are nothing but validation of Untrusted data.

http://excess-xss.com/ has a Great tutorial On XSS.
  

Friday, July 18, 2014

Top 10 OWASP 2013 attacks A2:.Broken Authentication and Session Management

 When a developer writes their own authentication and session management system, there are a number of things that could go wrong. A flawed login mechanism or a week password management scheme could be exploited by hackers. Session management and time outs, password reset, remember me check-box, secret questions or account update features like changing username could be some point/features where things could go wrong. Bug or gaps in one of these components could range in impact, from assisting in a social engineering attack to a full compromise of user accounts.

Some factors:
1.       Session Id and predictably
2.       Server Side Credentials be overwritten through weak account management function.
3.       Session ID exposed to URL.
4.       Session timeout, Manual Expire
a.       Logout
b.      Can a user manually expire all other session from other devices and kick out attackers who may be logged in.

Examples of a flawed Login logic:
 boolean isLoginSucess= true;  
 try{  
            isLoginSucess= validateLogin(user,passWord);}  
 catch(Exception e){  
 //some logger used here  
 }  
        if(!loginSucess){  
            redirect to loginpage;  
 }else{//do something after loginsucessfull.  
 }  

Such a code where the default logging is true is a risk. (I actually found this code in a college project submitted by an engineering graduate).
As you may have guessed an exception in validateLogin() will result in successful authentication.

Other attacks:

        Brute force:
        When a password requirement scheme is not strong, i.e. simple dictionary password is used, the application is in risk of brute force attack, where the attacker tries to get into all words in a dictionary.

       Session Fixation: 
        Using tools like Brup proxy, cookies and requested parameter can be spoofed. 

Tuesday, July 1, 2014

Top 10 OWASP 2013 attacks. Attack 1: Sql Injection.

In this series I will be try to explain top 10 OWASP security attacks and how these attacks are used.

https://www.owasp.org/index.php/Top_10_2013-A1-Injection.

http://en.wikipedia.org/wiki/SQL_injection  says:
"SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker)"

Let’s create a simple authentication system and try this attack. I will be using Java servlet and html in this exercise. I assume that you have basic understanding of servlet and html.

I will be using Mysql database server.

Let’s create a database to save my user authentication info.
 The table looks like:


Note that the password storing scheme a very week one. This is how you should not store password. How to store a password is a separate story. But for now let’s keep it simple and use the same. For our purpose we don’t care what the password is, we will try to break into the system without using any password.

The query
SELECT count (*) from logininfo   
          where password= ’pass’ and userName='user'  
should give me result 1 if the username is ‘user’ and password is ‘pass’.

 I will create a simple html page that will post username password to a servlet which will check the database to identify valid user and prints a message accordingly.

index.html:
<body>  
      <form action="login" method="post">  
           UserName<input type="text" name="user"/><br />   
           Password<input type="password" name="pass" /><br />  
           <input type="submit" value="Login" />  
      </form>  
 </body> 

LoginCheckDAO: this checks if user is valid

public class LoginCheckDAO {  
      Connection con;  
      Statement stmt;  
      LoginCheckDAO() throws ClassNotFoundException, SQLException {  
           Class.forName("com.mysql.jdbc.Driver");  
           con = DriverManager.getConnection(  
                     "jdbc:mysql://localhost/afterHelloWorld", "root", "");  
           stmt = con.createStatement();  
      }  
      public boolean validateUser(String userName, String password) throws SQLException {  
           String sql = "SELECT count(*) from logininfo where password ='"+  
                      password + "' and userName='" + userName + "'";  
           System.out.println(sql);  
           stmt.execute(sql);  
           ResultSet rs= stmt.getResultSet();  
           rs.next();  
           if(rs.getInt(1)==1){  
                return true;  
           }  
           return false;  
      }  
 }  

Login.java-This is a servlet.

 public class Login extends HttpServlet {  
      private static final long serialVersionUID = 8466351087171796777L;  
      @Override  
      protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
                throws IOException {  
           LoginCheckDAO loginCheckDAO;  
           boolean isLoginSucess= false;  
           try {  
                loginCheckDAO = new LoginCheckDAO();  
                 isLoginSucess = loginCheckDAO.validateUser(  
                               req.getParameter("user"), req.getParameter("pass"));  
           } catch (ClassNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           PrintWriter out = resp.getWriter();  
           if (isLoginSucess) {  
                // do Something sucessful login should be able to do.  
                out.println("Login SUCESS");  
           } else {  
                // display error message.  
                out.println("Login FAIL");  
           }  
      }  
 }  

web.xml

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns="http://java.sun.com/xml/ns/javaee"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
      version="3.0">  
      <display-name>SqlInjection</display-name>  
      <servlet id="login">  
           <servlet-name>login</servlet-name>  
           <servlet-class>com.afterHelloWorld.Login</servlet-class>  
      </servlet>  
      <servlet-mapping>  
           <servlet-name>login</servlet-name>  
           <url-pattern>/login</url-pattern>  
      </servlet-mapping>  
      <welcome-file-list>  
           <welcome-file>index.html</welcome-file>  
      </welcome-file-list>  
 </web-app>  

Lets now lunch the application. 

you should see a page:

 This should work fine and you will be correctly authenticated in most of the cases. So far so good.


NOTE: Please don't use any of the information below to attack any sites. If you try to do something bad using the information presented below, YOU AND ONLY YOU ARE RESPONSIBLE FOR ANY CONSEQUENCES.

Lets forget the implementation for now and focus our attention into breaking into the system.
Now lets try getting authenticated without using password.

The trick is to input a carefully crafted input that would beat the purpose of login page or force or application to un-expected state.

We know the authentication sql is something like:

SELECT ....... where  condition.......

What if you can cause the query to be 

SELECT ....... where condition or true.?

Any value we input is likely to be used as

Select ....... where fieldName='value'

So if we insert something like value' or true or password='  in the input fields

The sql query would be something like

Select ....... where fieldName='value' or true or password='. This will always return a count greater than 0 in our query construct.
 The query would be:

SELECT count(*) from logininfo where   
 password ='asdasd' and userName='user1' or true or password='' 

which is a valid query.

Note that any attacker would only have to guess the name of field containing password and a valid username which is not a very difficult task.

Had we checked the count value > 0, the attacker would have got into the system. Luckily we have checked for count value==1;

If we could force the application to create a sql  that will return 1, we would get into the system.
Such a query should be like

SELECT ...... where password=''   
 and userName='user1'   
 or (true and userName='user1') and '1=1'  

If we input the userName as

 user1' or (true and userName='user1') and '1=1   
the resultant query would always return 1

A attacker needs to guess only the a columnName and a userName which is not difficult either. This input will break our authentication system and the attacker is able to login successfully without using a password.

This is a simple example of SQL injection.

Sunday, June 29, 2014

Jsf Spring Maven Jetty

This tutorial explains the basics of integrating JSF-Spring integration. I will try and inject a jdbcTemplete in a jsf application.

I assume that you have gone through the basics of JSF and Spring and at least tired a hello world application. I also assume that you are able to create a maven-archetype-webtype project.

I will also be using Primefaces to build a web page.

I will be using maven and jetty plugin to build the application and Eclipse to edit the codes. The database server is Mysql.

Environment Setup:

Create a database and a table: In my case the database is "tele" and the table is "member".



Insert some values. We will query the table from our application.

Lets Start.

Create a maven project with  maven-archetype-webtype. I created a project called

The basic structure will be something like


Now lets write come codes.

The  pom:

I plan to create a jsf application using Primefaces and inject jdbcTempete. We will need  mysql connector to connect to database. We will also require servlet.

I will also require Spring-web because i will be using listeners to integrate Jsf and Spring. The final dependencies end up with will be something like:


          <!-- Spring Dependencies -->  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-jdbc</artifactId>  
                <version>4.0.5.RELEASE</version>  
           </dependency>  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-web</artifactId>  
                <version>4.0.5.RELEASE</version>  
           </dependency>  

           <!-- jsf dependencies -->  
           <dependency>  
                <groupId>com.sun.faces</groupId>  
                <artifactId>jsf-api</artifactId>  
                <version>2.2.2</version>  
           </dependency>  
           <dependency>  
                <groupId>com.sun.faces</groupId>  
                <artifactId>jsf-impl</artifactId>  
                <version>2.2.2</version>  
           </dependency>  
           <!-- Prime faces -->  
           <dependency>  
                <groupId>org.primefaces</groupId>  
                <artifactId>primefaces</artifactId>  
                <version>5.0</version>  
           </dependency>  

           <!-- servlet -->  
           <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>javax.servlet-api</artifactId>  
                <version>3.0.1</version>  
           </dependency>  
           <!-- Mysql -->  
           <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>5.1.9</version>  
           </dependency>  

Jetty Plugin:
I will be using jetty:run maven goal. This will save me from having to use other application server. Jetty is a light weight web server and javax.servlet container.

 I don't want jetty scan for changes in my code changes. So I add the following plugin under. This requires me to reload jetty manually.


<plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <configuration> <scanIntervalSeconds>0</scanIntervalSeconds> <reload>manual</reload> <webApp> <contextPath>/Springjsf</contextPath> </webApp> </configuration> </plugin>

Now lets write some java codes.

The final structure of source package is something like.
Go ahead and create these classes:

DAOBase and Member are very simple classes. MemberDAO extends DAOBase and uses the jdbcTemplate. MemberRowMapper is the implementation of rowmapper Interface.

Lets hava a look in these classes one by one:

Member.java: This is a just POJO
public class Member {  
   private String id;  
   private String fName;  
   private String lName;  
   private String address;  
   public String getId() {  
     return id;  
   }  
   public void setId(String id) {  
     this.id = id;  
   }  
   public String getFName() {  
     return fName;  
   }  
   public void setFName(String fName) {  
     this.fName = fName;  
   }  
   public String getLName() {  
     return lName;  
   }  
   public void setLName(String lName) {  
     this.lName = lName;  
   }  
   public String getAddress() {  
     return address;  
   }  
   public void setAddress(String address) {  
     this.address = address;  
   }  
 }  

DAOBase.java:


 public class DAOBase {  
   private JdbcTemplate templete;  
   public JdbcTemplate getTemplete() {  
     return templete;  
   }  
   public void setTemplete(JdbcTemplate templete) {  
     this.templete = templete;  
   }  
 }  

MemberDAO.java

public class MemberDAO extends DAOBase {  
   public List<Member> getAllMembers() {    
     String sql = "Select MemID,First_Name,Last_Name,Address from member";  
     return this.getTemplete().query(sql, new MemberRowMapper());  
   }  
 }  

MemberRowMapper.java
 public class MemberRowMapper implements RowMapper<Member>{  
   public Member mapRow(ResultSet rs, int i) throws SQLException {  
     Member mem= new Member();  
     mem.setId(rs.getString("MemID"));  
     mem.setFName(rs.getString("First_Name"));  
     mem.setLName(rs.getString("Last_Name"));  
     mem.setAddress( rs.getString("Address"));  
     return mem;  
   }  
 }  
Now I am done with the classes.
Now lets start wiring things up.

web.xml:


We need to define a context parameter which is the location of spring context xml.
<context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>/WEB-INF/applicationContext.xml</param-value>  
   </context-param>  

Add listeners: We need to configure ConfigurationListner, ContextLoaderListener and RequestContextListner.

 <listener>  
     <listener-class>com.sun.faces.config.ConfigureListener</listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.ContextLoaderListener  
     </listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.request.RequestContextListener  
     </listener-class>  
   </listener>  


Servlet mappings:
 <servlet>  
     <servlet-name>Faces Servlet</servlet-name>  
     <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>Faces Servlet</servlet-name>  
     <url-pattern>/faces/*</url-pattern>  
   </servlet-mapping>  

Final web.xml:

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">    
   <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>/WEB-INF/applicationContext.xml</param-value>  
   </context-param>  
   <listener>  
     <listener-class>com.sun.faces.config.ConfigureListener</listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.ContextLoaderListener  
     </listener-class>  
   </listener>  
   <listener>  
     <listener-class>  
       org.springframework.web.context.request.RequestContextListener  
     </listener-class>  
   </listener>  
   <servlet>  
     <servlet-name>Faces Servlet</servlet-name>  
     <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>Faces Servlet</servlet-name>  
     <url-pattern>/faces/*</url-pattern>  
   </servlet-mapping>  
   <welcome-file-list>  
     <welcome-file>faces/index.xhtml</welcome-file>  
   </welcome-file-list>  
 </web-app>  

Now  I need to inject the jdbcTemplate to our DAO class. We will use Spring IOC(inversion of control) and JSF dependency injection for this purpose.

applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
 ">  
   <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
     <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
     <property name="url" value="jdbc:mysql://localhost/tele" />  
     <property name="username" value="root" />  
     <property name="password" value="" />  
   </bean>  
   <bean id="templete" class ="org.springframework.jdbc.core.JdbcTemplate">  
     <property name="dataSource" ref="ds"/>  
   </bean>  
 </beans>  

faces-config.xml:
 <?xml version='1.0' encoding='UTF-8'?>  
 <faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">  
      <application>  
           <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>  
      </application>  
      <managed-bean>  
           <managed-bean-name>viewBean</managed-bean-name>  
           <managed-bean-class>com.afterHelloWorld.springjsf.DAO.MemberDAO</managed-bean-class>  
           <managed-bean-scope>view</managed-bean-scope>  
           <managed-property>  
                <property-name>templete</property-name>  
                <value>#{templete}</value>  
           </managed-property>  
      </managed-bean>  
 </faces-config>  

Notice the el-resolver tag. Spring integrates to jsf using the
org.springframework.web.jsf.el.SpringBeanFacesELResolver

I am almost done. I only need a view.

index.xhtml:
<html xmlns="http://www.w3.org/1999/xhtml"  
    xmlns:h="http://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:p="http://primefaces.org/ui">  
   <h:head>  
     <title>View</title>  
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/>  
   </h:head>  
   <h:body>  
     <p:outputLabel value="This is my 1st primefaces String JSF"/>  
     <p:dataTable value="#{viewBean.allMembers}" var="mem">  
     <p:column headerText="Id">  
         <h:outputText value="#{mem.id}"/>  
       </p:column>  
       <p:column headerText="First Name">  
         <h:outputText value="#{mem.FName}"/>  
       </p:column>  
       <p:column headerText="Last Name">  
         <h:outputText value="#{mem.LName}"/>  
       </p:column>  
       <p:column headerText="Address">  
         <h:outputText value="#{mem.address}"/>  
       </p:column>  
     </p:dataTable>  
   </h:body>  
 </html>  

To use Primefaces I am required to add
  xmlns:p="http://primefaces.org/ui"
in html tag.

Now lets run mvn jetty:run command, and browse "http://localhost:8080/Springjsf/faces/index.xhtml"

Conclusion:
Spring integrates with JSF using el-resolver.