Skip to content

enderphan94/Code-Review

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 

Repository files navigation

Code-Review

Inspired by OWAPS

Secure Code Checklist for JAVA SE

https://www.oracle.com/java/technologies/javase/seccodeguide.html
Secure Coding Checklist for Java SE
# Checklist Item Desc
1 Fundamentals
1.1 Avoid duplication Duplication of code and data causes many problems. Both code and data tend not to be treated consistently when duplicated, e.g., changes may not be applied to all copies.
1.2 Restrict privileges: Application to run with the least privilege mode required for functioning Using the Java security mechanism this can be implemented statically by restricting permissions through policy files and dynamically with the use of the java.security.AccessController.doPrivileged mechanism
1.3 Establish trust boundaries - Are the code and data used sufficiently trusted? - Could a library be replaced with a malicious implementation? - Is untrusted configuration data being used? - Is code calling with lower privileges adequately protected against?
1.4 Minimise the number of permission checks SecurityManager checks should be considered a last resort. Perform security checks at a few defined points and return an object (a capability) that client code retains so that no further permission checks are required.
1.5 Encapsulate Allocate behaviors and provide succinct interfaces. Fields of objects should be private and accessors avoided. The interface of a method, class, package, and module should form a coherent set of behaviors, and no more.
1.6 Document security-related information documentation should cover security-related information such as required permissions, security-related exceptions, caller sensitivity
2 Denial of Service
2.1 Beware of activities that may use disproportionate resources - Integer overflow & underflow errors can cause sanity checking of sizes to fail.- Causing many keys to be inserted into a hash table with the same hash code, turning an algorithm of around O(n) into O(n2)- Regular expressions may exhibit catastrophic backtracking.
2.2 Release resources in all cases Some objects, such as open files, locks and manually allocated memory, behave as resources which require every acquire operation to be paired with a definite release. It is easy to overlook the vast possibilities for executions paths when exceptions are thrown. Resources should always be released promptly no matter what.
2.3 Resource limit checks should not suffer from integer overflow overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable.As of Java SE 8, the java.lang.Math class also contains methods for various operations (addExact, multiplyExact, decrementExact, etc.) that throw an ArithmeticException if the result overflows the given type
2.4 Resource limit checks should not suffer from integer underflow overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable.As of Java SE 8, the java.lang.Math class also contains methods for various operations (addExact, multiplyExact, decrementExact, etc.) that throw an ArithmeticException if the result overflows the given type
3 Confidential Information
3.1 Purge sensitive information from exceptions Exceptions may also include sensitive information about the configuration and internals of the system.- Propagating exceptions back to the method caller exposes the layout of the file system as such java.io.FileInputStream, java.io.FileNotFoundException. Many forms of attack require knowing or guessing locations of files.- Exposing a file path containing the current user's name or home directory exacerbates the problem. SecurityManager checks guard this information when it is included in standard system properties (such as user.home) and revealing it in exception messages- Internal exceptions should be caught and sanitized before propagating them to upstream callers. The type of an exception may reveal sensitive information, even if the message has been removed. For instance, FileNotFoundException reveals whether or not a given file exists.- It is sometimes also necessary to sanitize exceptions containing information derived from caller inputs. For example, exceptions related to file access could disclose whether a file exists. An attacker may be able to gather useful information by providing various file names as input and analyzing the resulting exception
3.2 Do not log highly sensitive information Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators
3.3 Consider purging highly sensitive from memory after use To narrow the window when highly sensitive information may appear in core dumps, debugging, and confidentiality attacks, it may be appropriate to zero memory containing the data immediately after us
4 Injection and Inclusion
4.1 Generate valid formatting If the input string has a particular format, combining correction and validation is highly error-prone. Parsing and canonicalization should be done before validation. If possible, reject invalid data and any subsequent data, without attempting correction.
4.2 Avoid dynamic SQL For parameterised SQL statements using Java Database Connectivity (JDBC), use java.sql.PreparedStatement or java.sql.CallableStatement instead of java.sql.Statement. In general, it is better to use a well-written, higher-level library to insulate application code from SQL
4.3 XML and HTML generation requires care Untrusted data should be properly sanitized before being included in HTML or XML output. Failure to properly sanitize the data can lead to many different security problems, such as Cross-Site Scripting (XSS) and XML Injection vulnerabilities. It is important to be particularly careful when using Java Server Pages (JSP).Characters that are problematic for the specific type of output can be filtered, escaped, or encoded. Alternatively, characters that are known to be safe can be allowed, and everything else can be filtered, escaped, or encoded. Implementing correct data sanitization and encoding can be tricky and error-prone. Therefore, it is better to use a library to perform these tasks during HTML or XML construction.
4.4 Avoid any untrusted data on the command line When creating new processes, do not place any untrusted data on the command line. Any data that needs to be passed to the new process should be passed either as encoded arguments (e.g., Base64), in a temporary file, or through a inherited channel.
4.5 Restrict XML inclusion XML External Entity (XXE) attacks insert local files into XML data which may then be accessible to the client. The safest way to avoid these problems while maintaining the power of XML is to reduce privileges and to use the most restrictive configuration possible for the XML parser.
4.6 Care with BMP files BMP images files may contain references to local ICC (International Color Consortium) files. Whilst the contents of ICC files is unlikely to be interesting, the act of attempting to read files may be an issue. Either avoid BMP files, or reduce privileges.
4.7 Disable HTML display in Swing components Many Swing pluggable look-and-feels interpret text in certain components starting with as HTML. If the text is from an untrusted source, an adversary may craft the HTML such that other components appear to be present or to perform inclusion attacks.To disable the HTML render feature, set the "html.disable"" client property of each component to Boolean.TRUE (no other Boolean true instance will do). label.putClientProperty(""html.disable""
4.8 Take care interpreting untrusted code (RCE) Code can be hidden in a number of places. If the source is not trusted to supply code, then a secure sandbox must be constructed to run it in
4.9 Prevent injection of exceptional floating point values As the NaN (not a number) or infinite values can be injected into applications via untrusted input data, for example by conversion of (untrusted) Strings converted by the Double.valueOf methodThe Double and Float classes help with sanitization by providing the isNan and isInfinite methods. Comparing instances of Double.NaN via the equality operator always results to be false, which may cause lookup problems in maps or collections when using the equality operator on a wrapped double field within the equals method in a class definition
5 Accessibility and Extensibility
5.1 Limit the accessibility of packages,classes, interfaces, methods, and fields Declare any class or interface public if it is specified as part of a published API, otherwise, declare it package-private. Similarly, declare class members and constructors (nested classes, methods, or fields) public or protected as appropriate, if they are also part of the API. Otherwise, declare them private or package-private to avoid exposing the implementation. Note that members of interfaces are implicitly publ
5.2 Limit the extensibility of classes and methods Design classes and methods for inheritance or declare them final. Left non-final, a class or method can be maliciously overridden by an attacker. A class that does not permit subclassing is easier to implement and verify that it is secure. Prefer composition to inheritance.
6 Input Validation
6.1 Validate inputs for valid data, size, range, boundary conditions, etc Input from untrusted sources must be validated before use. Maliciously crafted inputs may cause problems, whether coming through method arguments or external streams
6.2 Validate output from untrusted objects as input In general method arguments should be validated but not return values. However, in the case of an upcall (invoking a method of higher level code) the returned value should be validated. Likewise, an object only reachable as an implementation of an upcall need not validate its inputs.
6.3 Define wrappers around native methods Java code is subject to runtime checks for type, array bounds, and library usage. Native code, on the other hand, is generally not. While pure Java code is effectively immune to traditional buffer overflow attacks, native methods are not. To offer some of these protections during the invocation of native code, do not declare a native method public. Instead, declare it private and expose the functionality through a public Java-based wrapper method. A wrapper can safely perform any necessary input validation prior to the invocation of the native method:
7 Mutability
7.1 Create copies of mutable output values & Treat passing input to untrusted object as output If a method returns a reference to an internal mutable object, then client code may modify the internal state of the instance. Unless the intention is to share state, copy mutable objects and return the copy.To create a copy of a trusted mutable object, call a copy constructor or the clone method
7.2 Treat output from untrusted object as input Appropriate copying and validation should be applied.
7.3 The java.lang.Cloneable mechanism should not be used Implementing classes must explicitly copy all mutable fields which is highly error-prone. Copied fields may not be final
7.4 Do not trust identity equality when overridable on input reference objects Object.equals may be overridden to return true for different objects. In particular when used as a key in a Map, an object may be able to pass itself off as a different object that it should not have access to.If possible, use a collection implementation that enforces identity equality, such as IdentityHashMap
7.5 Make public static fields final Fields with subclassable types may be set to objects with malicious implementations. Always declare public static fields as final.
7.6 The java.util.Date should not be used The java.util.Date is a mutable API class. In an application, it would be preferable to use the new Java Date and Time API (java.time.*) which has been designed to be immutable.
8 Object Construction
8.1 Avoid exposing constructors of sensitive classes Define static factory methods instead of public constructors. Support extensibility through delegation rather than inheritance. Implicit constructors through serialization and clone should also be avoided
8.2 Defend against partially initialized instances of non-final classes When a constructor in a non-final class throws an exception, attackers can attempt to gain access to partially initialized instances of that class. Ensure that a non-final class remains totally unusable until its constructor completes successfully.
8.3 Defend against cloning of non-final classes A non-final class may be subclassed by a class that also implements java.lang.Cloneable. The result is that the base class can be unexpectedly cloned, although only for instances created by an adversary
9 Serialization and Deserialization
9.1 Avoid serialization for security-sensitive classes Lambdas should be scrutinized before being made serializable. Functional interfaces should not be made serializable without due consideration for what could be exposed.
9.2 Guard sensitive data during serialization Do not serialize sensitive data in a serializable class (java.io.Serializable). Approaches for handling sensitive fields in serializable classes are:- Declare sensitive fields transient- Define the serialPersistentFields array field appropriately- Implement writeObject and use ObjectOutputStream.putField selectively- Implement writeReplace to replace the instance with a serial proxy- Implement the Externalizable interface
9.3 Understand the security permissions given to serialization and deserialization Permissions appropriate for deserialization should be carefully checked. Additionally, deserialization of untrusted data should generally be avoided whenever possible.
9.4 Filter untrusted serial data Security guidelines consistently require that input from external sources be validated before use; serialization filtering provides a mechanism to validate classes before they are deserialized

