Jul 21, 2026·6 min read·12 visits
Unvalidated image fetches during token counting in LangChain allow attackers to perform Server-Side Request Forgery (SSRF) against internal endpoints and cloud metadata services.
Prior to version 1.2.11, the LangChain LLM framework is affected by a Server-Side Request Forgery (SSRF) vulnerability inside its image token counting mechanism. Specifically, the ChatOpenAI.get_num_tokens_from_messages() method retrieves arbitrary image_url values from user prompts without validating the destination host or IP address. Attackers can exploit this issue to scan internal infrastructure, access local services, or harvest credentials from cloud metadata services.
The vulnerability affects the langchain-openai integration package and its underlying dependency, langchain-core. To support token budgeting and pricing calculation, the ChatOpenAI.get_num_tokens_from_messages() method computes token costs for vision-enabled models like gpt-4o or gpt-4-vision-preview. This calculation process requires identifying the dimensions of user-supplied images.
When a prompt containing an image block is sent to the LLM application, the framework processes the payload and extracts the image URL. The application then automatically initiates a network request to retrieve the image. This exposure creates a significant attack surface, as the input origin is completely untrusted and controlled by the user.
Because the resolution and request functions did not enforce any destination constraints, the system is susceptible to Server-Side Request Forgery (SSRF). Attackers can submit malicious URLs pointing to restricted internal networks instead of actual images. This enables access to administrative ports and configuration resources that are otherwise shielded from direct external access.
The underlying flaw resides within the _url_to_size() utility function located inside langchain_openai. This helper is triggered whenever a message contains an image_url element with its detail field set to high or omitted entirely. Under this configuration, the token count is determined by the physical width and height of the target image.
To ascertain these dimensions, the _url_to_size() function performs an outbound HTTP transaction using the httpx Python client. In vulnerable versions, the function directly passes the user-supplied string to httpx.get() without validating the schema, domain, or resolved IP address. No application-level validation filters restrict the target domain.
Furthermore, the request was executed synchronously without a timeout configuration or resource allocation boundaries. Consequently, the application would attempt to resolve and connect to any address, including loopback interfaces, private subnets, or cloud-specific IP addresses like the Link-Local address. This absence of pre-request validation constitutes a classic CWE-918 flaw.
The primary code change occurs in the transition to version 1.2.11. The patch implements strict validation logic before the network transaction is initiated by the HTTP client.
Below is the vulnerable implementation of the _url_to_size function:
# VULNERABLE CODE PATH
def _url_to_size(image_source: str) -> tuple[int, int] | None:
# httpx.get is executed directly with no destination validation or timeout
response = httpx.get(image_source)
response.raise_for_status()
width, height = Image.open(BytesIO(response.content)).size
return width, heightThe remediated code implements the validate_safe_url utility to inspect the destination domain and resolved IP address before allowing the transaction to proceed. It also adds a default connection timeout of 5 seconds and enforces a maximum image size limit of 50 megabytes to prevent resource exhaustion:
# PATCHED CODE PATH
def _url_to_size(image_source: str) -> tuple[int, int] | None:
# ... dependency checks ...
try:
from langchain_core._security._ssrf_protection import validate_safe_url
# The image_source URL is checked against RFC 1918 and metadata endpoints
validate_safe_url(image_source, allow_private=False, allow_http=True)
except ImportError:
logger.warning("SSRF protection not available. Update langchain-core.")
except ValueError as e:
logger.warning("Image URL failed SSRF validation: %s", e)
return None
timeout = 5.0
max_size = 50 * 1024 * 1024 # 50 MB limits payload sizes
try:
# Connection includes timeout parameters
response = httpx.get(image_source, timeout=timeout)
response.raise_for_status()
# ... content length checks ...
width, height = Image.open(BytesIO(response.content)).size
return width, height
except Exception as e:
logger.warning("Failed to fetch image: %s", e)
return NoneThe validation module performs a DNS lookup via socket.getaddrinfo() and cross-references each resolved IP address with list-based blacklists. These blacklists cover private networks (RFC 1918), IPv6 loopbacks, localhost variations, and metadata services.
Exploitation is straightforward and does not require active authentication if the application exposes a prompt interface to end-users. The attacker designs a structured payload for a vision model containing a remote image URL pointing to an internal target.
To scan internal networks, an attacker can specify loopback addresses such as http://127.0.0.1:8080 or local subnets like http://10.0.0.1/. If the targeted port hosting an internal service is active, the application may return a delayed timeout response or throw a specific processing error, allowing the attacker to perform port scanning and enumerate active services.
In cloud environments (such as AWS, GCP, or Azure), the attacker can target the Instance Metadata Service (IMDS) at http://169.254.169.254/. In systems prior to the patch, accessing the metadata service could expose temporary IAM credentials, host identity configurations, or instance metadata, leading to potential privilege escalation or cloud environment compromise.
Additionally, attackers can cause denial-of-service states through resource exhaustion. By supplying slow-responding web servers or referencing massive raw data streams (e.g., zip-bombs or raw byte streams), attackers can hang application threads indefinitely or induce memory starvation during image parsing in the PIL library.
Although the patch introduced in version 1.2.11 provides significant defense, structural analysis indicates potential vectors for bypass under specific configurations. The principal challenge relates to Time-of-Check to Time-of-Use (TOCTOU) conditions inherent in decoupled DNS resolution.
During validation, validate_safe_url resolves the target hostname and inspects the IP. If validation succeeds, httpx.get(image_source) is subsequently executed, which triggers a separate, secondary DNS resolution. An attacker can exploit this behavior using DNS rebinding: configuring a DNS server with a Time-To-Live (TTL) of zero to return a benign IP during validation and a local IP during the subsequent fetch.
Another bypass vector concerns HTTP redirects. If the HTTP client's default parameters allow automatic redirection, an attacker can input a benign external domain that immediately issues a redirect header (e.g., 302 Found) pointing to http://127.0.0.1/. Since the client handles redirects internally without re-running the validation logic, this can lead to an SSRF bypass.
Furthermore, standard address parsers can occasionally fail to identify IPv4-mapped IPv6 formats (such as ::ffff:127.0.0.1) depending on the environment's network configuration and the resolution library's parsing logic. This discrepancy could allow requests to localhost addresses to bypass standard IPv4 range filters.
The security implications of CVE-2026-26013 range from low to critical depending entirely on the deployment environment and network architecture. In containerized environments, the impact is often restricted to local network scanning and denial of service.
In standard cloud hosting architectures (AWS EC2, GCP Compute Engine, Azure Virtual Machines) implementing IMDSv1, the risk is severe. Unauthenticated access to the metadata endpoint allows immediate exfiltration of IAM role credentials, which can compromise the cloud account's control plane.
Furthermore, the lack of network isolation in many microservice architectures means an attacker can access adjacent REST APIs, database management endpoints, or orchestration interfaces. The low CVSS score of 3.7 reflects high attack complexity and no direct read/write impact on the host system itself, but the downstream risk to connected infrastructure remains substantial.
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L| Product | Affected Versions | Fixed Version |
|---|---|---|
langchain-core LangChain | < 1.2.11 | 1.2.11 |
langchain-openai LangChain | < 1.2.11 | 1.2.11 |
| Attribute | Detail |
|---|---|
| CWE ID | CWE-918 |
| Attack Vector | Network |
| CVSS Severity Score | 3.7 (Low) |
| EPSS Score | 0.00379 (Percentile: 30.21%) |
| Exploit Status | PoC (Proof of Concept) available |
| CISA KEV Status | Not Listed |
| Ransomware Use | No |
The web server receives a URL or similar vector from an upstream application and does not validate it or restrict the request destination before performing a query to fetch resources.
CVE-2026-12243 is a path traversal vulnerability in the Natural Language Toolkit (NLTK) version 3.9.4. The flaw exists because the input validation routine fails to account for percent-encoded directory traversal sequences like '..%2f' before passing them to urllib.request.url2pathname(), which decodes them into active traversal sequences.
CVE-2026-73654 is a high-severity prototype pollution vulnerability in Trigger.dev. The flaw occurs during the handling of run-metadata updates through the PUT /api/v1/runs/:runId/metadata endpoint. Because user-supplied keys are parsed directly by the @jsonhero/path library without sanitization, an authenticated attacker with low privileges can pollute the global Object.prototype. This causes database queries via Prisma ORM to fail validation and induces unhandled exceptions in the Prometheus metrics client, resulting in a process-wide denial of service.
CVE-2026-73559 is an uncontrolled resource consumption vulnerability in the vLLM engine, specifically within the /v1/completions API endpoint, allowing authenticated attackers to cause application-level denial of service via unbounded prompt arrays.
A critical security bypass vulnerability in Argo Workflows allows authenticated attackers with workflow submission privileges to bypass 'Strict' or 'Secure' template referencing restrictions. By injecting unvalidated fields into the nested ArtifactGC configuration, attackers can execute arbitrary pod patches, leading to host namespace escape and cluster-wide privilege escalation.
A Server-Side Request Forgery (SSRF) / Confused Deputy vulnerability has been identified in Pydantic AI UI Adapters (such as VercelAIAdapter). Under certain conditions, a malicious client can supply manipulated message history with provider metadata that forces the server to resolve files within privileged cloud environments (AWS S3, Google Cloud Storage) or model providers. This occurs because the adapters deserialize client-provided metadata structures directly into UploadedFile instances without validation, which are subsequently fetched using high-privilege server credentials.
A path traversal vulnerability in the optional dashboard server of atomic-agents-stack before version 1.1.0 allows unauthenticated remote attackers to read arbitrary files from the host filesystem.