My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY






Wednesday, June 25, 2014

Ethical Hack Insufficient Session Destruction

1. Create a HttpSessionBindingListener

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener {
 public void sessionCreated(HttpSessionEvent evt) {
  HttpSession session = evt.getSession();
  session.getServletContext().log(
    "CREATED Session ID: " + session.getId() + "\t time: "
      + new java.util.Date());
 }

 public void sessionDestroyed(HttpSessionEvent evt) {
  HttpSession session = evt.getSession();
  session.getServletContext().log(
    "DESTROYED Session ID: " + session.getId() + "\t time: "
      + new java.util.Date());
 }
}

2. Configure this Session Listener in your web.xml


         com.pearson.cat.web.session.MySessionListener
    

3.So all you can do is to copy the method invalidate()from the above code into the logout.jsp and wait and see if the Listener is spilling the messages that the Session has been destroyed or not.

public void invalidate() {
        if (this.session != null) {
            this.cleanAttributes();
            this.session.invalidate();
        }
    }

    public void cleanAttributes() {
       if (this.session != null) {
            Enumeration attributes = session.getAttributeNames();
            while (attributes.hasMoreElements()) {
                String name = (String) attributes.nextElement();
                session.removeAttribute(name);
            }
        }
    }

Remove TRace from web server

1. Disable trace OFF in web server (httpd.conf) file

          TraceEnable off

2. If the above does not work , here is a simple REDIRECT statement

           RewriteEngine On
           RewriteCond %{REQUEST_METHOD} ^TRAC(E|K)
           RewriteRule .* - [F]

3. Do this in the application server if not

Simply edit $TOMCAT/conf/server.xml, 
and for the  element, add an attribute: allowTrace="false". 
Restart Tomcat and enjoy

Frameable response (potential Clickjacking)- Penetration testing - Fix

Detail :
CheatSheet :


Fix



    OWASP ClickjackFilter
    
        ClickjackFilterDeny
        org.owasp.filters.ClickjackFilter
        
            modeDENY
    
    
    
        ClickjackFilterSameOrigin
        org.owasp.filters.ClickjackFilter
        
            modeSAMEORIGIN
    
    
    
     
        ClickjackFilterDeny
        /*
    
    


Add the following java file to your classes
/**
 *  Software published by the Open Web Application Security Project (http://www.owasp.org)
 *  This software is licensed under the new BSD license.
 *
 * @author     Jeff Williams Aspect Security
 * @created    February 6, 2009
 */

