LDAP Injection Primer for Java Developers

LDAP Injection attacks are popular due to the common use of LDAP to authenticate user. The Lightweight Directory Access Protocol (LDAP) origins started with the set of OSI standards called X.500. The X.500 standards are large and heavy which communicated over the Open Systems Interconnection (OSI) protocol stack. X.500 described the Directory Access Protocol (DAP) for how clients communicate with an X.500 Directory Service. DAP was not broadly implemented due to lack of OSI Stack implementations but core services were extracted and implemented in LDAP and the Novell Directory Service. Any software that dynamically generates LDAP requests, like SQL Injection, can be vulnerable to LDAP Injection if input is not sanitized and then manipulated the dynamic request creation. Since there is no parameterized query interface for LDAP, these attacks are popular due to the common use of LDAP to authenticate user.

LDAP Injection Impact

The Lightweight Directory Access Protocol (LDAP) allows software to construct queries to back end directory services. These queries are frequently made as part of an authentication step. If an attacker can inject their own code into the dynamically generated query then they could bypass the authentication step or potentially assume the rights of another user or administrator. Alternatively, they could extract information not originally intended for the authenticated users authorization level or hijack a valid users session.

Testing for LDAP Injection

LDAP Injection testing can be performed by attempting to inject LDAP Search Filter metacharacters into any external untrusted parameters to determine if the server responds with additional information. If the input parameter is used in a filter query to the directory server then we can attempt to enter information to make the query always true.

Examples of LDAP Injection

In this example there is a web application with a login form containing a username and password fields and a login button. Once the user presses the login button the contents of the username and password fields are transferred to code which uses a LDAP search filter to confirm the login credentials. The LDAP filter looks likes this:


If user input is not sanitized or validated against a whitelist then an attacker could user metacharacters to inject into this filter. If an attacker enters a valid username of :


And enters any string as a password then the directory server will receive a filter query like this:


Since the server only processes the first filter and johnsmith is a valid username then the above statement is always true. If the result is used in an authentication decision then the attacker gains access to the system as johnsmith only for knowing a valid username.

Fixes for LDAP Injection

Perform server-side validation of all user-supplied data

  • Ideally the data should be validated against a white list of known-good characters, such as only upper and lower case letters and numbers 0-9. Characters that do not match the expression (such as special or meta characters) should be rejected
  • Always do server side validation on user inputs
  • Never concatenate strings, leverage the chosen libraries features to create filters programmatically, for example
String filter = "(|(uid=" + userInput + ")(mail=" + userInput + "))";

should be modified to,

Filter filter = Filter.createORFilter(
     Filter.createEqualityFilter("uid", userInput),
     Filter.createEqualityFilter("mail", userInput));


Want to check your projects for free?


CWE-90: Improper Neutralization of Special Elements used in an LDAP Query (‘LDAP Injection’)
OWASP: Testing for LDAP Injection (OTG-INPVAL-006)
BlackHat: LDAP Injection & Blind LDAP Injection
Wikipedia: LDAP Injection

JSP XSLT Primer for Java Developers

jsp xslt


Extensible Stylesheet Language Transformations (XSLT) is a transformation language that ingests an XML document and transforms that document into another XML document. If an attacker can control the content of the style sheet, he/she would potentially be able to trigger remote code execution (RCE) or server-side path traversal.

Fixes for JSP XSLT

Take for example a simple XSLT transform,

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/technology_companies">
	<xsl:value-of select="system-property('xsl:vendor')"/>

In this example the logic injects value matching /technology_companies, this could be a potential area to inject code. If an attacker were to be able to inject directives, they could discover the XSLT library being used and exploit further, e.g. system-property('xsl:vendor')

A general solution if XSLT is required to be used:

  • Avoid interpreting user defined XSLT documents
  • Do not generate XSLT documents and internal fields from inputs that can be controlled by the user, e.g. company name
  • Based upon the XSLT library in use, review the library’s default settings and disable unsafe functionality that could lead to XML External Entities from being executed

Want to check your projects for free?


WS-Attack: XML Signature – XSLT Code Execution
ContextIS: XSLT Server Side Injection Attacks
OWASP: Path Traversal

JSP JSTL Out Primer for Java Developers

Java Server Pages(JSP) currently can define tag definitions through the Standard Tag Library (JSTL). One of the tag functions is the ability to disable escapeXml which could potentially be dangerous in Cross-Site Scripting attacks. By disabling escapeXml an attacker can manipulate an XML document which is reflected within a client browser and inject HTML and/or Javascript syntax.

Impact of JSP JSTL Out

Exploiting the Standard Tag Library leading to a successful Cross Site Scripting (XSS) attack results in javascript code running in a users browser without their knowledge. That code then reads the session cookie of a logged in session to their bank, work account, or any other account they have a session with. Once in possession of the session cookie, the malicious code then transmits that value to the attacker who can then connect to the site with that session cookie assuming the role of the original user. Now the attacker can do anything as that user.

Fixes for JSP JSTL Out

