diff --git a/wiki/src/main/java/com/scalesec/vulnado/Comment.java.md b/wiki/src/main/java/com/scalesec/vulnado/Comment.java.md new file mode 100755 index 00000000..18e1896b --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/Comment.java.md @@ -0,0 +1,136 @@ +# Documentation: `Comment` Class + +## Overview + +The `Comment` class is a Java implementation for managing user comments. It provides functionality to create, retrieve, and delete comments from a PostgreSQL database. Each comment is represented by attributes such as `id`, `username`, `body`, and `created_on`. The class interacts with the database using SQL queries and leverages JDBC for database connectivity. + +--- + +## Class Details + +### Package +The class is part of the `com.scalesec.vulnado` package. + +### Dependencies +The class relies on the following imports: +- `org.apache.catalina.Server` (Unused in the current implementation) +- `java.sql.*` (For database operations) +- `java.util.*` (For utility classes like `Date`, `List`, `ArrayList`, and `UUID`) + +--- + +## Attributes + +| Attribute | Type | Description | +|--------------|--------------|------------------------------------------| +| `id` | `String` | Unique identifier for the comment. | +| `username` | `String` | Username of the person who made the comment. | +| `body` | `String` | Content of the comment. | +| `created_on` | `Timestamp` | Timestamp indicating when the comment was created. | + +--- + +## Constructor + +### `Comment(String id, String username, String body, Timestamp created_on)` +Initializes a new `Comment` object with the provided attributes. + +| Parameter | Type | Description | +|---------------|-------------|------------------------------------------| +| `id` | `String` | Unique identifier for the comment. | +| `username` | `String` | Username of the person who made the comment. | +| `body` | `String` | Content of the comment. | +| `created_on` | `Timestamp` | Timestamp indicating when the comment was created. | + +--- + +## Methods + +### `static Comment create(String username, String body)` +Creates a new comment and saves it to the database. + +| Parameter | Type | Description | +|-------------|-----------|------------------------------------------| +| `username` | `String` | Username of the person creating the comment. | +| `body` | `String` | Content of the comment. | + +- Generates a unique `id` using `UUID`. +- Sets the `created_on` timestamp to the current time. +- Calls the private `commit()` method to save the comment to the database. +- Throws a `BadRequest` exception if the comment cannot be saved. +- Throws a `ServerError` exception in case of other errors. + +--- + +### `static List fetch_all()` +Retrieves all comments from the database. + +| Return Type | Description | +|-------------|------------------------------------------| +| `List` | A list of all comments stored in the database. | + +- Executes a `SELECT * FROM comments` query. +- Maps each row in the result set to a `Comment` object. +- Returns a list of `Comment` objects. + +--- + +### `static Boolean delete(String id)` +Deletes a comment from the database based on its `id`. + +| Parameter | Type | Description | +|-----------|-----------|------------------------------------------| +| `id` | `String` | Unique identifier of the comment to delete. | + +| Return Type | Description | +|-------------|------------------------------------------| +| `Boolean` | `true` if the comment was successfully deleted, `false` otherwise. | + +- Executes a `DELETE FROM comments WHERE id = ?` query. +- Uses a prepared statement to prevent SQL injection. + +--- + +### `private Boolean commit() throws SQLException` +Saves the current `Comment` object to the database. + +| Return Type | Description | +|-------------|------------------------------------------| +| `Boolean` | `true` if the comment was successfully saved, `false` otherwise. | + +- Executes an `INSERT INTO comments` query. +- Uses a prepared statement to insert the comment attributes into the database. + +--- + +## Insights + +1. **Database Dependency**: The class relies on a `Postgres.connection()` method to establish a database connection. This method is not defined in the class and is assumed to be part of another utility class. + +2. **Error Handling**: + - The `create` method throws custom exceptions (`BadRequest` and `ServerError`) for specific error scenarios. + - Other methods use `try-catch` blocks but do not propagate exceptions effectively, which may lead to silent failures. + +3. **SQL Injection Prevention**: Prepared statements are used in the `commit` and `delete` methods to prevent SQL injection attacks. + +4. **Unused Import**: The `org.apache.catalina.Server` import is not used in the current implementation and can be removed. + +5. **Potential Bug in `delete` Method**: + - The `finally` block always returns `false`, overriding the actual result of the `executeUpdate()` method. This needs to be corrected. + +6. **Scalability**: + - The `fetch_all` method retrieves all comments without any pagination or filtering, which may lead to performance issues with large datasets. + +7. **Thread Safety**: The class is not thread-safe as it uses shared database connections without synchronization. + +8. **Timestamp Handling**: The `created_on` timestamp is generated using the system's current time, which may lead to inconsistencies in distributed systems. + +--- + +## Potential Enhancements + +- **Pagination**: Add support for pagination in the `fetch_all` method to handle large datasets efficiently. +- **Connection Pooling**: Use a connection pool to manage database connections more effectively. +- **Validation**: Add input validation for `username` and `body` to ensure data integrity. +- **Logging**: Replace `System.err.println` with a proper logging framework for better error tracking and debugging. +- **Unit Tests**: Implement unit tests to validate the functionality of each method. diff --git a/wiki/src/main/java/com/scalesec/vulnado/CommentsController.java.md b/wiki/src/main/java/com/scalesec/vulnado/CommentsController.java.md new file mode 100755 index 00000000..e0719c26 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/CommentsController.java.md @@ -0,0 +1,133 @@ +# Documentation: `CommentsController.java` + +## Overview + +The `CommentsController` class is a RESTful controller implemented using the Spring Boot framework. It provides endpoints for managing comments, including fetching, creating, and deleting comments. The controller enforces authentication via a custom header (`x-auth-token`) and supports cross-origin requests. + +## Features + +- **Authentication**: Validates requests using a token passed in the `x-auth-token` header. +- **Endpoints**: + - Fetch all comments (`GET /comments`) + - Create a new comment (`POST /comments`) + - Delete a comment by ID (`DELETE /comments/{id}`) +- **Error Handling**: Custom exceptions for `BadRequest` and `ServerError` with appropriate HTTP status codes. +- **Cross-Origin Resource Sharing (CORS)**: Allows requests from any origin. + +--- + +## Class Details + +### 1. `CommentsController` + +#### Annotations +- `@RestController`: Marks the class as a RESTful controller. +- `@EnableAutoConfiguration`: Enables Spring Boot's auto-configuration feature. +- `@CrossOrigin(origins = "*")`: Allows cross-origin requests from any domain. + +#### Fields +| Field Name | Type | Description | +|------------|--------|--------------------------------------| +| `secret` | String | Application secret for authentication. | + +#### Methods + +| Method Name | HTTP Method | Endpoint | Description | +|-------------------|-------------|---------------------|-----------------------------------------------------------------------------| +| `comments` | `GET` | `/comments` | Fetches all comments. Requires `x-auth-token` for authentication. | +| `createComment` | `POST` | `/comments` | Creates a new comment. Requires `x-auth-token` and a JSON body. | +| `deleteComment` | `DELETE` | `/comments/{id}` | Deletes a comment by its ID. Requires `x-auth-token` for authentication. | + +#### Method Details + +1. **`comments`** + - **Parameters**: + - `@RequestHeader(value="x-auth-token") String token`: Authentication token. + - **Returns**: A list of all comments (`List`). + - **Logic**: + - Validates the token using `User.assertAuth(secret, token)`. + - Fetches all comments using `Comment.fetch_all()`. + +2. **`createComment`** + - **Parameters**: + - `@RequestHeader(value="x-auth-token") String token`: Authentication token. + - `@RequestBody CommentRequest input`: JSON body containing the comment details. + - **Returns**: The created comment (`Comment`). + - **Logic**: + - Creates a new comment using `Comment.create(input.username, input.body)`. + +3. **`deleteComment`** + - **Parameters**: + - `@RequestHeader(value="x-auth-token") String token`: Authentication token. + - `@PathVariable("id") String id`: ID of the comment to delete. + - **Returns**: A boolean indicating success or failure (`Boolean`). + - **Logic**: + - Deletes the comment using `Comment.delete(id)`. + +--- + +### 2. `CommentRequest` + +#### Description +A data structure representing the request body for creating a comment. + +#### Fields +| Field Name | Type | Description | +|------------|--------|------------------------------| +| `username` | String | The username of the commenter. | +| `body` | String | The content of the comment. | + +#### Notes +- Implements `Serializable` for potential serialization needs. + +--- + +### 3. `BadRequest` + +#### Description +A custom exception representing a `400 Bad Request` error. + +#### Annotations +- `@ResponseStatus(HttpStatus.BAD_REQUEST)`: Maps the exception to a `400 Bad Request` HTTP status. + +#### Constructor +| Parameter | Type | Description | +|-------------|--------|---------------------------------| +| `exception` | String | The error message for the exception. | + +--- + +### 4. `ServerError` + +#### Description +A custom exception representing a `500 Internal Server Error`. + +#### Annotations +- `@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)`: Maps the exception to a `500 Internal Server Error` HTTP status. + +#### Constructor +| Parameter | Type | Description | +|-------------|--------|---------------------------------| +| `exception` | String | The error message for the exception. | + +--- + +## Insights + +1. **Authentication**: + - The `User.assertAuth(secret, token)` method is used for token validation. This implies a dependency on the `User` class, which is not included in this file. + +2. **Comment Management**: + - The `Comment` class is responsible for fetching, creating, and deleting comments. Its implementation is not provided, but it is expected to handle database interactions or other storage mechanisms. + +3. **CORS Configuration**: + - The `@CrossOrigin(origins = "*")` annotation allows requests from any origin. This is useful for development but may pose security risks in production if not restricted to specific domains. + +4. **Error Handling**: + - Custom exceptions (`BadRequest` and `ServerError`) provide a clear mechanism for handling and responding to errors with appropriate HTTP status codes. + +5. **Scalability**: + - The controller assumes a flat structure for comments. If nested or hierarchical comments are required, additional logic would need to be implemented. + +6. **Security**: + - The use of a secret for token validation suggests a shared secret-based authentication mechanism. Consider using more robust authentication methods (e.g., OAuth2) for production systems. diff --git a/wiki/src/main/java/com/scalesec/vulnado/CowController.java.md b/wiki/src/main/java/com/scalesec/vulnado/CowController.java.md new file mode 100755 index 00000000..e5f76ae3 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/CowController.java.md @@ -0,0 +1,45 @@ +# CowController Documentation + +## Overview +The `CowController` class is a Spring Boot REST controller that provides an endpoint for generating text output using the `Cowsay` utility. It is designed to handle HTTP requests and return a response based on the input provided by the user. + +## Class Details + +### Metadata +- **File Name**: `CowController.java` +- **Package**: `com.scalesec.vulnado` + +### Annotations +- `@RestController`: Indicates that this class is a REST controller, meaning it handles HTTP requests and returns responses in a RESTful manner. +- `@EnableAutoConfiguration`: Enables Spring Boot's auto-configuration mechanism, which automatically configures the application based on its dependencies. + +### Dependencies +- **Spring Framework**: Used for REST API development and dependency injection. +- **Cowsay Utility**: A utility (assumed to be implemented elsewhere) that generates ASCII art text output. + +## Endpoint + +### `/cowsay` +#### Description +This endpoint generates a response using the `Cowsay` utility. The user can provide an input string, which will be processed and returned as ASCII art. + +#### HTTP Method +- `GET` + +#### Parameters +| Name | Type | Default Value | Description | +|------------|--------|---------------------|-----------------------------------------------------------------------------| +| `input` | String | `"I love Linux!"` | The text to be processed by the `Cowsay` utility. If not provided, defaults to `"I love Linux!"`. | + +#### Response +- **Type**: `String` +- **Description**: Returns the ASCII art generated by the `Cowsay` utility based on the input string. + +## Insights +- **Security Considerations**: The `input` parameter is directly passed to the `Cowsay.run()` method. If `Cowsay.run()` executes system commands or processes the input in an unsafe manner, this could lead to vulnerabilities such as command injection. Proper input validation and sanitization should be implemented to mitigate risks. +- **Default Behavior**: If no input is provided, the endpoint defaults to the message `"I love Linux!"`, ensuring the endpoint always returns a meaningful response. +- **Scalability**: The controller is lightweight and does not maintain state, making it suitable for scaling in distributed systems. +- **Extensibility**: Additional endpoints or features can be added to the controller to expand its functionality. + +## Related Components +- **Cowsay Utility**: The `Cowsay.run()` method is assumed to be implemented elsewhere in the application. Its functionality and implementation details are critical to understanding the behavior of this controller. diff --git a/wiki/src/main/java/com/scalesec/vulnado/Cowsay.java.md b/wiki/src/main/java/com/scalesec/vulnado/Cowsay.java.md new file mode 100755 index 00000000..a18a8e3e --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/Cowsay.java.md @@ -0,0 +1,96 @@ +# Documentation: `Cowsay.java` + +## Overview + +The `Cowsay` class provides a method to execute the `cowsay` command-line utility, which generates ASCII art of a cow saying a given input message. This class uses Java's `ProcessBuilder` to execute the command in a shell environment and captures the output. + +--- + +## Class: `Cowsay` + +### Purpose +The `Cowsay` class is designed to interact with the `cowsay` utility installed on the system. It takes a string input, passes it to the `cowsay` command, and returns the resulting ASCII art as a string. + +--- + +### Method: `run(String input)` + +#### Description +The `run` method executes the `cowsay` command with the provided input string and captures the output. It uses a `ProcessBuilder` to invoke the command in a bash shell and reads the output using a `BufferedReader`. + +#### Parameters +| Parameter | Type | Description | +|-----------|--------|--------------------------------------| +| `input` | String | The message to be displayed by `cowsay`. | + +#### Return Value +| Type | Description | +|--------|--------------------------------------------------| +| String | The ASCII art output generated by the `cowsay` command. | + +#### Logic Flow +1. Constructs the command string: `/usr/games/cowsay ''`. +2. Configures a `ProcessBuilder` to execute the command in a bash shell. +3. Starts the process and captures the output using a `BufferedReader`. +4. Appends each line of the output to a `StringBuilder`. +5. Returns the final output as a string. + +#### Exception Handling +- Catches any `Exception` that occurs during the process execution and prints the stack trace using `e.printStackTrace()`. + +--- + +## Insights + +### Security Concerns +- **Command Injection Vulnerability**: The method directly concatenates the user-provided `input` into the command string without sanitization. This makes the application vulnerable to command injection attacks. For example, an attacker could pass malicious input like `"; rm -rf /;"` to execute arbitrary commands on the system. +- **Mitigation**: Use parameterized commands or sanitize the input to prevent injection attacks. + +### Dependencies +- The `cowsay` utility must be installed on the system at `/usr/games/cowsay` for this class to function correctly. If the utility is not installed or located elsewhere, the method will fail. + +### Usability +- The method assumes a Unix-like environment with bash available. It will not work on systems without bash or the `cowsay` utility. + +### Error Handling +- The method does not provide robust error handling. It only prints the stack trace in case of an exception, which may not be suitable for production environments. Consider logging errors or returning meaningful error messages. + +### Output Formatting +- The method appends a newline character (`\n`) after each line of the output. This ensures the ASCII art is formatted correctly when returned. + +--- + +## Example Usage + +```java +public class Main { + public static void main(String[] args) { + String message = "Hello, world!"; + String result = Cowsay.run(message); + System.out.println(result); + } +} +``` + +### Expected Output +If the `cowsay` utility is installed and the input is `"Hello, world!"`, the output might look like: + +``` + _______________ +< Hello, world! > + --------------- + \ ^__^ + \ (oo)\_______ + (__)\ )\/\ + ||----w | + || || +``` + +--- + +## Metadata + +| Key | Value | +|-------------|---------------| +| File Name | `Cowsay.java` | +| Package | `com.scalesec.vulnado` | diff --git a/wiki/src/main/java/com/scalesec/vulnado/LinkLister.java.md b/wiki/src/main/java/com/scalesec/vulnado/LinkLister.java.md new file mode 100755 index 00000000..7ae33441 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/LinkLister.java.md @@ -0,0 +1,99 @@ +# Documentation: `LinkLister.java` + +## Overview +The `LinkLister` class provides functionality to extract hyperlinks from a given URL. It uses the `Jsoup` library for HTML parsing and includes methods to retrieve links with additional validation for private IP addresses. + +--- + +## Class: `LinkLister` + +### Purpose +The class is designed to fetch and process hyperlinks (`` tags) from a web page. It includes two methods: +1. `getLinks`: Extracts all hyperlinks from a given URL. +2. `getLinksV2`: Adds validation to ensure the URL does not point to a private IP address before extracting links. + +--- + +## Methods + +### `getLinks(String url)` +#### Description +Fetches all hyperlinks (`` tags) from the HTML content of the provided URL. + +#### Parameters +| Name | Type | Description | +|------|--------|---------------------------------| +| `url` | `String` | The URL of the web page to parse. | + +#### Returns +| Type | Description | +|---------------|--------------------------------------| +| `List` | A list of absolute URLs extracted from the web page. | + +#### Exceptions +| Type | Description | +|---------------|--------------------------------------| +| `IOException` | Thrown if there is an issue connecting to the URL or fetching its content. | + +#### Logic +1. Connects to the provided URL using `Jsoup.connect(url).get()`. +2. Selects all `` elements using `doc.select("a")`. +3. Extracts the absolute URL of each hyperlink using `link.absUrl("href")`. +4. Returns the list of extracted URLs. + +--- + +### `getLinksV2(String url)` +#### Description +Fetches hyperlinks from the provided URL after validating that the URL does not point to a private IP address. + +#### Parameters +| Name | Type | Description | +|------|--------|---------------------------------| +| `url` | `String` | The URL of the web page to parse. | + +#### Returns +| Type | Description | +|---------------|--------------------------------------| +| `List` | A list of absolute URLs extracted from the web page. | + +#### Exceptions +| Type | Description | +|---------------|--------------------------------------| +| `BadRequest` | Thrown if the URL points to a private IP address or if any other error occurs during processing. | + +#### Logic +1. Parses the URL using `new URL(url)` to extract the host. +2. Checks if the host starts with private IP address prefixes (`172.`, `192.168`, or `10.`). + - If true, throws a `BadRequest` exception with the message "Use of Private IP". +3. If the host is valid, calls the `getLinks` method to fetch hyperlinks. +4. Catches any exceptions and wraps them in a `BadRequest` exception. + +--- + +## Insights + +### Key Features +- **HTML Parsing**: Utilizes the `Jsoup` library to parse HTML and extract `` tags. +- **Private IP Validation**: Ensures URLs pointing to private IP addresses are rejected for security reasons. +- **Error Handling**: Implements robust exception handling to manage invalid URLs or connection issues. + +### Dependencies +- **Jsoup Library**: Required for HTML parsing and manipulation. +- **Java Networking**: Uses `java.net.URL` for URL validation and host extraction. + +### Security Considerations +- The `getLinksV2` method prevents access to private IP addresses, mitigating potential security risks such as SSRF (Server-Side Request Forgery). +- The `BadRequest` exception is used to handle invalid inputs gracefully. + +### Potential Enhancements +- **Customizable IP Validation**: Allow users to specify additional IP ranges or domains to block. +- **Timeout Handling**: Add timeout settings for `Jsoup.connect()` to prevent long delays during network issues. +- **Logging**: Implement detailed logging for debugging and monitoring purposes. + +--- + +## File Metadata +| Key | Value | +|-------------|--------------------| +| **File Name** | `LinkLister.java` | diff --git a/wiki/src/main/java/com/scalesec/vulnado/LinksController.java.md b/wiki/src/main/java/com/scalesec/vulnado/LinksController.java.md new file mode 100755 index 00000000..4e8486e3 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/LinksController.java.md @@ -0,0 +1,88 @@ +# Documentation: `LinksController.java` + +## Overview +The `LinksController` class is a REST controller implemented using the Spring Boot framework. It provides two endpoints (`/links` and `/links-v2`) for retrieving a list of links from a given URL. The class leverages the `LinkLister` utility to process the input URL and extract links. + +## Class Details + +### Class Name +`LinksController` + +### Annotations +- **`@RestController`**: Indicates that this class is a REST controller, meaning it handles HTTP requests and produces HTTP responses. +- **`@EnableAutoConfiguration`**: Enables Spring Boot's auto-configuration mechanism, simplifying the setup of the application. + +### Dependencies +- **Spring Boot**: Used for building and running the application. +- **Spring Web**: Provides annotations and utilities for handling HTTP requests and responses. +- **Java IO**: Used for handling input/output operations, such as exceptions related to `IOException`. + +--- + +## Endpoints + +### `/links` +#### Description +Retrieves a list of links from the provided URL. + +#### HTTP Method +`GET` + +#### Parameters +| Name | Type | Description | +|------|--------|------------------------------| +| `url` | `String` | The URL to extract links from. | + +#### Response +- **Type**: `List` +- **Content-Type**: `application/json` +- **Description**: A list of links extracted from the provided URL. + +#### Exceptions +- **`IOException`**: Thrown if an error occurs during the processing of the URL. + +--- + +### `/links-v2` +#### Description +Retrieves a list of links from the provided URL using an alternative method. + +#### HTTP Method +`GET` + +#### Parameters +| Name | Type | Description | +|------|--------|------------------------------| +| `url` | `String` | The URL to extract links from. | + +#### Response +- **Type**: `List` +- **Content-Type**: `application/json` +- **Description**: A list of links extracted from the provided URL using the `LinkLister.getLinksV2` method. + +#### Exceptions +- **`BadRequest`**: Thrown if the input URL is invalid or cannot be processed. + +--- + +## Insights + +### Key Features +1. **Dynamic Link Extraction**: The controller provides two endpoints for extracting links from a URL, offering flexibility in implementation (`getLinks` vs `getLinksV2`). +2. **Error Handling**: The endpoints handle specific exceptions (`IOException` and `BadRequest`) to ensure robust error reporting. + +### Potential Enhancements +1. **Validation**: Add input validation for the `url` parameter to ensure it is a valid URL before processing. +2. **Error Responses**: Implement custom error responses for exceptions to provide more informative feedback to the client. +3. **Security**: Consider sanitizing the `url` parameter to prevent potential security vulnerabilities such as SSRF (Server-Side Request Forgery). + +### Dependencies on External Classes +The controller relies on the `LinkLister` class for the actual link extraction logic. Ensure that `LinkLister` is implemented securely and efficiently to handle various edge cases. + +--- + +## Metadata +| Key | Value | +|-------------|------------------------| +| File Name | `LinksController.java` | +| Package | `com.scalesec.vulnado` | diff --git a/wiki/src/main/java/com/scalesec/vulnado/LoginController.java.md b/wiki/src/main/java/com/scalesec/vulnado/LoginController.java.md new file mode 100755 index 00000000..7ee90987 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/LoginController.java.md @@ -0,0 +1,115 @@ +# Documentation: `LoginController.java` + +## Overview +The `LoginController` class is part of a Spring Boot application and provides functionality for user authentication. It exposes an endpoint for login requests, validates user credentials, and returns a token upon successful authentication. The class also handles unauthorized access scenarios. + +--- + +## File Metadata +- **File Name**: `LoginController.java` + +--- + +## Components + +### 1. **LoginController** +#### Description +The main controller class that handles login requests. It uses Spring Boot annotations to define RESTful behavior and configuration. + +#### Key Features +- **Endpoint**: `/login` + - **HTTP Method**: POST + - **Consumes**: JSON + - **Produces**: JSON + - **Cross-Origin**: Enabled for all origins (`*`). +- **Authentication Logic**: + - Fetches user details using `User.fetch(username)`. + - Compares the hashed password from the request with the stored hashed password. + - Generates a token using a secret key if authentication is successful. + - Throws an `Unauthorized` exception if authentication fails. + +#### Dependencies +- **Spring Boot**: + - `@RestController` + - `@EnableAutoConfiguration` + - `@CrossOrigin` + - `@RequestMapping` + - `@Value` +- **HTTP Status**: + - `HttpStatus.UNAUTHORIZED` + +#### Fields +| Field Name | Type | Description | +|------------|--------|--------------------------------------| +| `secret` | String | Secret key used for token generation.| + +--- + +### 2. **LoginRequest** +#### Description +A data structure representing the login request payload. It implements `Serializable` for potential serialization needs. + +#### Fields +| Field Name | Type | Description | +|------------|--------|---------------------------------| +| `username` | String | Username provided by the user. | +| `password` | String | Password provided by the user. | + +--- + +### 3. **LoginResponse** +#### Description +A data structure representing the login response payload. It contains the authentication token. + +#### Fields +| Field Name | Type | Description | +|------------|--------|---------------------------------| +| `token` | String | Authentication token. | + +#### Constructor +| Constructor Signature | Description | +|----------------------------------------|--------------------------------------| +| `LoginResponse(String msg)` | Initializes the response with a token.| + +--- + +### 4. **Unauthorized** +#### Description +A custom exception class that represents unauthorized access. It is annotated with `@ResponseStatus(HttpStatus.UNAUTHORIZED)` to automatically return a 401 status code when thrown. + +#### Constructor +| Constructor Signature | Description | +|----------------------------------------|--------------------------------------| +| `Unauthorized(String exception)` | Initializes the exception with a message.| + +--- + +## Insights + +### Security Considerations +1. **Hardcoded Secret**: The `secret` field is injected via `@Value("${app.secret}")`. Ensure that the secret is securely stored and not exposed in the codebase or environment variables. +2. **Password Hashing**: The password comparison uses `Postgres.md5`. Verify that MD5 hashing is sufficient for your security requirements, as MD5 is considered weak for cryptographic purposes. +3. **Cross-Origin Requests**: The `@CrossOrigin(origins = "*")` annotation allows requests from all origins. This could expose the endpoint to potential security risks. Consider restricting origins to trusted domains. + +### Error Handling +- The `Unauthorized` exception provides a clear mechanism for handling failed authentication attempts. However, ensure that error messages do not leak sensitive information. + +### Scalability +- The `User.fetch(username)` method is assumed to retrieve user details from a database. Ensure that this operation is optimized for performance, especially in high-traffic scenarios. + +### Serialization +- Both `LoginRequest` and `LoginResponse` implement `Serializable`. This is useful for scenarios where objects need to be serialized, such as caching or distributed systems. + +### RESTful Design +- The `/login` endpoint adheres to RESTful principles by using HTTP POST for data submission and returning JSON responses. + +--- + +## Summary Table + +| Component | Type | Purpose | +|--------------------|-----------------|-------------------------------------------| +| `LoginController` | Controller | Handles login requests and authentication.| +| `LoginRequest` | Data Structure | Represents the login request payload. | +| `LoginResponse` | Data Structure | Represents the login response payload. | +| `Unauthorized` | Exception Class | Handles unauthorized access scenarios. | diff --git a/wiki/src/main/java/com/scalesec/vulnado/Postgres.java.md b/wiki/src/main/java/com/scalesec/vulnado/Postgres.java.md new file mode 100755 index 00000000..0aa9a5d9 --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/Postgres.java.md @@ -0,0 +1,117 @@ +# Documentation for `Postgres.java` + +## Overview +The `Postgres` class provides functionality for interacting with a PostgreSQL database. It includes methods for establishing a database connection, setting up the database schema, inserting seed data, and hashing passwords using the MD5 algorithm. This class is designed to initialize and manage a database for a user and comment system. + +--- + +## File Metadata +- **File Name**: `Postgres.java` +- **Package**: `com.scalesec.vulnado` + +--- + +## Features and Functionality + +### 1. **Database Connection** +The `connection()` method establishes a connection to a PostgreSQL database using credentials and connection details provided via environment variables. + +#### Environment Variables Used: +| Variable Name | Description | +|---------------|-------------| +| `PGHOST` | Hostname of the PostgreSQL server | +| `PGDATABASE` | Name of the database to connect to | +| `PGUSER` | Username for authentication | +| `PGPASSWORD` | Password for authentication | + +#### Key Points: +- Uses `DriverManager` to establish the connection. +- Requires the PostgreSQL JDBC driver (`org.postgresql.Driver`). +- Prints error details and exits the program if the connection fails. + +--- + +### 2. **Database Setup** +The `setup()` method initializes the database by: +1. Creating tables (`users` and `comments`) if they do not already exist. +2. Cleaning up any existing data in the tables. +3. Inserting seed data for users and comments. + +#### Tables Created: +| Table Name | Columns | +|------------|---------------------------------------------------------------------------------------------| +| `users` | `user_id` (Primary Key), `username` (Unique), `password`, `created_on`, `last_login` | +| `comments` | `id` (Primary Key), `username`, `body`, `created_on` | + +#### Seed Data: +- **Users**: `admin`, `alice`, `bob`, `eve`, `rick` with predefined passwords. +- **Comments**: Comments by `rick` and `alice`. + +--- + +### 3. **Password Hashing** +The `md5()` method generates an MD5 hash for a given input string. This is used to securely store user passwords in the database. + +#### Key Points: +- Uses `MessageDigest` to compute the MD5 hash. +- Converts the hash into a hexadecimal string. +- Pads the hash to ensure it is 32 characters long. + +--- + +### 4. **Data Insertion** +#### `insertUser(String username, String password)` +Inserts a new user into the `users` table with the following details: +- `user_id`: A randomly generated UUID. +- `username`: Provided username. +- `password`: MD5 hash of the provided password. +- `created_on`: Current timestamp. + +#### `insertComment(String username, String body)` +Inserts a new comment into the `comments` table with the following details: +- `id`: A randomly generated UUID. +- `username`: Provided username. +- `body`: Content of the comment. +- `created_on`: Current timestamp. + +--- + +## Insights + +### Security Concerns +1. **MD5 for Password Hashing**: + - MD5 is considered cryptographically weak and vulnerable to collision attacks. It is recommended to use stronger hashing algorithms like `bcrypt`, `PBKDF2`, or `Argon2` for password storage. + +2. **Hardcoded Seed Data**: + - The seed data includes sensitive information such as the `admin` password. This could be a security risk if the database is exposed. + +3. **Environment Variables**: + - The reliance on environment variables for database credentials is a good practice, but ensure these variables are securely managed and not exposed. + +### Database Design +- The `users` table includes a `last_login` column, but it is not utilized in the current implementation. This could be used for tracking user activity in the future. +- The `comments` table does not enforce foreign key constraints between `username` in `comments` and `username` in `users`. This could lead to data integrity issues. + +### Error Handling +- The error handling in the `connection()` and data insertion methods prints stack traces but does not provide robust recovery mechanisms. Consider implementing logging and retry mechanisms. + +### Scalability +- The current implementation clears all data during setup, which may not be suitable for production environments. A more sophisticated migration strategy should be considered. + +--- + +## Dependencies +- **PostgreSQL JDBC Driver**: Required for database connectivity (`org.postgresql.Driver`). +- **Java Standard Libraries**: + - `java.sql`: For database operations. + - `java.security`: For password hashing. + - `java.util.UUID`: For generating unique identifiers. + +--- + +## Usage +1. Set the required environment variables (`PGHOST`, `PGDATABASE`, `PGUSER`, `PGPASSWORD`). +2. Call the `setup()` method to initialize the database. +3. Use `insertUser()` and `insertComment()` methods to add data programmatically. + +--- diff --git a/wiki/src/main/java/com/scalesec/vulnado/User.java.md b/wiki/src/main/java/com/scalesec/vulnado/User.java.md new file mode 100755 index 00000000..c67603ac --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/User.java.md @@ -0,0 +1,149 @@ +# Documentation: `User` Class + +## Overview + +The `User` class is part of the `com.scalesec.vulnado` package and provides functionality for user management, including token generation, authentication, and database retrieval. It interacts with a PostgreSQL database to fetch user details and uses JSON Web Tokens (JWT) for authentication. + +--- + +## Class: `User` + +### Fields + +| Field Name | Type | Description | +|------------------|----------|--------------------------------------------------| +| `id` | `String` | Unique identifier for the user. | +| `username` | `String` | Username of the user. | +| `hashedPassword` | `String` | Hashed password of the user. | + +--- + +### Constructor + +#### `User(String id, String username, String hashedPassword)` + +Initializes a new `User` object with the provided `id`, `username`, and `hashedPassword`. + +| Parameter | Type | Description | +|-------------------|----------|--------------------------------------------------| +| `id` | `String` | Unique identifier for the user. | +| `username` | `String` | Username of the user. | +| `hashedPassword` | `String` | Hashed password of the user. | + +--- + +### Methods + +#### `String token(String secret)` + +Generates a JSON Web Token (JWT) for the user using the provided secret key. + +| Parameter | Type | Description | +|-----------|----------|--------------------------------------------------| +| `secret` | `String` | Secret key used to sign the JWT. | + +**Returns:** +A signed JWT as a `String`. + +--- + +#### `static void assertAuth(String secret, String token)` + +Validates a given JWT token using the provided secret key. If the token is invalid, an `Unauthorized` exception is thrown. + +| Parameter | Type | Description | +|-----------|----------|--------------------------------------------------| +| `secret` | `String` | Secret key used to validate the JWT. | +| `token` | `String` | JWT token to be validated. | + +**Throws:** +- `Unauthorized` if the token is invalid. + +--- + +#### `static User fetch(String un)` + +Fetches a user from the PostgreSQL database based on the provided username. If no user is found, it returns `null`. + +| Parameter | Type | Description | +|-----------|----------|--------------------------------------------------| +| `un` | `String` | Username of the user to fetch. | + +**Returns:** +A `User` object if the user is found, otherwise `null`. + +--- + +## Insights + +### Security Concerns +1. **SQL Injection Vulnerability**: + The `fetch` method constructs SQL queries using string concatenation, which makes it vulnerable to SQL injection attacks. Use prepared statements to mitigate this risk. + +2. **Weak Secret Management**: + The `token` and `assertAuth` methods rely on a secret key passed as a string. Ensure the secret is securely stored and managed (e.g., using environment variables or a secure vault). + +3. **Exception Handling**: + The `assertAuth` method catches exceptions but rethrows them as `Unauthorized`. Ensure sensitive information is not leaked in the exception message. + +4. **Password Storage**: + The `hashedPassword` field suggests that passwords are hashed. Ensure a strong hashing algorithm (e.g., bcrypt, Argon2) is used. + +--- + +### Dependencies +- **JWT Library**: + The class uses the `io.jsonwebtoken` library for JWT generation and validation. + +- **Database Connection**: + The `fetch` method relies on a `Postgres.connection()` method, which is assumed to provide a valid database connection. + +--- + +### Potential Enhancements +1. **Use Prepared Statements**: + Replace the raw SQL query in the `fetch` method with a prepared statement to prevent SQL injection. + +2. **Token Expiry**: + Add an expiration time to the JWT for enhanced security. + +3. **Error Logging**: + Improve error logging to avoid exposing sensitive information while maintaining sufficient detail for debugging. + +4. **Input Validation**: + Validate the `username` input in the `fetch` method to ensure it meets expected criteria. + +--- + +### Example Usage + +#### Creating a User +```java +User user = new User("1", "john_doe", "hashed_password"); +``` + +#### Generating a Token +```java +String secret = "my_secret_key"; +String token = user.token(secret); +``` + +#### Validating a Token +```java +try { + User.assertAuth(secret, token); + System.out.println("Token is valid."); +} catch (Unauthorized e) { + System.out.println("Invalid token: " + e.getMessage()); +} +``` + +#### Fetching a User from the Database +```java +User fetchedUser = User.fetch("john_doe"); +if (fetchedUser != null) { + System.out.println("User found: " + fetchedUser.username); +} else { + System.out.println("User not found."); +} +``` diff --git a/wiki/src/main/java/com/scalesec/vulnado/VulnadoApplication.java.md b/wiki/src/main/java/com/scalesec/vulnado/VulnadoApplication.java.md new file mode 100755 index 00000000..b6712f5d --- /dev/null +++ b/wiki/src/main/java/com/scalesec/vulnado/VulnadoApplication.java.md @@ -0,0 +1,46 @@ +# Documentation: `VulnadoApplication.java` + +## Overview +The `VulnadoApplication` class serves as the entry point for a Spring Boot application. It is annotated with `@SpringBootApplication` and `@ServletComponentScan`, enabling Spring Boot's auto-configuration and scanning for servlet components. The application also includes a call to a custom `Postgres.setup()` method, which likely initializes database-related configurations. + +--- + +## Class: `VulnadoApplication` + +### Purpose +This class is the main entry point for the application. It initializes the Spring Boot framework and performs any necessary setup for the application, including database configuration. + +--- + +### Annotations +| Annotation | Description | +|-------------------------|-----------------------------------------------------------------------------| +| `@SpringBootApplication`| Combines `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan`. It enables Spring Boot's auto-configuration and component scanning. | +| `@ServletComponentScan` | Enables scanning for servlet components, such as filters and listeners, within the application. | + +--- + +### Methods + +#### `public static void main(String[] args)` +- **Purpose**: The main method starts the Spring Boot application and performs any necessary setup before the application runs. +- **Logic**: + 1. Calls `Postgres.setup()` to initialize database-related configurations. + 2. Invokes `SpringApplication.run()` to bootstrap the Spring Boot application. + +--- + +## Insights + +1. **Database Initialization**: The `Postgres.setup()` method is called before the application starts. This indicates that the application relies on a PostgreSQL database, and the setup method likely handles connection pooling, schema initialization, or other database-related configurations. + +2. **Servlet Component Scanning**: The use of `@ServletComponentScan` suggests that the application may include custom servlets, filters, or listeners. These components are automatically detected and registered by Spring Boot. + +3. **Spring Boot Framework**: The class leverages Spring Boot's auto-configuration capabilities, simplifying the setup and configuration of the application. + +4. **Modular Design**: The separation of database setup into a dedicated `Postgres.setup()` method promotes modularity and maintainability. + +--- + +## File Metadata +- **File Name**: `VulnadoApplication.java` diff --git a/wiki/src/test/java/com/scalesec/vulnado/VulnadoApplicationTests.java.md b/wiki/src/test/java/com/scalesec/vulnado/VulnadoApplicationTests.java.md new file mode 100755 index 00000000..46cd9f55 --- /dev/null +++ b/wiki/src/test/java/com/scalesec/vulnado/VulnadoApplicationTests.java.md @@ -0,0 +1,37 @@ +# Documentation: `VulnadoApplicationTests.java` + +## Overview +This file contains a test class for the `Vulnado` application. It is designed to verify the basic functionality of the Spring Boot application by ensuring that the application context loads successfully. This is a standard test in Spring Boot applications to validate the configuration and setup of the application. + +## Class: `VulnadoApplicationTests` + +### Purpose +The `VulnadoApplicationTests` class is a test suite for the `Vulnado` application. It uses the Spring Boot testing framework to ensure that the application context is correctly initialized. + +### Annotations +- **`@RunWith(SpringRunner.class)`**: Specifies that the test class should use the `SpringRunner`, which is a part of the Spring Test framework. This enables Spring-specific features in the test environment. +- **`@SpringBootTest`**: Indicates that the test should bootstrap the entire Spring application context. This is useful for integration testing. + +### Method: `contextLoads` + +#### Description +- **Purpose**: The `contextLoads` method is a simple test case that verifies whether the Spring application context loads without any issues. +- **Annotation**: + - **`@Test`**: Marks the method as a test case to be executed by the JUnit framework. +- **Logic**: The method does not contain any logic or assertions. Its success is determined by the absence of exceptions during the application context initialization. + +## Insights + +- **Test Scope**: This test is a basic "smoke test" for the application. It ensures that the Spring Boot application is correctly configured and can start without errors. +- **Frameworks Used**: + - **JUnit**: For defining and running the test case. + - **Spring Boot Test**: For bootstrapping the application context and providing Spring-specific testing utilities. +- **Best Practices**: While this test is useful for verifying the application's basic setup, additional tests should be implemented to cover specific functionalities and edge cases of the application. +- **Dependencies**: The test relies on the Spring Boot framework and its testing utilities. It assumes that the application is correctly configured with all required dependencies. + +## File Metadata + +| **Attribute** | **Value** | +|------------------|-------------------------------| +| **File Name** | `VulnadoApplicationTests.java` | +| **Package** | `com.scalesec.vulnado` |