Tuesday, April 22

How to avoid CSRF - Cross Side Request Forgery attack






How to prevent CSRF using.

CSRF attack can be prevented using Synchronized Token Pattern.

When an HTML form is rendered ,server assigns it a unique and random identifier in the form of hidden http parameter. Server

Also stored the unique identifier in user session profile

When This form is submitted server compares the identifier's value in hidden field with value stored in user session profile . If value matches only then request is further processed otherwise request is aborted.

Thus if any evil website tries to submit a form with forging the client request information in that , it is not able to generate the unique identifier As
It does not know How to get it , It's not there on client cookie , it's not guessable . So attacker can't make CSRF attack.





For example : If a form named businessForm is rendered is follow ,server creates random token and form store that in hidden field. Also it's value is sotred
in user session

businessForm
">


CSRF_identifier">123#rret_val</>



When user submit this form token value is validated. Evil site can't steal this random number So that request will be rejected and CSRF attack will be prevented







CSRF - Cross Side Request Forgery





When you are accessing your bank website ,Why should you not open any other tab in same window with some unknown /evil application?

You might become s CSRF prey.

How does that happen ?

LEt's understand this with an simple example.

Let's say you open the browser and login to you bank website www.mybank.com with your username/password.

When you Do this bank might persist your authentication token in cookie. For eample : You login to the website using your username/password and bank website
,after successful authentication , stores in client cookie "isUserALreadyLoggenzIn"="true"







After this you open an evil website in new tab , may be by clicking on some link on some other page in the same window . Now that evil website might contain

a form like this



name="amonut" value="50000"

Win Lottery

On on page opened with evil website link you click on Win Lottery button. This click submits a request of money tranfer and money is transferred to some
other account without your knowledge. Application identifies the logged in your using cookie data and there "isUserLoggedIn" is already set to true So no problem comes in authentication.



This example is Just to cover the CRSF i.e. cross side request forgery . These days bank application and browsers are much more intellient to

defend against these evils .


Thursday, March 20

Configuring apache mod security -Mod Security rules configuration








Below are the detailed around Mod Security configuration on apache server. Please let me know If you need any further details on that .

1.       Add  below configuration  in httpd.conf file

LoadModule security2_module modules/mod_security2.so
LoadModule unique_id_module modules/mod_unique_id.so
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin

Include /etc/httpd/modsecurity_crs/*.conf
SecAuditEngine On
#SecFilterScanPOST On
SecAuditLog logs/audit_log

2.       mod_security2.so and mod_unique_id.so are modules that needs to be placed in apache modules folder

/etc/httpd/modsecurity_crs is the place where rules files exist .

We have placed below rule file at this location





Mod_security_rules.conf
--------------------------------------------------------------------------------------------------------------
SecDefaultAction  "phase:1,phase:2,auditlog,logdata:'%{MATCHED_VAR_NAME}=%{MATCHED_VAR}',deny,redirect:/errorpage.html"

SecRule ARGS_NAMES "!^(post-name_)+$" "id:'1000010'"

SecRule ARGS:post-name "!^[a-zA-Z0-9_]{0,4096}$" "id:'1000237'"
 -----------------------------------------------------------------------------------------

This configuration will allow only post-name attribute with alphanumeric and _ characters allowed in the value . Every other request parameter will be rejected and user will be redirected to errorpage.html

Logs captured by mod security can be viewed in  logs/audit_log file. 


3.       I have created simple Form with GET and POST request on apache server

<html>
<body>
<h1>GET!! Test Apache Redirection</h1>
<form name='f1' method="GET" action="/getService">
Enter Your Name : <input type="text" name="name" value=""/>
<input type="submit" id="Go" value="GET Submit"/>
</form>
 
 
<h1>POST !! Test Apache Redirection</h1>
<form name='f2' method="POST" action="/postService">
Enter Your Name : <input type="text" name="post-name" value=""/>
<input type="submit" id="submit" value="Post Submit"/>
</form>
</body>
</html>

4.       So in above form through GET request we are submitting form with request attribute name and through post request attribute is post-name.


post-name will pass  and name will fail as name is not configured as allowed parameter in mod security rules configuration file.





Wednesday, March 19

Grizzly jax-ws file upload service and client






Server Side code : 


Below file start the Grizzly server and register the uploadService class as jax-ws web service 


package com.sap;

import com.sun.grizzly.http.embed.GrizzlyWebServer;

import java.io.IOException;

import javax.xml.ws.Endpoint;
import javax.xml.ws.spi.http.HttpContext;

import org.jvnet.jax_ws_commons.transport.grizzly_httpspi.GrizzlyHttpContextFactory;

public class JaxwsMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        String contextPath = "/ws";
        String path = "/test";
        int port = 8081;

        String address = "http://localhost:"+port+contextPath+path;

        GrizzlyWebServer server = new GrizzlyWebServer(port);
        HttpContext context = GrizzlyHttpContextFactory.createHttpContext(server, contextPath, path);

        Endpoint endpoint = Endpoint.create(new UploadService());
        //endpoint.create(new UploadService());
        endpoint.publish(context); 
     
        try {
            server.start();
            
            System.out.println(12121);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        
   
        
    }

}








below is uploadService class that basically upload the file 


package com.sap;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;

@WebService
public class UploadService {
  /*  @WebMethod
    public int up(@WebParam(name="value1") int value1, @WebParam(name="value2") int value2) {
        return value1 + value2;
    }
  */  
    @WebMethod
