Thursday, September 11, 2014

Application Vulnerabilities


1) HttpOnly

When cookies are not marked as “HttpOnly”, potential perpetrator could exploit this by sending malicious code (such as cross-site scripting) to retrieve cookie information, and using that information to conduct further exploitation on the affected service or request.

It is recommended to modify the web application to set the “HttoOnly” attribute for all cookies to reduce the risk of cross-site scripting exploit.

You can set this under “tomcat/conf/context.xml” and change to <Context useHttpOnly="true">

2) Charset

The non-standard characters in the response may cause the browser to interpret the content using different character set, this might cause unexpected results such as cross-site scripting vulnerability, in which non-standard encodings (e.g UTF-7) can be used to bypass the application's defensive filters.

It is recommended to review the application, for every response containing HTML content the Content-type header must be returned and specify the standard recognized character set (e.g charset=ISO-8859-1)

3) Content-type

If the specified type is an image format, then the browser will usually detect the anomaly and will analyze the actual content and attempt to determine its MIME type. Either case can lead to unexpected results, and if the content contains any user-controllable data may lead to cross-site scripting or other client-side vulnerabilities.

It is recommended that, for every response containing a message body, the application should include a single Content-type header (e.g application/json) which correctly and unambiguously states the MIME type of the content in the response body.

4) Clickjacking

It might be possible for a web page controlled by an attacker to load the content of this response within an iframe on the attacker’s page. This may enable a "clickjacking" attack, in which the attacker's page overlays the target application's interface with a different interface provided by the attacker. By inducing victim users to perform actions such as mouse clicks and keystrokes, the attacker can cause them to unwittingly carry out actions within the application that is being targeted. This technique allows the attacker to circumvent defenses against cross-site request forgery, and may result in unauthorized actions.

It is recommended to review the application and ensure that it should return a response header with the name X-Frame Options and the value DENY (e.g "X-FRAME-OPTIONS", "DENY") to prevent framing altogether or the value SAMEORIGIN to allow framing only by pages on the same as the response itself.

5) Insecure HTTP methods

Depending on the types of allowed methods, an attacker can plan and launch direct attacks against the server. For example, PUT and DELETE methods would enable the attacker to upload or delete files and resources from the server. With more advanced crafted attack, there is a possibility for the attacker to take over the server; therefore the impact of finding is rated “High”. The likelihood is rated “High” because it is very easy to query the server from client’s side, using different HTTP methods. For instance, it would only take one line of HTTP query (OPTIONS / HTTP/1.1) to discover what HTTP methods are supported by remote web server.

It is recommended to disable support for the above-mentioned HTTP methods. Only allow the standard GET, POST & HEAD methods unless there is a specific requirement. Even so, it is recommended to provide strong check on it and ensure proper mitigations are in place.

6) Non-generic / runtime error messages

Error messages give very useful information to an attacker about the application and is usually the first stepping stone to help carry out an attack. Error messages in .NET can give out the following information: The language it was developed in, such as c# or vb.net, the stack trace of the program that failed, the version numbers for the .NET framework and ASP.NET, development class names and object structures. With the source codes being available to the attacker, they will be able to understand how the code works and craft specifics attack to exploit it.

It is recommended to put validate all user inputs at server-side. In addition, proper exception handling should be incorporated into the application to catch exception that could possibly occur during the processing of user input. A generic error page should be displayed if there is unexpected error encountered. The error page should not reveal information such as paths, variables, file names, row and columns, table names in databases and database specific errors codes that may help perpetrator to plan for future attack.

7) SSL certificate pinning bypass

The information leakage of the backend infrastructure could play critical role in revealing known vulnerabilities for exploitation.

It is recommended to implement anti-debugging strategies (code obfuscation) into the secure design of mobile application. This is applied to IOS application.

8) Password autocomplete

If this function is enabled, then credentials entered by the user are stored on their local computer and retrieved by the browser and future visits to the same application. The stored credentials can be captured by an attacker who gains access to the computer, either locally or through some remote compromise. Further, methods have existed whereby a malicious website can retrieve the stored credentials for other applications, by exploiting browser vulnerabilities or through application level cross domain attacks.

It is recommended to prevent browsers from storing credentials entered into the HTML forms, the attribute "autocomplete=off" should be included within the FORM tag to protect all form fields or within the relevant INPUT tags such as password fields.

Monday, November 4, 2013

Eclipse Tomcat unable to start within 30 seconds



Have you encountered the following error when you start up your tomcat in eclipse?


Server Tomcat v4.1 Server at localhost was unable to start within 30 seconds. If the server requires more time, try increasing the timeout in the server editor.







FATAL ERROR in native method: No transports initialized
err:: No such file or directory
Error [2] in connect() call!
Socket transport failed to init.
Transport dt_socket failed to initialize, rc = -1.




I have no idea what caused this error. But what I did was changed the following setting in my eclipse tomcat server and it work now.

Under the “Timeouts > Specify the time limit to complete server operations.” Change the “Start (in seconds)” from 30 to 45.
 

Thursday, October 31, 2013

