store = $store; $this->clock = $clock ?? static function (): int { return time(); }; } /** * Makes the connection key for one backup. Replaces any key that is already out there: there is only * ever one. * * @param array{file:string,size:int,mtime:int,chunk_size:int} $backup * @param bool $pin Also hold the destination to the address that makes the handshake. Off by default: the signature already proves the key is held, and many connections change address between requests. * @return array{key:string,id:string,expires:int} * @throws \RuntimeException When the site is not reachable over HTTPS. */ public function create( string $site_url, array $backup, int $user_id, bool $pin = false ): array { $reason = Transport::insecureReason( $site_url ); if ( null !== $reason ) { throw new \RuntimeException( esc_html( $reason ) ); } $now = $this->now(); $id = bin2hex( random_bytes( 16 ) ); $secret = bin2hex( random_bytes( 32 ) ); $this->store->set( self::KEY_OPTION, array( 'id' => $id, 'secret' => $secret, 'created' => $now, 'expires' => $now + self::TTL, 'user' => $user_id, 'file' => $backup['file'], 'size' => $backup['size'], 'mtime' => $backup['mtime'], 'chunk_size' => $backup['chunk_size'], 'pinned_ip' => null, 'connected' => false, 'pin' => $pin, ) ); return array( 'key' => ConnectionKey::encode( $site_url, $id, $secret, $now ), 'id' => $id, 'expires' => $now + self::TTL, ); } public function revoke(): void { $this->store->delete( self::KEY_OPTION ); } /** * What the admin screen shows, without the secret. * * @return array{id:string,file:string,size:int,expires_in:int,connected:bool,pinned:bool,last_denied:array|null}|null */ public function status(): ?array { $record = $this->liveRecord(); if ( null === $record ) { return null; } return array( 'id' => $record['id'], 'file' => $record['file'], 'size' => (int) $record['size'], 'expires_in' => max( 0, (int) $record['expires'] - $this->now() ), 'connected' => ! empty( $record['connected'] ), 'pinned' => self::pinningFor( $record ), 'last_denied' => $record['last_denied'] ?? null, ); } /** * Checks a request. * * @param string $purpose "handshake", "chunk" or "finish": a signature for one cannot be used for another. * @param string $key_id The key id the request names. * @param int $timestamp The request's own time. * @param string $signature Hex HMAC-SHA256 from the request. * @param string[] $parts The request's details that the signature covers (chunk index, destination URL, ...). * @param string $ip The address the request came from (see clientIp()). * @return array{ok:bool,record:array|null,reason:string} */ public function authorize( string $purpose, string $key_id, int $timestamp, string $signature, array $parts, string $ip ): array { if ( $this->locked( $ip ) ) { return $this->deny( 'locked', false, $ip ); } $record = $this->liveRecord(); if ( null === $record || ! hash_equals( (string) $record['id'], $key_id ) ) { return $this->deny( 'unknown_key', true, $ip ); } if ( abs( $this->now() - $timestamp ) > self::MAX_SKEW ) { return $this->deny( 'stale_timestamp', true, $ip ); } $expected = self::sign( (string) $record['secret'], $purpose, $key_id, $timestamp, $parts ); if ( 1 !== preg_match( '/^[a-f0-9]{64}$/', $signature ) || ! hash_equals( $expected, $signature ) ) { return $this->deny( 'bad_signature', true, $ip ); } // The first handshake pins the address; every later request has to come from it. if ( 'handshake' === $purpose && empty( $record['connected'] ) ) { $record['connected'] = true; if ( self::pinningFor( $record ) ) { $record['pinned_ip'] = $ip; } $this->store->set( self::KEY_OPTION, $record ); } elseif ( empty( $record['connected'] ) ) { return $this->deny( 'not_pinned', true, $ip ); } elseif ( self::pinningFor( $record ) && null !== $record['pinned_ip'] && ! hash_equals( (string) $record['pinned_ip'], $ip ) ) { return $this->deny( 'ip_mismatch', true, $ip, (string) $record['pinned_ip'] ); } $this->forgetFailures( $ip ); return array( 'ok' => true, 'record' => $record, 'reason' => '', ); } /** * Agrees the piece size with the destination: the key's own size, or the smaller one the destination asked * for. The result is what describe() reports and what every chunk request is cut by. A multiple of 64 KB, * never below 64 KB. * * @param array $record * @return array The record with the agreed chunk_size. */ public function negotiateChunkSize( array $record, int $asked ): array { $size = min( (int) $record['chunk_size'], $asked ); $size = max( 65536, $size - ( $size % 65536 ) ); if ( $size !== (int) $record['chunk_size'] ) { $record['chunk_size'] = $size; $this->store->set( self::KEY_OPTION, $record ); } return $record; } /** * Ends the key for good: the destination has what it came for, or has given up. */ public function finish(): void { $this->revoke(); } /** * The signature a request must carry. Public so the destination signs with the very same function. * * @param string[] $parts */ public static function sign( string $secret_hex, string $purpose, string $key_id, int $timestamp, array $parts ): string { $message = implode( "\n", array_merge( array( $purpose, $key_id, (string) $timestamp ), $parts ) ); return hash_hmac( 'sha256', $message, (string) hex2bin( $secret_hex ) ); } /** * Cloudflare's published address ranges (https://www.cloudflare.com/ips/, checked October 2026). * Cloudflare changes them now and then; the migratex_remote_cloudflare_ranges filter replaces the list. */ private const CLOUDFLARE = array( '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32', ); /** * The address a request really came from. * * That is REMOTE_ADDR, the TCP peer, which a client cannot choose. Forwarding headers are anyone's to * send, so they are believed ONLY when the peer is a proxy this site trusts: * * - Cloudflare (its published ranges): the client is in CF-Connecting-IP, which Cloudflare sets itself; * failing that, the first address in X-Forwarded-For, from the right, that is not a trusted proxy. * - A Cloudflare Tunnel connector (cloudflared), if the site lists its address in the * migratex_remote_cloudflare_peers filter: the same, CF-Connecting-IP. * - Any other proxy or load balancer the site lists in the migratex_remote_trusted_proxies filter * (CIDR ranges): only X-Forwarded-For, read from the right. CF-Connecting-IP is ignored here, because * an ordinary proxy passes a client's own copy of that header straight through. * * A request that reaches the server directly, around the proxy, comes from an address that is not * trusted, so none of its headers count. This is what lets a site behind Cloudflare pin the real * destination address instead of whichever Cloudflare edge server happened to carry the request. * * The caller passes in values it has already unslashed and sanitized, never the $_SERVER array itself: * REMOTE_ADDR as a string, and from the forwarding headers only the two this method may read. * * @param string $remote_addr REMOTE_ADDR. * @param array $headers Optional: 'cf_connecting_ip' (CF-Connecting-IP) and 'x_forwarded_for' (X-Forwarded-For). */ public static function clientIp( string $remote_addr, array $headers = array() ): string { $peer = self::normalize( $remote_addr ); $ip = $peer; if ( '' !== $peer ) { // Cloudflare's own servers, or a connector that sits in front of the site on Cloudflare's behalf // (cloudflared, for a Cloudflare Tunnel, connects from the local machine): CF-Connecting-IP is // believed from these and only these. $cloudflare = self::inRanges( $peer, self::cloudflareRanges() ) || self::inRanges( $peer, self::tunnelPeers() ); $trusted = array_merge( self::cloudflareRanges(), self::tunnelPeers(), self::extraProxies() ); if ( $cloudflare || self::inRanges( $peer, self::extraProxies() ) ) { $forwarded = $cloudflare ? self::normalize( isset( $headers['cf_connecting_ip'] ) ? (string) $headers['cf_connecting_ip'] : '' ) : ''; if ( '' === $forwarded ) { $forwarded = self::fromForwardedFor( isset( $headers['x_forwarded_for'] ) ? (string) $headers['x_forwarded_for'] : '', $trusted ); } if ( '' !== $forwarded ) { $ip = $forwarded; } } } return self::normalize( (string) apply_filters( 'migratex_remote_client_ip', $ip ) ); } /** * Whether the site asks for address pinning on every key. OFF by default. * * Pinning holds the destination to the address that made the handshake. It is a second lock on top of the * signature, and a brittle one: a destination on a mobile or shared connection, behind carrier-grade NAT, * or with both IPv4 and IPv6 reaches the source from different addresses in the same transfer. So it is * opt-in: per key (a box on the Site-to-Site screen), or for the whole site with * define( 'MIGRATEX_ENABLE_IP_PINNING', true ) or the migratex_remote_ip_pinning filter returning true. * define( 'MIGRATEX_DISABLE_IP_PINNING', true ) forces it off everywhere. */ public static function pinning(): bool { if ( defined( 'MIGRATEX_DISABLE_IP_PINNING' ) && constant( 'MIGRATEX_DISABLE_IP_PINNING' ) ) { return false; } if ( defined( 'MIGRATEX_ENABLE_IP_PINNING' ) && constant( 'MIGRATEX_ENABLE_IP_PINNING' ) ) { return true; } return (bool) apply_filters( 'migratex_remote_ip_pinning', false ); } /** * Whether this key holds its destination to one address: the admin asked for it when making the key, or * the site asks for it for every key (constant or filter). MIGRATEX_DISABLE_IP_PINNING overrides all. * * @param array $record */ public static function pinningFor( array $record ): bool { if ( defined( 'MIGRATEX_DISABLE_IP_PINNING' ) && constant( 'MIGRATEX_DISABLE_IP_PINNING' ) ) { return false; } return true === ( $record['pin'] ?? false ) || self::pinning(); } /** * @return string[] */ private static function cloudflareRanges(): array { return array_values( array_filter( array_map( 'strval', (array) apply_filters( 'migratex_remote_cloudflare_ranges', self::CLOUDFLARE ) ) ) ); } /** * Addresses a Cloudflare Tunnel connector connects from, e.g. array( '127.0.0.1' ). Empty unless the site * says so with the migratex_remote_cloudflare_peers filter: trusting loopback by default would let any * other program on the server claim to be anyone. * * @return string[] */ private static function tunnelPeers(): array { return array_values( array_filter( array_map( 'strval', (array) apply_filters( 'migratex_remote_cloudflare_peers', array() ) ) ) ); } /** * @return string[] */ private static function extraProxies(): array { return array_values( array_filter( array_map( 'strval', (array) apply_filters( 'migratex_remote_trusted_proxies', array() ) ) ) ); } /** * The client in an X-Forwarded-For list: walking from the right (the hop nearest us, which our own * proxy wrote), the first address that is not one of our proxies. Anything further left was supplied * by whoever sent the request and is not believed. * * @param string[] $trusted */ private static function fromForwardedFor( string $header, array $trusted ): string { $hops = array_reverse( explode( ',', $header ) ); foreach ( $hops as $hop ) { $hop = self::normalize( trim( $hop ) ); if ( '' === $hop ) { return ''; // garbage in the chain: believe nothing from it. } if ( ! self::inRanges( $hop, $trusted ) ) { return $hop; } } return ''; } /** * One spelling per address ("::1" vs "0:0:0:0:0:0:0:1"), or '' for anything that is not an IP address. */ private static function normalize( string $ip ): string { $ip = trim( $ip ); if ( '' === $ip || false === filter_var( $ip, FILTER_VALIDATE_IP ) ) { return ''; } $packed = inet_pton( $ip ); return false === $packed ? '' : (string) inet_ntop( $packed ); } /** * @param string[] $ranges CIDR blocks or single addresses. */ private static function inRanges( string $ip, array $ranges ): bool { $packed = inet_pton( $ip ); if ( false === $packed ) { return false; } foreach ( $ranges as $range ) { $parts = explode( '/', $range, 2 ); $base = inet_pton( trim( $parts[0] ) ); if ( false === $base || strlen( $base ) !== strlen( $packed ) ) { continue; // a different address family, or not an address. } $bits = isset( $parts[1] ) ? (int) $parts[1] : strlen( $base ) * 8; if ( $bits < 0 || $bits > strlen( $base ) * 8 ) { continue; } $whole = intdiv( $bits, 8 ); if ( substr( $packed, 0, $whole ) !== substr( $base, 0, $whole ) ) { continue; } $rest = $bits % 8; if ( 0 === $rest ) { return true; } $mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF; if ( ( ord( $packed[ $whole ] ) & $mask ) === ( ord( $base[ $whole ] ) & $mask ) ) { return true; } } return false; } /** * The record, or null when there is none or it has expired (an expired key is deleted on sight). * * @return array|null */ private function liveRecord(): ?array { $record = $this->store->get( self::KEY_OPTION ); if ( ! is_array( $record ) || ! isset( $record['id'], $record['secret'], $record['expires'] ) ) { return null; } if ( $this->now() > (int) $record['expires'] ) { $this->revoke(); return null; } $record += array( 'pinned_ip' => null ); return $record; } /** * @return array{ok:bool,record:null,reason:string,ip:string,pinned:string} */ private function deny( string $reason, bool $counts, string $ip, string $pinned = '' ): array { if ( $counts ) { $this->recordFailure( $ip ); } // Tell the admin why the last request was refused (on the Site-to-Site screen), so a proxy // that rotates addresses is a line of text instead of a mystery. Only while a key exists. $record = $this->store->get( self::KEY_OPTION ); if ( is_array( $record ) && 'locked' !== $reason && 'unknown_key' !== $reason ) { $record['last_denied'] = array( 'reason' => $reason, 'ip' => $ip, 'pinned' => $pinned, 'at' => $this->now(), ); $this->store->set( self::KEY_OPTION, $record ); } return array( 'ok' => false, 'record' => null, 'reason' => $reason, 'ip' => $ip, 'pinned' => $pinned, ); } private function locked( string $ip ): bool { $entry = $this->failures()[ self::ipKey( $ip ) ] ?? null; return is_array( $entry ) && (int) $entry['until'] > $this->now(); } /** * Counts a failed attempt; the fifth in a row locks the address for an hour. */ private function recordFailure( string $ip ): void { $all = $this->failures(); $key = self::ipKey( $ip ); $entry = $all[ $key ] ?? array( 'count' => 0, 'until' => 0, 'seen' => 0, ); // An old lock that has run out starts a fresh count. if ( (int) $entry['until'] > 0 && (int) $entry['until'] <= $this->now() ) { $entry['count'] = 0; $entry['until'] = 0; } ++$entry['count']; $entry['seen'] = $this->now(); if ( $entry['count'] >= self::MAX_FAILURES ) { $entry['until'] = $this->now() + self::LOCKOUT; } $all[ $key ] = $entry; $this->store->set( self::FAILURE_OPTION, $this->prune( $all ) ); } /** * A good request resets the count ("consecutive" failures), unless the address is locked. */ private function forgetFailures( string $ip ): void { $all = $this->failures(); $key = self::ipKey( $ip ); if ( isset( $all[ $key ] ) ) { unset( $all[ $key ] ); $this->store->set( self::FAILURE_OPTION, $all ); } } /** * @return array */ private function failures(): array { $all = $this->store->get( self::FAILURE_OPTION ); return is_array( $all ) ? $all : array(); } /** * Drops entries that no longer matter and caps the table, so the list cannot be used to grow the database. * * @param array $all * @return array */ private function prune( array $all ): array { $now = $this->now(); foreach ( $all as $key => $entry ) { $locked = (int) $entry['until'] > $now; if ( ! $locked && $now - (int) $entry['seen'] > self::LOCKOUT ) { unset( $all[ $key ] ); } } if ( count( $all ) > 200 ) { uasort( $all, static function ( $a, $b ) { return (int) $b['seen'] <=> (int) $a['seen']; } ); $all = array_slice( $all, 0, 200, true ); } return $all; } /** * Addresses are stored hashed: the list is a record of who attacked, not a log of visitors. */ private static function ipKey( string $ip ): string { return substr( hash( 'sha256', $ip ), 0, 24 ); } private function now(): int { return (int) ( $this->clock )(); } }