Author: Amit Ranjan

Insecure coding practices can put problem codes in two categories, the superset is the code that is Vulnerable and the subset is the code which is Exploitable. The Exploitable code helps getting fancy POCs during a Penetration Testing exercise and remaining are waiting for a development mistake that will transform a vulnerable code into an exploitable code for more POCs.

Secure code review is the practice of identifying vulnerable code either by manual review of the entire code or by eliminating false positives from the results generated by a code review tool. Most of the code review tools can be categorized as either a Static analyzer or Dynamic analyzer. Static analyzer does the Vulnerability Analysis by pattern matching in the code before compiling the code. Dynamic analyzer on the other hand compiles the code first and then performs the analysis.

This article is about the programming language fundamentals required for a successful secure code reviews. We can concentrate on specific programming language constructs in order to find vulnerabilities. I am starting with the most used high-level language ‘Java’ to discuss the language basics. Since most of the constructs in other languages are similar to below examples, it will cover code review practices for other high level languages as well.

There are series of articles about secure code reviews where I will try to cover most of the frequently used frameworks, delta constructs in other prevalent programming languages that are significant for code review, and commonly vulnerabilities found during code review and their mitigations using scalable, reusable and robust code with the idea of defense in depth wherever it can be applied. All the examples in this article have to be very concise as these are not to teach programming.

Secure code review is an art and art is subjective so it is necessary for the reader to delve deep into programming language concepts to develop more concrete understanding as most of the reviewers are not regular programmer but they need to deal with them in each review exercise.

*Comments starting with ‘//’ are provided to explain the code better

Language Basics:-

A class denotes a category of objects and acts as a blueprint for creating such objects.


<strong>package</strong> com.aujas.examples; <br>
  <strong>public class</strong> rectangle {<br>
  //Example #1 <br>
  <strong>int</strong> height; <br>
  <strong>int</strong> breadth; <br>
  <br>
  //Below is an  explicit constructor <br>
  //rectangle(<u>int</u> <u>ht</u>, <u>int</u> <u>bd</u>){this.height = <u>ht</u>; this.breadth = <u>bd</u>;

        <strong>double</strong> calculateArea(){ <br>
  <strong>return this</strong>.height*<strong>this</strong>.breadth; <br>
  } <br>
  } 

A class can be instantiated as:


<strong>public static void</strong> main(String[] args){// <u>Main method is the entry point of a java program</u><br>
  <strong>        </strong>        //Example #2 <br>
  rectangle <u>rect</u> = <strong>new</strong> rectangle();//<u>rectangle()  is the default constructor</u><br>
  //default  constructor is the one provided by jvm if we have not specified one<br>
  //An explicit  constructor is the one commented above //rectangle… <br>
  }

We use interface and abstract class to define most generic template in an inheritance hierarchy


<strong>package</strong> com.aujas.examples; <br>
  <strong>public interface</strong> Shape {<br>
  //Example #3 <br>
  <strong>public static final double <em>pi</em></strong> = 1.414; <br>
  <strong>double</strong> calculateArea(); <br>
  } 

