JAVA Secure Coding
JAVA Secure Coding Guide Note
This Note is about ways to secure code JAVA against various attacks
- Types of Secure Coding
- Input data verification
- Security feauture
- Time and State
- Error handling
- Code error
- Encapsulation
- API Missuse
SQLi
Use of user's input as a query directly.
- Use
prepared StatementsandsetString().
1 2 3 4 5 6 | |
makeSecureString()
1. strlen limit
2. Keywords blacklisting
3. use of [^\p{Alnum}] \ only use alphabets and digits
4. Also limit keywords like IF, CHAR, CONCAT, ASCII, UNION, @, exec, ;, SUBSTRING, BENCHMARK, MD5,SHA1, etc...
makeSecureString()
1 2 3 4 5 6 | |
Improper Control of Resource Identifiers, Resource Injection
Happens when user's input is directly used to identify socket port, file, etc.
- Use list(dictionary) to restrict input value to what it's supposed to be.
XSS
Availability of inserting script on page.
-
Switch
<, >, &, "to< > & "usingreplaceall() -
use OWASP supported API,
ESAPI.encoder().encodeForHTMLAttriute();
Commnad Injection
Use of user's input as part of system commnad.
- Must make dictionary so that the user's input doesn't directly go into the command.
Unrestricted Uploading
- Avalability of uploading script file. 2. Avalability to access them.
- Make upload directory outside of Web server document. (Different Domain)
- Using whitelisting, restirct file types(regardless of capitalization of extention).
- File name must not consist
.*%00.*|.*%ZZ.*|.*;.*, which are indicatingeol. - Use
if(extractFileType(file) == EXECUTABLE_FILE_TYPE)with exeption handling.
- File name must not consist
- Block user from executing files directly. If possible, control the file authority.
- Randomize file name with hash table
Open Redirect
Following code is weak against open redirect exploit. Cracker could redirect url and use
phishingattack.
1 2 3 4 5 6 7 8 | |
indexService(), contains
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
XQuery Injection
! Must study more..
- use
bind...()functions
1 2 3 4 5 | |
XPath Injection
- Filter
", [, ], /, =, @, etcand Query keywords - Use XQuery class.
XQuery xquery = new XQueryFactory().createXQuery(new File("dologin.xq"));,vars.put("loginID", name);
LDAP Injection
LDAP : (Lightweight Directory Access Protocol). Protocol for directory service.
ctx.search()inside LDAP, so one must consider injections.
-
LDAP Authentication Flow

-
LDAP Directory struction

