├── HttpOnly Flag not set.md
├── README.md
├── Reflected Cross-Site-Scripting (XSS).md
├── Secure Cookie not set.md
├── Session Fixation.md
├── DOM Cross-Site-Scripting (XSS).md
├── Open Redirection.md
├── Weak Password Policy.md
├── Insecure direct object references (IDOR).md
├── SQL Injection.md
├── Log Injection.md
├── Missing CSP Header.md
├── Server-side template injection (SSTI).md
├── Remote File Inclusion (RFI).md
├── Remote Code Execution (RCE).md
├── HSTS not Implemented.md
├── Clickjacking.md
├── Host Header Injection.md
├── Java Deserialization.md
├── XXE injection.md
├── Stored Cross-Site-Scripting (XSS).md
├── CORS Misconfiguration.md
├── Cross-Site Request Forgery (CSRF).md
├── Server-Side Request Forgery (SSRF).md
├── Local File Inclusion(LFI).md
├── Application-level Denial of Service (DoS).md
├── Brute Force.md
├── Unrestricted File Upload.md
├── Insecure Password Reset – Token Exposed in Response.md
└── Insecure Password Storage.md
/HttpOnly Flag not set.md:
--------------------------------------------------------------------------------
1 | Here is an example of code where httponly flag is not set with session token cookie:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | Cookie cookie = new Cookie("sessionToken", sessionTokenValue);
6 | response.addCookie(cookie);
7 | ```
8 | ## 😎 Secure Code
9 | To secure the code, you can set the “HttpOnly” flag on the cookie to prevent it from being accessed by client-side scripts. This can help to mitigate certain types of cross-site scripting (XSS) attacks:
10 |
11 | ```java
12 | Cookie cookie = new Cookie("sessionToken", sessionTokenValue);
13 | cookie.setHttpOnly(true);
14 | response.addCookie(cookie);
15 | ```
16 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🖥️ Vulnerable Code Snippets
2 | Welcome to this repository containing vulnerable code snippets for various security vulnerabilities. The purpose of this repository is to help educate developers and security enthusiasts about common security flaws and how to mitigate them. 😈
3 |
4 | ## Web Link
5 | https://securitycipher.com/docs/security/secure-code-explain/
6 | ## Maintainer
7 |
8 | This project is developed and maintained by [Piyush Kumawat](https://www.linkedin.com/in/piyush-kumawat). Feel free to reach out to me for any issues, concerns, or contributions. Your feedback and contributions are highly appreciated!
9 |
10 |
11 | ## 😍 Contributing
12 | Feel free to contribute additional code snippets for different security vulnerabilities or improvements to the existing ones.
13 |
14 | ## 📱 Follow me on social media
15 | - [Twitter](https://twitter.com/piyush_supiy)
16 | - [Twitter - BugBounty](https://twitter.com/bountywriteups)
17 | - [GitHub](https://github.com/securitycipher)
18 | - [Website](https://securitycipher.com)
19 | - [Telegram](https://t.me/dailybountywriteup)
20 | - [Discord](https://discord.gg/C5qSP77kS3)
21 | - [LinkedIn](https://www.linkedin.com/in/piyush-kumawat/)
22 |
--------------------------------------------------------------------------------
/Reflected Cross-Site-Scripting (XSS).md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to reflected Cross-Site Scripting (XSS) attacks on a search page:
2 | ## 🥺 Vulnerable Code
3 | ```java
4 | String searchTerm = request.getParameter("term");
5 | out.println("
Search Results for: " + searchTerm + "
");
6 | ```
7 | This code takes the user-provided search term and reflects it back to the user in the search results header. An attacker could inject malicious JavaScript code into the search term, which would then be executed by the victim’s browser when they view the search results.
8 |
9 | ## 😎 Secure Code
10 | To secure this code against XSS attacks, we can use the “escapeHtml4“ method from the “org.apache.commons.text.StringEscapeUtils” class to encode the search term as HTML. This will prevent the injected JavaScript code from being executed by the browser:
11 | ```java
12 | import org.apache.commons.text.StringEscapeUtils;
13 | ...
14 | String searchTerm = request.getParameter("term");
15 | searchTerm = StringEscapeUtils.escapeHtml4(searchTerm);
16 | out.println("Search Results for: " + searchTerm + "
");
17 | ```
18 | This will ensure that any HTML or JavaScript code injected into the search term is displayed as plain text, rather than being executed as code.
19 |
--------------------------------------------------------------------------------
/Secure Cookie not set.md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code where Secure Cookie is not set for the Session token cookie:
2 |
3 | ## 🥺 Vulnerable Code
4 | Here is an example of vulnerable code that does not set the “secure” flag when creating a session token cookie:
5 |
6 | ```java
7 | String sessionToken = "abc123";
8 | Cookie cookie = new Cookie("session_token", sessionToken);
9 | response.addCookie(cookie);
10 | ```
11 | This code creates a new cookie and adds it to the HTTP response. However, it does not set the “secure” flag, which means that the cookie can be transmitted over an unencrypted connection. This makes it vulnerable to interception by attackers.
12 |
13 | ## 😎 Secure Code
14 | To secure this code and set the “secure” flag on the session token cookie, you can specify the “secure” flag when creating the cookie. Here is an example of how you can do this:
15 |
16 |
17 | ```java
18 | String sessionToken = "abc123";
19 | Cookie cookie = new Cookie("session_token", sessionToken);
20 | cookie.setSecure(true);
21 | response.addCookie(cookie);
22 | ```
23 | This code creates a new cookie and sets the “secure” flag to “true“. This ensures that the cookie is only transmitted over a secure, encrypted connection. This helps to protect the cookie from being intercepted by attackers.
24 |
--------------------------------------------------------------------------------
/Session Fixation.md:
--------------------------------------------------------------------------------
1 | Here is a vulnerable Java code snippet that is susceptible to Session Fixation attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | HttpSession session = request.getSession();
6 | String sessionId = request.getParameter("sessionId");
7 |
8 | if (sessionId != null) {
9 | session.setId(sessionId);
10 | }
11 | ```
12 | This code is vulnerable to session fixation attacks because it allows an attacker to specify the session ID that should be used for the user’s session. An attacker could potentially fixate a user’s session by sending them a link with a malicious session ID, and then use that session ID to impersonate the user and gain access to their session.
13 |
14 | ## 😎 Secure Code
15 | To secure the code against session fixation attacks, you should not allow the session ID to be specified by the client. Instead, you should generate a new, unique session ID for the user when they log in, and store it in a secure cookie that is not accessible to the client.
16 |
17 | ```java
18 | HttpSession session = request.getSession();
19 | String sessionId = UUID.randomUUID().toString();
20 |
21 | session.setId(sessionId);
22 |
23 | Cookie cookie = new Cookie("sessionId", sessionId);
24 | cookie.setHttpOnly(true);
25 | cookie.setSecure(true);
26 | response.addCookie(cookie);
27 | ```
28 | This secure code generates a new, unique session ID for the user when they log in, and stores it in a secure cookie. The session ID is not accessible to the client, which helps to prevent session fixation attacks.
29 |
--------------------------------------------------------------------------------
/DOM Cross-Site-Scripting (XSS).md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to DOM-based cross-site scripting (XSS) attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | String userInput = request.getParameter("input");
6 | String output = "You entered: " + userInput;
7 | document.getElementById("output").innerHTML = output;
8 | ```
9 | This code takes the user’s input, which is obtained from an HTTP request, and assigns it to the inner HTML of an element on the page. If the user input is not properly sanitized, it could contain malicious code, such as JavaScript.
10 |
11 | ## 😎 Secure Code
12 | To secure this code against DOM-based XSS attacks, you can sanitize the user input by HTML-escaping it before assigning it to the inner HTML of the element. Here is an example of how you could do this:
13 |
14 | ```java
15 | import org.owasp.html.HtmlPolicyBuilder;
16 | import org.owasp.html.PolicyFactory;
17 |
18 | PolicyFactory policy = new HtmlPolicyBuilder()
19 |
20 | .allowElements("a")
21 | .allowUrlProtocols("https")
22 | .allowAttributes("href").onElements("a")
23 | .toFactory();
24 |
25 | String userInput = request.getParameter("input");
26 | String output = policy.sanitize(userInput);
27 | document.getElementById("output").innerHTML = "You entered: " + output;
28 | ```
29 | This code uses the OWASP HTML Sanitizer library to sanitize the user input. It allows only “” elements and “href” attributes, and only allows links that use the “https” protocol. This helps to prevent malicious code from being injected into the page.
30 |
--------------------------------------------------------------------------------
/Open Redirection.md:
--------------------------------------------------------------------------------
1 | Here is a vulnerable Java code snippet that is susceptible to an Open Redirection attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | String redirectUrl = request.getParameter("url");
6 | response.sendRedirect(redirectUrl);
7 | ```
8 | This code takes a URL parameter from an HTTP request and redirects the user to that URL. If the URL parameter is not properly validated, an attacker could specify a malicious URL that redirects the user to a phishing site or other malicious destination.
9 |
10 | ## 😎 Secure Code
11 | To secure this code against open redirect attacks, you can validate the URL parameter before redirecting the user. Here is an example of how you could do this:
12 |
13 | ```java
14 | import java.net.MalformedURLException;
15 | import java.net.URL;
16 |
17 | String redirectUrl = request.getParameter("url");
18 | try {
19 | URL url = new URL(redirectUrl);
20 | String host = url.getHost();
21 | if (host.equals("example.com") || host.endsWith(".example.com")) {
22 | response.sendRedirect(redirectUrl);
23 | } else {
24 | response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid redirect URL");
25 | }
26 | } catch (MalformedURLException e) {
27 | response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid redirect URL");
28 | }
29 | ```
30 | This code uses the java.net.URL class to parse the redirect URL and validate its hostname. It only allows redirects to URLs on the example.com domain, and sends an error response for any other URLs. This helps to prevent attackers from redirecting users to malicious sites.
31 |
--------------------------------------------------------------------------------
/Weak Password Policy.md:
--------------------------------------------------------------------------------
1 | Here is a vulnerable Java code snippet that is susceptible to a Weak Password Policy :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.util.regex.*;
6 |
7 | public class WeakPasswordPolicy {
8 | public static boolean isValidPassword(String password) {
9 | // Weak password policy: At least 8 characters, no requirements for special characters or numbers
10 | String regex = "^.{8,}$";
11 | return Pattern.matches(regex, password);
12 | }
13 | }
14 | ```
15 | This code enforces a password policy that requires the password to be at least 8 characters long, but it does not have any requirements for the use of special characters or numbers. This means that passwords such as password, 12345678, and qwertyuiop would all be considered valid, which is not secure.
16 |
17 | ## 😎 Secure Code
18 | Here is a version of the same code that enforces a stronger password policy:
19 |
20 | ```java
21 | import java.util.regex.*;
22 |
23 | public class StrongPasswordPolicy {
24 | public static boolean isValidPassword(String password) {
25 | // Strong password policy: At least 8 characters, at least 1 special character, at least 1 number
26 | String regex = "^(?=.*[0-9])(?=.*[!@#$%^&*])(?=\\S+$).{8,}$";
27 | return Pattern.matches(regex, password);
28 | }
29 | }
30 | ```
31 | This version of the code enforces a password policy that requires the password to be at least 8 characters long, and to contain at least 1 special character and at least 1 number. This helps to ensure that the passwords are more secure and less likely to be guessed by attackers.
32 |
--------------------------------------------------------------------------------
/Insecure direct object references (IDOR).md:
--------------------------------------------------------------------------------
1 | Here is an example of code that is vulnerable to IDOR (Insecure Direct Object Reference) vulnerability:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | // This code allows the user to view a list of accounts by specifying the account ID in the URL parameter
6 | String accountId = request.getParameter("accountId");
7 | Account account = accountDao.getAccountById(accountId);
8 | response.getWriter().write(account.toString());
9 | ```
10 | This code is vulnerable because it does not properly verify that the user has the necessary permissions to view the account with the specified ID. An attacker could manipulate the “accountId” parameter in the URL to view sensitive information for accounts that they are not authorized to access.
11 |
12 | ## 😎 Secure Code
13 | To secure this code, we can add a check to verify that the user has the necessary permissions before displaying the account information:
14 | ```java
15 | String accountId = request.getParameter("accountId");
16 | Account account = accountDao.getAccountById(accountId);
17 |
18 | // Check if the user has the necessary permissions to view the account
19 | if (user.getId().equals(account.getOwnerId()) || user.hasRole("ADMIN")) {
20 | response.getWriter().write(account.toString());
21 | } else
22 | { response.sendError(403, "Forbidden");
23 | }
24 | ```
25 | In the secure code, we added a check to see if the user’s ID matches the ID of the owner of the account, or if the user has the “ADMIN” role. If either of these conditions is true, the account information is displayed. Otherwise, a “Forbidden” error is returned to the user.
26 |
--------------------------------------------------------------------------------
/SQL Injection.md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to SQL Injection attack on productId parameter:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | String productId = request.getParameter("id");
6 | String query = "SELECT * FROM products WHERE id = " + productId;
7 |
8 | Statement st = connection.createStatement();
9 | ResultSet rs = st.executeQuery(query);
10 |
11 | while (rs.next()) {
12 | String name = rs.getString("name");
13 | String description = rs.getString("description");
14 | // display product details
15 | }
16 | ```
17 | This code is vulnerable to SQL injection attacks because it is directly concatenating user input (the “productId” parameter) into the SQL query string. An attacker could input a malicious value for the “productId” parameter that modifies the SQL query in unintended ways, such as adding additional clauses or comments.
18 |
19 | ## 😎 Secure Code
20 | To secure this code, you should use prepared statements with parameterized queries. This will prevent attackers from being able to inject malicious input into the query:
21 |
22 | ```java
23 | String productId = request.getParameter("id");
24 | String query = "SELECT * FROM products WHERE id = ?";
25 |
26 | PreparedStatement st = connection.prepareStatement(query);
27 | st.setString(1, productId);
28 | ResultSet rs = st.executeQuery();
29 |
30 | while (rs.next()) {
31 | String name = rs.getString("name");
32 | String description = rs.getString("description");
33 | // display product details
34 | }
35 | ```
36 | This code will safely escape any special characters in the “productId” parameter, preventing attackers from injecting malicious input into the query.
37 |
--------------------------------------------------------------------------------
/Log Injection.md:
--------------------------------------------------------------------------------
1 | Here is an example of a vulnerable Java code that is prone to log injection attacks:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | public void logUserAction(String username, String action) {
6 | // The following line is vulnerable to log injection attacks
7 | logger.info("User " + username + " performed action: " + action); }
8 | ```
9 | This code is vulnerable because the “username” and “action” variables are being concatenated directly into the log message without any validation or sanitization. This means that an attacker could potentially inject malicious strings as the “username” or “action” variables in order to manipulate the log message in a way that could be harmful to the system.
10 |
11 | ## 😎 Secure Code
12 | To secure this code against log injection attacks, we can sanitize the “username” and “action” variables before including them in the log message:
13 |
14 | ```java
15 | public void logUserAction(String username, String action) {
16 |
17 | // Sanitize the input to prevent log injection attacks
18 | username = sanitizeInput(username);
19 | action = sanitizeInput(action);
20 |
21 | // The following line is no longer vulnerable to log injection attacks
22 | logger.info("User " + username + " performed action: " + action); }
23 |
24 | private String sanitizeInput(String input) {
25 | // Implement sanitization logic here
26 |
27 | return input; }
28 | ```
29 | In this secure code example, the “sanitizeInput()” method can be used to sanitize the “username” and “action” variables before they are included in the log message. This helps to prevent log injection attacks by ensuring that the input strings do not contain any malicious characters or strings that could be used to manipulate the log message.
30 |
--------------------------------------------------------------------------------
/Missing CSP Header.md:
--------------------------------------------------------------------------------
1 | Here is an example of a Java code that does not set a Content Security Policy (CSP) header, leaving it vulnerable to injection attacks:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 |
9 | public class NoCSPVulnerable extends HttpServlet {
10 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11 | // Generate response
12 | PrintWriter out = response.getWriter();
13 | out.println("");
14 | out.println("This page does not set a Content-Security-Policy header.");
15 | out.println("");
16 | }
17 | }
18 | ```
19 | This code is vulnerable to injection attacks because it does not set a CSP header, allowing an attacker to potentially inject malicious script or other content into the page.
20 |
21 | ## 😎 Secure Code
22 | Here is a version of the same code that sets a CSP header in a secure way:
23 |
24 | ```java
25 | import java.io.*;
26 | import javax.servlet.*;
27 | import javax.servlet.http.*;
28 |
29 | public class NoCSPSecure extends HttpServlet {
30 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31 | // Secure code: The application sets a default-src CSP header to block all untrusted sources
32 | response.setHeader("Content-Security-Policy", "default-src 'none'");
33 |
34 | // Generate response
35 | PrintWriter out = response.getWriter();
36 | out.println("");
37 | out.println("This page sets a Content-Security-Policy header to block all untrusted sources.");
38 | out.println("");
39 | }
40 | }
41 | ```
42 | This version of the code sets a default-src CSP header to block all untrusted sources. This helps to prevent injection attacks by ensuring that the page only loads trusted resources, and blocks any potentially malicious ones.
43 |
--------------------------------------------------------------------------------
/Server-side template injection (SSTI).md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Server-side template injection (SSTI) Vulnerability :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import org.springframework.ui.Model;
6 | import org.springframework.web.bind.annotation.GetMapping;
7 | import org.springframework.web.bind.annotation.RequestParam;
8 | import org.springframework.stereotype.Controller;
9 |
10 | @Controller
11 | public class TemplateController {
12 |
13 | @GetMapping("/greet")
14 | public String greet(@RequestParam(value = "name", defaultValue = "Guest") String name, Model model) {
15 | // Vulnerable code: Embeds user input directly into a template
16 | model.addAttribute("message", "Hello, " + name + "!");
17 | return "greeting";
18 | }
19 | }
20 | ```
21 | In the vulnerable code snippet above, user input (name) is directly concatenated into the template without proper validation or sanitization. An attacker could potentially exploit this by injecting malicious template code, leading to SSTI.
22 |
23 | ## 😎 Secure Code
24 | ```java
25 | import org.springframework.ui.Model;
26 | import org.springframework.web.bind.annotation.GetMapping;
27 | import org.springframework.web.bind.annotation.RequestParam;
28 | import org.springframework.stereotype.Controller;
29 | import org.owasp.encoder.Encode;
30 |
31 | @Controller
32 | public class TemplateController {
33 |
34 | @GetMapping("/greet")
35 | public String greet(@RequestParam(value = "name", defaultValue = "Guest") String name, Model model) {
36 | // Secure code: Properly encode user input to prevent SSTI
37 | model.addAttribute("message", "Hello, " + Encode.forHtml(name) + "!");
38 | return "greeting";
39 | }
40 | }
41 | ```
42 | In the secure code snippet, we use the OWASP Java Encoder (Encode.forHtml) to properly encode the user input before embedding it into the template. This prevents any malicious template code from being executed and mitigates the risk of SSTI.
43 |
--------------------------------------------------------------------------------
/Remote File Inclusion (RFI).md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to Remote File Inclusion (RFI) attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import java.net.*;
7 |
8 | public class RFI {
9 | public static void main(String[] args) throws Exception {
10 |
11 | // Vulnerable code: URL is not sanitized and is directly included in the program
12 | URL url = new URL(args[0]); // args[0] can be manipulated by attacker
13 | BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
14 |
15 | String inputLine;
16 | while ((inputLine = in.readLine()) != null)
17 | System.out.println(inputLine);
18 | in.close();
19 | }
20 | }
21 | ```
22 | ## 😎 Secure Code
23 | Here is a version of the same code that is secured against Remote File Inclusion (RFI) attack:
24 |
25 | ```java
26 | import java.io.*;
27 | import java.net.*;
28 | import java.util.regex.*;
29 |
30 | public class RFI {
31 | public static void main(String[] args) throws Exception {
32 |
33 | // Secure code: URL is sanitized using regex to only allow local files
34 | String pattern = "^(file://)?/[A-Za-z0-9_/.-]*$"; // regex for local file URLs
35 | Pattern p = Pattern.compile(pattern);
36 | Matcher m = p.matcher(args[0]);
37 | if (!m.matches()) {
38 | System.out.println("Invalid URL");
39 | return;
40 | }
41 | URL url = new URL(args[0]);
42 | BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
43 |
44 | String inputLine;
45 | while ((inputLine = in.readLine()) != null)
46 | System.out.println(inputLine);
47 | in.close();
48 | }
49 | }
50 | ```
51 | The line URL “url = new URL(args[0]);” was vulnerable in the original code, as it allowed an attacker to pass in a malicious URL that could be used to execute arbitrary code on the server. In the secure code, the URL is first checked against a regex pattern to ensure that it is a local file URL before it is included in the program.
52 |
--------------------------------------------------------------------------------
/Remote Code Execution (RCE).md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to Remote Code Execution (RCE) attack.
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 |
7 | public class RCE {
8 | public static void main(String[] args) throws Exception {
9 |
10 | // Vulnerable code: user input is directly passed to the system command
11 | Process p = Runtime.getRuntime().exec(args[0]); // args[0] can be manipulated by attacker
12 | BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
13 | String line;
14 | while ((line = in.readLine()) != null) {
15 | System.out.println(line);
16 | }
17 | }
18 | }
19 | ```
20 | The program uses the “Runtime.getRuntime().exec()” method to execute a system command that is passed as an argument to the program. The command is passed to the program through the “args[0]” parameter, which is accessible to the attacker.
21 |
22 | ## 😎 Secure Code
23 | Here is a version of the same code that is secured against Remote Code Execution (RCE) attack:
24 |
25 | ```java
26 | import java.io.*;
27 | import java.util.regex.*;
28 |
29 | public class RCE {
30 | public static void main(String[] args) throws Exception {
31 |
32 | // Secure code: user input is sanitized using regex to only allow approved commands
33 | String pattern = "^[A-Za-z0-9_-]*$"; // regex for approved commands
34 |
35 | Pattern p = Pattern.compile(pattern);
36 | Matcher m = p.matcher(args[0]);
37 | if (!m.matches()) {
38 | System.out.println("Invalid command");
39 | return;
40 | }
41 |
42 | Process p = Runtime.getRuntime().exec(args[0]);
43 | BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
44 | String line;
45 | while ((line = in.readLine()) != null) {
46 | System.out.println(line);
47 | }
48 | }
49 | }
50 | ```
51 | The line “Process p = Runtime.getRuntime().exec(args[0]);” was vulnerable in the original code, as it allowed an attacker to execute arbitrary code on the server. In the secure code, the user input is first checked against a regex pattern to ensure that it is an approved command before it is executed.
52 |
--------------------------------------------------------------------------------
/HSTS not Implemented.md:
--------------------------------------------------------------------------------
1 | Here is an example of a Java code that does not set an HTTP Strict Transport Security (HSTS) header, leaving it vulnerable to man-in-the-middle attacks:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 |
9 | public class NoHSTSVulnerable extends HttpServlet {
10 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11 | // Generate response
12 | PrintWriter out = response.getWriter();
13 | out.println("");
14 | out.println("This is Sample Text");
15 | out.println(""); } }
16 | ```
17 | This code is vulnerable to man-in-the-middle attacks because it does not set an HSTS header, which tells the browser to only access the site using HTTPS. Without HSTS, an attacker could intercept the victim’s request and redirect them to a malicious site, potentially leading to sensitive information being compromised.
18 |
19 | ## 😎 Secure Code
20 | Here is a version of the same code that sets an HSTS header in a secure way:
21 | ```java
22 |
23 | import java.io.*;
24 | import javax.servlet.*;
25 | import javax.servlet.http.*;
26 |
27 | public class NoHSTSSecure extends HttpServlet {
28 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29 | // Secure code: The application sets an HSTS header to enforce HTTPS for the specified duration
30 | response.setHeader("Strict-Transport-Security", "max-age=31536000");
31 |
32 | // Generate response
33 | PrintWriter out = response.getWriter();
34 | out.println("");
35 | out.println("This page sets an HTTP Strict Transport Security header to enforce HTTPS for 1 year.");
36 | out.println("");
37 | }
38 | }
39 | ```
40 | This version of the code sets an HSTS header with a max-age of 1 year, telling the browser to only access the site using HTTPS for the specified duration. This helps to prevent man-in-the-middle attacks by ensuring that the connection to the site is always encrypted.
41 |
--------------------------------------------------------------------------------
/Clickjacking.md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to Clickjacking attack.
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 |
9 | public class ClickjackingVulnerable extends HttpServlet {
10 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11 |
12 | // Generate response
13 | PrintWriter out = response.getWriter();
14 | out.println("");
15 | out.println("This page is vulnerable to clickjacking attacks.");
16 | out.println("");
17 | }
18 | }
19 | ```
20 | This code is vulnerable to clickjacking attacks because it does not set any headers or use any techniques to prevent the page from being embedded in a malicious frame or iframe. An attacker could create a page with a hidden frame that overlays the victim’s page, tricking the victim into clicking on it and potentially leading to sensitive information being compromised.
21 |
22 | ## 😎 Secure Code
23 | Here is a version of the same code that is secured against clickjacking attack:
24 |
25 | ```java
26 | import java.io.*;
27 | import javax.servlet.*;
28 | import javax.servlet.http.*;
29 |
30 | public class ClickjackingSecure extends HttpServlet {
31 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
32 |
33 | // Secure code: The application sets the X-Frame-Options header to prevent the page from being embedded in a frame or iframe
34 | response.setHeader("X-Frame-Options", "DENY");
35 |
36 | // Generate response PrintWriter out = response.getWriter();
37 | out.println("");
38 | out.println("This page is secured against clickjacking attacks with the X-Frame-Options header.");
39 | out.println("");
40 | }
41 | }
42 | ```
43 | This version of the code sets the X-Frame-Options header to “DENY“, which tells the browser to not allow the page to be embedded in a frame or iframe. This helps to prevent clickjacking attacks by ensuring that the page cannot be overlaid by a malicious frame.
44 |
--------------------------------------------------------------------------------
/Host Header Injection.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Host Header Injection Attack :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.IOException;
6 | import javax.servlet.http.HttpServletRequest;
7 | import javax.servlet.http.HttpServletResponse;
8 |
9 | public class PasswordResetServlet {
10 | public void resetPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
11 | String email = request.getParameter("email");
12 | String resetLink = "https://" + request.getHeader("Host") + "/reset-password?email=" + email;
13 |
14 | // Send password reset link to the user's email
15 | // ...
16 |
17 | response.sendRedirect(resetLink);
18 | }
19 | }
20 | ```
21 | In the vulnerable code snippet above:
22 |
23 | The resetPassword method takes an HTTP request and response as parameters and extracts the email parameter from the request.
24 | It constructs a password reset link by directly using the Host header from the HTTP request. This allows an attacker to manipulate the Host header and potentially redirect the password reset link to a malicious site.
25 | ## 😎 Secure Code
26 | ```java
27 | import java.io.IOException;
28 | import javax.servlet.http.HttpServletRequest;
29 | import javax.servlet.http.HttpServletResponse;
30 |
31 | public class PasswordResetServlet {
32 | private static final String APP_DOMAIN = "example.com";
33 |
34 | public void resetPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
35 | String email = request.getParameter("email");
36 | String resetLink = "https://" + APP_DOMAIN + "/reset-password?email=" + email;
37 |
38 | // Send password reset link to the user's email
39 | // ...
40 |
41 | response.sendRedirect(resetLink);
42 | }
43 | }
44 | ```
45 | In the secure code snippet above:
46 |
47 | We’ve introduced a constant APP_DOMAIN, which represents the legitimate domain of the application. This domain is not derived from the Host header.
48 | Instead of using request.getHeader("Host"), we use the constant APP_DOMAIN to construct the password reset link. This ensures that the link is always generated using the expected and trusted domain, mitigating the host header injection vulnerability.
49 |
--------------------------------------------------------------------------------
/Java Deserialization.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Java Deserialization :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 |
7 | public class VulnerableDeserialization {
8 | public static void main(String[] args) {
9 | try {
10 | // Deserialize data from a file
11 | FileInputStream fileIn = new FileInputStream("data.ser");
12 | ObjectInputStream in = new ObjectInputStream(fileIn);
13 |
14 | // Deserialize the object and cast it
15 | Object obj = in.readObject(); // Vulnerable point
16 |
17 | // Do something with the deserialized object
18 | // For a real attack, an attacker could place malicious code here.
19 | System.out.println("Deserialized object: " + obj.toString());
20 |
21 | in.close();
22 | fileIn.close();
23 | } catch (IOException | ClassNotFoundException e) {
24 | e.printStackTrace();
25 | }
26 | }
27 | }
28 | ```
29 | In the vulnerable code above, we are deserializing an object from a file using ObjectInputStream. The problem is that this code does not validate or sanitize the data being deserialized. An attacker could potentially craft a malicious serialized object and inject harmful code or exploit the application.
30 |
31 | ## 😎 Secure Code
32 | ```java
33 | import java.io.*;
34 |
35 | public class SecureDeserialization {
36 | public static void main(String[] args) {
37 | try {
38 | // Deserialize data from a file
39 | FileInputStream fileIn = new FileInputStream("data.ser");
40 | ObjectInputStream in = new ObjectInputStream(fileIn);
41 |
42 | // Deserialize the object and cast it safely
43 | Object obj = in.readObject();
44 |
45 | // Perform type checking to ensure the deserialized object is of the expected type
46 | if (obj instanceof SomeClass) {
47 | SomeClass secureObject = (SomeClass) obj;
48 | // Use the deserialized object safely
49 | System.out.println("Deserialized object: " + secureObject.toString());
50 | } else {
51 | System.out.println("Invalid object type. Aborting deserialization.");
52 | }
53 |
54 | in.close();
55 | fileIn.close();
56 | } catch (IOException | ClassNotFoundException e) {
57 | e.printStackTrace();
58 | }
59 | }
60 | }
61 | ```
62 | In the secure code, we perform the following security measures:
63 |
64 | We ensure that the deserialized object is of the expected type (SomeClass) by using the instanceof operator.
65 | We cast the deserialized object to the expected type only if the type check is successful.
66 | If the object’s type is not as expected, we abort the deserialization process.
67 |
--------------------------------------------------------------------------------
/XXE injection.md:
--------------------------------------------------------------------------------
1 | Here is a vulnerable Java code snippet that is susceptible to XXE (XML External Entity) injection attacks:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.StringReader;
6 | import javax.xml.parsers.DocumentBuilderFactory;
7 | import org.w3c.dom.Document;
8 | import org.xml.sax.InputSource;
9 |
10 | public class VulnerableXXE {
11 | public static void main(String[] args) throws Exception {
12 | String xmlData = "" +
13 | "John";
14 |
15 | // Vulnerable code: Parsing XML without disabling external entities
16 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
17 | Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlData)));
18 |
19 | // Processing the document
20 | String name = document.getElementsByTagName("name").item(0).getTextContent();
21 | System.out.println("Name: " + name);
22 | }
23 | }
24 | ```
25 | In this vulnerable code snippet, we parse an XML document without disabling external entity resolution. An attacker can craft a malicious XML input that references an external entity (e.g., a file on the server), leading to information disclosure or other attacks.
26 |
27 | ## 😎 Secure Code
28 | Here is an example of a secure version of the code that properly disables external entity resolution:
29 |
30 | ```java
31 | import java.io.StringReader;
32 | import javax.xml.XMLConstants;
33 | import javax.xml.parsers.DocumentBuilderFactory;
34 | import org.w3c.dom.Document;
35 | import org.xml.sax.InputSource;
36 |
37 | public class SecureXXE {
38 | public static void main(String[] args) throws Exception {
39 | String xmlData = "" +
40 | "John";
41 |
42 | // Secure code: Disable external entity processing
43 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
44 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
45 | Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlData)));
46 |
47 | // Processing the document
48 | String name = document.getElementsByTagName("name").item(0).getTextContent();
49 | System.out.println("Name: " + name);
50 | }
51 | }
52 | ```
53 | In the secure code snippet, we disable external entity processing by setting the FEATURE_SECURE_PROCESSING feature to true. This prevents the parser from resolving external entities, making the code immune to XXE attacks. It’s a crucial security measure when dealing with XML data from untrusted sources.
54 |
--------------------------------------------------------------------------------
/Stored Cross-Site-Scripting (XSS).md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code for a profile update page that is susceptible to Stored Cross-site-Scripting (XSS) attacks:
2 |
3 | # 🥺 Vulnerable Code
4 | ```java
5 | public class ProfileServlet extends HttpServlet {
6 | protected void doPost(HttpServletRequest request, HttpServletResponse response) {
7 | String name = request.getParameter("name");
8 | String bio = request.getParameter("bio");
9 | String website = request.getParameter("website");
10 |
11 | User user = new User();
12 | user.setName(name);
13 | user.setBio(bio);
14 | user.setWebsite(website);
15 | // Save the user profile
16 | saveUserProfile(user);
17 |
18 | // Redirect to the profile page
19 | response.sendRedirect("/profile");
20 |
21 | }
22 | }
23 | ```
24 |
25 | This code allows a user to update their profile by submitting a form with their name, bio, and website. However, it does not properly sanitize the user input, making it vulnerable to XSS attacks.
26 |
27 | An attacker could exploit this vulnerability by submitting a form with malicious JavaScript code in the “name“, “bio“, or “website” field. When the form is submitted, the malicious code would be stored in the database and displayed on the user’s profile page, potentially allowing the attacker to execute arbitrary JavaScript in the context of the user’s browser.
28 |
29 | # 😎 Secure Code
30 | To secure this code against XSS attacks, we can sanitize the user input by escaping special characters in the user input. Here is an example of how the code could be modified to do this:
31 | ```java
32 | public class ProfileServlet extends HttpServlet {
33 | protected void doPost(HttpServletRequest request, HttpServletResponse response) {
34 |
35 | String name = request.getParameter("name");
36 | String bio = request.getParameter("bio");
37 | String website = request.getParameter("website");
38 |
39 | // Sanitize user input
40 | name = sanitizeInput(name);
41 | bio = sanitizeInput(bio);
42 | website = sanitizeInput(website);
43 |
44 | User user = new User();
45 | user.setName(name);
46 | user.setBio(bio);
47 | user.setWebsite(website);
48 |
49 | // Save the user profile
50 | saveUserProfile(user);
51 |
52 | // Redirect to the profile page
53 | response.sendRedirect("/profile");
54 | }
55 | private String sanitizeInput(String input) {
56 | return input.replaceAll("<", "<").replaceAll(">", ">");
57 | }
58 | }
59 | ```
60 | This code sanitizes the user input by replacing the “<” and “>” characters with their HTML escape codes, which prevents them from being interpreted as HTML tags. This effectively neutralizes any malicious code submitted by the user and makes the code more secure against XSS attacks.
61 |
62 |
--------------------------------------------------------------------------------
/CORS Misconfiguration.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a CORS Misconfiguration:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.IOException;
6 | import javax.servlet.ServletException;
7 | import javax.servlet.http.HttpServlet;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | public class VulnerableServlet extends HttpServlet {
12 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
13 | throws ServletException, IOException {
14 | // This is a vulnerable code snippet with no CORS configuration
15 | response.setHeader("Access-Control-Allow-Origin", "*"); // Allow any origin (Not recommended)
16 | response.getWriter().write("This is a vulnerable resource.");
17 | }
18 | }
19 | ```
20 | In this vulnerable code snippet, we have a servlet that does not have proper CORS configuration. It sets the Access-Control-Allow-Origin header to "*" which means it allows any origin to access the resource. This is dangerous because it allows any website, including potentially malicious ones, to make cross-origin requests to this resource, which could lead to security vulnerabilities such as CSRF attacks.
21 |
22 | ## 😎 Secure Code
23 | ```java
24 | import java.io.IOException;
25 | import javax.servlet.ServletException;
26 | import javax.servlet.http.HttpServlet;
27 | import javax.servlet.http.HttpServletRequest;
28 | import javax.servlet.http.HttpServletResponse;
29 |
30 | public class SecureServlet extends HttpServlet {
31 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
32 | throws ServletException, IOException {
33 | // This is a secure code snippet with proper CORS configuration
34 | String allowedOrigin = "https://trusted-website.com";
35 | String origin = request.getHeader("Origin");
36 |
37 | if (allowedOrigin.equals(origin)) {
38 | response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
39 | response.getWriter().write("This is a secure resource.");
40 | } else {
41 | response.setStatus(HttpServletResponse.SC_FORBIDDEN);
42 | response.getWriter().write("Access denied. This resource can only be accessed from a trusted origin.");
43 | }
44 | }
45 | }
46 | ```
47 | In this secure code snippet, we have a servlet that implements proper CORS security. It first checks the Origin header in the incoming request to determine where the request is coming from. If the origin matches the trusted origin (https://trusted-website.com in this case), it sets the Access-Control-Allow-Origin header to that trusted origin, allowing only that specific origin to access the resource. If the origin doesn’t match the trusted origin, it returns a 403 Forbidden response, denying access to the resource.
48 |
--------------------------------------------------------------------------------
/Cross-Site Request Forgery (CSRF).md:
--------------------------------------------------------------------------------
1 | Here is an example of a Java code that is vulnerable to Cross-Site Request Forgery (CSRF) attacks:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 |
9 | public class CSRFVulnerable extends HttpServlet {
10 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11 | // Read form data from request
12 | String newName = request.getParameter("new_name");
13 |
14 | // Get the logged-in user from the session
15 | User user = (User) request.getSession().getAttribute("user");
16 | if (user == null) {
17 | response.sendError(HttpServletResponse.SC_FORBIDDEN, "Not logged in");
18 | return;
19 | }
20 |
21 | // Update the user's name
22 | user.setName(newName);
23 | updateUser(user);
24 | }
25 | }
26 | ```
27 | This code is vulnerable to CSRF attacks because it does not include any protection against forged requests. An attacker could create a malicious website that includes a form that submits a request to this servlet to update the victim’s name. If the victim is currently logged in to the application and visits the malicious website, their browser will automatically submit the forged request and the attacker will be able to update the victim’s name.
28 |
29 | ## 😎 Secure Code
30 | Here is a version of the same code that is secured against CSRF attacks:
31 |
32 | ```java
33 | import java.io.*;
34 | import javax.servlet.*;
35 | import javax.servlet.http.*;
36 |
37 | public class CSRFSecure extends HttpServlet {
38 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
39 | // Check for a valid CSRF token
40 | String csrfToken = request.getParameter("csrf_token");
41 | if (!csrfToken.equals(request.getSession().getAttribute("csrf_token"))) {
42 | response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid CSRF token");
43 | return;
44 | }
45 |
46 | // Read form data from request
47 | String newName = request.getParameter("new_name");
48 |
49 | // Get the logged-in user from the session
50 | User user = (User) request.getSession().getAttribute("user");
51 | if (user == null) {
52 | response.sendError(HttpServletResponse.SC_FORBIDDEN, "Not logged in");
53 | return;
54 | }
55 |
56 | // Update the user's name
57 | user.setName(newName);
58 | updateUser(user);
59 | }
60 | }
61 | ```
62 | This version of the code includes a check for a valid CSRF token in the request. The CSRF token is a random value that is stored in the user’s session and is included in any sensitive requests that are made by the application. By checking for a valid CSRF token, the application can ensure that the request is genuine and not a forged request from an attacker.
63 |
--------------------------------------------------------------------------------
/Server-Side Request Forgery (SSRF).md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Serer-Side Request Forgery attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.net.*;
6 | import java.io.*;
7 |
8 | public class SSRFVulnerable {
9 | public static void main(String[] args) throws Exception {
10 | // Read URL from user input
11 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
12 | System.out.print("Enter URL: ");
13 | String url = reader.readLine();
14 |
15 | // Send HTTP request to the URL
16 | URL target = new URL(url);
17 | HttpURLConnection connection = (HttpURLConnection) target.openConnection();
18 | connection.setRequestMethod("GET");
19 |
20 | // Print response from the server
21 | BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
22 | String inputLine;
23 | while ((inputLine = responseReader.readLine()) != null) {
24 | System.out.println(inputLine);
25 | }
26 | responseReader.close();
27 | }
28 | }
29 | ```
30 | This code takes a URL as input from the user and sends an HTTP GET request to it. It then prints the response from the server. However, this code is vulnerable to SSRF attacks because it does not properly validate the user input. An attacker could enter a URL that points to an internal network resource, such as http://localhost/secret, and potentially gain unauthorized access to that resource.
31 |
32 | ## 😎 Secure Code
33 | Here is a version of the same code that is secured against SSRF attacks:
34 |
35 | ``` java
36 | import java.net.*;
37 | import java.io.*;
38 | import java.util.regex.*;
39 |
40 | public class SSRFSecure {
41 | public static void main(String[] args) throws Exception {
42 | // Read URL from user input
43 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
44 | System.out.print("Enter URL: ");
45 | String url = reader.readLine();
46 |
47 | // Validate the URL using a regular expression
48 | String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
49 | Pattern pattern = Pattern.compile(regex);
50 | Matcher matcher = pattern.matcher(url);
51 | if (!matcher.matches()) {
52 | System.out.println("Invalid URL");
53 | return;
54 | }
55 |
56 | // Send HTTP request to the URL
57 | URL target = new URL(url);
58 | HttpURLConnection connection = (HttpURLConnection) target.openConnection();
59 | connection.setRequestMethod("GET");
60 |
61 | // Print response from the server
62 | BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
63 | String inputLine;
64 | while ((inputLine = responseReader.readLine()) != null) {
65 | System.out.println(inputLine);
66 | }
67 | responseReader.close();
68 | }
69 | }
70 | ```
71 | This version of the code uses a regular expression to validate the user input and ensure that it is a well-formed URL. This helps to prevent an attacker from entering a URL that points to an internal network resource.
72 |
--------------------------------------------------------------------------------
/Local File Inclusion(LFI).md:
--------------------------------------------------------------------------------
1 | Here is an example of Java code that is vulnerable to Local File Inclusion (LFI) attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.FileInputStream;
6 | import java.io.IOException;
7 | import javax.servlet.ServletException;
8 | import javax.servlet.ServletOutputStream;
9 | import javax.servlet.http.HttpServlet;
10 | import javax.servlet.http.HttpServletRequest;
11 | import javax.servlet.http.HttpServletResponse;
12 |
13 | public class FileInclusionServlet extends HttpServlet {
14 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
15 | throws ServletException, IOException {
16 |
17 | // VULNERABLE: The value of the "file" parameter is used to construct the path to a file on the server
18 | String fileName = request.getParameter("file");
19 | FileInputStream fis = new FileInputStream(fileName);
20 | ServletOutputStream outputStream = response.getOutputStream();
21 |
22 | int ch;
23 | while ((ch = fis.read()) != -1) {
24 | outputStream.write(ch);
25 | }
26 | fis.close();
27 | outputStream.close();
28 | }
29 | }
30 | ```
31 | This line of code takes the value of the “file” parameter in the request and uses it to construct the path to a file on the server. If an attacker can control the value of the “file” parameter, they can potentially access any file on the server that the Java process has permissions to read.
32 |
33 | ## 😎 Secure Code
34 | Here is a secure version of the same code that prevents LFI attack:
35 |
36 | ```java
37 | import java.io.FileInputStream;
38 | import java.io.FileNotFoundException;
39 | import java.io.IOException;
40 | import javax.servlet.ServletException;
41 | import javax.servlet.ServletOutputStream;
42 | import javax.servlet.http.HttpServlet;
43 | import javax.servlet.http.HttpServletRequest;
44 | import javax.servlet.http.HttpServletResponse;
45 |
46 | public class FileInclusionServlet extends HttpServlet {
47 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
48 | throws ServletException, IOException {
49 | String fileName = request.getParameter("file");
50 | FileInputStream fis = null;
51 |
52 | try {
53 | // SECURE: Only allow access to files in a specific directory
54 | fis = new FileInputStream("/allowed/files/" + fileName);
55 | } catch (FileNotFoundException e) {
56 | // SECURE: Return a 404 error if the requested file is not found in the allowed directory
57 | response.sendError(HttpServletResponse.SC_NOT_FOUND);
58 | return;
59 | }
60 | ServletOutputStream outputStream = response.getOutputStream();
61 | int ch;
62 | while ((ch = fis.read()) != -1) {
63 | outputStream.write(ch);
64 | }
65 | fis.close();
66 | outputStream.close();
67 | }
68 | }
69 | ```
70 | This line of code only allows access to files in a specific directory, preventing an attacker from being able to access arbitrary files on the server. The secure code also returns a 404 error if the requested file is not found in the allowed directory, further enhancing security.
71 |
72 |
73 |
--------------------------------------------------------------------------------
/Application-level Denial of Service (DoS).md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Application-level Denial of Service (DoS) Vulnerability:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import java.net.*;
7 |
8 | public class VulnerableDoSApp {
9 | public static void main(String[] args) {
10 | try {
11 | ServerSocket serverSocket = new ServerSocket(8080);
12 | while (true) {
13 | Socket socket = serverSocket.accept();
14 | Thread thread = new Thread(new RequestHandler(socket));
15 | thread.start();
16 | }
17 | } catch (IOException e) {
18 | e.printStackTrace();
19 | }
20 | }
21 | }
22 |
23 | class RequestHandler implements Runnable {
24 | private final Socket socket;
25 |
26 | public RequestHandler(Socket socket) {
27 | this.socket = socket;
28 | }
29 |
30 | public void run() {
31 | try {
32 | // Simulate some heavy processing
33 | Thread.sleep(1000);
34 |
35 | // Read the request and send a response
36 | BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
37 | PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
38 | String request = reader.readLine();
39 | writer.println("Response to: " + request);
40 |
41 | // Close the socket
42 | socket.close();
43 | } catch (IOException | InterruptedException e) {
44 | e.printStackTrace();
45 | }
46 | }
47 | }
48 | ```
49 |
50 | In this vulnerable code, we have a simple server that accepts incoming connections and processes requests using a new thread for each connection. The vulnerability here is that it creates a new thread for each incoming connection without any rate limiting or resource management, which can lead to resource exhaustion if an attacker floods the server with connections.
51 |
52 | ## 😎 Secure Code
53 | ```java
54 | import java.io.*;
55 | import java.net.*;
56 | import java.util.concurrent.*;
57 |
58 | public class SecureDoSApp {
59 | private static final int MAX_THREADS = 10;
60 | private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
61 |
62 | public static void main(String[] args) {
63 | try {
64 | ServerSocket serverSocket = new ServerSocket(8080);
65 | while (true) {
66 | Socket socket = serverSocket.accept();
67 | executor.execute(new RequestHandler(socket));
68 | }
69 | } catch (IOException e) {
70 | e.printStackTrace();
71 | }
72 | }
73 | }
74 |
75 | class RequestHandler implements Runnable {
76 | private final Socket socket;
77 |
78 | public RequestHandler(Socket socket) {
79 | this.socket = socket;
80 | }
81 |
82 | public void run() {
83 | try {
84 | // Simulate some processing
85 | Thread.sleep(1000);
86 |
87 | // Read the request and send a response
88 | BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
89 | PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
90 | String request = reader.readLine();
91 | writer.println("Response to: " + request);
92 |
93 | // Close the socket
94 | socket.close();
95 | } catch (IOException | InterruptedException e) {
96 | e.printStackTrace();
97 | }
98 | }
99 | }
100 | ```
101 | In this secure code, we limit the number of concurrent threads using a thread pool (ExecutorService) with a fixed number of threads (MAX_THREADS). This prevents an attacker from overwhelming the server with too many simultaneous connections, thus mitigating the application-level DoS vulnerability. The server can only handle a limited number of connections concurrently, ensuring that resources are not exhausted.
102 |
--------------------------------------------------------------------------------
/Brute Force.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to Brute Force on Login Page attack:
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.*;
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 |
9 | public class LoginVulnerable extends HttpServlet {
10 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11 | String username = request.getParameter("username");
12 | String password = request.getParameter("password");
13 |
14 | User user = authenticate(username, password);
15 | if (user != null) {
16 | // Login successful, set session attribute and redirect to dashboard
17 | request.getSession().setAttribute("user", user);
18 | response.sendRedirect("/dashboard");
19 | } else {
20 | // Login failed, increment failed login count in session and show error message
21 | Integer failedLoginCount = (Integer) request.getSession().getAttribute("failed_login_count");
22 | if (failedLoginCount == null) {
23 | failedLoginCount = 0;
24 | }
25 | failedLoginCount++;
26 | request.getSession().setAttribute("failed_login_count", failedLogincount);
27 | request.setAttribute("errorMessage", "Invalid username or password");
28 | request.getRequestDispatcher("/login.jsp").forward(request, response);
29 | }
30 | }
31 | }
32 | ```
33 | This code is vulnerable to brute-force attacks because it does not have any protection against an attacker trying multiple invalid passwords. An attacker could write a script to try thousands of password combinations in a short period of time, potentially leading to the victim’s account being compromised.
34 |
35 | ## 😎 Secure Code
36 | Here is a version of the same code that is secured against brute-force attacks:
37 |
38 | ```java
39 | import java.io.*;
40 | import javax.servlet.*;
41 | import javax.servlet.http.*;
42 |
43 | public class LoginSecure extends HttpServlet {
44 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
45 | String username = request.getParameter("username");
46 | String password = request.getParameter("password");
47 |
48 | User user = authenticate(username, password);
49 | if (user != null) {
50 | // Login successful, set session attribute and redirect to dashboard
51 | request.getSession().setAttribute("user", user);
52 | response.sendRedirect("/dashboard");
53 | } else {
54 | // Login failed, increment failed login count in session and show error message
55 | Integer failedLoginCount = (Integer) request.getSession().getAttribute("failed_login_count");
56 | if (failedLoginCount == null) {
57 | failedLoginCount = 0;
58 | }
59 | failedLoginCount++;
60 | request.getSession().setAttribute("failed_login_count", failedLogincount);
61 |
62 | // Secure code: If the failed login count exceeds a threshold, log the user out for a specified duration
63 | if (failedLoginCount > 5) {
64 | request.getSession().setMaxInactiveInterval(1800); // 30 minutes
65 | request.setAttribute("errorMessage", "Too many failed login attempts. You have been logged out for 30 minutes.");
66 | request.getRequestDispatcher("/login.jsp").forward(request, response);
67 | return;
68 | }
69 |
70 | request.setAttribute("errorMessage", "Invalid username or password");
71 | request.getRequestDispatcher("/login.jsp").forward(request, response);
72 | }
73 | }
74 | }
75 | ```
76 | This version of the code includes a check for the number of failed login attempts, and if the threshold is exceeded, the user’s session is set to expire in 30 minutes. This helps to prevent an attacker from trying multiple invalid password combinations and potentially compromising the victim’s account.
77 |
--------------------------------------------------------------------------------
/Unrestricted File Upload.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to a Unrestricted File Upload vulnerability :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.OutputStream;
10 |
11 | import javax.servlet.ServletException;
12 | import javax.servlet.annotation.MultipartConfig;
13 | import javax.servlet.annotation.WebServlet;
14 | import javax.servlet.http.HttpServlet;
15 | import javax.servlet.http.HttpServletRequest;
16 | import javax.servlet.http.HttpServletResponse;
17 | import javax.servlet.http.Part;
18 |
19 | @WebServlet("/upload")
20 | @MultipartConfig
21 | public class VulnerableFileUploadServlet extends HttpServlet {
22 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23 | Part filePart = request.getPart("file");
24 | String fileName = filePart.getSubmittedFileName();
25 |
26 | InputStream fileContent = filePart.getInputStream();
27 | File uploadedFile = new File("/uploads/" + fileName); // Vulnerable - no validation
28 |
29 | try (OutputStream outputStream = new FileOutputStream(uploadedFile)) {
30 | byte[] buffer = new byte[1024];
31 | int bytesRead;
32 | while ((bytesRead = fileContent.read(buffer)) != -1) {
33 | outputStream.write(buffer, 0, bytesRead);
34 | }
35 | }
36 |
37 | response.getWriter().println("File uploaded successfully.");
38 | }
39 | }
40 | ```
41 | In this vulnerable code, there is no validation on the file type or any checks to ensure that the uploaded file is not malicious. An attacker can upload any file, including executable scripts, which can lead to server compromise.
42 |
43 | ## 😎 Secure Code
44 | ```java
45 | import java.io.File;
46 | import java.io.FileOutputStream;
47 | import java.io.IOException;
48 | import java.io.InputStream;
49 | import java.io.OutputStream;
50 |
51 | import javax.servlet.ServletException;
52 | import javax.servlet.annotation.MultipartConfig;
53 | import javax.servlet.annotation.WebServlet;
54 | import javax.servlet.http.HttpServlet;
55 | import javax.servlet.http.HttpServletRequest;
56 | import javax.servlet.http.HttpServletResponse;
57 | import javax.servlet.http.Part;
58 |
59 | @WebServlet("/upload")
60 | @MultipartConfig
61 | public class SecureFileUploadServlet extends HttpServlet {
62 | private static final String UPLOAD_DIRECTORY = "/uploads/";
63 | private static final int MAX_FILE_SIZE = 1024 * 1024; // 1 MB
64 |
65 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
66 | Part filePart = request.getPart("file");
67 | String fileName = filePart.getSubmittedFileName();
68 |
69 | // Check file type (allow only image files)
70 | if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".gif")) {
71 | InputStream fileContent = filePart.getInputStream();
72 | File uploadedFile = new File(getServletContext().getRealPath("") + UPLOAD_DIRECTORY + fileName);
73 |
74 | if (filePart.getSize() <= MAX_FILE_SIZE) {
75 | try (OutputStream outputStream = new FileOutputStream(uploadedFile)) {
76 | byte[] buffer = new byte[1024];
77 | int bytesRead;
78 | while ((bytesRead = fileContent.read(buffer)) != -1) {
79 | outputStream.write(buffer, 0, bytesRead);
80 | }
81 | }
82 | response.getWriter().println("File uploaded successfully.");
83 | } else {
84 | response.getWriter().println("File size exceeds the limit.");
85 | }
86 | } else {
87 | response.getWriter().println("Invalid file type.");
88 | }
89 | }
90 | }
91 | ```
92 | In this secure code, the uploaded file is checked to ensure it is an image file (jpg, png, or gif), and there is a size limit to prevent excessively large files. This restricts the types of files that can be uploaded and helps mitigate the unrestricted file upload vulnerability. Additionally, the uploaded file is stored in a secure directory and not executed as code.
93 |
--------------------------------------------------------------------------------
/Insecure Password Reset – Token Exposed in Response.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to an Insecure Password Reset Vulnerability :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.util.HashMap;
6 | import java.util.Map;
7 | import java.util.UUID;
8 |
9 | public class InsecurePasswordReset {
10 |
11 | // Vulnerable method for sending reset token in the response
12 | public Map requestPasswordReset(String email) {
13 | // Check if the email exists in the system (simplified for illustration)
14 | if (userExists(email)) {
15 | // Generate a reset token (UUID for simplicity)
16 | String resetToken = UUID.randomUUID().toString();
17 |
18 | // Send the reset token in the response
19 | Map response = new HashMap<>();
20 | response.put("message", "Reset token sent to your email.");
21 | response.put("resetToken", resetToken);
22 | return response;
23 | } else {
24 | // User does not exist
25 | Map response = new HashMap<>();
26 | response.put("message", "Email not found in our system.");
27 | return response;
28 | }
29 | }
30 |
31 | // Check if the user exists (simplified for illustration)
32 | private boolean userExists(String email) {
33 | // Simulated database lookup
34 | return true; // Assume user exists for this example
35 | }
36 |
37 | public static void main(String[] args) {
38 | InsecurePasswordReset resetService = new InsecurePasswordReset();
39 | Map response = resetService.requestPasswordReset("user@example.com");
40 | System.out.println(response);
41 | }
42 | }
43 | ```
44 | In the vulnerable code snippet, the reset token is generated and sent directly in the response. This exposes the token to potential attackers, making it easy for them to reset the password of any user if they can intercept the response. This is a significant security risk.
45 |
46 | ## 😎 Secure Code
47 | ```java
48 | import java.util.HashMap;
49 | import java.util.Map;
50 | import java.util.UUID;
51 |
52 | public class SecurePasswordReset {
53 |
54 | // Secure method for requesting a password reset
55 | public Map requestPasswordReset(String email) {
56 | // Check if the email exists in the system (simplified for illustration)
57 | if (userExists(email)) {
58 | // Generate a reset token (UUID for simplicity)
59 | String resetToken = UUID.randomUUID().toString();
60 |
61 | // Store the reset token securely, e.g., in a database
62 | storeResetToken(email, resetToken);
63 |
64 | // Send a confirmation message without exposing the token
65 | Map response = new HashMap<>();
66 | response.put("message", "Reset instructions sent to your email.");
67 | return response;
68 | } else {
69 | // User does not exist
70 | Map response = new HashMap<>();
71 | response.put("message", "Email not found in our system.");
72 | return response;
73 | }
74 | }
75 |
76 | // Check if the user exists (simplified for illustration)
77 | private boolean userExists(String email) {
78 | // Simulated database lookup
79 | return true; // Assume user exists for this example
80 | }
81 |
82 | // Securely store the reset token in a database
83 | private void storeResetToken(String email, String resetToken) {
84 | // Simulated database storage (replace with actual database code)
85 | // Store the reset token securely associated with the user's email
86 | }
87 |
88 | public static void main(String[] args) {
89 | SecurePasswordReset resetService = new SecurePasswordReset();
90 | Map response = resetService.requestPasswordReset("user@example.com");
91 | System.out.println(response);
92 | }
93 | }
94 | ```
95 | In the secure code snippet, we address the vulnerability by not sending the reset token in the response. Instead, we generate the token, securely store it (in a database, for example), and send a confirmation message to the user without exposing the token. This way, the reset token remains confidential and can only be used by the legitimate user to reset their password, enhancing the security of the password reset functionality.
96 |
--------------------------------------------------------------------------------
/Insecure Password Storage.md:
--------------------------------------------------------------------------------
1 | Here is an example of vulnerable code that is susceptible to an Insecure Password Storage Practice Vulnerability :
2 |
3 | ## 🥺 Vulnerable Code
4 | ```java
5 | import java.security.MessageDigest;
6 | import java.security.NoSuchAlgorithmException;
7 | import java.sql.Connection;
8 | import java.sql.DriverManager;
9 | import java.sql.PreparedStatement;
10 | import java.sql.SQLException;
11 |
12 | public class VulnerablePasswordStorage {
13 | public static void main(String[] args) {
14 | String username = "user123";
15 | String plainPassword = "insecurePassword";
16 |
17 | // Vulnerable: Storing plain text password in the database
18 | storePasswordInsecurely(username, plainPassword);
19 | }
20 |
21 | public static void storePasswordInsecurely(String username, String password) {
22 | try {
23 | Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
24 | String query = "INSERT INTO users (username, password) VALUES (?, ?)";
25 | PreparedStatement pstmt = conn.prepareStatement(query);
26 | pstmt.setString(1, username);
27 | pstmt.setString(2, password); // Vulnerable: Storing plain text password
28 |
29 | pstmt.executeUpdate();
30 | pstmt.close();
31 | conn.close();
32 | } catch (SQLException e) {
33 | e.printStackTrace();
34 | }
35 | }
36 | }
37 | ```
38 | In the vulnerable code above, the plain text password is stored directly in the database, which is highly insecure. If an attacker gains access to the database, they can easily obtain the user’s passwords.
39 |
40 | ## 😎 Secure Code
41 | ```java
42 | import java.security.MessageDigest;
43 | import java.security.NoSuchAlgorithmException;
44 | import java.security.SecureRandom;
45 | import java.sql.Connection;
46 | import java.sql.DriverManager;
47 | import java.sql.PreparedStatement;
48 | import java.sql.SQLException;
49 | import java.util.Base64;
50 |
51 | public class SecurePasswordStorageWithSalt {
52 | public static void main(String[] args) {
53 | String username = "user123";
54 | String plainPassword = "securePassword";
55 |
56 | // Generate a random salt for the user
57 | byte[] salt = generateSalt();
58 |
59 | // Secure: Storing salted and hashed password in the database
60 | storePasswordSecurely(username, salt, hashPassword(plainPassword, salt));
61 | }
62 |
63 | public static void storePasswordSecurely(String username, byte[] salt, String hashedPassword) {
64 | try {
65 | Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
66 | String query = "INSERT INTO users (username, salt, password) VALUES (?, ?, ?)";
67 | PreparedStatement pstmt = conn.prepareStatement(query);
68 | pstmt.setString(1, username);
69 | pstmt.setString(2, Base64.getEncoder().encodeToString(salt)); // Storing salt as a Base64 encoded string
70 | pstmt.setString(3, hashedPassword); // Secure: Storing salted and hashed password
71 |
72 | pstmt.executeUpdate();
73 | pstmt.close();
74 | conn.close();
75 | } catch (SQLException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 |
80 | public static byte[] generateSalt() {
81 | SecureRandom random = new SecureRandom();
82 | byte[] salt = new byte[16]; // 16 bytes (128 bits) is a common choice for salt length
83 | random.nextBytes(salt);
84 | return salt;
85 | }
86 |
87 | public static String hashPassword(String password, byte[] salt) {
88 | try {
89 | MessageDigest md = MessageDigest.getInstance("SHA-256");
90 |
91 | // Combine the password and salt, then hash
92 | md.update(salt);
93 | byte[] hashedBytes = md.digest(password.getBytes());
94 |
95 | // Convert bytes to hexadecimal representation
96 | StringBuilder sb = new StringBuilder();
97 | for (byte b : hashedBytes) {
98 | sb.append(String.format("%02x", b));
99 | }
100 |
101 | return sb.toString();
102 | } catch (NoSuchAlgorithmException e) {
103 | e.printStackTrace();
104 | return null;
105 | }
106 | }
107 | }
108 | ```
109 | In this Secure code, a random salt is generated for each user and stored alongside the hashed password in the database. When verifying a user’s login, you retrieve the salt from the database and use it to hash the provided password before comparing it to the stored hash. This combination of salting and hashing provides a strong defense against password attacks.
110 |
--------------------------------------------------------------------------------