package org.owasp.filters;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ClickjackFilter implements Filter 
{

    private String mode = "DENY";
     
    /**
     * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
     * decide to implement) not to display this content in a frame. For details, please
     * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse)response;
        res.addHeader("X-FRAME-OPTIONS", mode );   
        chain.doFilter(request, response);
    }
    
    public void destroy() {
    }
    
    public void init(FilterConfig filterConfig) {
        String configMode = filterConfig.getInitParameter("mode");
        if ( configMode != null ) {
            mode = configMode;
        }
    }
    
}

SSL cookie without secure flag set- Penetration testing - Fix

web.xml changes
Servlet 3.0 (Java EE 6) introduced a standard way to configure secure attribute for the session cookie, this can be done by applying the following configuration in web.xml



  true


Monday, June 23, 2014

Securing EXT-JS from CSRF

  • First, you need to have the JAR part of your WAR (pom.xml changes)

  • 
       org.owasp
       csrfguard
       3.0.0
    
    
  • Next you will need to modify your web.xml to add all the CSRF Servlets, Filters, and Configuration as this all works using standard servlet technology (web.xml changes)

  • 
       Owasp.CsrfGuard.Config   WEB-INF/csrfguard.properties
    
       Owasp.CsrfGuard.Config.Print   true
    
    
       CsrfGuard
       org.owasp.csrfguard.CsrfGuardFilter
    
    
       
       CsrfGuard
       *
    
    
    
       org.owasp.csrfguard.CsrfGuardServletContextListener
    
    
       org.owasp.csrfguard.CsrfGuardHttpSessionListener
    
     
    
       CsrfJavaScriptServlet
       org.owasp.csrfguard.servlet.JavaScriptServlet
       
          source-file      scripts/resources/csrfguard.js   
       
          inject-into-forms      true   
       
          inject-into-attributes      false   
       
          domain-strict      true   
       
          x-requested-with      OWASP CSRFGuard   
    
    
    
       CsrfJavaScriptServlet
       /CsrfJavaScriptServlet
    
    
    

  • Third We need to add the two CSRF files required above to the WAR file. The folder names are in line to what you have described in the web.xml and it is customizable

  • • scripts/resources/csrfguard.js (preferably under webapp\scripts\resources folder)
    • /WEB-INF/csrfguard.properties (should be in your classpath)
    

  • One property that is critical in csrfguard.properties is "org.owasp.csrfguard.Ajax=true"


  • Lastly , in the main ExtJS launch page which is typically /index.html

  •  
       
    

    Monday, June 9, 2014

    Spring AOP Log4j

  • Spring-aop.xml – I am AOPing all packages using the pointcut.
      
      
    
         
                                      
        
                            
                            
    
                            
    
                                              
       
    
  • Import this XML into your main spring xml
  • Next is the source for the performance logging advice
    package com.test.common;
    
    import java.lang.reflect.Method;
    
    import org.springframework.aop.AfterReturningAdvice;
    import org.springframework.aop.MethodBeforeAdvice;
    import org.apache.log4j.Logger;
    
    public class PerformanceLoggingAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
        /** Time in milliseconds */
     long startTime = 0;
    
     /** Time in milliseconds */
     long finishTime = 0;
    
     protected static final Logger loggerObj =Logger.getLogger(PerformanceLoggingAdvice.class);
     
        public PerformanceLoggingAdvice() {
        }
    
        @Override
        public void afterReturning(Object returnValue,
      Method method, Object[] args, Object target) throws Throwable {
     finishTime = System.currentTimeMillis();
     double totalDuration = finishTime - startTime;
     loggerObj.info("Finished executing method " + method.getName()
      + " on object " + target.getClass().getName() + " in "
      + totalDuration / 1000 + " seconds.");
        }
    
        @Override
        public void before(Method method, Object[] args,
      Object target) throws Throwable {
     startTime = System.currentTimeMillis();
     loggerObj.info("Executing method " + method.getName()
      + " on object " + target.getClass().getName());
        }
    
    }
    
  • pom.xml file entries you may need





  • 
                aopalliance
                aopalliance
                1.0
    
    
                org.aspectj
                aspectjrt
                1.8.0
    
    
                org.aspectj
                aspectjweaver
                1.8.0
    
    
                cglib
                cglib-nodep
                3.1
    
    
                org.springframework
                spring-aop
                3.1.3
    
    
                org.springframework
                spring-aspects
                3.1.3
    
    


    Here is the logger from the log files

    2014-06-09 12:41:45,491 INFO (PerformanceLoggingAdvice.java:35) - Executing method onMessage on object com.test..client.CalculationsMessageListener
    2014-06-09 12:41:45,493 INFO (PerformanceLoggingAdvice.java:35) - Executing method calculateAvailThrottler on object com.test..handler.CalculationServiceHandler
    2014-06-09 12:41:45,616 INFO (PerformanceLoggingAdvice.java:35) - Executing method getPrioritizeReleaseTemp on object com.test..service.ThrottlerCalcService
    2014-06-09 12:41:45,617 INFO (PerformanceLoggingAdvice.java:35) - Executing method getPrioritizeReleaseTemp on object com.test..dao.impl.PreReleaseDAOImpl
    2014-06-09 12:41:45,957 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method getPrioritizeReleaseTemp on object com.test..dao.impl.PreReleaseDAOImpl in 0.34 seconds.
    2014-06-09 12:41:45,960 INFO (PerformanceLoggingAdvice.java:35) - Executing method reCalculateLiquidity on object com.test..dao.impl.AdjustmentsDAOImpl
    2014-06-09 12:41:46,178 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method reCalculateLiquidity on object com.test..dao.impl.AdjustmentsDAOImpl in 0.218 seconds.
    2014-06-09 12:41:46,178 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method getPrioritizeReleaseTemp on object com.test..service.ThrottlerCalcService in 0.218 seconds.
    2014-06-09 12:41:46,187 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method calculateAvailThrottler on object com.test..handler.CalculationServiceHandler in 0.227 seconds.
    2014-06-09 12:41:46,188 INFO (PerformanceLoggingAdvice.java:26) - Finished executing method onMessage on object com.test..client.CalculationsMessageListener in 0.228 seconds.

    Thursday, June 5, 2014

    Hibernate getCurrentSession() versus openSession()

  • getCurrentSession()
  • this means that you have ONE session for the whole web app.
  • Bear in mind, Sessions are not THREAD SAFE.
  • You should never use "one session per web app" - session is not a thread safe object - cannot be shared by multiple threads.
  • You should always use "one session per request" or "one session per transaction".
  • The advantage is returns a session bound to a context - you don't need to close this
  • SessionFactory.openSession()
  • always opens a new session that you have to close once you are done with the operations.
  • If you are using Spring to manage transactions you can configure them to open / close sessions along with the transactions


          Private Session sessionObj = null;
           private Session getHibSession() throws ORMException {
                  SessionFactory sessionFactObj = null;
                  try {
                         if (sessionObj != null) {
                               return sessionObj;
                         } else {
                               sessionFactObj = HibernateSessionFactory.getInstance().getSessionFactory(hibernateConfig);
                               sessionObj = sessionFactObj.openSession();
                               return sessionObj;
                         }
                  } catch (HibernateException hibex) {
                         throw new Exception(hibex);
                  } catch (RuntimeException rte) {
                         throw new Exception(rte);
                  }
           }
    
    
  • @PersistenceUnit versus @PersistenceContext

    @PersistenceUnit(unitName = "myJPA")
    EntityManagerFactory emf;
    ...
    EntityManager entityManager = emf.createEntityManager();
    
    @PersistenceContext(unitName = "myJPA")
    private EntityManager entityManager;
    
    

    PersistenceUnit injects an EntityManagerFactory
  • With EntityManagerFactory and @PersistenceUnit you should create/destroy EntityManager every time by hands and manage transactions too
    and PersistenceContext injects an EntityManager.
  • EntityManager interface is used and instantiated directly. It has an internal mutable thread-local reference to a real EntityManager
  • Implementations of methods just redirect calls to this real EntityManager.
  • And there is a servlet listener, that before each request obtain EM by calling EMF.createEntityManager()
  • and assign it to that inner reference of special EM.
  • Also this listener manages transactions by calling getTransaction().begin(), .commit() and .rollback() on the real EM

    for(int i=0; i < 100; i++){
       insert into table
    }
    
    Question is whether the above will use single connection (or) more connections.
  • The answer is below
  • A JPA EntityManager that is JTA managed will use the same JDBC/database connection for the duration of a JTA transaction.
  • So as long as your method is in a JTA transaction, your code will have the same connection.
  • Outside of a transaction, the container may acquire a new EntityManager for each operation,
  • Across every JTA transaction boundary the proxy will release its JPA EntityManager and acquire a new one (or at least clear it).
  • Tuesday, June 3, 2014

    Atomikos Spring and Tomcat7 JPA integration



    Create the JTA specific LDAP datasource (OR) you can very well use regular datasource spring beans.
    When you create the datasoruce make sure it has only the following properties

    Java Factory:com.atomikos.tomcat.EnhancedTomcatAtomikosBeanFactory
     Java Class:com.atomikos.jdbc.AtomikosDataSourceBean
     URL: jdbc:oracle:thin:@hostname:port/SID
     Driver ClassName: oracle.jdbc.driver.OracleDriver
     maxPoolSize  10
     uniqueResourceName jdbc/myJTA (this is the name you give in your spring config and context.xml file)
    xaDataSourceClassName oracle.jdbc.xa.client.OracleXADataSource
    


    Define this datasource in your META-INF\Context.xml file
    
    
    
    

    Change the ojdbc driver version just in case in your pom.xml file
    
    com.oracle
    ojdbc6
    11.1.0.7.0
    
    

    Add the following for JTA in your pom.xml file
    
    
    org.springframework.data
    spring-data-jpa
    1.3.2.RELEASE
    
    
    javax.transaction
    jta
    1.1
    
    
    
    org.aspectj
    aspectjrt
    1.6.9
    
    
    org.aspectj
    aspectjweaver
    1.6.9
    
    
    cglib
    cglib
    2.2
    
    
    
    
    
    com.atomikos
    atomikos-parent
    3.8.0
    pom
    
    
    com.atomikos
    atomikos-util
    3.8.0
    
    
    com.atomikos
    transactions-api
    3.8.0
    
    
    com.atomikos
    transactions-jdbc
    3.8.0
    
    
    com.atomikos
    transactions-jms
    3.8.0
    
    
    com.atomikos
    transactions-jta
    3.8.0
    
    
    com.atomikos
    transactions-hibernate3
    3.8.0
    
    
    com.atomikos
    transactions
    3.8.0
    
    
    com.atomikos.tomcat
    atomikos-integration-extension
    3.7.1-201303261
    
    
    xjp
    xjp.ldap.tomcat
    1.2.1
    
    
    
    
    


    Spring JMS changes
    Add the property for your jmsTemplate which needs to be as part of the transaction. For example my spring config will look like as below

    
    
    
    
    
    
    false
    
    
    
    
    
    
    
    




    Sprring data changes
    
    
    Note that JPA and CONTEXT should be before TX

    Add the following
    
    
    


    Add the bean for the data source spring bean
    
       
       
       
           
        myuserid
        mypwd
        jdbc:oracle:thin:@host:port:SID
           
       
       
      
    

    or it could be as simple as referencing from META-INF\Context.xml file
    
      
      
     
    


    CONSTRUCT ATOMIKOS USERTRANSACTIONMANAGER, NEEDED TO CONFIGURE SPRING
    
     
      
     
    
     
      
     
    
     
     
      
      
      
     
    

    LEAVE THE TRANSACTION MANAGER to "org.springframework.orm.jpa.JpaTransactionManager"
    
      
     
    


    If you try to switch the transaction manage transaction manager to "jtaTransactionManager" you will get exceptions stating "Transaction is not in progress".
    The only way to associate the atomikos transaction manager to that of the JPA Entity Manager is to add the following tag

      
    



    Now is the beauty . Way to associate the the JTA for a resource like Spring Batch
    Change this

    
    
    to
    
        
        
      
     
    


    Just as a piece, Atomikos will normally use annoying loggers. To prevent this add the following property in your log4j.properties
    log4j.logger.com.atomikos=WARN


    Lastly you can annotate the java files as usual with the regular annotations
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = { Exception.class })
    

    Load same class from 2 different jar files



     File file = new File("c:\\myjar.jar");
     URL url = file.toURL(); 
     URL[] urls = new URL[]{url};
     ClassLoader cl = new URLClassLoader(urls);
     Class cls = cl.loadClass("com.mypackage.myclass");