HIGH email injectionfastapihmac signatures

Email Injection in Fastapi with Hmac Signatures

Email Injection in Fastapi with Hmac Signatures — how this specific combination creates or exposes the vulnerability

Email Injection is a class of injection flaws where untrusted data is used to manipulate email headers or the address fields in SMTP-based workflows. In Fastapi applications that rely on Hmac Signatures for request integrity, the interaction between signature validation and email handling can inadvertently expose injection paths if the signature is verified before strict input validation of email parameters.

Consider a typical pattern where a Fastapi endpoint accepts an email address and a signature, verifies the Hmac to confirm the request originated from a trusted source, and then passes the email directly to an outbound mail function. If the email field contains newline characters (e.g., %0A or %0D encoded) or other header injection sequences, and validation is not enforced prior to signing or after verification, the payload can inject additional headers such as Cc:, Bcc:, or even inject a new To: line. This can redirect emails, expose sensitive information to unintended recipients, or facilitate phishing through compromised notification channels.

When Hmac Signatures are used, developers sometimes assume that signature verification guarantees the integrity and safety of the contained data. However, if the signature covers only a subset of parameters or is computed over the raw, unvalidated email value, an attacker can supply a malicious email that passes verification but still breaks downstream email libraries. For example, an email like [email protected]%0ACc:%[email protected] may validate under Hmac if the server does not canonicalize the input before signing. Once the email is passed to libraries such as fastapi_mail or SMTP clients that parse headers line-by-line, the injected line can be interpreted as a separate header, altering routing and visibility.

In practice, this risk is amplified when the Fastapi route also incorporates OpenAPI/Swagger spec analysis and runtime findings are cross-referenced against definitions. An unvalidated email field that participates in signature generation may appear benign in the spec but can be abused at runtime due to missing constraints on format and content. Attack patterns such as CRLF injection (CVE-2021-21342 in related libraries) demonstrate how newline injection can bypass assumptions about header safety. Therefore, even with Hmac Signatures ensuring request authenticity, email parameters must be treated as untrusted input and subjected to strict allowlist validation before any cryptographic verification or downstream processing.

Hmac Signatures-Specific Remediation in Fastapi — concrete code fixes

To mitigate Email Injection in Fastapi when using Hmac Signatures, enforce strict input validation before signature verification and apply canonicalization consistently. Below is a complete, syntactically correct example that demonstrates secure handling.

from fastapi import Fastapi, Header, HTTPException, Depends
import hmac
import hashlib
import re
from typing import Optional

app = Fastapi()

SECRET_KEY = b'super-secret-key'

# Strict email regex: local-part@domain with basic RFC 5322 constraints
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$')

def verify_hmac(headers: dict) -> bool:
    signature = headers.get('x-api-signature')
    if not signature:
        return False
    # Reconstruct the payload used for signing (example: email + timestamp)
    payload = f'{headers.get("x-email", "")}:{headers.get("x-timestamp", "")}'
    expected = hmac.new(SECRET_KEY, payload.encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)

def validate_email(email: str) -> str:
    if not EMAIL_REGEX.match(email):
        raise ValueError('Invalid email format')
    # Reject CR/LF encoded forms even if URL-decoded
    if '%0a' in email.lower() or '%0d' in email.lower() or '\\r' in email or '\\n' in email:
        raise ValueError('Email contains disallowed characters')
    return email.strip()

@app.post('/notify')
async def notify_email(
    email: str,
    timestamp: str,
    signature: str = Header(None)
):
    # Step 1: Validate email before any cryptographic operations
    clean_email = validate_email(email)
    # Step 2: Verify Hmac using canonicalized values
    if not verify_hmac({'x-api-signature': signature, 'x-email': clean_email, 'x-timestamp': timestamp}):
        raise HTTPException(status_code=401, detail='Invalid signature')
    # Step 3: Safe usage: pass clean_email to mail provider
    # Example using a hypothetical mail library:
    # mail_client.send(
    #     to=clean_email,
    #     subject='Notification',
    #     body='Your request was processed'
    # )
    return {'status': 'queued', 'to': clean_email}

Key remediation points:

  • Validate email format with an allowlist regex before Hmac verification to eliminate newline and encoding attacks.
  • Canonicalize input (trim, lower-case where appropriate) and ensure the same canonical form is used during signing and verification.
  • Never include raw user input in the signed payload without normalization; include only validated, canonicalized values.
  • Treat email-related libraries as untrusted; even after Hmac verification, ensure outputs are sanitized to prevent header injection in downstream mail transports.

By combining strict input validation with consistent canonicalization, the combination of Fastapi, Hmac Signatures, and email workflows remains resilient against Email Injection while preserving the integrity guarantees provided by cryptographic signatures.

Frequently Asked Questions

Can Hmac Signatures alone prevent Email Injection in Fastapi?
No. Hmac Signatures ensure request integrity but do not sanitize or validate email content. Without explicit validation of email format and rejection of control characters, malicious payloads can bypass signature checks and trigger injection in mail libraries.
How does middleBrick handle Email Injection findings in Fastapi scans?
middleBrick scans the unauthenticated attack surface and tests email parameters for injection vectors. If Hmac Signatures are used, checks verify whether signatures cover canonicalized inputs. Findings include severity, guidance on input validation, and references to relevant standards such as OWASP API Top 10.