Security of Java Applications: Top 10 Vulnerabilities in Practice
Security of Java applications is not just a checkbox on a checklist, but a critically important aspect of development. According to OWASP, more than 70% of modern web applications contain at least one critical vulnerability. In this article, we will analyze the 10 most common threats with real code examples and ways to fix them. The material will be useful for both beginner and experienced Java developers.
1. SQL Injections (Injection)
SQL injection remains the leader among vulnerabilities. An attacker can inject malicious SQL code through user input.
Vulnerable code:
String query = "SELECT * FROM users WHERE username = '" + username + "'";Statement stmt = connection.createStatement();ResultSet rs = stmt.executeQuery(query);Fixed code (using PreparedStatement):
String query = "SELECT * FROM users WHERE username = ?";PreparedStatement pstmt = connection.prepareStatement(query);pstmt.setString(1, username);ResultSet rs = pstmt.executeQuery();2. XSS (Cross-Site Scripting)
XSS attacks allow injecting client-side scripts into web pages. The main defense is output escaping.
Vulnerable code (JSP):
<%= request.getParameter("comment") %>Fixed code:
<%= Encode.forHtml(request.getParameter("comment")) %>Use the OWASP Java Encoder library for reliable escaping:
import org.owasp.encoder.Encode;String safeOutput = Encode.forHtml(userInput);3. Insecure Deserialization
Java deserialization can lead to remote code execution (RCE).
Vulnerable code:
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());Object obj = ois.readObject(); // Danger!Protection recommendations:
- Do not deserialize data from untrusted sources
- Use a whitelist of classes during deserialization
- Use JSON or XML instead of Java serialization
// Safe approach with class validationObjectInputStream ois = new ObjectInputStream(inputStream) { @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!allowedClasses.contains(desc.getName())) { throw new InvalidClassException(desc.getName(), "Unauthorized deserialization"); } return super.resolveClass(desc); }};4. CSRF (Cross-Site Request Forgery)
CSRF attacks force a user to perform unwanted actions on a site where they are authenticated.
Protection using tokens (Spring Security):
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }}Adding a token to the form:
<form action="/transfer" method="POST"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <input type="text" name="amount"/> <button type="submit">Transfer</button></form>5. Information Leakage Through Exceptions
Detailed error messages can reveal the internal structure of the application.
Vulnerable code:
try { // business logic} catch (SQLException e) { response.getWriter().println("Error: " + e.getMessage()); // Leak!}<