All data elements rendered within response content must be properly encoded to ensure the data is not interpreted as markup code by the user’s web browser. Depending on where within the response the data is rendered, one of the following encoding methods should be used: HTML: HtmlEncoding should be used to escape all rendered output. For example, script tags are escaped by replacing the < and > characters with < and >. JavaScript: Data rendered within JavaScript code can be encoded into the format \xDD where DD is the hexadecimal value of the ASCII character. This causes the encoded characters to be taken literally by the browser, rather than interpreted as meta characters. URL: Data rendered within a URL should be URLEncoded into the format %DD, where DD is the hexadecimal value of the ASCII character. HTML Attributes: Properly quoted attributes can only be escaped with the corresponding quote. Ensure that the attribute is quoted and that any quotes within the data value are encoded. Most development platforms have a native encoding mechanism that can be leveraged to perform the above encodings. Additionally, there are a number of publicly available APIs that provide encoding functionality.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="${param.test_param}" escapeXml="false"/>

must be changed to,

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:out value="${param.test_param}"/>

Want to check your projects for free?


CWE-79: Improper Neutralization of Input During Web Page Generation (‘Cross-site Scripting’)
Tutorial Point: JSTL fn:escapeXml definition
Oracle: JSTL core Tag out

JSP Spring Eval Primer for Java Developers

JSP Spring Eval
Spring can specify functionality within a Java Server Page(JSP) to inject into the eval tag an expression to be executed at render time. If the expression can be wholly or partially control by user input, an attacker could inject dynamic values to inject code to be executed when the page is rendered on the server.

Impact of JSP Spring Eval

Method invocation and arbitrary code execution can occur within the context of the application allowing for sensitive data exposure, system access and even the risk of the entire server being compromised.

Fixes for JSP Spring Eval

The source of the value(s) should be verified to avoid unfiltered values falling into this risky code evaluation

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="${param.lang}" var="lang" />
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="'${param.lang}'=='fr'" var="languageIsFrench" />

must be changed to,

<c:set var="lang" value="${param.lang}"/>
<c:set var="languageIsFrench" value="${param.lang == 'fr'}"/>

Want to check your projects for free?


CWE-94: Improper Control of Generation of Code (‘Code Injection’)
CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code (‘Eval Injection’)
Spring Documentation: Class EvalTag

Insecure Object Primer for Java Developers


Java Server Pages (JSP) allows the ability to include dynamic values within its file definition to be rendered by the server at runtime. A feature of JSP pages is to have the ability to include files via the jsp:include or c:import tag. If the tag is rendered on the server with an unvalidated user input this will give the ability of the user to specify content from the hosting server or even from a remote site. The impact of the exploit can lead to information leakage

Fixes for JSP Include

By injecting unsanitized user input the user will be able to fetching what might be accessible from the host system

   String p = request.getParameter("p");
   @include file="<%="includes/" + p +".jsp"%>"

Sending a HTTP request with parameters ‘p’, an attacker can retrieve the password file from the local file system


Solution: Listed below are recommendations to fix unsanitized user inputs being included within JSP

  • All-together disallow user inputs from being populated within the file include for JSP
  • Disallow user input for file system calls
  • Use enum/integers to translate user input into sane values, e.g. 1 = ‘en-ca’, 2 = ‘en-us’, etc.
  • Only allow users to partially specify file path
  • Jail file or code access with such mechanisms as chroot jails for fetching and saving files

Want to check your projects for free?


InfoSec Institute: Dangerous File Inclusion Attacks
Stack Overflow: File Inclusion Local Vulnerability Protection
Wikipedia: Definition of File Inclusion Vulnerability
OWASP: Testing for Local File Inclusion

Insecure Data Storage Primer for Java Developers

insecure data storage

Insecure data storage is when files can be identified and contain plain text or encoded credentials. These credentials include usernames, passwords, private encryption keys, and other potentially sensitive data that can be leveraged to obtain unauthorized application access. Depending on the nature of the embedded data, these secrets can be used to obtain access to various application resources, such as back-end database servers and/or administrative functionality.

Fixes for Insecure Data Storage

Remove all instances of plaintext or encoded credentials from within all files. Developers and administrators should always work with the assumption that a malicious attacker is likely to obtain access to application source code (via source code disclosure vulnerability, de-compilation, etc) or other files and scripts used for administration purposes. This assumption is especially critical when considering code that is deployed on externally accessible systems (resources located in web accessible directories, client-side code, etc). Usernames and passwords stored for access to other systems must always be encrypted when stored and should only be decrypted on-the-fly as needed by applications or other systems. Consider encrypting sensitive personally identifiable information, such as social security numbers, to help protect it in the event of unauthorized access to the storage medium.

Want to check your projects for free?


CWE-922: Insecure Storage of Sensitive Information
SE Works: Understanding Insecure Data Storage & How To Approach It
OWASP Mobile Top 10: Exploring Insecure Mobile Data Storage

Insecure Crypto Primer for Java Developers

insecure cryptography