Automation tools

For Java:

  1. Download the latest version of PMD
  2. Decompress the file and compile the souce code as the following
  3. The files should be placed in pmd-pmd_releases-6.25.0/pmd-dist/target/pmd-bin-6.25.0/bin
  4. ./run.sh pmd -d /Users/macbookpro/Downloads/java/contract.java -R ../../../../pmd-java/src/main/resources/category/java/bestpractices.xml -f html >> report_sample.html

The rule files should be taken from pmd-java/src/main/resources/category/java/.

Read the documentation for more details

  1. Download the latest version of DeepDive
  2. Decompress the zip file
  3. The run.sh should be in /bin
  4. It might return the error of JAVA_HOME must point to a valid JRE (You may want to set it permanently in setenv.sh).
  5. Run these 2 commands to get rid of the above issue and pop up the GUI

export CLASSPATH=../discotek.deepdive-1.5.5-beta.jar:../lib/discotek.deepdive-engine-1.5.5-beta.jar

java -Xmx4G -jar ../lib/discotek.deepdive-engine-1.5.5-beta.jar -decompile=true -project-directory=../sample-config -output-directory=/temp/report ../discotek.deepdive-1.5.5-beta.jar

  • Semgrep (java, python, golang, javascript)
  1. Clone the repo and read the Readme
  2. Run semgrep --config=https://semgrep.live/c/p/java <PathToFile>
  1. Download the latest version
  2. Install it in WIndows
  3. Select the language
  4. Open the folder that contains the source code files.

Manual Review

https://github.com/AlDanial/cloc

About

The repo is created for security code review

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published