The Best Java Secure Coding Standards

  1. Input Validation
Input validation is the process of validating the input to an application prior to use. Input validation is critical to application security as the majority of application risks arise due to weak input validation. Input Validation is primarily conducted in order to ensure that no invalid or unexpected data is supplied to the system/application which could result in the application behaving in an undesirable manner. Validation of input comprises of comprehensive verification of every input that is supplied to the application including the data that is coming from the user interface, external applications/sources, HTML controls, cookies, HTTP header variables and any other un-trusted sources. When software fails to properly validate input, an attacker will be able to craft the input in a format that is not expected by the application.  The attacker may inject malicious input, control resource references or cause a program to crash. If unaddressed, weak input validation may lead to the following implications:
  • Disclosure of confidential and restricted information
  • Unauthenticated and unauthorized access to information and system functionality
  • Denial-of-service of the application and server
  • Altered control flow, arbitrary control of a resource or arbitrary code execution
  1. Validate all inputs for length, type, syntax, and business rules before accepting the data for further processing, display or storage. This includes the validation of data and files coming from untrusted sources covering all parameters, URLs and HTTP header content (e.g. cookie name and value)
  2. Validate input at each tier of the application. Perform validation pertaining to the length, type and syntax (security validations) at the web tier while the business logic validation should be performed separately at the business tier. As business tier components can be re-used by different applications, the tier’s validation logic will ensure that the data is validated properly even if the web tier is not properly validated
  3. Perform input validations both at the client side and server side. Client side validation must be adopted in scenarios where the data is not going to the server and is processed / displayed in the client side itself. In all the other scenarios, server side validation should be mandated in the application. Client side validation will also help to reduce the load on the server by performing the first level of validation at the client side before the data is posted / submitted to the server.
  4. Validate the following when accepting files from the user as an attachment/file upload:
    1. File Name
    2. Size of the file
    3. File type
    4. Content format
    5. File within file
    6. Signature
    7. Malware(using anti-virus solutions present in the file server)
  5. Canonicalize path names before validating them. Use getCanonicalPath() to isolate code from operating system and file system-specific naming conventions. Validate the path name against benign directories
  6. Do not log unsanitized user input. To avoid log injection attacks, validate user input before logging it.
  7. Safely extract files from ZipInputStream. Validate the name of each entry before extracting the entry, e.g. by Canonicalizing the path name. Enforce limits on the number of zip files and the size of each file, to mitigate possible denial of service attacks
  8. Exclude unsanitized input from format string, regular expressions, and Runtime.exec()
  9. Prevent XML Injection. Use input validation and/or XML schema validation using a Document Type Definition (DTD) to prevent injections from being mistaken for valid XML
  10. Use white list validations. Always check and validate the input based on the valid set of characters including numbers, alphabets and special characters.  White listing presents a strict set of valid inputs rather than black listing which presents a broad set of invalid inputs. This valid set of characters should be defined during the design phase and should be in-line with the application requirement
  11. Identify and validate every input source in the web tier.  Possible sources of input include but are not limited to:
    1. GET, POST & PUT parameters
    2. Hidden Fields
    3. Cookies
    4. HTTP Headers
    5. Environment variables
  12. Use a centralized validation mechanism and common validation modules throughout the application and these modules should be called whenever there is a requirement for data validation. Usage of centralized modules will ensure that the data validation is performed consistently across the application and can be used to mitigate potential validation problems by doing the following:
    1. Sanitizing data
    2. Logging events
    3. Invalidating sessions
    4. Notifications such as display of customized error messages and alerts
  13. Handle all the errors identified during the validation process in a secure manner
  14. Note that frameworks such as Struts provide validator plugins that can be used to validate user input. The “Struts validator” plug-in validates the data against a set of required characters using regular expressions and other validation features provided by Struts framework
  15. Perform data validation to mitigate flaws arising within the business logic affecting sequence and order of transaction flow
  16. Perform appropriate validation checks before using data retrieved from application processes (e.g. downloaded or uploaded between central and/or remote computers) from different systems
  17. Prevent SQL Injection – Use the JDCB library API, like PreparedStatement, to build SQL commands that sanitize untrusted data and validate the length and content of input variables.
  18. Normalize strings before validating them – Normalizer.normalize() transforms Unicode text into the standard normalizations forms described in Unicode Standard Annex #15 Unicode Normalization Forms. Most suitable normalization form for arbitrarily encoded strings is frequently KC (NFKC)
Input Validation – Examples Example 1: The following code demonstrates the configuration details of validator plug-ins and dynavalidatorform in the Struts Config file:
// Validator plug in configuration <plug-in className=”org.apache.struts.validator.ValidatorPlugIn”> <set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml”/> </plug-in> //Configuration details for dynavalidatorform <form-beans > <form-bean name=”exampleForm” type=”org.apache.struts.validator.DynaValidatorForm”> <form-property name=”age” type=”java.lang.Integer” /> <form-property name=”name” type=”java.lang.String” /> </form-bean> </form-beans>
Example 2: The code below utilizes validator plug-in to validate phone numbers. This verifies and ensures that phone numbers contain only numbers in a particular format (for eg: 111-111-1111)
<form-validation> <formset> <form name=”userForm”> <field property=”phoneNumber” depends=”required, mask”> <arg0 key=”phoneNumber.mask”/> <var> <var-name>mask</var-name> <var-value> ^\d{3}-\d{3}-\d{4}$ </var-value> </var> </field> <field property=”userId” depends=”required, userId”> <arg0 key=”phoneNumber.mask”/> </field> </form> </formset> </form-validation>
Example 3: Data is checked for its length – The variable ‘Name’ is checked to ensure that it contains less than 20 characters, otherwise data is not processed IF (LENGTH(Name) < 20) THEN — Process the data as the data is less than 20 characters END IF;
  1. Output Validation
