The OWASP (Open Web Application Security Project) is an
organization that focuses on improving the security of software. They publish a
list of the top security risks for web applications, known as the OWASP Top 10.
As of my last update, the list is the OWASP Top 10 for 2021. Here is a detailed
understanding of each of these risks along with examples and explanations
OWASP Top 10 – 2021
- Broken
Access Control
- Description:
Occurs when an application does not properly restrict user access to data
or functionality.
- Scenario:
An application has an admin panel accessible at admin.example.com.
However, there is no proper access control in place, and any user can
access it by typing the URL.
- Example:
Unauthorized users accessing restricted pages by manipulating URLs or
bypassing security controls.
- Reproducing:
A servlet that does not check user
roles before accessing admin functions
@WebServlet("/admin") public class AdminServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
String userRole = (String)
request.getSession().getAttribute("role");
// Missing role check, any user can access this endpoint
response.getWriter().write("Admin Content");
} } |
- Mitigation:
Implement proper access control checks on the server side, use secure
coding practices, and conduct regular access control testing.
- Process:
- Implement
role-based access control (RBAC).
- Use
annotations like @Secured or @RolesAllowed to enforce security at the
method level.
- Validate
access control on the server side.
import
org.springframework.security.access.annotation.Secured; @RestController public class AdminController {
@Secured("ROLE_ADMIN")
@GetMapping("/admin")
public String adminAccess() {
return "Admin Content";
} } |
- Cryptographic
Failures
- Description:
Failures in implementing cryptography correctly, such as using weak
algorithms or improper key management.
- Scenario:
A web application stores user passwords in plain text in the database
- Example:
Storing passwords using weak hashing algorithms like MD5.
- Reproducing:
Storing passwords in plain text.
public class PasswordService {
private Map<String, String> userDatabase = new
HashMap<>();
public void registerUser(String username, String password) {
// Storing password in plain text
userDatabase.put(username, password);
}
public boolean authenticateUser(String username, String password) {
return password.equals(userDatabase.get(username));
} } |
- Mitigation:
Use strong, tested cryptographic algorithms, ensure proper key
management, and use libraries that are designed for secure cryptographic
operations.
- Process:
- Use
strong encryption algorithms like AES.
- Use
secure hashing algorithms like bcrypt for passwords.
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordService {
private BCryptPasswordEncoder passwordEncoder = new
BCryptPasswordEncoder();
public String hashPassword(String plainPassword) {
return passwordEncoder.encode(plainPassword);
}
public boolean checkPassword(String plainPassword, String
hashedPassword) {
return passwordEncoder.matches(plainPassword, hashedPassword);
} } |
- Injection
- Description:
Occurs when an attacker is able to send malicious data to an interpreter,
leading to unintended commands or queries.
- Scenario:
An application constructs SQL queries using user input without proper
sanitization: SELECT * FROM users WHERE username = 'user' AND password =
'password';
- Example:
SQL Injection, where an attacker can manipulate a SQL query to access
unauthorized data.
- Reproducing:
SQL Injection through user input.
public class UserDao {
public User getUserById(Connection conn, String userId) throws
SQLException {
String query = "SELECT * FROM users WHERE id = '" + userId +
"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
// SQL Injection possible
return rs.next() ? new User(rs.getString("id"),
rs.getString("name")) : null;
} } |
- Mitigation:
Use parameterized queries, input validation, and escaping.
- Process:
- Use
prepared statements for database queries.
- Use
ORM frameworks like Hibernate to prevent SQL injection.
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class UserDao {
public void getUserById(Connection conn, String userId) throws
SQLException {
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, userId);
stmt.executeQuery();
} } |
- Insecure
Design
- Description:
A broader category referring to issues stemming from insecure design
patterns.
o
Scenario: A web application does not
consider security during the design phase, leading to multiple vulnerabilities.
- Reproducing:
Directly exposing database error
messages.
@WebServlet("/user") public class UserServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
String userId = request.getParameter("id");
try { User user = getUserById(userId);
response.getWriter().write("User: " + user.getName());
} catch (SQLException e) { // Exposing database error
message
response.getWriter().write("Error: " + e.getMessage());
}
}
private User getUserById(String userId) throws SQLException {
// Simulated database access
return new User(userId, "John Doe");
} } |
- Example:
Lack of threat modeling, security requirements, or secure design
patterns.
- Mitigation:
Incorporate security into the design phase, conduct threat modeling, and
use secure design principles.
- Process:
- Conduct
threat modeling and use secure design patterns.
- Incorporate
security requirements in the design phase.
- Security
Misconfiguration
- Description:
Occurs when security settings are not defined, implemented, or maintained
properly.
o Scenario:
A web server runs with default settings, including default usernames and
passwords.
- Example:
Default accounts and passwords left unchanged.
- Reproducing:
Using an old version of a library
with known vulnerabilities.
public class DefaultCredentials {
public boolean authenticate(String username, String password) {
// Default credentials
return "admin".equals(username) &&
"password".equals(password);
} } |
- Mitigation:
Ensure secure settings are configured, remove unused features, and
regularly update software.
- Process:
- Disable
default accounts and update default credentials.
- Configure
security settings properly and keep them up to date.
# application.yml for Spring Boot server:
port: 8443
ssl:
enabled: true
key-store: classpath:keystore.jks
key-store-password: changeit
key-password: changeit |
- Vulnerable
and Outdated Components
- Description:
Using components with known vulnerabilities or not updating components.
- Example:
Using a library with a known critical vulnerability.
- Reproducing:
A servlet that does not check user
roles before accessing admin functions
<!-- pom.xml --> <!-- pom.xml for Maven --> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.2</version> <!-- Known vulnerabilities
in this version --> </dependency> |
- Mitigation:
Regularly update and patch components, use tools to scan for
vulnerabilities.
- Process:
- Regularly
update dependencies.
- Use
tools like OWASP Dependency-Check to identify vulnerable components.
<!-- pom.xml for Maven --> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version> <!-- Ensure this is the
latest version --> </dependency> |
- Identification
and Authentication Failures
- Description:
Issues in identifying and authenticating users, leading to unauthorized
access.
- Example:
Weak password policies, lack of multi-factor authentication.
- Reproducing:
Weak session management.
@WebServlet("/login") public class LoginServlet extends
HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// No password hashing, weak session management
if ("admin".equals(username) &&
"password".equals(password)) {
request.getSession().setAttribute("user", username);
response.getWriter().write("Login Successful");
} else {
response.getWriter().write("Login Failed");
}
} } |
- Mitigation:
Implement strong authentication mechanisms, enforce strong password
policies, and use multi-factor authentication.
- Process:
- Use
frameworks like Spring Security.
- Implement
multi-factor authentication (MFA).
import
org.springframework.security.config.annotation.web.builders.HttpSecurity; import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; public class SecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http .authorizeRequests()
.antMatchers("/admin/**").authenticated() .and() .formLogin()
.loginPage("/login") .permitAll();
} } |
- Software
and Data Integrity Failures
- Description:
Failures related to software updates, critical data, and CI/CD pipeline
integrity.
- Example:
An attacker compromising the update process to include malicious code.
- Reproducing:
Loading unsigned code.
public class CodeLoader {
public void loadAndExecuteCode(String code) throws Exception {
// Dynamic loading of unsigned code
Class<?> clazz = Class.forName(code);
Runnable runnable = (Runnable)
clazz.getDeclaredConstructor().newInstance();
runnable.run();
} } |
- Mitigation:
Use signed updates, protect the CI/CD pipeline, and use integrity checks.
- Process:
- Use
digital signatures to verify software integrity.
- Implement
integrity checks for data
- Security
Logging and Monitoring Failures
- Description:
Inadequate logging and monitoring, failing to detect and respond to
security breaches.
- Example:
Lack of log monitoring, making it difficult to detect a breach.
- Reproducing:
No logging of authentication
failures.
@WebServlet("/login") public class LoggingService extends
HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (!"admin".equals(username) ||
!"password".equals(password)) { // No logging of failed login
attempts
response.getWriter().write("Login Failed"); return;
}
request.getSession().setAttribute("user", username);
response.getWriter().write("Login Successful");
} } |
- Mitigation:
Implement comprehensive logging and monitoring, and establish an incident
response plan.
- Process:
- Implement
comprehensive logging using frameworks like SLF4J or Logback.
- Monitor
logs and set up alerting mechanisms.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingService {
private static final Logger logger =
LoggerFactory.getLogger(LoggingService.class);
public void logEvent(String message) {
logger.info("Event: " + message);
}
public void logError(String message, Throwable t) {
logger.error("Error: " + message, t);
} } |
- Server-Side
Request Forgery (SSRF)
- Description:
Occurs when an attacker can make the server-side application send HTTP
requests to an unintended location.
- Example:
Exploiting a URL parameter to make the server request an internal
resource.
- Reproducing:
Fetching data from user-supplied
URL.
public class URLService {
public String fetchData(String url) throws IOException {
URL fetchUrl = new URL(url);
BufferedReader in = new BufferedReader(new
InputStreamReader(fetchUrl.openStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) { content.append(inputLine);
}
in.close();
return content.toString();
} } |
- Mitigation:
Validate and sanitize user inputs, implement network segmentation and
access controls.
- Process:
- Validate
and sanitize all user inputs.
- Implement
network segmentation and access controls
import
org.apache.commons.validator.routines.UrlValidator; public class URLService {
private static final String[] SCHEMES =
{"http","https"};
private static final UrlValidator urlValidator = new
UrlValidator(SCHEMES);
public boolean isValidUrl(String url) {
return urlValidator.isValid(url);
} } |
Additional OWASP Risks Beyond
Top 10
- Insufficient
Logging & Monitoring
- Description:
Lack of adequate logging and monitoring to detect and respond to
breaches.
- Mitigation:
Implement logging and monitoring mechanisms and ensure they are reviewed
regularly.
- Insecure
Data Storage
- Description:
Storing sensitive data without proper encryption and security controls.
- Mitigation:
Use strong encryption and access controls for sensitive data storage.
- Insufficient
Attack Protection
- Description:
Lack of mechanisms to detect and prevent automated attacks.
- Mitigation:
Implement rate limiting, CAPTCHAs, and other defenses against automated
attacks.
- Under
protected APIs
- Description:
APIs that lack proper security controls.
- Mitigation:
Secure APIs with authentication, authorization, and input validation.
- Insufficient
Authorization
- Description:
Inadequate enforcement of user permissions.
- Mitigation:
Implement robust authorization checks on all access points.
- Insecure
Mobile Interfaces
- Description:
Mobile applications that do not secure data or communications properly.
- Mitigation:
Use secure coding practices for mobile development and secure data
transmission.
- Insecure
Cloud Interfaces
- Description:
Cloud services that are not properly secured.
- Mitigation:
Implement cloud security best practices, including proper access controls
and encryption.
- Misconfigured
Security Settings
- Description:
Security settings that are not configured correctly, leaving the system
vulnerable.
- Mitigation:
Regularly review and update security configurations.
- Vulnerable
Third-Party Components
- Description:
Using third-party components that have known vulnerabilities.
- Mitigation:
Regularly update third-party components and monitor for vulnerabilities.
- Unvalidated
Redirects and Forwards
- Description:
Allowing redirects and forwards without proper validation.
- Mitigation:
Validate all redirects and forwards to ensure they go to expected
destinations.
Open Web Application Security Project
0 Comments