How to send batch email using Gmail in Java

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class BatchEmailer {

      public static void main(String[] args) {
            Properties props = System.getProperties();
        props.put("mail.smtp.user", "abc@gmail.com");
        props.put("mail.smtp.password", "12345678");
            props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.stmp.sendpartial", "true");
       
        Session session = Session.getDefaultInstance(props);
            Message message = new MimeMessage(session);
           
            try {
                  message.setFrom(new InternetAddress("abc@gmail.com"));

                  String[] toAddress = new String[] { "aaa@aaa.com", "bbb@bbb.com", "ccc@ccc.com" };
                  for (int i = 0; i < toAddress.length; i++) {
                        InternetAddress address = new InternetAddress(toAddress[i]);
                        message.addRecipient(Message.RecipientType.TO, address);
                  }

                  message.setSubject("Batch Email Testing");
                  message.setText("Batch Email Testing 1 2 3");

                  Transport.send(message);
            } catch (MessagingException e) {
                  e.printStackTrace();
            }
      }
}

Tuesday, July 2, 2013

Generate Large Excel Report by Using Apache POI Performance Tuning

If you are using Apache POI to generate large excel file, please take note the sheet.autoSizeColumn((short) p); line because this will impact the performance.


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CSVToExcelConverter {

       public static void main(String args[]) throws IOException {
              ArrayList arList = null;
              ArrayList al = null;
              String fName = "test.csv";
              String thisLine;
              int count = 0;
              FileInputStream fis = new FileInputStream(fName);
              DataInputStream myInput = new DataInputStream(fis);
              int i = 0;
              arList = new ArrayList();
              while ((thisLine = myInput.readLine()) != null) {
                     al = new ArrayList();
                     String strar[] = thisLine.split(",");
                     for (int j = 0; j < strar.length; j++) {
                           al.add(strar[j]);
                     }
                     arList.add(al);
                     i++;
              }

              try {
                     HSSFWorkbook hwb = new HSSFWorkbook();
                     HSSFSheet sheet = hwb.createSheet("new sheet");
                     for (int k = 0; k < arList.size(); k++) {
                           ArrayList ardata = (ArrayList) arList.get(k);
                           HSSFRow row = sheet.createRow((short) 0 + k);
                           for (int p = 0; p < ardata.size(); p++) {
                                  HSSFCell cell = row.createCell((short) p);
                                  sheet.autoSizeColumn((short) p); // this will slow down the performance
                                  String data = ardata.get(p).toString();
                                  if (data.startsWith("=")) {
                                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                         data = data.replaceAll("\"", "");
                                         data = data.replaceAll("=", "");
                                         cell.setCellValue(data);
                                  } else if (data.startsWith("\"")) {
                                         data = data.replaceAll("\"", "");
                                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                         cell.setCellValue(data);
                                  } else {
                                         data = data.replaceAll("\"", "");
                                         cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                         cell.setCellValue(data);
                                  }
                                  // */
                                  // cell.setCellValue(ardata.get(p).toString());
                           }
                           System.out.println();
                     }
                     FileOutputStream fileOut = new FileOutputStream("test.xls");
                     hwb.write(fileOut);
                     fileOut.close();
                     System.out.println("Your excel file has been generated");
              } catch (Exception ex) {
                     ex.printStackTrace();
              } // main method ends
       }
}



Hope this can save you time.

Monday, August 20, 2012

Why Bedok instead of Punggol?

Recently 1 of my friend ask me, why you want to buy a HDB Flat in Bedok instead of Punggol while Bedok Flat are more then 30 years old and Punggol Flat are less then 10 years old. The answer is very simple. I not buying the flat only, I buy with the environment.

Most of the people in Singapore are busy with their work, study and family everyday. People have not enough time for their family and friends. So I would choose a location that convenient for my daily activity to save more time.

When I choose a location to stay, I will consider the following:-

1)      Location
How far from my house to office (Raffles Place)?
How far from my house to public transport like MRT Station?
How far from my house to major express way like ECP or PIE?

2)      Food
Is there any food court or kopi tiam nearby?
Is there any wet market?
Is there any supermarket?

3)      School
Is there any child care?
Is there any primary school?
Is there any secondary school?

These 3 things I am doing everyday and will be doing for the next 10 years as well. If you find a place that make your life easy, you won’t keep on searching for house and moving around.

Hopefully this post can help someone to choose their best location to settle down.


Tuesday, March 6, 2012

How to set the PDF file show on the browser or download from the browser

Do you notice some website download the PDF file from the browser and some show the on the browser?

You can set it in your Java Servlet. Checkout the following.

This will open the PDF file on the browser.

response.setContentType("application/pdf");

response.setHeader("Content-Disposition", "inline; filename=abc.pdf);

This will download the PDF file from the browser.

response.setContentType("application/x-download");

response.setHeader("Content-Disposition", "attachment; filename=abc.pdf);

Friday, February 24, 2012

How to add your sitemap file located in Amazon S3 into Google Webmaster tools

If you hosted your rails website in Heroku, you are most properly using https://github.com/kjvarga/sitemap_generator gem to dynamically generate your sitemap file.

I won’t go into the details of how to use sitemap_generator, there are many website guide you for this, just google it.

Once you got your sitemap generated and uploaded to Amazon S3 successfully, you might want to track your sitemap in Google Webmaster Tools as well.

First, add your Amazon S3 site into Google Webmaster Tools. For example, http://s3.amazonaws.com/mybucket/sitemaps


Second, verify your Amazon S3 site by copy the googleXXXXX.html file into your bucket and give the permission accordingly.


Third, go into your Amazon S3 site in Google Webmaster Tools. Navigate to Site Configuration > Sitemaps, add the sitemap located in Amazon S3 for your Rails website.


Done! That All.

Google can accept “Cross-site submissions” for your sitemap.

http://googlewebmastercentral.blogspot.com/2007/10/dealing-with-sitemap-cross-submissions.html