Relative references
-
Filtering. Replace all the
\in DN, and consider special characters(=, +, <, >, #, ; \, (, ), etc)as regular letter
LDAP Maniupulation
Similar to LDAP Injection
- Replace all the
\s withstr.replaceAll("\\","")
CSRF(Cross-Site Request Forgery)
Unauthorized requests done by attacker
- Use Post Method?? => What if you can modify it by MITM(Man in the Middle) Attack using
burpsuite.
Path Traversal
- Use
replaceAll()to filter (", \, /). - Check file path with
getAbsolutePath() -
Make document lists and get url by dictionary system.
-
Why in path we need "-report"?
HTTP Response Splitting
Happens on
HTTP. If the application allowdCR(%0d,\r) andLF(%0a,\n), HTTLP Response Splitting attack is possible. This known to be fixed in most of the modern JAVA EE Application servers.
Useful to understand HTTP Response Splitting Ref
Relative references
- https://blog.detectify.com/2019/06/14/http-response-splitting-exploitations-and-mitigations/
- Cross-User Defacement
- Must filter all the header values that are direclty obtained by user. Filter out
\n and \r
Integer Overflow
When receiving value as an integer, if the value is greater than 2147483647, it goes negative (2's complement).
- Make sure to check if the value is greater than 0
- Also, make sure value doesn't exceed the maximum value of the data type.
Reliance on Untrusted Inputs in a Security Decision
Trusting that the hidden values or the header values wouldn't be manipulated by users.
- Store sensetive informations like user session information in the server and do a security checkup inside the server.
- Use session information instead of Cookie.
- Design the program so that the program doesn't not depends on input values.
JDO(JAVA Data Objects), Persistent API, mybatis Data Map (SQLi)
Another way to execute SQLs. 1. Use paramatized query (the one with
?s) 2. Use makeSecureString
Relative Reference
mybatis Data Map
- Include filter.
- Do not use
($...$)but use#<...>#
Relative Reference
External Control of Sys. config.
- DO NOT use external input as parameter of
Connection.setCatalog() - Use whitelisting
When port is already in use, do not switch to new one
- Secure Coding Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
if (command.equals(CHANGE_FTP_PORT)) { ... String servicePortIndex = request.getParameter(PORT_INDEX_PARM); ... if(servicePortIndex == DEFAULT) { servicemanage.changeSerivcePort(FTP_SERVICE, DEFAULT_FTP_PORT); } else if(servicePortIndex == ALTERNATIVE) { servicemanage.changeSerivcePort(FTP_SERVICE, ALTERNATIVE_FTP_PORT); } }
XSS, DOM
When
Document.write()happens, it could be vulernable toXSS.
- Encode the letters (
<, >, &, ", ', /) to (<, >, &, ", ', /). UseStringEscapeUntils()2.
1 2 3 4 5 6 7 | |
EVAL
Watch what goes in to the
evalparameter. Escape letters like (<, >, &, (, ), ", ')
- Use ESAPI.encoder().encodeForJavaScript()
Process Control
When the process loads library without absolute path, the attacker may change the environment variable and set it to what the attacker wishes.
- Use absolute path.
- Use hash table. => limit what the users can do...
Unsafe Reflection
Use of input as selection of class.
- Use whitelist. Control the input.
Download without Integrity check
Remote download without checking the integrity of the file.
- Sever : Encript the file with
private key. And decript it withpublic key(It's in reverse order because everyone can acess it but noone can deform it.) - Check checksum first, then decrypt it and use the file.
1 2 3 4
_download(checksumFilePath, checksumURL); decrypt(checksumFilePath, publicKey); _download(localPath, remoteURL); return checkCheckSum(localPath, checksumFilePath);
SQLi : Hibernate
Similar to Hibernate : TopLink, CoCoBase.
- Use
setParameter()
1 2 3 4 | |
Reliance on Untrusted Inputs
Believing values like cookies, env. variables and hidden field input values are inmanipulatable.
- Save system status info in server(use session)
- If data must be preserved in client side, encrypt it and do integrity check
- Even after js does filtering do another one in server.
1 2 3 | |
1 2 3 4 5 6 | |
Authentification
Missing Authentification on Critical Functions
- Disable client from bypassing authentication
- Important page must be re-authenticated.
- Use verified to be safe libraries and frameworks like
OpenSSL&ESAPI
- Use verified to be safe libraries and frameworks like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Improper Authorization
SW not checking all the routes from users to access data.
- Reduce
attack surface. - Use frameworks like
JAAS,ESAPI
example
This is an example of LDAP setting
1 2 3 4 5 6 | |
The following example uses ruleMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Improper Permission Assignment
Assignment of read or write authority to unauthorized user.
- Config. files and exec files and libs must be only read and executed by admin.
- Important files like config. files must checked if others can access to it.
1 2 3 4 | |
Use of Broken Cryptographic algorithm
Use of algorithms like
RC2, RC4, RC5, RC6, MD4, MD5, SHA1,DESKey size should be long enough
Following code uses RSA + OAEP, which is known to be strongest cryptophically safe combination.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
Missing Encryption of sensitive data
Sending sensitive information without encryption
- Encrypt all the sensitive infos when sending it across internet
- Use Secure Cookies(HTTPS only).
Hard coded Password
Not good for passwords to be hard coded. It's better to be written in seperate file.
package com.qpalzmm22.test;
Following code is how to use AES and RSA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
Not-So-Random
use of
Math.random()is not so random due to the lack of seed.
- Use
java.util.Randomclass instead - Use
SecureRandom()for key generation
Plaintext Storage of Password
Saving password as is... ex)old passwd file in unix systems.
- Using
RSAwithOAEP
Hard Coded Keys
Hard coded keys give away information about the encryption. Attacker may use this to brute force the code.
- It is recommended to use
AES, ARIA, SEED, 3DESfor symmetric keys andRSAthat's 2048 bit long for asymmnetric key algorithm. DO NOT USEMD4, MD5, SHA1 - Encrypt the keys in diffrent file.
Weak Passwords
Weak Passwords cause user account to be vulnerable.
- Check for the password and require better passwords from user
Permanent Cookies
External input deciding max age of cookies
- System must check and require user to type stronger password.
- Something like this...
1 2 3 4 5 6
Cookie c = new Cookie("sessionID", sessionID); int t = Integer.parseInt(maxAge); if (t > 3600){ t = 3600; } c.setMaxAge(t); - Cookie.setMaxAge to negetive value.(only exists when browser is not shutdown).
Use of One-way Hash Function without Salt && Hardcoded Salt
- Also, do not hard code the salt, but use random values using following code.
Without salt, has functions are weak against rainbow table.
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
PS
The KeyPairGenerator class is used to generate pairs of public and private keys. Key pair generators are constructed using the getInstance factory methods (static methods that return instances of a given class). A Key pair generator for a particular algorithm creates a public/private key pair that can be used with this algorithm. It also associates algorithm-specific parameters with each of the generated keys.
There are two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object:
PSS
Also interestingly, KeyPairGenerator automatically uses highest-priorty installed secureRandom as a source of randomness when initialize() fucntion is called with parameter of AlgorithmParameterSpec. That is not the case for MessageDigest classes
No Integrity Check
Executing or uploading files without checking the integrity of file.
1.DNS lookup
Inappropriate Session Config.
SessionMAxInactiveIntervalshouldn't be -1
- session.setMaxInactiveInterval(-1);
- Also in xml
-1
Password Management Heap Inspection
It's not safe to save infortant data in String class. They always reside in memory until garbage collector in JVM activates.
- No saving imfos like this
String str = new String(pass); - Use local String variable. It will disappear as soon as function disappears.
Hard-Codede Username
DO NOT hard-code login infos, it makes software management hard, or cause bug and of course, login info will be exposed when someone is accessible to code(duh).
- Instead recieve it through parameter.
- It's safer to
load log infosandreceive the infoswith structered programming method.
RSA Padding
RSA must be used with Padding, must be used with
Cipher cipher = Cipher.getInstnaces("RSA/EBC/OAEPPadding"). Not"RSA/**none**/OAEPPadding".
(What is EBC, CBC)[https://ko.wikipedia.org/wiki/%EB%B8%94%EB%A1%9D_%EC%95%94%ED%98%B8_%EC%9A%B4%EC%9A%A9_%EB%B0%A9%EC%8B%9D]
OAEP

Anti CSRF Token
Multiple Binds to Same Port
Could be weak against
packet snipping
socket.setReuseAddress(false);
Insecurity due to State | Time
TOUTOC(Time of check, Time of use)
Parellel threads must be manged with multi-processing safe functions
- Use
synchronizedmodifier for the block to be synchronized with other threads.
EX : (notice synchronized)
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 | |
Infinite Loop
Always put recursion in
if-elsestatement. Always check if file issymbolic link. link when traversing directories withisSymbolicLink()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Connection must be done like so because if we only allow conn not equal to null,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
Static Database Connection
Do not use
Statickeyword for DB connection. This will cause race condition if it's called in multiple places.
1 2 3 4 5 6 | |
Race Condtion : Singleton Member Field
servlet member fields are shared among other threads, so they may be exposed to unauthorized user.
- Do Not save user input data's in Servlet field, but save in local variable
-
or use
newto allocate the memory. -
Something like this...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
public class RaceCon extends javax.servlet.http.HttpServlet { // private String name; <= do not use this as memberd field protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Instead recieve it on local variable String name = req.getParameter("name"); if(name == null || "".equals(name)) return; ... } ... } --- 2. ```JAVA String [] loginInfo = new String[2]; loginInfo[1] = request.getParameter(USER_ID_PARM); loginInfo[0] = request.getParameter(PASSWORD_PARM);
J2EE Bad Practices : Direct Use of Threads (Not in 47 )
J2EErestrictes one from user threads in web applications. Instead, one must use defined framework.
- No new
Thread(Runnable).start();
Safe code looks someting like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Symbolic Name not Mapping to Correct Object
Attackers could try to manipulate what the symbolic name is pointing.
- Do not call classes by
Class.forName("...");, but call by default way(use constructor),new ... - Do not link the important file but read the file directly.
Do not do this, but use the file directly
Double-checked Locking
Double-checked locking does not work as intended. Method Synchonization is the most secure way to synchronize.
Error handling
Information exposure on error messages
Users could obtain information about system by error messages.
- Send minimum error messages and deal with exceptions inside the source code.
- Be careful when using
printStackTrace() - Do not include any system info in the error messages
Detection of Error Condition without action
A situation where the error was found but not handled correctly
- Must do something in try-catch block
- In Try-catch statment, one must make sure after try{}, we must set sensitive values to default values so that the users can't access the value.
Improper Check for Unusual or Exceptional Conditions
Do not use broad exceptions (Exception e ), but use specific exceptions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Combine to the security rule above(Detection of Error Condition without action), one must consider all the possibilities and apply actions to each one of them.
Strong Passwords
Secure Passwords Guide
- Passwords should be 9 ~ 15 letters
- At least one special character.
- Do not have id as substring of password
- Do not have same password as one before.
Null Pointer Reference
Not dereferencing an object without checking if the value is null.
It's simple yet easy to make mistakes
- should be applied when getting parameter value by getParameter();
Improper Resouce Shutdown or Release
Open File Descriptos, heap memory, and socketsnot being closed after usuage.
- do not close connection on
trystatment but usefinallyto close it
FOR EXAMPLE :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
This goes same for sockets
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Call to Notify()
Notifymethod is not clear on which thread to wake. Do not use this method.
- Instead, use
lock1.lock(), andlock2.unlock()with class variableLock lock1;.
One liners (not vul, but mistakes)
- Do not use
serialPersistentFiledswithpublicmodifier, but withprivate static final. - Use
thread.start()instead ofthread.run()for most cases. details - Do not override
synchronized methodbyasynchronized method. - Use
ServerThreadPool.getInstnace().alloc(), ServerThreadPool.getInstnace().free(this)to allocate memory to thread.
Encapsulation
Exposure of Data Element to Wrong Session
Things to Study
- XSS Injection vs. XSS Manipulation
- LDAP
- unsafe reflection
- Integer overflow ex.2
- RuleMap
- Cipher class
- MessageDigest
- Connection con = DriverManager.getConnection(url, "scott", "tiger"); pg.140
- MessageDigest class
- 16번 무결성 검사없는 코드 다운로드
- page 243 .why set max_length as local variable?