> ## Documentation Index
> Fetch the complete documentation index at: https://docs.openhands.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Vulnerability Remediation

> Using OpenHands to identify and fix security vulnerabilities in your codebase

<Card title="View Example Plugin" icon="github" href="https://github.com/OpenHands/extensions/tree/main/plugins/vulnerability-remediation">
  Check out the complete vulnerability remediation plugin with ready-to-use code and configuration.
</Card>

Security vulnerabilities are a constant challenge for software teams. Every day, new security issues are discovered—from vulnerabilities in dependencies to code security flaws detected by static analysis tools. The National Vulnerability Database (NVD) reports thousands of new vulnerabilities annually, and organizations struggle to keep up with this constant influx.

## The Challenge

The traditional approach to vulnerability remediation is manual and time-consuming:

1. Scan repositories for vulnerabilities
2. Review each vulnerability and its impact
3. Research the fix (usually a version upgrade)
4. Update dependency files
5. Test the changes
6. Create pull requests
7. Get reviews and merge

This process can take hours per vulnerability, and with hundreds or thousands of vulnerabilities across multiple repositories, it becomes an overwhelming task. Security debt accumulates faster than teams can address it.

**What if we could automate this entire process using AI agents?**

## Automated Vulnerability Remediation with OpenHands

The [OpenHands Software Agents SDK](https://docs.openhands.dev/sdk) provides powerful capabilities for building autonomous AI agents capable of interacting with codebases. These agents can tackle one of the most tedious tasks in software maintenance: **security vulnerability remediation**.

OpenHands assists with vulnerability remediation by:

* **Identifying vulnerabilities**: Analyzing code for common security issues
* **Understanding impact**: Explaining the risk and exploitation potential
* **Implementing fixes**: Generating secure code to address vulnerabilities
* **Validating remediation**: Verifying fixes are effective and complete

## Two Approaches to Vulnerability Fixing

### 1. Point to a GitHub Repository

Build a workflow where users can point to a GitHub repository, scan it for vulnerabilities, and have OpenHands AI agents automatically create pull requests with fixes—all with minimal human intervention.

### 2. Upload Security Scanner Reports

Enable users to upload reports from security scanners such as Snyk (as well as other third-party security scanners) where OpenHands agents automatically detect the report format, identify the issues, and apply fixes.

This solution goes beyond automation—it focuses on making security remediation accessible, fast, and scalable.

## Architecture Overview

A vulnerability remediation agent can be built as a web application that orchestrates agents using the [OpenHands Software Agents SDK](https://docs.openhands.dev/sdk) and [OpenHands Cloud](https://docs.openhands.dev/openhands/usage/key-features) to perform security scans and automate remediation fixes.

The key architectural components include:

* **Frontend**: Communicates directly with the OpenHands Agent Server through the [TypeScript Client](https://github.com/OpenHands/typescript-client)
* **WebSocket interface**: Enables real-time status updates on agent actions and operations
* **LLM flexibility**: OpenHands supports multiple LLMs, minimizing dependency on any single provider
* **Scalable execution**: The Agent Server can be hosted locally, with self-hosted models, or integrated with OpenHands Cloud

This architecture allows the frontend to remain lightweight while heavy lifting happens in the agent's execution environment.

## Example: Vulnerability Fixer Application

An example implementation is available at [github.com/OpenHands/vulnerability-fixer](https://github.com/OpenHands/vulnerability-fixer). This React web application demonstrates the full workflow:

1. User points to a repository or uploads a security scan report
2. Agent analyzes the vulnerabilities
3. Agent creates fixes and pull requests automatically
4. User reviews and merges the changes

## Security Scanning Integration

Use OpenHands to analyze security scanner output:

```
We ran a security scan and found these issues. Analyze each one:

1. SQL Injection in src/api/users.py:45
2. XSS in src/templates/profile.html:23
3. Hardcoded credential in src/config/database.py:12
4. Path traversal in src/handlers/files.py:67

For each vulnerability:
- Explain what the vulnerability is
- Show how it could be exploited
- Rate the severity (Critical/High/Medium/Low)
- Suggest a fix
```

## Common Vulnerability Patterns

OpenHands can detect these common vulnerability patterns:

| Vulnerability     | Pattern                         | Example                                             |
| ----------------- | ------------------------------- | --------------------------------------------------- |
| SQL Injection     | String concatenation in queries | `query = "SELECT * FROM users WHERE id=" + user_id` |
| XSS               | Unescaped user input in HTML    | `<div>${user_comment}</div>`                        |
| Path Traversal    | Unvalidated file paths          | `open(user_supplied_path)`                          |
| Command Injection | Shell commands with user input  | `os.system("ping " + hostname)`                     |
| Hardcoded Secrets | Credentials in source code      | `password = "admin123"`                             |

## Automated Remediation

### Applying Security Patches

Fix identified vulnerabilities:

<Tabs>
  <Tab title="SQL Injection">
    ```
    Fix the SQL injection vulnerability in src/api/users.py:

    Current code:
    query = f"SELECT * FROM users WHERE id = {user_id}"
    cursor.execute(query)

    Requirements:
    1. Use parameterized queries
    2. Add input validation
    3. Maintain the same functionality
    4. Add a test case for the fix
    ```

    **Fixed code:**

    ```python theme={null}
    # Using parameterized query
    query = "SELECT * FROM users WHERE id = %s"
    cursor.execute(query, (user_id,))
    ```
  </Tab>

  <Tab title="XSS">
    ```
    Fix the XSS vulnerability in src/templates/profile.html:

    Current code:
    <div class="bio">${user.bio}</div>

    Requirements:
    1. Properly escape user content
    2. Consider Content Security Policy
    3. Handle rich text if needed
    4. Test with malicious input
    ```

    **Fixed code:**

    ```html theme={null}
    <!-- Using auto-escaping template engine -->
    <div class="bio">{{ user.bio | escape }}</div>
    ```
  </Tab>

  <Tab title="Command Injection">
    ```
    Fix the command injection in src/utils/network.py:

    Current code:
    def ping_host(hostname):
        os.system(f"ping -c 1 {hostname}")

    Requirements:
    1. Use safe subprocess calls
    2. Validate input format
    3. Avoid shell=True
    4. Handle errors properly
    ```

    **Fixed code:**

    ```python theme={null}
    import subprocess
    import re

    def ping_host(hostname):
        # Validate hostname format
        if not re.match(r'^[a-zA-Z0-9.-]+$', hostname):
            raise ValueError("Invalid hostname")
        
        # Use subprocess without shell
        result = subprocess.run(
            ["ping", "-c", "1", hostname],
            capture_output=True,
            text=True
        )
        return result.returncode == 0
    ```
  </Tab>
</Tabs>

### Code-Level Vulnerability Fixes

Fix application-level security issues:

```
Fix the broken access control in our API:

Issue: Users can access other users' data by changing the ID in the URL.

Current code:
@app.get("/api/users/{user_id}/documents")
def get_documents(user_id: int):
    return db.get_documents(user_id)

Requirements:
1. Add authorization check
2. Verify requesting user matches or is admin
3. Return 403 for unauthorized access
4. Log access attempts
5. Add tests for authorization
```

**Fixed code:**

```python theme={null}
@app.get("/api/users/{user_id}/documents")
def get_documents(user_id: int, current_user: User = Depends(get_current_user)):
    # Check authorization
    if current_user.id != user_id and not current_user.is_admin:
        logger.warning(f"Unauthorized access attempt: user {current_user.id} tried to access user {user_id}'s documents")
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return db.get_documents(user_id)
```

## Security Testing

Test your fixes thoroughly:

```
Create security tests for the SQL injection fix:

1. Test with normal input
2. Test with SQL injection payloads:
   - ' OR '1'='1
   - '; DROP TABLE users; --
   - UNION SELECT * FROM passwords
3. Test with special characters
4. Test with null/empty input
5. Verify error handling doesn't leak information
```

## Automated Remediation Pipeline

Create an end-to-end automated pipeline:

```
Create an automated vulnerability remediation pipeline:

1. Parse Snyk/Dependabot/CodeQL alerts
2. Categorize by severity and type
3. For each vulnerability:
   - Create a branch
   - Apply the fix
   - Run tests
   - Create a PR with:
     - Description of vulnerability
     - Fix applied
     - Test results
4. Request review from security team
5. Auto-merge low-risk fixes after tests pass
```

## Building Your Own Vulnerability Fixer

The example application demonstrates that AI agents can effectively automate security maintenance at scale. Tasks that required hours of manual effort per vulnerability can now be completed in minutes with minimal human intervention.

To build your own vulnerability remediation agent:

1. Use the [OpenHands Software Agent SDK](https://github.com/OpenHands/software-agent-sdk) to create your agent
2. Integrate with your security scanning tools (Snyk, Dependabot, CodeQL, etc.)
3. Configure the agent to create pull requests automatically
4. Set up human review workflows for critical fixes

As agent capabilities continue to evolve, an increasing number of repetitive and time-consuming security tasks can be automated, enabling developers to focus on higher-level design, innovation, and problem-solving rather than routine maintenance.

## Automate This

You can run vulnerability scans on a schedule using [OpenHands Automations](/openhands/usage/automations/overview).
Copy this prompt into a new conversation to set one up:

```
Create an automation called "Security Scan" that runs daily at 3 AM.

It should run a security audit:
1. Check for known vulnerabilities in dependencies
2. Scan for hardcoded secrets or API keys
3. Look for common security misconfigurations

Create a detailed report and alert #security if any high or critical issues are found.

Learn more at https://docs.openhands.dev/openhands/usage/use-cases/vulnerability-remediation
```

You can also use the [vulnerability-remediation plugin](https://github.com/OpenHands/extensions/tree/main/plugins/vulnerability-remediation)
for automated fix PRs alongside the scan.

## Related Resources

* [Vulnerability Fixer Example](https://github.com/OpenHands/vulnerability-fixer) - Full implementation example
* [OpenHands SDK Documentation](https://docs.openhands.dev/sdk) - Build custom AI agents
* [Dependency Upgrades](/openhands/usage/use-cases/dependency-upgrades) - Updating vulnerable dependencies
* [Prompting Best Practices](/openhands/usage/tips/prompting-best-practices) - Write effective prompts
