*/ private const IPV4_BLOCKED_RANGES = array( array( '0.0.0.0', 8 ), array( '10.0.0.0', 8 ), array( '100.64.0.0', 10 ), array( '127.0.0.0', 8 ), array( '169.254.0.0', 16 ), array( '172.16.0.0', 12 ), array( '192.0.0.0', 24 ), array( '192.0.2.0', 24 ), array( '192.88.99.0', 24 ), array( '192.168.0.0', 16 ), array( '198.18.0.0', 15 ), array( '198.51.100.0', 24 ), array( '203.0.113.0', 24 ), array( '224.0.0.0', 4 ), array( '240.0.0.0', 4 ), ); /** * IPv6 ranges that are never a public, fetchable address. * * Checked after unwrapping an IPv4-mapped/NAT64/compatible address to its * embedded IPv4 form (see {@see extractEmbeddedIpv4()}). Covers: * unspecified, loopback, the discard-only prefix, Teredo, documentation, * 6to4, unique-local (which also covers the fd00:ec2::254 metadata * convention some clouds use), link-local and multicast. * * @var array */ private const IPV6_BLOCKED_RANGES = array( array( '::', 128 ), array( '::1', 128 ), array( '100::', 64 ), array( '2001::', 32 ), array( '2001:db8::', 32 ), array( '2002::', 16 ), array( 'fc00::', 7 ), array( 'fe80::', 10 ), array( 'ff00::', 8 ), ); /** * Injectable DNS resolver: fn( string $host ): string[] (A + AAAA addresses). * * @var callable|null */ private $resolver; /** * Constructor. * * @param callable|null $resolver Resolver override for tests; defaults to * a real gethostbynamel()/dns_get_record() lookup. */ public function __construct( ?callable $resolver = null ) { $this->resolver = $resolver; } /** * Validate a candidate URL against every SSRF-relevant rule. * * Performs no network fetch; only DNS resolution (via the injected or * default resolver) and pure classification. * * @param string $url Candidate URL (original, or a redirect target). * @param string[] $allowedHosts Optional host allowlist; empty = any public host. * @param bool $httpsOnly When true, an `http` URL is refused (`https_required`) * instead of being classified normally; a caller * re-runs this on every redirect hop, so the check * applies to the original URL and to every hop alike. * @return array{ok:bool,code:string,message:string,host:string,port:int,scheme:string,ips:string[],normalizedUrl:string} */ public function validate( string $url, array $allowedHosts = array(), bool $httpsOnly = false ): array { $base = array( 'ok' => false, 'code' => '', 'message' => '', 'host' => '', 'port' => 0, 'scheme' => '', 'ips' => array(), 'normalizedUrl' => '', ); $url = trim( $url ); if ( '' === $url || strlen( $url ) > self::MAX_URL_LENGTH ) { return array_merge( $base, array( 'code' => 'invalid_url', 'message' => __( 'The URL is empty or too long.', 'ai-product-tools' ), ) ); } $parts = parse_url( $url ); if ( ! is_array( $parts ) || empty( $parts['host'] ) ) { return array_merge( $base, array( 'code' => 'invalid_url', 'message' => __( 'The URL could not be parsed.', 'ai-product-tools' ), ) ); } $scheme = isset( $parts['scheme'] ) ? strtolower( (string) $parts['scheme'] ) : ''; if ( ! in_array( $scheme, array( 'http', 'https' ), true ) ) { return array_merge( $base, array( 'code' => 'invalid_scheme', 'message' => __( 'Only http and https URLs are allowed.', 'ai-product-tools' ), ) ); } if ( $httpsOnly && 'https' !== $scheme ) { return array_merge( $base, array( 'code' => 'https_required', 'message' => __( 'Only https URLs are allowed for this request.', 'ai-product-tools' ), 'scheme' => $scheme, ) ); } if ( isset( $parts['user'] ) || isset( $parts['pass'] ) ) { return array_merge( $base, array( 'code' => 'userinfo_not_allowed', 'message' => __( 'URLs with embedded credentials are not allowed.', 'ai-product-tools' ), 'scheme' => $scheme, ) ); } $host = $this->normalizeHost( (string) $parts['host'] ); if ( '' === $host ) { return array_merge( $base, array( 'code' => 'invalid_url', 'message' => __( 'The URL host is invalid.', 'ai-product-tools' ), 'scheme' => $scheme, ) ); } $port = isset( $parts['port'] ) ? (int) $parts['port'] : ( 'https' === $scheme ? 443 : 80 ); if ( ! in_array( $port, self::ALLOWED_PORTS, true ) ) { return array_merge( $base, array( 'code' => 'invalid_port', 'message' => __( 'Only ports 80 and 443 are allowed.', 'ai-product-tools' ), 'host' => $host, 'scheme' => $scheme, ) ); } if ( ! empty( $allowedHosts ) && ! $this->hostAllowed( $host, $allowedHosts ) ) { return array_merge( $base, array( 'code' => 'host_not_allowed', 'message' => __( 'This host is not in the allowed list for this source.', 'ai-product-tools' ), 'host' => $host, 'port' => $port, 'scheme' => $scheme, ) ); } $ips = $this->resolveIps( $host ); if ( empty( $ips ) ) { return array_merge( $base, array( 'code' => 'dns_resolution_failed', 'message' => __( 'The host name could not be resolved.', 'ai-product-tools' ), 'host' => $host, 'port' => $port, 'scheme' => $scheme, ) ); } foreach ( $ips as $ip ) { if ( ! self::isPublicIp( $ip ) ) { return array_merge( $base, array( 'code' => 'private_ip', 'message' => __( 'This address points to a private or restricted network and cannot be read.', 'ai-product-tools' ), 'host' => $host, 'port' => $port, 'scheme' => $scheme, 'ips' => $ips, ) ); } } return array( 'ok' => true, 'code' => '', 'message' => '', 'host' => $host, 'port' => $port, 'scheme' => $scheme, 'ips' => $ips, 'normalizedUrl' => $this->buildNormalizedUrl( $scheme, $host, $port, $parts ), ); } /** * Whether a single IP address is a public, routable address. * * Fails closed: anything that is not a syntactically valid IPv4/IPv6 * address, or that cannot be classified because `inet_pton()` is * unavailable, is treated as NOT public. * * @param string $ip IP address (no brackets, no zone id). * @return bool */ public static function isPublicIp( string $ip ): bool { $ip = trim( $ip ); if ( '' === $ip || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } if ( ! function_exists( 'inet_pton' ) ) { return false; } $packed = @inet_pton( $ip ); if ( false === $packed ) { return false; } if ( 4 === strlen( $packed ) ) { return self::isPublicIpv4( $packed ); } if ( 16 === strlen( $packed ) ) { return self::isPublicIpv6( $packed ); } return false; } /** * Classify a packed (4-byte) IPv4 address. * * @param string $packed4 Packed binary IPv4 address. * @return bool */ private static function isPublicIpv4( string $packed4 ): bool { $octets = array_values( unpack( 'C4', $packed4 ) ); $int = ( $octets[0] << 24 ) | ( $octets[1] << 16 ) | ( $octets[2] << 8 ) | $octets[3]; foreach ( self::IPV4_BLOCKED_RANGES as $range ) { list( $network, $prefix ) = $range; $mask = 0 === $prefix ? 0 : ( 0xFFFFFFFF << ( 32 - $prefix ) ) & 0xFFFFFFFF; $networkInt = self::ipv4StringToInt( $network ); if ( ( $int & $mask ) === ( $networkInt & $mask ) ) { return false; } } return true; } /** * Classify a packed (16-byte) IPv6 address. * * @param string $packed16 Packed binary IPv6 address. * @return bool */ private static function isPublicIpv6( string $packed16 ): bool { $embeddedIpv4 = self::extractEmbeddedIpv4( $packed16 ); if ( null !== $embeddedIpv4 ) { return self::isPublicIpv4( $embeddedIpv4 ); } foreach ( self::IPV6_BLOCKED_RANGES as $range ) { list( $network, $prefix ) = $range; if ( self::ipv6InCidr( $packed16, $network, $prefix ) ) { return false; } } return true; } /** * Extract the embedded IPv4 address from an IPv4-mapped (::ffff:0:0/96), * NAT64 (64:ff9b::/96) or deprecated IPv4-compatible (::/96) IPv6 address. * * @param string $packed16 Packed binary IPv6 address. * @return string|null Packed 4-byte IPv4 address, or null when not one of these forms. */ private static function extractEmbeddedIpv4( string $packed16 ): ?string { $prefix = substr( $packed16, 0, 12 ); if ( "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff" === $prefix ) { return substr( $packed16, 12, 4 ); } if ( "\x00\x64\xff\x9b\x00\x00\x00\x00\x00\x00\x00\x00" === $prefix ) { return substr( $packed16, 12, 4 ); } if ( "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" === $prefix ) { return substr( $packed16, 12, 4 ); } return null; } /** * Whether a packed IPv6 address falls within a CIDR range. * * @param string $packed Packed binary IPv6 address being tested. * @param string $networkIp Network address of the range, e.g. 'fc00::'. * @param int $prefixBits Prefix length in bits (0-128). * @return bool */ private static function ipv6InCidr( string $packed, string $networkIp, int $prefixBits ): bool { $network = @inet_pton( $networkIp ); if ( false === $network || 16 !== strlen( $network ) ) { return false; } $fullBytes = intdiv( $prefixBits, 8 ); $remBits = $prefixBits % 8; if ( $fullBytes > 0 && substr( $packed, 0, $fullBytes ) !== substr( $network, 0, $fullBytes ) ) { return false; } if ( 0 === $remBits ) { return true; } $mask = ( 0xFF << ( 8 - $remBits ) ) & 0xFF; return ( ord( $packed[ $fullBytes ] ) & $mask ) === ( ord( $network[ $fullBytes ] ) & $mask ); } /** * Convert a dotted IPv4 string literal (one of our own constants) to an int. * * @param string $ip Dotted IPv4 string. * @return int */ private static function ipv4StringToInt( string $ip ): int { $bytes = array_map( 'intval', explode( '.', $ip ) ); return ( $bytes[0] << 24 ) | ( $bytes[1] << 16 ) | ( $bytes[2] << 8 ) | $bytes[3]; } /** * Resolve a host to its A + AAAA addresses, or treat it as a literal IP. * * @param string $host Host name or literal IP (brackets already stripped). * @return string[] */ private function resolveIps( string $host ): array { if ( filter_var( $host, FILTER_VALIDATE_IP ) ) { return array( $host ); } if ( null !== $this->resolver ) { $ips = call_user_func( $this->resolver, $host ); return is_array( $ips ) ? array_values( array_filter( array_map( 'strval', $ips ) ) ) : array(); } return $this->defaultResolve( $host ); } /** * Real DNS resolution (A + AAAA), used only when no resolver was injected. * * A minimal stub resolver over UDP, bounded by {@see DNS_QUERY_TIMEOUT} * per query, is used whenever the system's own resolver configuration * can be read. Querying the system's own configured resolver (not the * target host's authoritative server directly) keeps this a normal * recursive lookup, identical in effect to {@see legacyResolve()}'s * gethostbynamel()/dns_get_record() calls, but bounded instead of * inheriting the OS resolver's own retry policy (which can block a PHP * worker for 30+ seconds against an unresponsive or black-holed * nameserver). * * @param string $host Host name. * @return string[] */ private function defaultResolve( string $host ): array { $hosts_file_ips = self::hostsFileAddresses( $host ); if ( ! empty( $hosts_file_ips ) ) { return $hosts_file_ips; } return $this->resolveViaConfiguredNameserver( $host, self::systemNameserver() ); } /** * Run the bounded stub resolver against $nameserver, or fall back to * {@see legacyResolve()} when no nameserver configuration could be * determined at all (the configuration file is unreadable — e.g. an * open_basedir restriction that excludes it — or holds no `nameserver` * line). * * Split out from {@see defaultResolve()} as its own method so the * fallback branch can be exercised directly with an explicit null, * since nothing in a test can make `/etc/resolv.conf` unreadable on * demand to reach it through defaultResolve() itself. * * @param string $host Host name. * @param string|null $nameserver Resolver IP from {@see systemNameserver()}, or null when none could be read. * @return string[] */ private function resolveViaConfiguredNameserver( string $host, ?string $nameserver ): array { if ( null === $nameserver ) { return self::legacyResolve( $host ); } $ips = array_merge( $this->queryDns( $nameserver, $host, self::DNS_TYPE_A ), $this->queryDns( $nameserver, $host, self::DNS_TYPE_AAAA ) ); return array_values( array_unique( $ips ) ); } /** * The original, unbounded resolver calls, kept only as the fallback * {@see resolveViaConfiguredNameserver()} uses when the system resolver * configuration cannot be read at all (open_basedir-restricted hosting, * or a PHP build with no `/etc/resolv.conf`, such as native Windows): a * host still resolves on such an environment, without the bounded * timeout above, rather than every lookup failing outright. * * @param string $host Host name. * @return string[] */ private static function legacyResolve( string $host ): array { $ips = array(); $v4 = @gethostbynamel( $host ); if ( is_array( $v4 ) ) { $ips = array_merge( $ips, $v4 ); } if ( function_exists( 'dns_get_record' ) ) { $records = @dns_get_record( $host, DNS_AAAA ); if ( is_array( $records ) ) { foreach ( $records as $record ) { if ( isset( $record['ipv6'] ) ) { $ips[] = (string) $record['ipv6']; } } } } return array_values( array_unique( $ips ) ); } /** * Every address this host maps to in `/etc/hosts` — the "files" step * the OS resolver itself consults before DNS (`/etc/nsswitch.conf`'s * usual `hosts: files dns`), checked first here for the same reason: * a loopback alias like "localhost", or an admin's own hosts-file * override, resolves without ever reaching the network, and a * short-timeout DNS query for it would otherwise just fail (most real * nameservers hold no record for a purely local name). * * @param string $host Host name (already lowercased). * @return string[] */ private static function hostsFileAddresses( string $host ): array { $contents = is_readable( '/etc/hosts' ) ? file_get_contents( '/etc/hosts' ) : false; if ( ! is_string( $contents ) ) { return array(); } $ips = array(); foreach ( preg_split( '/\r\n|\r|\n/', $contents ) as $line ) { $line = trim( (string) preg_replace( '/#.*/', '', $line ) ); if ( '' === $line ) { continue; } $fields = preg_split( '/\s+/', $line ); if ( ! is_array( $fields ) || count( $fields ) < 2 ) { continue; } $address = (string) array_shift( $fields ); $hostnames = array_map( 'strtolower', $fields ); if ( filter_var( $address, FILTER_VALIDATE_IP ) && in_array( $host, $hostnames, true ) ) { $ips[] = $address; } } return array_values( array_unique( $ips ) ); } /** * The first nameserver address from `/etc/resolv.conf`, the standard * Linux/Unix resolver config virtually every real WordPress host runs * (the OS calls this same file resolves through). No readable file, or * none found in it, means no bounded query can be addressed to * anything; {@see resolveViaConfiguredNameserver()} then falls back to * {@see legacyResolve()}'s unbounded lookup instead. * * @return string|null */ private static function systemNameserver(): ?string { $contents = is_readable( '/etc/resolv.conf' ) ? file_get_contents( '/etc/resolv.conf' ) : false; if ( ! is_string( $contents ) ) { return null; } foreach ( preg_split( '/\r\n|\r|\n/', $contents ) as $line ) { if ( preg_match( '/^\s*nameserver\s+([0-9a-fA-F.:]+)/', $line, $match ) ) { return $match[1]; } } return null; } /** * One bounded A or AAAA query against $nameserver. * * @param string $nameserver Resolver IP (v4 or v6). * @param string $host Host name to resolve. * @param int $qtype self::DNS_TYPE_A or self::DNS_TYPE_AAAA. * @return string[] */ private function queryDns( string $nameserver, string $host, int $qtype ): array { $query = self::buildDnsQuery( $host, $qtype ); if ( null === $query ) { return array(); } $response = $this->sendDnsQuery( $nameserver, $query ); return null !== $response ? self::parseDnsAnswers( $response, $query, $qtype ) : array(); } /** * Build a minimal, single-question DNS query packet (header + QNAME + * QTYPE + QCLASS=IN), recursion desired. * * @param string $host Host name (a trailing "." FQDN dot is dropped first). * @param int $qtype self::DNS_TYPE_A or self::DNS_TYPE_AAAA. * @return string|null Null when a label is empty or over 63 bytes. */ private static function buildDnsQuery( string $host, int $qtype ): ?string { $qname = ''; foreach ( explode( '.', rtrim( $host, '.' ) ) as $label ) { $length = strlen( $label ); if ( $length < 1 || $length > 63 ) { return null; } $qname .= chr( $length ) . $label; } $qname .= "\x00"; $header = pack( 'n6', random_int( 0, 0xFFFF ), 0x0100, 1, 0, 0, 0 ); return $header . $qname . pack( 'n2', $qtype, 1 ); } /** * Send one query over UDP and read its response, bounded by * {@see DNS_QUERY_TIMEOUT}. * * @param string $nameserver Resolver IP (v4 or v6). * @param string $query Encoded query packet. * @return string|null Raw response bytes, or null on any failure or timeout. */ private function sendDnsQuery( string $nameserver, string $query ): ?string { $address = false !== strpos( $nameserver, ':' ) ? '[' . $nameserver . ']' : $nameserver; $socket = @stream_socket_client( 'udp://' . $address . ':53', $errno, $errstr, self::DNS_QUERY_TIMEOUT ); if ( false === $socket ) { return null; } stream_set_timeout( $socket, self::DNS_QUERY_TIMEOUT ); fwrite( $socket, $query ); $response = fread( $socket, self::DNS_MAX_RESPONSE_BYTES ); $timed_out = stream_get_meta_data( $socket )['timed_out'] ?? false; fclose( $socket ); return ( is_string( $response ) && '' !== $response && ! $timed_out ) ? $response : null; } /** * Parse a DNS response's answer section for addresses of the asked type. * * Verifies only the transaction id matches $query (a connected UDP * socket already filters by source address/port); everything else is * walked structurally, each read bounded against the response's actual * length, so a short, truncated or malformed reply yields whatever * answers were readable before it ran out rather than an error. * * @param string $response Raw response bytes. * @param string $query The query this is expected to answer (for the id check). * @param int $qtype self::DNS_TYPE_A or self::DNS_TYPE_AAAA. * @return string[] */ private static function parseDnsAnswers( string $response, string $query, int $qtype ): array { if ( strlen( $response ) < 12 || substr( $response, 0, 2 ) !== substr( $query, 0, 2 ) ) { return array(); } $counts = unpack( 'nqd/nan', substr( $response, 4, 4 ) ); if ( ! is_array( $counts ) ) { return array(); } $offset = 12; for ( $i = 0; $i < $counts['qd']; $i++ ) { $offset = self::skipDnsName( $response, $offset ); if ( null === $offset ) { return array(); } $offset += 4; } $ips = array(); for ( $i = 0; $i < $counts['an']; $i++ ) { $offset = self::skipDnsName( $response, $offset ); if ( null === $offset || $offset + 10 > strlen( $response ) ) { return $ips; } $record = unpack( 'ntype/nclass/Nttl/nrdlength', substr( $response, $offset, 10 ) ); $offset += 10; if ( ! is_array( $record ) || $offset + $record['rdlength'] > strlen( $response ) ) { return $ips; } $rdata = substr( $response, $offset, $record['rdlength'] ); $offset += $record['rdlength']; if ( $qtype === $record['type'] && 1 === $record['class'] ) { $ip = self::formatAddress( $rdata, $qtype ); if ( null !== $ip ) { $ips[] = $ip; } } } return $ips; } /** * Advance past one DNS NAME field (a label sequence ending in a zero * byte, or a 2-byte compression pointer) without following a pointer's * target — this only needs to know how many bytes the field occupies at * $offset, never what it names. Bounded by the response length and a * hard hop cap, so a truncated or malicious (self-referential) name * cannot loop or read out of bounds. * * @param string $response Raw response bytes. * @param int $offset Start of the NAME field. * @return int|null Offset of the first byte after the field, or null when it runs past the response. */ private static function skipDnsName( string $response, int $offset ): ?int { $length = strlen( $response ); for ( $hops = 0; $offset < $length && $hops < 128; $hops++ ) { $byte = ord( $response[ $offset ] ); if ( 0 === $byte ) { return $offset + 1; } if ( 0xC0 === ( $byte & 0xC0 ) ) { return $offset + 2; } $offset += 1 + $byte; } return null; } /** * @param string $rdata A record's raw RDATA. * @param int $qtype self::DNS_TYPE_A or self::DNS_TYPE_AAAA. * @return string|null */ private static function formatAddress( string $rdata, int $qtype ): ?string { $expected = self::DNS_TYPE_A === $qtype ? 4 : 16; if ( strlen( $rdata ) !== $expected ) { return null; } $address = inet_ntop( $rdata ); return false !== $address ? $address : null; } /** * Strip IPv6 brackets and apply IDN-to-ASCII conversion when available. * * @param string $host Raw host component from parse_url(). * @return string Normalized, lowercase host, or '' when invalid. */ private function normalizeHost( string $host ): string { $host = trim( $host ); if ( strlen( $host ) > 1 && '[' === $host[0] && ']' === substr( $host, -1 ) ) { $host = substr( $host, 1, -1 ); } if ( '' === $host ) { return ''; } if ( filter_var( $host, FILTER_VALIDATE_IP ) ) { return strtolower( $host ); } if ( function_exists( 'idn_to_ascii' ) ) { $ascii = defined( 'INTL_IDNA_VARIANT_UTS46' ) ? @idn_to_ascii( $host, 0, INTL_IDNA_VARIANT_UTS46 ) : @idn_to_ascii( $host ); if ( is_string( $ascii ) && '' !== $ascii ) { $host = $ascii; } } elseif ( class_exists( '\WpOrg\Requests\IdnaEncoder' ) ) { try { $host = \WpOrg\Requests\IdnaEncoder::encode( function_exists( 'mb_strtolower' ) ? mb_strtolower( $host, 'UTF-8' ) : strtolower( $host ) ); } catch ( \Exception $e ) { unset( $e ); } } return strtolower( $host ); } /** * Whether a host matches one of an explicit allowlist (case-insensitive, exact). * * Each allowlist entry is normalized through the same * {@see normalizeHost()} as the URL's own host (IDN-to-ASCII, then * lowercase), so a domain typed in Unicode and its punycode form compare * equal regardless of which form either side happens to be in. * * @param string $host Normalized host. * @param string[] $allowedHosts Allowlist entries. * @return bool */ private function hostAllowed( string $host, array $allowedHosts ): bool { foreach ( $allowedHosts as $allowed ) { if ( $host === $this->normalizeHost( (string) $allowed ) ) { return true; } } return false; } /** * Rebuild a safe, canonical URL from its validated components. * * Drops any fragment (irrelevant to a server-side fetch) and userinfo * (already rejected above). * * @param string $scheme 'http' | 'https'. * @param string $host Normalized host. * @param int $port Resolved effective port. * @param array $parts Original parse_url() components (for path/query). * @return string */ private function buildNormalizedUrl( string $scheme, string $host, int $port, array $parts ): string { $hostPart = ( false !== strpos( $host, ':' ) ) ? '[' . $host . ']' : $host; $defaultPort = ( 'https' === $scheme ) ? 443 : 80; $portPart = ( $port === $defaultPort ) ? '' : ':' . $port; $path = isset( $parts['path'] ) && '' !== $parts['path'] ? (string) $parts['path'] : '/'; $query = isset( $parts['query'] ) ? '?' . $parts['query'] : ''; return $scheme . '://' . $hostPart . $portPart . $path . $query; } }