<strong>public class</strong> rectangle <strong>implements</strong> Shape{<br>
  <strong>double</strong> calculateArea(){//rectangle&rsquo;s implementation to calculate area}<br>
  }

<strong>public class</strong> Triangle <strong>implements</strong> Shape{<br>
  <strong>double</strong> calculateArea(){//Triangle&rsquo;s  implementation to calculate area}<br>
  }
  1. Member variables are by default public static final in an interface
  2. Methods are by default public and always without any implementation.
  3. An interface cannot be instantiated
  4. If a class implements an interface it has to provide definition for all methods in the interface else it cannot be instantiated with the new operator.
  5. An interface is an implicit abstract class.
  6. A class imlements an interface is called design by contract.
  7. A class extends another class is general Inheritence
  8. An interface can extend multiple interfaces, a class can
  9. final class cannot be extended, final method cannot be overridden, final int var = 10 (variable) cannot change its value
  10. static methods(), static int var = 10 belong to a class shared by all objects instantiated from that class, non-static methods and variables belongs to objects instantiated from a class using new

Polymorphism (One Name, Multiple forms/actions):

Two Types

  1. Compile Time or static polymorphism(Method Overloading, mostly in the same class)
    
    <strong>public class</strong> Math {<br>
      <strong>        </strong>//Example #4 <br>
      <strong>public double</strong> max(<strong>double</strong> i, <strong>double</strong> j){ <br>
      <strong>return</strong> i&gt;j?i:j; //ternary operator,  if i greater than j return j else j <br>
      } <br>
      <strong>public int</strong> max(<strong>int</strong> i, <strong>int</strong> j){<br>
      <strong>    </strong>//Same name but  different number of, type of or order of parameters<br>
      //Identified at  compilation of program which method gets called <br>
      <strong>return</strong> i&gt;j?i:j; <br>
      } <br>
      }
    
  2. Run Time or Dynamic polymorphism(Method Overriding, in an inheritance hierarchy)

    Look at Example#3 first for Example#5

      <strong>public class</strong> AreaCalculateTest {<br>
      //Example #5 <br>
      <strong>public static void</strong> main(String[] arg){  <br>
      Shape iShape = <strong>null</strong>;//Generic interface <br>
      iShape = <strong>new</strong> rectangle();//Specific  implementation assignment <br>
      iShape.calculateArea();//Calculates area of  rectangle <br>
      iShape = <strong>new</strong> Triangle();//Another specific  implementation assignment <br>
      iShape.calculateArea();//same call as above  but calculates area of triangle <br>
      } <br>
      }
      
  1. double calculateArea(){.. are overridden in multiple subclasses.
  2. Signature(name, parameter types/ordering/numbers, return type(double) and exceptions in throws clause) have to be exactly same in two overridden methods
  3. rectangle and triangle class is a type of Shape interface that’s why assignment of rectangle, triangle objects possible to Shape variable

Exception Handling


<strong>public double</strong> division(<strong>int</strong> a, <strong>int</strong> b) <strong>throws</strong> Exception{// throws to tell  caller to handle exception <br>
  <strong>double</strong> div = 0.0; <br>
  <strong>try</strong>{ //put the code that  may throw exception in try block <br>
  <strong>if</strong>(b==0) <strong>throw new</strong> ArithmeticException(&quot;Division by  Zero&quot;);  //  throw to explicitly throw an exception <br>
  div = a/b; <br>
  }<strong>catch</strong>(ArithmeticException ae){//catching a  specific exception to handle it <br>
  ae.printStackTrace(); <br>
  } <br>
  <strong>catch</strong>(Exception e){//catching a generic  exception to handle it <br>
  e.printStackTrace(); <br>
  } <br>
  <strong>finally</strong>{}//put code here that  should be executed even if exception occurs <br>
  <strong>return</strong> div; <br>
  }

Reflection & Introspection

  1. Reflection is the ability to examine and modify the structure and behavior of an object at runtime.
  2. Introspection is the ability of a program to examine the type or properties of an object at runtime.

<strong>public static void</strong> main(String[] args) { <br>
  <strong>try</strong>{ <br>
  Class&lt;?&gt;  c = Class.<em>forName</em>(&quot;com.aujas.examples.rectangle&quot;);//Load a class <br>
  Object  rect = c.newInstance();//Instantiate <br>
  Method  m = c.getDeclaredMethod(&quot;calculateArea&quot;, <strong>new</strong> Class&lt;?&gt;[0]);//introspect,get a  method <br>
  m.invoke(rect); //Call a method on  a class object while running <br>
  } <br>
  <strong>catch</strong>(Exception e){e.printStackTrace();} <br>
  }

<strong>public static void</strong> main(String[] args){ <br>
  Object obj = <strong>new</strong> com.aujas.examples.rectangle(); <br>
  <strong>if</strong>(obj <strong>instanceof</strong> rectangle) //introspect if  object is of specific type <br>
  ((rectangle)  obj).calculateArea();//call method if of  that type <br>
  } <br>

Servlet

A Servlet is a web component managed by the web container (Web server i.e tomcat) that handles http methods (get, post, put, delete, options etc)


<strong>public class</strong> HelloServlet <strong>extends</strong> HttpServlet { <br>
  <strong>public void</strong> doGet(HttpServletRequest request, HttpServletResponse response) <strong>throws</strong> ServletException, IOException //request object  have access to all html parameters as well as running session <br>
  { <br>
  //Handle Get request on http <br>
  } <br>
  <strong>public void</strong> doPost(HttpServletRequest  request, HttpServletResponse response) <strong>throws</strong> ServletException,  IOException //response can be used to write to interface or select a jsp to  create interface <br>
  { <br>
  //Handle Post request on http <br>
  } <br>
  }<br>

Web.xml

Web.xml is a deployment descriptor of a j2ee application used to configure all components, it resides in /WEB-INF folder. We can configure error page, servlets, url mapping to servlet, init parameters or any other configuration. Any framework (struts, spring) is configured in web.xml


&lt;?xml version=&quot;1.0&quot;  encoding=&quot;ISO-8859-1&quot; ?&gt;<br>
  &lt;web-app  xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot;<br>
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>
  xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;<br>
  version=&quot;2.4&quot;&gt;<br>
  &lt;display-name&gt;HelloWorld Application&lt;/display-name&gt;<br>
  &lt;description&gt;<br>
  This is a simple web application with a  source code organization<br>
  based on the recommendations of the  Application Developer's Guide.<br>
  &lt;/description&gt;<br>
  &lt;servlet&gt;<br>
  &lt;servlet-name&gt;HelloServlet&lt;/servlet-name&gt;<br>
  &lt;servlet-class&gt;examples.Hello&lt;/servlet-class&gt;<br>
  &lt;/servlet&gt;<br>
  &lt;servlet-mapping&gt;<br>
  &lt;servlet-name&gt;HelloServlet&lt;/servlet-name&gt;<br>
  &lt;url-pattern&gt;/hello&lt;/url-pattern&gt;<br>
  &lt;/servlet-mapping&gt;<br>
  &lt;/web-app&gt;

JSP

JSP is used to create dynamic web pages. It is java code between inside html codes.

  <strong>&lt;% ...&nbsp;%&gt; </strong>(Scriplet) where  fragment of java code is written<br>
  <strong>&lt;%= ...&nbsp;%&gt;</strong>(Expression) anything  goes here directly prints on web interface<br>
  EL(Expression language) ${javabean.variable}

<strong>Log4j</strong><br>
  log4j.properties contains configurations related to logging such  as log file name, location, type of appender etc.

<strong>final static</strong> <u>Logger</u> <strong><em>logger</em></strong> = <u>Logger</u>.getLogger(<u>classname</u>.<strong>class</strong>); //Logging Example <br>
  logger.error(&quot;This is error :  &quot; + parameter);<br>
  logger.info(&quot;This is info : &quot;  + parameter);<br>
  logger.debug(&quot;This is debug :  &quot; + parameter);

Maven Build

Maven is build tool to compile and build the jar, war file. Pom.xml contains the dependencies to compile, these dependencies can be internal on any internal project jar or on any external jar such as itext, log4j etc.