How to make code secure in Java

2 comments
 Java-Make your code secure 

Lets make our code more secure…..when we google the same...1st n foremost thing we could see is validate your inputs…..validate in what terms…1.Inputs must be in the proper format or type..(string,integer..etc) 2.Inputs if integer must be within the proper range .3.Regular expressions are used to allow the special characters along with the valid input.
Code is said to be not secured ..when it contains loopholes termed as Vulnerabilities which can cause harm to the application or project…so here are  some efforts to make code less vulnerable…



Vulnerability
        Vulnerability is a weakness in the application, which can be in the form of  design flaw or an implementation bug that allows an attacker to cause harm to the stakeholders of an application. Stakeholders include the application owner, application users, and other entities that rely on the application. The term "vulnerability" is also known as threats, attacks.


How to get rid of such loopholes or vulnerabilities??

Following are some generalisedsolution for the same..
public interface Randomizer
The Randomizer interface defines a set of methods for creating cryptographically random numbers and strings. Implementers should be sure to use a strong cryptographic implementation, such as the JCE or BouncyCastle. The specific algorithm used is configurable in ESAPI.properties.
  •         ESAPI.randomizer()

   getRandomInteger

ESAPI (The OWASP Enterprise Security API) is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications.
Public interface Validator
The Validator interface defines a set of methods for canonicalizing and validating untrusted input. Implementers’ should feel free to extend this interface to apply their own data formats.
  •          ESAPI.validator()

We have used here 2 methods getValidInput and getValidInteger...


To implement ESAPI we need esapi2.1.0 which is a latest jar.



The properties files….ESAPI. Properties file must be kept under resource folder…where we usually keep our properties files..Click here for the Properties file.
/resources/ESAPI.properties
We come across one more concept called Normailization….
Normalizing an input in nothing but standardizing the input before we can apply any validation.
Input can be normalisedin  any of the followingforms

Normaliser forms
NFC:- Canonical decomposition, followed by canonical composition.
NFD:-Canonical decomposition.
NFKC:-Compatibility decomposition, followed by canonical composition.
NFKD:-Compatibility decomposition.

Public final class Normalizer extends Object
This class provides the method normalize which transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text.
  •        public static String normalize (CharSequencesrc, Normalizer. Form form)


NOTE
Whenwe validate  request parameters use both normaliser       and Esapi.validator ()
Otherwise normalizer itself will also work  .
Canonicalization ( normalization) is a process for converting data which can be represented in more than one form into a "standard", "normal", or canonical form.


Few vulnerabilities that can be seen mostly along with the above discussed solutions are :

1. MEDIUM VULNERABILITIES

I.   Use of Cryptographically Weak PRNG
The product uses a Pseudo-Random Number Generator (PRNG) in a security manner, but the PRNG is not cryptographically strong. When a non-cryptographic PRNG is used in a cryptographic context, it can expose the cryptography to certain types of attacks.
 Cause:-
Weak generators generally take less processing power and/or do not use the precious sources on a system. While such PRNGs might have very useful features, these same features could be used to break the cryptography.
Solution:-
  •        ESAPI.randomizer()

getRandomInteger
int getRandomInteger (int min, int max)
Example:-
int index =ESAPI.randomizer ().getRandomInteger(9, 9);


II. Use of Insufficiently Random Values
The software may use insufficiently random numbers or values in a security context that depends on unpredictable numbers.
Cause:-
When software generates predictable values in a context which should be unpredictable it may be possible for an attacker to guess the next value that will be generated, and use this guess to access sensitive information.
Solution:-
  •        ESAPI.randomizer()

int getRandomInteger (int min, int max);
Example:-
int index =ESAPI.randomizer ().getRandomInteger(9, 9);
III. Trust Boundary Violation
Application developers may treat user input as trusted data, potentially creating an input-based vulnerability such as SQL Injection or Cross-Site Scripting.
Cause:-
The application places user inputs untrusted data, in the server-side Session folder, which is considered a trusted location. This could lead developers to treat untrusted data as trusted.
Solution:-
  •        public static String normalize (CharSequence src, Normalizer.Form form)
  •         Syntax