Insecure Cryptography is a general vulnerability in which the encryption algorithm chosen for use cases such as authentication, integrity checks, signature verification is weak and susceptible to attacks. Typical attacks exploit the algorithms collision characteristics, i.e. the ability of the attacker to control/predict what the algorithm produces for two different data inputs. If an attacker was able to identify a collision of two inputs that produce the same output, they would be able to identify the original text.

Impact of Insecure Cryptography

If an attacker can exploit a poorly chosen encryption algorithm, this may allow for an attacker to decrypt the text and violate data confidentiality and/or message integrity.

Fixes for Insecure Cryptography

Reconfigure the service to use a strong encryption algorithm along with key lengths that provide a minimum of 112-bits of effective key strength.

Examples of industry-tested and accepted standards and algorithms include AES (128 bits and higher), RSA (2048 bits and higher), ECC (224 bits and higher), and DSA/D-H (2048/224 bits and higher).

Want to check your projects for free?


CWE-310: Consolidation of Cryptographic Issues
Shattered.IO: How We Broke SHA-1 in Practice
Stack Exchange: What Cryptographic Algorithms Are Not Considered Secure

Information Leakage Primer for Java Developers

Information leakage is a weakness where an application reveals sensitive information such as technical details, environment details, or user-specific data. Sensitive data may be used by an attacker to plan out more refined attacks against the application.

Resources, such as files and directories may be inadvertently exposed through mechanisms such as insecure permissions, or when a program accidentally operates on the wrong object. Alternatively, information is accidentally transmitted over an insecure channel. In addition, information identifying architecture, software, and versions, may provide an attacker with details to focus further attacks. Error messages are also a big source of sensitive information.

Regardless the result is that a resource has been exposed to the an entity that is not authorized to view the data because the software incorrectly maintains control over a resource throughout its lifetime.

Impact of Information Leakage

Customer Names: Amazon exposed customer names and emails in a ‘technical error’

Some Amazon customers received an email from the company telling them their names and emails had been exposed due to a “technical error.” The impact of information leakage issues such as this can range from customers having to reset passwords, change significant elements of their identity (SIN/SSN), to providing an attacker with information about the site and its hosting environment.

Testing for Information Leakage for Java

Testing for information leakage involves:

  • Using a search engine to discover any information about the web application (google dorks, etc)
  • Attempting to fingerprint the web server and web application
  • Access web server meta files for information on file paths
  • fingerprint web application framework via cookies and header
  • Follow all code paths to attempt to generate exception errors
  • unit test extreme error conditions and confirm errors and exception are handled

Examples of Information Leakage

The code below exposes that a given username does not exist in an error message. This enables an attacker to itemize valid and invalid usernames.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  PrintWriter out = response.getWriter();

  String username = request.getParameter("username");
  String password = request.getParameter("password");

  if(LoginDao.validateUser(username)) {

    out.print("Sorry - no such username");
    RequestDispatcher rd=request.getRequestDispatcher("index.html");


Java Fixes for Information Leakage

Scrub HTML pages for user information, environment specific information, and technical details that would help attackers learn more about the application, its users, or it’s environments Be careful to not provide sensitive information in error messages and ensure all errors and exceptions are handled in a controlled manner.


Information Leakage Example: UNICEF data leak reveals personal info of 8,000 online learners

The United Nations Children’s Fund (UNICEF) accidentally exposed the personal information of thousands of users of its online learning portal. This was caused by an email which was sent to 20,000 users of the same portal.

Want to check your projects for free?


CWE-200: Information Exposure
CWE-664: Improper Control of a Resource Through its Lifetime
WASC-13: Information Leakage
OWASPTop 10-2017 A3: Sensitive Data Exposure

HTTP Header Injection Primer for Java Developers

Header Injection

Hypertext Transfer Protocol (HTTP) header injection can only occur when user-supplied unsanitized data is copied into a response header. If an attacker can inject a carriage return and line feed (CRLF) into the response header, they can add new HTTP headers and/or any arbitrary content into the application’s response. This can lead to a large number of exploits including HTTP response splitting, session fixation, cross-site scripting, and malicious redirect attacks.

Impact of Header Injection

Header Injection can lead to many exploits by manipulating the header via user input and injecting additional content, control not only the headers of the HTTP but also session and content manipulation within the response. Listed below are some exploits that can occur from header injection.

  • Cross-site scripting attack, which can lead to session hijacking
  • Session fixation attacks by setting new cookies
  • Poisoning the cache of any proxy server and/or browser

Fixes for Header Injection in Java

In general, replacing all occurrences of “\n” might still not be enough. It is best practice to remove both “\n” and “\r” with “” (nothing) when transferring from user input into a response header for CRLF attacks. For HTTP attributes stripping ” “, “”” and “;” can also be used based upon context.

Vulnerable Code:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String value = req.getParameter("value");
  resp.addHeader("X-Header", value); // Noncompliant
  // ...

Sanitizing User-data:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String value = req.getParameter("value");

  // Allow only alphanumeric characters
  if (!value.matches("[a-zA-Z0-9]++"))
    throw new IOException();

  resp.addHeader("X-Header", value);
  // ...

Want to check your projects for free?


OWASP: HTTP Response Splitting
CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers (‘HTTP Response Splitting’)