public void upload(String fileName, byte[] imageBytes) {
     
    String filePath = "D:/desktops/12march2014/uploads/" + fileName;
     
    try {
        FileOutputStream fos = new FileOutputStream(filePath);
        BufferedOutputStream outputStream = new BufferedOutputStream(fos);
        outputStream.write(imageBytes);
        outputStream.close();
         
        System.out.println("Received file: " + filePath);
         
    } catch (IOException ex) {
        System.err.println(ex);
        throw new WebServiceException(ex);
    }
}


    
}



run JaxwsMain Java class as java application . That will register the uploadService on Grizzly server\



use wsimport jax-ws utility from command line to generate the Client artifacts in Client project 

This will create below files 



  • ObjectFactory.java
  • package-info.java
  • Upload.java
  • UploadResponse.java
  • UploadService.java
  • UploadServiceService.java 






below the Client code file that will invoke the upload service


Execute this File and pass the file to be uploaded


package com.sa;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.FileHandler;

import javax.xml.ws.WebServiceRef;
import javax.xml.ws.soap.MTOMFeature;

public class JaxwsClient {

   

    /**
     * @param args
     */
    public static void main(String[] args) {
        JaxwsClient client =new JaxwsClient();
        client.doTest(args);

    }
    
    public void doTest(String[] args) {
        
        UploadServiceService service = new UploadServiceService();
    UploadService port = service.getPort(UploadService.class, new MTOMFeature(10240));

    String fileName = "tpd-alert-1.2.0.zip";
    String filePath = "D:/desktops/12march2014/" + fileName;
    File file = new File(filePath);
    
    if (args.length >0 && null != args[0]) {
        file = new File(args[0]);
    } else {
        
        System.out.println("Enter full path of file..");

        String path;

        Scanner scanIn = new Scanner(System.in);
        path = scanIn.nextLine();

        file = new File(path);

    }

    try {
        filePath=file.getPath();
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream inputStream = new BufferedInputStream(fis);
        byte[] imageBytes = new byte[(int) file.length()];
        inputStream.read(imageBytes);

        port.upload(file.getName(), imageBytes);
        inputStream.close();
        System.out.println("File uploaded: " + filePath);
    } catch (IOException ex) {
        System.err.println(ex);
    }}

}


Done!!!

Composition versus aggregation Java Code example



Aggregation


Read comments in Test class to understand the scenario / Code flow


package com.sam;

 class Car {
    Engine engine;

    public Car() {

        engine = Engine.getEngineInstance();

    }

    Engine getEngine() {
        return this.engine;
    }

}

class Engine {

    private Engine() {

    }

    public static Engine getEngineInstance() {

        return new Engine();
    }

    public void performAction(String str ) {

        System.out.println("Performed.."+str);
    }
}

public class Test {

    public static void main(String args[]) {

        Engine engine = Engine.getEngineInstance(); // can ncreate Engine instance ,
        // Engine can exist on its own ,
        // It can exist even without car instance
       
        engine.performAction("With Out Car Instance");

        Car car = new Car(); // Car class has dependency on ENgine class to perform Action
                             // But Engine Class instance can be created and used even without
                             // creating Car class instance

        car.getEngine().performAction("With Car Instance");

    }
}








composition


Read comments in Test class to understand the scenario / Code flow


package com.sam;
class Car {
    Engine engine;

    public Car() {

        engine = new Engine();

    }

    Engine getEngine() {
        return this.engine;
    }

    class Engine {

        private Engine() {

        }

        public Engine getEngineInstance() {

            return new Engine();
        }

        public void performAction(String str) {

            System.out.println("Performed.." + str);
        }
    }

}

public class Test {

    public static void main(String args[]) {

        Engine engine = Engine.getEngineInstance(); // compilation error / can not create Engine instance ,
        // Engine can not exist on its own ,
        // It can exist only with car instance

        engine.performAction("With Out Car Instance");

        Car car = new Car(); // Car class has dependency on ENgine class to perform Action
                             // SO Engine Class instance can be created only with
                             //  Car class instance

        car.getEngine().performAction("With Car Instance");

    }
}