java.lang.StringgetValidInput(java.lang.String context,     java.lang.String input,   java.lang.String type,  intmaxLength,   booleanallowNull)    throws ValidationExceptionIntrusionException
      Parameters
 type - The regular expression name that maps to the actual regular expression from "ESAPI.properties".

Example:-
String param1 =Normalizer.normalize (request.getParameter ("query"), Form.NFKC);
String param=ESAPI.validator ().getValidInput ("RequestParameter", param1, HTTPParameterValue", 1000, true);

IV. Session Fixation
Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.
Cause:-
Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID.
Solution:-
session.invalidate ();
Session=request.getSession (true);
Example:-
session.setAttribute ("paramName", paramValue);
session.invalidate ();

V. Unchecked Input for Loop Condition
The product does not properly check inputs that are used for loop conditions, potentially leading to a denial of service because of excessive looping.
Solution:-

  •         public static String normalize (CharSequence src, Normalizer. Form form)
  •          java.lang.IntegergetValidInteger(java.lang.String context, java.lang.String input, intminValue, intmaxValue, booleanallowNull)

          Returns a validated integer.
Example:-
int rp1 =  Integer.parseInt(Normalizer.normalize(request.getParameter("rp"), Form.NFKC));
rp = ESAPI.validator().getValidInteger("RequestParameter",       Integer.toString(rp1), 0,rp1,true);

VI. Input Not Normalized
The software validates input before it is canonicalized, which prevents the software from detecting data that becomes invalid after the canonicalizationstep.
Cause:-
This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.
Solution:-
  •         public static String normalize (CharSequence src, Normalizer. Form form)
  •         java.lang.IntegergetValidInteger(java.lang.String context, java.lang.String input, intminValue, intmaxValue, booleanallowNull)
  •    Returns a validated Integer

.Example:-
intparam1 =  Integer.parseInt(Normalizer.normalize(request.getParameter("param"), Form.NFKC));
rp = ESAPI.validator().getValidInteger("RequestParameter", Integer.toString(param1), 0,param1,true);

2. LOW VULNERABILITIES

I. Improper Exception Handling
Attacker could maliciously cause an exception that could crash the application, will result in a denial of service (which means not giving an access of an application to a valid user , on the other hand the access is restricted by an invalid user which might be an attacker ). Application crashes may also occur.
Cause:-
The application performs some operation, such as database or file access, that could throw an exception. Since the application is not designed to properly handle the exception, the application could crash.
Solution:-
Any method that could cause an exception should be wrapped in a try-catch block that:
● Explicitly handles expected exceptions
● Includes a default solution to explicitly handle unexpected exceptions    
Java
Always catch exceptions explicitly.
try{
// Database access or other potentially dangerous function
}catch (SQLException ex){
// Handle exception
}


Example:-
DataTable dg = new DataTable ();
    try{
dg.setId(rs.getLong(Data_ID));
            dg.setName(rs.getString(DATA _NAME));
    }catch (SQLException e){
            throw new SQLException ("Data Loading Exception");
}
    return dg;      
    }

II.Information Exposure through an Error Message

The software generates usually generates an  error message that includes sensitive information about its environment, users, or associated data.
Cause:-
The sensitive information can  be valuable information (such as a password), or it may be a cause for deadly attacks. If an attack fails, an attacker to launch another more focused attack may use error information provided by the server.
Solution:-
Problem:-
}catch(Exception e)
{ logger.error(e.getMessage()};
Solution:-
} catch (Exception e){              
            logger.error ("Data  not found");

    }

If you have any new ways to increase security of code in java,please do comment and share with others.
If You Enjoyed This, Take 5 Seconds To Share It

2 comments:

  1. Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in hyderabad. we want work out extra strategies in this regard, thanks for sharing.

    ReplyDelete
  2. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp a great deal more around this condition. and I could assume you are an expert on this subject. Same as your blog i found another one Oracle Fusion Financials.Actually I was looking for the same information on internet for Oracle Financials Cloud and came across your blog. I am impressed by the information that you have on this blog. Thanks a million and please keep up the gratifying work.

    ReplyDelete