Output validation is the process of validating each and every data obtained from the different components before displaying the data in the user interface. This is accomplished by ensuring that data output satisfies set criteria such as being safe for processing by the client and not leaking sensitive information. Output validation also ensures that the response is properly validated before displaying it to the end user (e.g. web browser), thus allowing for safe consumption of data by the client application (browser). If unaddressed, weak output validation may lead to the following implications:
  • Disclosure of confidential and restricted information
  • Execution of malicious scripts/commands affecting the confidentiality and integrity of the application and end user
Output Validation Standard
  1. Perform appropriate checks to validate all output data processed by the application. The following are some of the instances of output validation requirements specific to applications:
    1. Check and confirm if the output data is correct and in the secure format
    2. Ensure sufficient information (accuracy, completeness, precision, and classification of the information, where warranted) is provided or display
  2. Validate output and sanitize data by considering the application context and type of data involved (for example, displaying the * character instead of digits while displaying the credit card number)
  3. Use methods such as output encoding (for example, HTML encoding) and filtering on all information/data that is displayed in the browser before the application attempts to display data from un-trusted sources to the web interface
Table below lists the characters that the output filter converts as part of output encoding (using HTML encoding),
Character Encoded Value Character Encoded Value
< &lt; or &#60; ) &#41;
> &gt; or &#62; # &#35;
& &amp; or &#38; % &#37;
&quot; or &#34; ; &#59;
&apos; or &#34; + &#43;
( &#40; &#45;
  1. Only information that is required by the user to perform the authorized activities, must be present in the client side pages (such as in form fields, query string parameters, comments in the user interface pages, hidden variables etc.). Any additional information which is not required by the end-user to perform their application functionality must not be present anywhere in the client side pages. Additional information (such as information on user credentials, server/application details and other sensitive data) would help an attacker to successfully launch targeted attacks
  2. Use “security” attribute in FRAME and IFRAME tags to enforce user’s IE security settings. Typically use restricted security settings which do not allow any script execution
  3. Efficiently handle all the errors identified during the output validation process
Output Validation – Examples Example 1: In the following code, a function is used to encode any input passed to it for display in a web browser into its equivalent form, using decimal character references:
{ ….//Code present in Action class String address = encode(formaddress); public static String encode(String data) final StringBuffer buf = new StringBuffer(); final char[] chars = data.toCharArray(); for (int i = 0; i < chars.length; i++) { buf.append(“&#” + (int) chars[i]); } return buf.toString(); } request.setAttribute(“formAddress”, address); }
  1. Authentication and Password Management
Authentication is the process of confirming the identity of a user attempting to access an application or other information resources. secure authentication mechanisms control access to applications and information resources and the trust between multiple parties to communicate with them. If unaddressed, weak authentication may lead to the following implications:
  • Unauthenticated/anonymous access to the data present in the application
  • Insecure management of user /system authentication credentials
Authentication Standard and Password Management Standard
  1. Always authenticate users when accessing protected resources and data in the application
  2. Use trusted and secure mechanisms such as Kerberos, Integrated Windows Authentication, and One Time Password Tokens (OTP) between application tiers and between information resources
  3. Use multi-factor authentication/strong authentication when accessing critical application information or data processing. Implement other authentication methods such as usage of hardware or software tokens and biometric (e.g., fingerprint, retina pattern, voice print) whenever there is a greater assurance level of user identification is required
  4. Enforce strong passwords. Passwords are the key to protect account information. The strength and complexity of the password should be directly associated to the security requirements laid out for the application and the value of the asset being protected. Recommended values for various password attributes are listed below:
    1. Strong password minimum length should be 8 characters
    2. Password should comprise at least three of the following
    3. Uppercase character (A through Z)
    4. Lowercase character (a through z)
    5. Base 10 digit (0 through 9)
    6. Non-alphanumeric character (e.g., space, punctuation mark, special character)
    7. Password history value should be set to a number sufficient to prevent re-use within the last 12 months
    8. Maximum age of password is 180 days
    9. Do not use default passwords or easily guessable passwords
  5. Implement an account lock out policy after 5 unsuccessful attempts
  6. Implement multi-step login process (i.e., user name and password entry on separate pages) to ensure that no additional information is disclosed that helps an attacker to identify the user credentials
  7. Enable logging for all unsuccessful login attempts
  8. Securely develop the Change Password functionality so the current password is re-authenticated when changing the password of the user
  9. Notify the user of the new password for the Forgot/Reset Password functionality through secure email or other secure communication channels instead of displaying the information to the browser. The new password should meet the established password complexity requirements
  10. Never display the password on the screen / web page or send it to the client side in any manner (such as HTTP headers, cookies, or hidden form fields).
  11. Display the password expiration notification when the user logs-in
  12. Do not indicate which mechanism has caused the failure in the event of an authentication failure (e.g., an invalid user sign-on attempt) in the authentication system. For example, in a user ID and password authentication system, an authentication failure shall not indicate whether the user ID or the password was incorrect
  13. Employ the use of HTTP sessions for all authenticated users
  14. Do not allow web browsers to cache the restricted / confidential information present in the login forms during authentication
  15. Show minimal errors about last successful login and failed login attempts after successful user authentication. Allowing a user to verify their failed login attempts and last successful login date will help the user to determine if an unauthorized access to the account was attempted
  16. Use secure communication channel such as SSL when form based authentication is used to transmit login credentials
  17. Use mutual authentication when two servers/systems need to communicate restricted/confidential information or perform restricted/confidential transactions and transports
    1. Use authentication frameworks such as Java Authentication and Authorization (JAAS) framework to authenticate a client. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, a bean, or a servlet,
    2. Standard built-in frameworks such as JAAS authentication mechanism can be used to authenticate users against user repository
    3. Authenticate domain users against Active Directory to provide access to protected resources. Set SSL attribute to true in LDAP configuration to ensure secure communication of sensitive authentication information
  18. Use SSL to protect the transfer of user information among end-user, web-tier, Enterprise JavaBeans EJB-tier and data-tier (based on any methods implemented
  19. Pass Servlets/Java Server Pages (JSP) client credentials within the InitialContext object, which is used to look up the remote Enterprise Java Beans
  20. Do not hardcode passwords in code. Store them in an encrypted or hashed form separately in a configuration file or database, or fetch from a password vault at runtime.
  21. Hash stored passwords and concatenate a salt to the password before the digest operation. Apply a different salt for each stored entry. Avoid use of weak cryptographic hashes such as MD2, MD4, MD5 and SHA-1.
  22. Use the SecureRandom function to generate a cryptographically strong random number
  23. Use the Java Cryptography Architecture (JCA) API which includes the Java Cryptographic Extension to build secure applications
  24. Set up authentication requirements <login-config> in the corresponding deployment descriptor. For example:
    1. Configure <auth-method> to the type of authentication to use (e.g., Basic, Form, etc.,)
    2. Configure <form-login-page> and <form-error-page> under <form-login-config> with the path of logon and default error pages, respectively
Authentication and Password Management – Examples Example 1: The following sample code shows configuration details for SSL communication:
<user-data-constraint> <description>SSL required</description> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint>
Example 2: The following sample code shows LDAP login configuration details for JAAS Authentication:
Example { edu.vt.middleware.ldap.jaas.LdapLoginModule required host=”ldap.clientname.org” port=”<specify LDAP over SSL port number>” ssl=”true” tls=”false” base=”ou=people,dc=clientname,dc=org” subtreeSearch=”true” userField=”uid” serviceUser=”cn=administrator,dc=clientname,dc=org” serviceCredential=”password”;
Example 3: The following sample code shows the access of remote EJBs from a servlet or JavaBean, passing the credentials in the InitialContext object:
Hashtable env = new Hashtable(); env.put(“java.naming.provider.url”, “ormi://myhost/ejbsamples”); env.put(“java.naming.factory.initial””com.evermind.server.ApplicationClientInitialContextFactory”); env.put(Context.SECURITY_PRINCIPAL, “XYZ”); env.put(Context.SECURITY_CREDENTIALS, “welcome”); Context ic = new InitialContext (env); CustomerHome = (CustomerHome)ic.lookup(“java:comp/env/XYZpurchaseOrderBean”)
  1. Authorization
Authorization is the process of assigning and verifying user privileges to access protected information. Once a user has been authenticated, their credentials can be used to determine what privileges to assign and whether they should have access to application resources. Authorization provides access controls to applications and can be performed by specifying a role or list of roles to explicitly allow or deny access to the application resources. Proper authorization mechanisms ensure secure access to protected application resources. If unaddressed, weak authorization may lead to the following implications:
  • Unauthorized access to restricted/confidential information and the application functionality
  • Subversion of business processes
  • Fraud and reputation-related risks
Authorization Standard
  1. Ensure that the user is authenticated and authorized to access the application data and functionality before granting access to any protected application resource
  2. Perform access control at all layers (environment, presentation, business and data) in order to ensure authorized access to application resources. Use role based authorization both at the web tier and EJB tier
  3. Wherever applicable, use the Java Authentication and Authorization framework (JAAS) to control the access to protected resources. Perform the following steps as part of JAAS authorization:
    1. Create appropriate security policy file entries
    2. Create a custom Permission class, a subclass of the java.security.Permission class
    3. Create a custom action class, an implementation of java.security.PrivilegedAction
    4. Execute the static Subject doAsPrivileged method, passing the Subject instance containing the principals required and the custom PrivilegedAction, along with an optional AccessControlContext
    5. Within the body of the PrivilegedAction run method, access the SecurityManager and call the checkPermission method using the custom Permission class
  4. Use the principle of Least Privilege to limit processes and user access to the resources which are necessary to perform their tasks, and nothing more
  5. Use declarative (configurative) security wherever applicable. Declarative security is more flexible as the application’s security environment can be changed without modifying the application itself
  6. Use the principle of segregation of duties and implement approval workflow processes to ensure that no user has excessive control over any critical process. For example a person should not be able to grant himself rights to perform an action
  7. Enforce limits on business logic (such as transaction limits) to reduce the attack surface
  8. Disable directory indexing on all web applications
  9. Store authorization tokens on the server-side. Do not use client-side tokens, such as cookies, hidden form fields, or request headers for storing authorization information. Ensure authorization tokens are confidential, tamper proof, and not replayable using cryptographic mechanisms whenone must store or pass the authorization tokens
  10. Implement role-based authorization in the web-tier using standard frameworks such as struts. Struts role based authorization can be used in applications for:
    1. Form and Method level security, extend Request Processor  and override the method  processRoles() to perform the check against a HashMap that stores a mapping of roles and form IDs/Method IDs
    2. Field-level security, tag libraries are extended to perform the check against the field ID
  11. Use Java EE Filters to intercept requests to achieve a clean separation of concerns and invoke a method on the Java class to perform the work to verify that a user’s role or roles allow them to access the resource that is requested
  12. Ensure role based authorization based on risk (e.g. EJB resources). In Role based authorization, only users with valid role are allowed to access the requested resource
  13. EJB declarative role based authorization to protect EJB resources by:
    1. Granting access to EJB resources based on security roles
    2. Declaring method permissions for EJB resources. Method permissions indicate which roles are allowed to invoke which methods
  14. Assign roles to J2EE Users and Groups. J2EE security architecture provides a mechanism for automatically mapping of roles defined in the application to the users or groups defined in the run time realm
Authorization – Examples Example 1: The following sample code restricts direct access to JSPs in applications:
//Below code is to protect JSPs from direct access by end user <web-app> <security-constraint> <auth-constraint> <web-resource-collection> <web-resource-name>no_access</web-resource-name> <url-pattern>*.jsp</url-pattern> </web-resource-collection> <auth-constraint/> </security-constraint> </web-app> The following sample code protects directory indexing in applications: <servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>true</param-value> </init-param> </servlet>
Example 2 The following is the sample code snippet of java security files for JAAS authorization. The entries in the file create associations between the principal that was assigned using authentication and the permissions. These entries are checked by Java Security Manager when the checkPermission call is made.
JAAS Authorization Security Configuration grant Principal examples.jaas.DemoPrincipal « art » { permission java.util.PropertyPermission « user.home », « read »; permission examples.jaas.DemoPermission « doIt »; permission examples.jaas.DemoPermission « doThat »; permission examples.jaas.DemoPermission « doITAll»;
Example 3:
The following sample code performs privileged action: //Use static doAsPrivileged method to execute privileged code Object o = Subject.doAsPrivileged( lc.getSubject(), new PrivilegedAction() { Public Object run() { SecurityManager sm = System.getSecurityManager(); try{ sm.checkpermission( new DemoPermission(“doIT”)); System.out.println(“Did doIt”); sm.checkpermission( new DemoPermission(“doITAll”)); System.out.println(“Did doItAll”); } catch(SecurityException e){ System.out.println(“you do not have permission to do that….”); System.out.println(“Exception : ” + e); } finally{ return null; } } } null );
Example 4: The following sample code in a servlet verifies whether user has an employee role. If user has an employee role, they will be allowed to read customer information.
public double readEmployeeinformation(String employeeId) { java.security.Principal userPrincipal = request.getUserPrincipal(); String callerId = userPrincipal.getName(); // Checks whether user has employee role if ( ((request.isUserInRole(“employee”)) &&(callerId == employeeId)) ) { // return Salary information for the employee getCustomerInformation(employeeId); } else { // Log unauthorized access throw new SecurityException(“access denied”); } }
Example 5:
The following sample code shows use of ejb-jar.xml to control access to EJBs and EJB methods: <enterprise-beans> <assembly-descriptor> <security-role> <description>Managers in an organization </description> <role-name>manager</role-name> </security-role> <security<description>employees in an organization </description> <role-name>employee</role-name> </security-role> </assembly-descriptor> …… // An employee with manager role can update Customer information. <method-permission> <role-name>manager</role-name> <method> <ejb-name>Customerdetails</ejb-name> <method-name>UpdateCustomerInformation</method-name> </method> </method-permission> // An employee with employee role can view Organization policies <method-permission> <role-name>employee</role-name> <method> <ejb-name>Employeedetails</ejb-name> <method-name>viewOrganizationPolicies</method-name> </method> </method-permission> </assembly-descriptor>
  1. Error and Exception Management
Applications can unintentionally leak information about their configuration or internal workings, or expose privileged information through improper error handling methods. In order to avoid leakage of technical information, the errors and exception should be customized to display uniform user interface to end user and mask all technical information. Improper error and exception management can lead to disclosure of internal technology information which may allow the attacker to launch attacks specific to the technology that is being used to develop the application and also in the web, application and database server or to perform social engineering on the administrators of the application and the servers associated with the application. If unaddressed, weak error and exception handling may have the following implications:
  • Undetected/unmanaged errors and exceptions
  • Difficulty debugging the application
Error and Exception Management Standard
  1. Handle all possible errors and exceptions that are expected from the application using a structured exception handling mechanism (“try……catch…” mechanism)
  2. Handle specific or sub-classed exception or errors (such as IllegalArgumentException) but not a generic master exception (such as RuntimeException, Throwable or Exception)
  3. Display custom (i.e.,  messages generated by the application  and not the message thrown by the system/software) and generic (i.e., should not contain any restricted/confidential or system related information as well as any other information which is not required for the user to perform the application functionality) error messages Create separate exception classes for specific types of application attacks and throw an instance of these exception classes whenever the possibility of the attack is identified.  This will help to log the required information specific to the application attacks
  4. Log and protect the details of the error and exception in a log file by implementing proper access control mechanisms
  5. Do not log sensitive information present in the error/exception messages (such as password, credit card numbers etc.) in the log file
  6. Implement fail safe applications. If an application enters an unknown state, it is likely that an attacker may be able to exploit this indeterminate state to access unauthorized functionality
  7. Release all the memory space allocated to the resources which are associated with the error or exception as long as these resources are not being used anywhere else in the application when an error or exception occurs
  8. Redirect handled/unhandled errors or exceptions that occur in the application to a common error page
  9. Use the try, catch, finally connection pattern to prevent resource leaks and other undesired behavior
  10. Handle exceptions in the web or business tier of Java using the try-catch block or throw/throws statements
  11. Avoid use of the following:
    1. empty catch blocks
    2. overly broad catch or throws
    3. Returning from inside a finally block. This will cause exceptions to be lost
    4. Using a throw statement inside a finally block. This can bypass any cleanup code as the normal flow of the execution is interrupted
  12. Explicitly handle SSL exceptions as this will avoid leaving the connection in an unexpected or potentially insecure state.
  13. Catch and handle all possible errors and exceptions that are expected in database routines which use data from external data store or user controlled data
Error and Exception Management – Examples Example 1:
The following code snippet shows application exception handled in the catch block via ActionErrors class of Struts framework: try { //Code in Action class } catch (ApplicationException e) { log exception ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError(e.getErrorCode()); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); }//end of catch if (!actionErrors.isEmpty()) { forward = mapping.findForward(“Exception”); } else { forward = mapping.findForward(“success”); }
Example 2:
The following code from “struts-config.xml” shows application redirection to a custom page when an exception is encountered in “actionForm”: <action-mappings> <action path=”/action” name=”actionForm” scope=”request” type=”web.DefectsAction” parameter=”method” validate=”false”> <forward name=”Exception” path=”/exception/customexceptionpage.jsp” /> <forward name=”success” path=”/welcome.jsp” /> </action> </action-mappings>
  1. Logging
The information within a log provides information on who accessed the application, what information was accessed on the application, when and where events occurred, and where the user accessed the application from. Improper logging may allow an attacker to prevent a security professional from constructing a clear picture of the logical flow of events occurring before, during, and after an attack. Attackers may also fill the log with irrelevant information or invalid special characters; inject external data or user-controlled data directly into the log files, store log data in an insecure location, or transport data over an insecure network connection. If unaddressed, weak logging may lead to the following implications:
  • Information relevant to reconstruct an attack is not available affecting breach investigation and forensics
  • Denial of service if irrelevant data is logged
  • Removal of the trace of an attack
  • Breach of confidential/restricted information logged
Logging Standard
  1. Use a centralized logging mechanism within the application logic, wherever possible
  2. Use built-in logging frameworks such as “java.util.logging” or external component such as log4j instead of a custom logging module
  3. Categorize application related events to different types of logging mechanisms such as application logging, audit logging, security logging and profiling
  4. Prioritize logged events for the ease of review by log reviewers and auditors
  5. Validate the user controlled data (or data coming from untrusted sources) before appending the same as part of the log entry. Preference is to use a white list of approved characters before appending the data as part of the log entry. This ensures that no malicious content is stored in the log file
  6. Store relevant data in the log files so that it is possible to trace the activity related to a specific data or event back to the sources. At a minimum, following information needs to be logged as part of a log entry:
    • Type of event such as login, logout and database connection type
    • Date and timestamp of when the event occurred
    • Description of the event
    • A user identifier to link a user to the event
    • Contextual data of the event i.e.  server IP address and port number of the database used when creating a new database connection
  7. Do not log restricted/confidential data.  The presence of restricted/confidential information in the log file may lead to disclosure of this information to administrators or users who accesses the log data. This may lead to breach of confidentiality of restricted/confidential information and adversely affect the user, application or related IT infrastructure with which these information are associated
  8. Integrate the log information with the enterprise level Security Information Event Management (SIEM) system, wherever possible
  9. Enforce proper logging mechanisms in security as well as restricted/confidential areas such as authentication, authorization, session management, input validation, configuration, administration.  The following are some of the events to be logged in the application restricted/confidential areas:
    • Authentication: Events such as logging in successfully, logging out, failure to log in
    • Authorization:
      1. Any place where authorization to access a resource is requested by the user
      2. Impersonation failure, i.e., User attempting to access the protected application functionality or data, which the user is not authorized to access, affecting the confidentiality or integrity of the application data
    • Session mechanism usage:
      1. Session startup/teardown
      2. Session validation failures
      3. Session timeouts
    • Database usage:
      1. Any SQL statement execution on restricted/confidential data records
      2. Any actions requiring modification to a database, such as DROP, CREATE,  TRUNCATE, GRANT, REVOKE, STARTUP, and SHUTDOWN
      3. Database access failures
      4. Errors returned from a database
    • File system usage:
      1. Any actions requiring access or modifications to a file/directory
      2. File access failures
      3. Directory access failures
      4. Errors returned from the file system
    • Administrative usage:
      1. Account changes
      2. Permission changes
      3. Role changes
      4. Database security changes
      5. File system security changes
      6. Disabling/enabling of logging
  1. Store the log file in a secure location with necessary access controls and track access to log files/records separately
  2. Generate appropriate alerts/notifications if any security critical event is logged
  3. Write data to the log as soon as possible and as close to the occurrence event as possible.  When an  event occurs, log the event first and then take necessary actions for remediation if required
  4. Use a proper logging mechanism at the web and business tier of the application as all the major functionalities are performed at these application tiers
  5. Ensure protection of security logs by following the principle of least privileges for log file access. Retain audit trails history for at least one year, with a minimum of three months immediately available for analysis
  6. Ensure continuous or periodic monitoring of security logs and have reporting and alerting procedures in place
  7. Ensure protection of security logs by following the principle of least privileges for log file access
  8. When an event occurs, log the event first and then take necessary actions for remediation
Logging – Examples Example 1:
The following example shows that event is logged first before performing any other action: Try { // code } catch (exception e) { log.debug(“Error message descriptor”, “Location”, e); // Do any necessary cleanup here… }
  1. Session Management
Session Management is the process of tracking a user’s activity across various sessions of interaction with the application. Managing application user session is critical as web applications use HTTP as the underlying data transfer protocol and HTTP is a stateless protocol which does not maintain user state across subsequent requests. Web session management provides an integrated way for a web server/application to maintain states throughout a user’s subsequent requests. The server generates a session identifier (ID) at an early point in the user interaction, sends this identity to the user’s browser and requests the identity from the browser with each subsequent request. Session identities thereby become identification tokens for user sessions and servers can use them to maintain session data (for example, session variables containing user information such as user roles). If unaddressed, weak session management may lead to the following implications:
  • Session hijacking
  • Replay attacks
  • Unauthorized access/ privilege escalation
  • Request forging
Session Management Standard
  1. Session IDs must be unpredictable (random enough) to prevent guessing attacks, where an attacker is able to guess or predict the ID of a valid session through statistical analysis techniques. For this purpose, a good PRNG (Pseudo Random Number Generator) must be used. The session ID value must provide at least 64 bits of entropy.
  2. Session ID should not have any have any restricted/confidential information
  3. Create a new HTTP session object after user authenticates successfully to the application. This will ensure that an authenticated user session is assigned a new session identifier
  4. Do not create session objects in JSP pages
  5. Invalidate session at the server side when the user logs out
  6. Define idle session time out in web.xml.  Remove sessions which are not active in container and client side for specified period of time
  7. Always issue a new session ID when the user changes authentication state
  8. Seamlessly expire the current session token and regenerate token if the user session is inactive for an extended and defined period of time. This shortens the window of opportunity for brute force attack Use as few resources as possible to prevent denial of service attacks for unprotected pages, and do not leak information about the protected portion of the application
  9. Hash the Session ID, IP address, and other fixed/unchanging HTTP header attributes before processing each subsequent request; checking whether the hash has changed can reveal session tampering or man in the middle attacks.  If there are changes in the hash, the user should be logged off to prevent session fixation and session tampering
  10. Use separate session identifiers for secure (HTTPS) and insecure (HTTP) communication channel
  11. Do not transmit session identifiers via GET request (as part of query string parameter)
  12. Ensure that the session ID content is meaningless to prevent information disclosure attacks, where an attacker is able to decode the contents of the ID and extract details of the user, the session, of the inner workings of the web application. The session ID must not contain sensitive information (e.g., PII).
  13. If session management features of web development framework are used then ensure that the latest version of web development framework is used that potentially fixes all the well- known vulnerabilities related to session management, as well as review and change the default configuration to enhance its security.
  14. Ensure that session management mechanism used is strict and not permissive. The permissive mechanism allow the web application to initially accept any session ID value set by the user as valid, creating a new session for it, while the strict mechanism enforces that the web application will only accept session ID values that have been previously generated by the web application.
  15. Ensure that the session ID is renewed or regenerated by the web application after any privilege level change within the authenticated user session.
  16. If multiple cookies are used for a given session, the web application must verify all cookies (and enforce relationship between them) before allowing access to the user session.
  17. Idle or inactivity time out must be implemented for application session in-line with the requirement. Absolute time out must be implemented regardless of session activity.
Session Management – Examples Example 1:
The following code sample shows that configuration of session time out in the web.xml file: //Session time out configuration in web.xml <session-config> <session-timeout>timeValue</session-timeout> </session-config>
  1. Cookie Management
A cookie is a piece of information sent to a browser by a Web Server. Cookies are designed to handle user preferences and are used to identify the authenticated user’s requests from a client to the server.  Cookie management ensures that cookies used in the applications are securely managed. The improper management of cookies may allow an attacker to steal cookies or hijack a session. If unaddressed, weak cookie management may impact the security of the application session (provided session identity is stored as part of cookie) affecting the confidentiality and integrity. Cookie Management Standard
  1. Avoid the presence of restricted / confidential information in the cookies. If required, encrypt the restricted/confidential data used in cookies.  For example, if an application requirement mandates usage of user role in a cookie, then ensure that it is encrypted so that the end user is not aware of the presence of user role in the cookies. Another example is the use of persistent cookies as part of “Remember Me” functionality of the application. If the application wants to remember the user even after the user logs out, then the application should make use of persistent cookies and stores some restricted/confidential information in the cookies. This will help the application to identify this user when the user tries to access the application functionality next time from the same machine. In such a scenario, the application should encrypt the restricted/confidential information present in the cookies
  2. Perform proper input validation on all cookie parameters before processing
  3. Use the SECURE attribute in the cookie of the application which is using encrypted communication channel (such as HTTPS) between client and server. This will ensure that the application cookie will be transmitted only through the encrypted communication channel. If the application requirement mandates the inclusion of restricted/confidential information as part of cookie and the cookie does not carry the SECURE attribute, then there may be an opportunity for information disclosure of restricted/confidential information stored as part of the cookie during transmission over unencrypted channels
  4. Avoid usage of persistent cookies and if required, set the expiry date of persistent cookies to a short duration of time which is in-line with the requirements and sensitivity/criticality of the data handled by the application
  5. Implement domain-specific cookies such that the cookies will not be transmitted to other sites by setting the “Domain” and “Path” attributes
  6. Set cookies to HTTP-ONLY to prevent potential misuse of information present in cookies by client side scripts. When this attribute is enabled, web browsers return empty responses to the client side script requests when tried to access application cookie
  7. Web applications should not mix or use same session identifier for encrypted and unencrypted communication channel on the same host / domain, as the request of any web object over an unencrypted channel might disclose the session ID
Cookie Management – Examples Example 1:
The following example shows the secure implementation of cookie attributes: Cookie applnCookie = new Cookie(cookieName, cookieValue); //Ensure that max age value is very low applnCookie.setMaxAge(maxAge); applncookie.setSecure(true); //Set domain name to restrict cookie transmission to other domains applncookie.setDomain(domainname); //Set HTTP Only to the cookie using HTTPServletResponse object response.setHeader(“Set-Cookie”, “<cookiename>=<cookievalue>; HTTPOnly”);
  1. Cryptography
Cryptography is the fundamental security element that protects data from adversaries either during storage or in-transit. Cryptographic systems provide secure authentication, non-repudiation, confidentiality and integrity. If unaddressed, weak cryptography may lead to insecure storage or transmission of restricted/confidential data affecting the confidentiality and integrity. Cryptography Standard
  1. Use the framework provided built-in functionality such as Java Cryptography Extension (JCE) which provides a framework and implementation for encryption, key generation, key agreement and Message Authentication Code (MAC) algorithms. JCE provides support for encryption that includes symmetric, asymmetric, block, and stream ciphers.
  2. Use a strong cryptographic technique, taking into consideration the effectiveness of the algorithm, block size, and key size
  3. Do not use proprietary algorithms as these algorithms may be prone to weaknesses that could lead to compromise of information
  4. Generate random key and salt values in a secure way by using the built-in functionality, SecureRandom (java.security.SecureRandom) wherever required
  5. Do not transfer any restricted/confidential data in the URL(via HTTP GET or any other user viewable format) and if there is a requirement to do so, then use strong encryption or hashing to conceal the data
  6. Protect cryptographic keys stored in a file through encryption, role-based access control and/or file system permissions
  7. Log any changes made to the cryptographic keys
  8. Apply a process to upgrade the algorithms used over time as cryptography is always changing when using cryptographic functions
  9. Enforce the use of strong and secure cryptography controls (including encryption/hashing algorithms, key management and salt values) for securing the sensitive information while in transit and during storage (both temporary and permanent).
  10. Preferred set of cryptographic algorithms are listed in the table below for additional reference,
Preferred Symmetric Encryption Algorithms
Table Minimum Key Length Usage Restrictions
AES 128 bits Electronic Code Book (ECB) shall not be used. Other modes of operation are acceptable.
3DES   112 bits (excluding parity) Restricted to the following mode of operation:
  • CBC (cipher block chaining)
Preferred Asymmetric Encryption Algorithms
Table Minimum Key Length Usage Restrictions
RSA 2048 bit modulus No usage restriction
  1024 bit modulus Restricted to the following mode of operation:
  • CBC (cipher block chaining)
Preferred Digital Signature Algorithms
Table Minimum Key Length Usage Restrictions
RSA 2048 bit modulus No usage restriction
1024 bit modulus May be used where the key is associated with a valid certificate (i.e., one that is neither revoked nor expired) May be used where a 1024 bit key is a documented requirement for interoperability shall not be used after 01/01/2011 to effect a SAFE compliant signature Note1: Not recommended for use in validated environments Note2: Transition to the use of a 2048 bit modulus is strongly recommended
Other Symmetric Encryption Algorithms
Table Minimum Key Length Usage Restrictions
RC-4 128 bits May be used as part of an SSL or TLS cipher suite where use of a preferred algorithm would cause a performance issue or where no technical solution using a preferred algorithm is available.
Twofish 128 bits May be used where there is no technical solution available that uses a preferred algorithm.
Blowfish
IDEA
CAST
Generate the key and salt values in a secure manner using secure random algorithms. Use securely generated key or salt values along with encryption and hashing algorithms which will improve the overall security of the cryptographic control. For example, do not use unsalted password hashes in the application. The following hashing algorithms and digest lengths should be used, subject to the indicated restrictions (if any). They are listed in order of preference, starting with the most preferred. Hashing
Algorithm Digest Length(s) Usage Restrictions
SHA-3 224, 256, 384, or 512 bits No Usage restrictions
SHA-2 224, 256, 384, or 512 bits
SHA-1 224, 256, 384, or 512 bits
Cryptography – Example Example 1:
The following packages belonging to JCE, aid in data encryption: import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.Cipher;
Example 2: The following sample code shows AES key generation using KeyGenerator, initialization of the keysize to 128 followed by cipher creation and initialization by specifying the algorithm name i.e. AES:
KeyGenerator key = KeyGenerator.getInstance(“AES”); key.init(128); SecretKey secretKey = key.generateKey(); Cipher aesCipher = Cipher.getInstance(“AES”); aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
Example 3: The aesCipher.doFinal(byteDataToEncrypt) is used to encrypt the data (byte data). Decryption is achieved through the same method doFinal but after initializing the cipher for decryption:
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters())
  1. Configuration Management
Configuration management is the arrangement of the application’s functional units. It deals with the application configuration attributes which assist the application to be developed and deployed in a secure manner. The configuration settings of the application which are accessed and used throughout the application are specified in a centralized application configuration file. Some of the areas covered in the configuration file include database connection details, global variables used throughout the application, and compilation attributes. If unaddressed, weak configuration management may lead to the following implications:
  • Breach of the confidentiality and integrity of the application
  • Information leakage of internal workings
  • Unencrypted connection strings and network transmission
Configuration Management Standard
  1. Encrypt the username/password information present in configuration file as part of database connection string
  2. Lock the application configuration settings and enforce a machine wide policy by setting appropriate attributes in the server configuration file, “server.xml”. This tells the configuration system to throw an error if a lower-level configuration file attempts to override any locked configuration attribute
  3. Disable tracing on the production application
  4. Configure the request and response encoding
  5. Disable debug compilation on the application
  6. Access to administrative services should not be allowed over the Internet. Multifactor authentication mechanisms should be considered to enhance access control to such interfaces.
  7. Control access to application configuration files (such as web.xml). Consider the principle of “least privilege” and “need-to-know-basis” while setting up the access control to configuration files. These configuration files often contain restricted / confidential information such as passwords, connection parameters and access control information relating to the most critical assets in the system
  8. Prevent users from uploading very large files by enforcing restrictions on the size of the file to be uploaded using the application.
  9. Set global application error handler and redirect the error to a customized error page providing generic information without disclosing technology and sensitive details
  10. Set global data/input validation in the configuration file so that it can be used consistently throughout the application
  11. Do not store the configuration files in the public folder
  12. Do not store sensitive information in the application configuration file in plain text. Store the sensitive information (for example, database connection string) in an encrypted form either in the configuration file itself or in some external sources (such as registry) and provide reference in the configuration file.
  13. If a web development framework are used then ensure that the latest version of modules, libraries or extensions are used that potentially fixes all the well- known vulnerabilities, as well as review and change the default configuration to enhance its security.
  14. Access to the files in the server should be provided only to authenticated and authorized set of users by following the principle of least privilege and on a need-to-know-basis.
  15. Restrict the users and their access rights based on the requirement. The web server directories should not have write permissions enabled unless it is used for uploading files by the application. The directory in which the files are uploaded by the application should not be in the webroot.
  16. Disable directory listing in the web server configuration. Directory listing will lead to disclosure of web directory and file information to the unauthorized users who are access the application via web browser.
  17. Server operating system and software’s present in the server should be kept up-to-date and patched with the latest vendor supplied security patches.
  18. Vendor-supplied default user credentials and default unnecessary files/modules/functions should be removed from the systems. This should also include default stored procedures, views, tables and other database objects which are not required for the database system.
  19. Development, test and/or custom application accounts, user IDs, and passwords should be removed before applications become active or are released to customers.
  20. Unnecessary software’s and services should not be running on the system. The system should not have any additional software’s or services (which are related to each other) apart from the primary requirement for which the system is developed or used. For example, it is not advisable to have a database system present in the web/application server itself.
  21. Do not dynamically retrieve external build dependencies from untrusted sources. This may leave the build system vulnerable to malicious binaries and or lead to unexpected system/application behavior.
Configuration Management – Examples Example 1: The following code snippet shows configuration of application resources in struts using web.xml file:
<servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-value> com.example.ApplicationResources </param-value> </init-param> </servlet>
  1. Data Access
In Java enterprise applications, the data access layer includes the process of communication of data between the application and the storage repository (which could be a database, a flat-file, or a complete accounting system). If unaddressed, weak data access controls may lead to the following implications:
  • Unauthorized access to data
  • Performance of unauthorized operations on the application and related infrastructure
  • Breach of the confidentiality, integrity and availability of information
Data Access Standard
  1. Protect database login information
    • Allow web applications to use container managed connection pools to protect database login formation. Container managed connection pools should be used to configure applications and roles to use server resources
  2. Secure the communication between data source and data access layer
  3. Data validation
    • Use prepared statements or stored procedures instead of dynamically generated SQL in data access layer to avoid SQL injection
    • When making calls to backend databases, carefully validate the data provided to ensure that it does not contain any malicious content
    • Validate all input, even when using prepared queries and stored procedures
  4. Avoid external interpreters
    • Use library API’s to call external resources
    • Avoid using system calls such as exec, fork, Runtime.exe etc. to talk to external resources
  5. Return minimal error information to users. Handle database errors at the data access layer through the use of database queries (i.e. using PL/SQL error and exception handlers)
  6. Grant minimum privileges to the database user for access to the database resource. Follow the principle of Least Privilege wherein the user is given only the defined privileges required to perform the actions assigned to his role
  7. Do not allow unauthorized users to access or modify XML document information during transmission over the network by encrypting and digitally signing the XML documents. The following steps detail the process of creating a XML signature:
    • Determine the resources that are to be signed
    • Calculate the digest of each resource.  The <DigestMethod> element tells which algorithm is used to calculate the digest value
    • Collect the <Reference> elements (with their associated digests) within a <SignedInfo> element
    • Sign the digest and put the signature value in a <SignatureValue> element
    • Add the key information that includes public key needed for signature verification
    • Place the <SignedInfo>, <SignatureValue>, and <KeyInfo> elements into a <Signature> element. The <Signature> element comprises the XML signature
  8. Encrypt XML documents containing restricted / confidential information (such as user credentials, connection parameters, user account details etc.)
  9. Digitally sign the XML document. Create and verify electronic signatures. Such a signature may be used for different purposes such as verifying the integrity and ensuring the non-repudiation
  10. Only allow legitimate parties to view content
  11. Ensure database user has minimum privileges to access database resource
  12. Avoid using system calls such as exec, fork, Runtime.exe etc to call external resources. Use library API’s to call external resources
Data Access – Examples Example 1: The following sample code details the creation of an XML signature:
<? Xml version=”1.0″ encoding=”UTF-8″?> <Signature xmlns=”http://www.w3.org/2000/09/xmldsig#”> <SignedInfo Id=”foobar”> <CanonicalizationMethod Algorithm=”http://www.w3.org/TR/2001/REC-xml-c14n-20010315″/> <SignatureMethod Algorithm=”http://www.w3.org/2000/09/xmldsig#dsa-sha1″ /> <Reference URI=”http://www.abccompany.com/news/2000/03_27_00.htm”> <DigestMethod Algorithm=”http://www.w3.org/2000/09/xmldsig#sha1″/> <DigestValue>j6lwx3rvEPO0vKtMup4NbeVu8nk=</DigestValue> </Reference> <Reference URI=”http://www.w3.org/TR/2000/WD-xmldsig-core- 20000228/signature-example.xml”> <DigestMethod Algorithm=”http://www.w3.org/2000/09/xmldsig#sha1″/> <DigestValue>UrXLDLBIta6skoV5/A8Q38GEw44=</DigestValue> </Reference> </SignedInfo> <SignatureValue>MC0E~LE=</SignatureValue> <KeyInfo> <X509Data> <X509SubjectName>CN=Ed Simon,O=XMLSec Inc.,ST=OTTAWA,C=CA</X509SubjectName> <X509Certificate> MIID5jCCA0+gA…lVN </X509Certificate> </X509Data> </KeyInfo> </Signature>
Nitesh

Nitesh

Author

Bonjour. A curious dreamer enchanted by various languages, I write towards making technology seem fun here at Asha24.