My Java Codebashing Notes

25 April 2021

As part of our training, we were given access to some courses on codebashing and Java being my primary course. We were generously given access to other courses which I will pursue during my spare time. I'm looking forward to complete other Java-related courses too and time-permitting, I'll try Golang and Ruby on Rails courses. That's a very optimistic wish but if access to this resources will remain, might as well consider it as opportunity.

Java Codebashing Certificate

SQL Injection

Attack: or 1=1)#

Mitigation: Use SQL prepared statements

XXE (XML External Entity) Processing

Attack:

<!DOCTYPE foo [<!ELEMENT foo ANY >
<!ENTITY bar SYSTEM "file:///etc/passwd" >]>
<foo>&bar;</foo> <!-- added to the metadata -->

Mitigation:

documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

Command Injection

Attacker passed ;id to the URL after identifying that it executes a console command.

Mitigation:
myUiD here is exposed as URL parameter therefore sanitise the value before processing.

if (!Pattern.matches("[0-9A-Za-z]+", myUiD)) {  
    return false;
}
Runtime rt = Runtime.getRuntime();

Session Fixation

Attacker will copy the URL from the application login then send it as phising email to the target. If the target will use the login URL and authenticate himself, then the attack is successful.

Mitigation: Invalidate the sesssion after authentication and issue a new one.

Use Of Insufficiently Random Values

Attacker could use predictability of pseudo-random number generators to hijack valid user sessions.

Mitigation: Use random value generated by secure random generator. In an instance,

SecureRandom rand = new SecureRandom();
byte bytes[] = new byte[20];    
rand.nextBytes(bytes);  
String cookie = new String(Hex.encodeHex(bytes));   
return cookie;

Reflected Cross-Site Scripting (XSS)

Attacker found out that user input is returned in HTTP response to the browser.

Mitigation: Use escaping techniques each time user-supplied data is used by the application when building responses to users.

Stored Cross-Site Scripting (XSS)

Mitigation: User input should be sanitised before persisting to the database and after its retrieval from the database and then served to the user.

DOM (Document Object Model) XSS

Precondition: User input is not encoded and is rendered within a dynamic context.

Mitigation: Application should first HTML-encode and then JavaScript-encode any user-supplied data that is returned to the client.

Directory (Path) Traversal

Mitigation: Canonicalise the path then validate if it's the expected location

File file = new File("/tmp/" + filename);
String canonicalPath = file.getCanonicalPath();
if(!canonicalPath.startsWith("/tmp/")) {
    throw new GenericException("Unauthorized access");
}

Session Exposure within URL

Mitigation: Ensure that session identifiers are not transmitted to the application via GET requests, only via POST requests and should be over HTTPS.

User Enumeration

Precondition: Login form, password-recovery form reveals if user exists.

Mitigation: Don't reveal if a user (especially when email is the unique identifier) exists on your application.

Horizontal Privilege Escalation

Definition: Attackers being able to steal other, similar user privileges which apply to a different scope or domain of access.

Mitigation: Before doing CRUD operation, verify the current user using HttpServletRequest's getUserPrincipal().getName()

Vertical Privilege Escalation

Definition: Attacker gets access to the application's functionality that requires special privileges. For example, when a regular user gets access to the user management functionality that only the admin should be able to access.

Mitigation: Java Spring Framework provides support for Expression-Based Access Control with the hasRole([role]) expression.

Cross Site Request Forgery (POST)

Preconditions:

Mitigation: Use proper HTTP verbs for CRUD operations

Clickjacking

Preconditions:

Mitigation:

<IfModule mod_headers.so>
    # Prevent Clickjacking using X-Frame-Options header
    Header set X-Frame-Options "deny"

    # Prevent Clickjacking using Content Security Policy (Not supported by all major browsers yet)
    Header set Content-Security-Policy: frame-options 'deny'; # Chrome / Firefox
    Header set X-Content-Security-Policy: frame-options 'deny'; # Internet Explorer
</IfModule>

Insecure URL Redirect

Attack: Send the potential victim a link with malicious site in the URL parameter. The victim opens a legitimate site that redirects him to the malicious site where the attacker deployed a phising page

Mitigation: Validate the URL parameter before redirection. If URL redirect can be avoided, don't use it on your application.

Insecure TLS Validation

Note: DES, Blowfish and RC4 algorithms are vulnerable to attacks that allow an attacker to view communication in plaintext. Currently, AES has not been proved to be vulnerable so it is the best choice for encryption in TLS connections.

Mitigation: Use the java.security.cert to validate peer certificates.

HttpsURLConnection conn = (HttpsURLConnection) destinationURL.openConnection();
java.security.cert.Certificate[] certs = conn.getServerCertificates();
((X509Certificate) cert).checkValidity();