auth = $auth; } public function register(): void { add_action( 'rest_api_init', array( $this, 'registerRoutes' ) ); } public function registerRoutes(): void { $routes = array( 'handshake' => array( \WP_REST_Server::CREATABLE, 'handshake', 'permitHandshake' ), 'chunk' => array( \WP_REST_Server::READABLE, 'chunk', 'permitChunk' ), 'finish' => array( \WP_REST_Server::CREATABLE, 'finish', 'permitFinish' ), ); foreach ( $routes as $route => list( $methods, $callback, $permit ) ) { register_rest_route( MIGRATEX_REST_NAMESPACE, '/remote/' . $route, array( 'methods' => $methods, 'callback' => array( $this, $callback ), 'permission_callback' => array( $this, $permit ), ) ); } } /* ---------- permission callbacks: the authentication ---------- */ /** * @return true|\WP_Error */ public function permitHandshake( \WP_REST_Request $request ) { return $this->gate( $request, 'handshake', array( (string) $request->get_param( 'site' ), (string) $request->get_param( 'chunk_max' ) ), (string) $request->get_param( 'key_id' ), (int) $request->get_param( 'timestamp' ), (string) $request->get_param( 'signature' ) ); } /** * @return true|\WP_Error */ public function permitChunk( \WP_REST_Request $request ) { $index = (string) $request->get_param( 'index' ); if ( 1 !== preg_match( '/^\d{1,9}$/', $index ) ) { return $this->denied(); } return $this->gate( $request, 'chunk', array( $index ), (string) $request->get_header( 'x_om_key_id' ), (int) $request->get_header( 'x_om_timestamp' ), (string) $request->get_header( 'x_om_signature' ) ); } /** * @return true|\WP_Error */ public function permitFinish( \WP_REST_Request $request ) { $status = (string) $request->get_param( 'status' ); if ( ! in_array( $status, array( 'complete', 'error' ), true ) ) { return $this->denied(); } return $this->gate( $request, 'finish', array( $status ), (string) $request->get_header( 'x_om_key_id' ), (int) $request->get_header( 'x_om_timestamp' ), (string) $request->get_header( 'x_om_signature' ) ); } /** * @param string[] $parts * @return true|\WP_Error */ private function gate( \WP_REST_Request $request, string $purpose, array $parts, string $key_id, int $timestamp, string $signature ) { if ( ! Transport::requestIsSecure() ) { return $this->denied(); } $ip = $this->clientIp(); $result = '' === $ip ? array( 'ok' => false ) : $this->auth->authorize( $purpose, $key_id, $timestamp, $signature, $parts, $ip ); if ( empty( $result['ok'] ) ) { return $this->denied( (string) ( $result['reason'] ?? '' ), (string) ( $result['ip'] ?? '' ), (string) ( $result['pinned'] ?? '' ) ); } $request->set_attributes( array_merge( $request->get_attributes(), array( 'om_record' => $result['record'] ) ) ); return true; } /** * The address this request came from. Only three server values are read, each unslashed and * sanitized on its own (never the whole $_SERVER array), and Auth::clientIp() accepts nothing that * is not a valid IP address. */ private function clientIp(): string { $raw_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; if ( false === filter_var( $raw_ip, FILTER_VALIDATE_IP ) ) { return ''; } $headers = array( 'cf_connecting_ip' => isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) : '', 'x_forwarded_for' => isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) : '', ); return Auth::clientIp( $raw_ip, $headers ); } private function denied( string $reason = '', string $ip = '', string $pinned = '' ): \WP_Error { return new \WP_Error( 'om_remote_denied', __( 'Request denied.', 'migratex' ), self::denialData( $reason, $ip, $pinned ) ); } /** * What a refusal tells the caller. Everything is the same bare 403, with one exception: a request whose * signature WAS valid but that came from a different address than the one that connected. Only the holder * of the key can get that far, and it needs to be told, because the usual cause (the destination reaching * the source over IPv4 once and IPv6 the next time, or through another proxy) is invisible from its side. * It learns its own address as the source saw it, and the earlier one with its last part hidden. * * @return array */ public static function denialData( string $reason, string $ip, string $pinned ): array { $data = array( 'status' => 403 ); if ( 'ip_mismatch' === $reason && '' !== $ip && '' !== $pinned ) { $data['reason'] = 'ip_mismatch'; $data['ip'] = $ip; $data['pinned'] = self::maskAddress( $pinned ); } return $data; } /** * "203.0.113.x" or "2001:db8:1:x": enough to tell the address family and network, not the address. */ public static function maskAddress( string $ip ): string { $packed = inet_pton( $ip ); if ( false === $packed ) { return ''; } if ( 4 === strlen( $packed ) ) { return implode( '.', array_slice( explode( '.', $ip ), 0, 3 ) ) . '.x'; } return implode( ':', array_slice( explode( ':', (string) inet_ntop( $packed ) ), 0, 3 ) ) . ':x'; } /* ---------- routes ---------- */ /** * @return \WP_REST_Response|\WP_Error */ public function handshake( \WP_REST_Request $request ) { $record = (array) ( $request->get_attributes()['om_record'] ?? array() ); $record = $this->auth->negotiateChunkSize( $record, (int) $request->get_param( 'chunk_max' ) ); $meta = self::describe( $record ); if ( null === $meta ) { return new \WP_Error( 'om_remote_unavailable', __( 'The backup is no longer available.', 'migratex' ), array( 'status' => 410 ) ); } return new \WP_REST_Response( array( 'ok' => true, 'data' => $meta + array( 'expires_in' => max( 0, (int) $record['expires'] - time() ), ), ) ); } /** * Streams one chunk and ends the request. * * @return \WP_Error Only when the chunk cannot be served; otherwise this never returns. */ public function chunk( \WP_REST_Request $request ) { $record = (array) ( $request->get_attributes()['om_record'] ?? array() ); $chunk = self::prepareChunk( $record, (int) $request->get_param( 'index' ) ); if ( null === $chunk ) { return new \WP_Error( 'om_remote_unavailable', __( 'That part of the backup is not available.', 'migratex' ), array( 'status' => 404 ) ); } $this->stream( $chunk ); } /** * @return \WP_REST_Response */ public function finish( \WP_REST_Request $request ) { $this->auth->finish(); return new \WP_REST_Response( array( 'ok' => true ) ); } /* ---------- the parts the tests exercise directly ---------- */ /** * The backup's layout, signed with the key's secret so the destination knows the numbers were not altered. * * @param array $record * @return array|null Null when the backup is gone or no longer the file the key was made for. */ /** Version of the chunk format. 2 = chunks travel in a self-describing frame. */ public const PROTOCOL = 2; public static function describe( array $record ): ?array { $path = Library::path( (string) $record['file'] ); if ( null === $path || ! self::unchanged( $path, $record ) ) { return null; } $size = (int) $record['size']; $chunk = (int) $record['chunk_size']; $total = (int) ceil( $size / $chunk ); $name = (string) $record['file']; return array( 'proto' => self::PROTOCOL, 'name' => $name, 'size' => $size, 'chunk_size' => $chunk, 'total_chunks' => $total, 'signature' => hash_hmac( 'sha256', implode( "\n", array( 'meta', (string) $record['id'], (string) self::PROTOCOL, $name, (string) $size, (string) $chunk, (string) $total ) ), (string) hex2bin( (string) $record['secret'] ) ), ); } /** * Where chunk $index starts and how long it is, with its SHA-256 and signature. Reads the chunk once to * hash it, in blocks, so the archive is never held in memory. * * @param array $record * @return array{path:string,offset:int,length:int,index:int,total:int,hash:string,signature:string}|null */ public static function prepareChunk( array $record, int $index ): ?array { $path = Library::path( (string) $record['file'] ); if ( null === $path || ! self::unchanged( $path, $record ) ) { return null; } $size = (int) $record['size']; $chunk = (int) $record['chunk_size']; $total = (int) ceil( $size / $chunk ); if ( $index < 0 || $index >= $total ) { return null; } $offset = $index * $chunk; $length = min( $chunk, $size - $offset ); $handle = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- streams a multi-gigabyte archive in blocks. if ( false === $handle ) { return null; } $hash = null; if ( 0 === fseek( $handle, $offset ) ) { $context = hash_init( 'sha256' ); if ( hash_update_stream( $context, $handle, $length ) === $length ) { $hash = hash_final( $context ); } } fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose if ( null === $hash ) { return null; } return array( 'path' => $path, 'offset' => $offset, 'length' => $length, 'index' => $index, 'total' => $total, 'hash' => $hash, 'signature' => self::chunkSignature( (string) $record['secret'], (string) $record['id'], $index, $total, $hash, $length ), ); } /** * What the destination checks on every chunk it receives. */ public static function chunkSignature( string $secret_hex, string $key_id, int $index, int $total, string $hash, int $length ): string { return hash_hmac( 'sha256', implode( "\n", array( 'chunk', $key_id, (string) $index, (string) $total, $hash, (string) $length ) ), (string) hex2bin( $secret_hex ) ); } /** * The backup must still be exactly the file the key was made for. * * @param array $record */ private static function unchanged( string $path, array $record ): bool { clearstatcache( true, $path ); return (int) filesize( $path ) === (int) $record['size'] && (int) filemtime( $path ) === (int) $record['mtime']; } /** Marks where a chunk's own description starts in a response. */ public const FRAME_MAGIC = 'OMCHNK01'; /** * The bytes that go in front of a chunk's payload: a marker, then its index, count, SHA-256, length and * signature as JSON. The response is thereby self-describing and does not depend on HTTP headers * surviving (a proxy or host may drop or rewrite them), and the destination can skip any stray text * that was printed before it, such as a PHP notice, a BOM or a blank line from a plugin file. * * @param array{length:int,index:int,total:int,hash:string,signature:string} $chunk */ public static function framePrefix( array $chunk ): string { $meta = (string) wp_json_encode( array( 'i' => $chunk['index'], 't' => $chunk['total'], 'h' => $chunk['hash'], 'l' => $chunk['length'], 's' => $chunk['signature'], ) ); return self::FRAME_MAGIC . pack( 'N', strlen( $meta ) ) . $meta; } /** * Finds the chunk in a response body, whatever came before or after it. * * @return array{index:int,total:int,hash:string,length:int,signature:string,payload:string}|null Null when there is no complete chunk. */ public static function unframe( string $body ): ?array { $at = strpos( substr( $body, 0, 65536 ), self::FRAME_MAGIC ); if ( false === $at ) { return null; } $start = $at + strlen( self::FRAME_MAGIC ); if ( strlen( $body ) < $start + 4 ) { return null; } $json_length = (int) unpack( 'N', substr( $body, $start, 4 ) )[1]; if ( $json_length < 2 || $json_length > 2048 || strlen( $body ) < $start + 4 + $json_length ) { return null; } $meta = json_decode( substr( $body, $start + 4, $json_length ), true ); if ( ! is_array( $meta ) || ! is_int( $meta['i'] ?? null ) || ! is_int( $meta['t'] ?? null ) || ! is_int( $meta['l'] ?? null ) || ! is_string( $meta['h'] ?? null ) || ! is_string( $meta['s'] ?? null ) || $meta['l'] < 0 ) { return null; } $payload = substr( $body, $start + 4 + $json_length, $meta['l'] ); // anything after it is ignored. if ( strlen( $payload ) !== $meta['l'] ) { return null; // cut short. } return array( 'index' => $meta['i'], 'total' => $meta['t'], 'hash' => strtolower( $meta['h'] ), 'length' => $meta['l'], 'signature' => strtolower( $meta['s'] ), 'payload' => $payload, ); } /** * @param array{path:string,offset:int,length:int,index:int,total:int,hash:string,signature:string} $chunk */ private function stream( array $chunk ): void { // Nothing between PHP and the destination may compress or buffer the chunk. PHP's own compression // off; Apache and LiteSpeed told not to gzip this response; buffers emptied. if ( function_exists( 'ini_set' ) ) { @ini_set( 'zlib.output_compression', 'Off' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.PHP.IniSet.Risky,Squiz.PHP.DiscouragedFunctions.Discouraged -- the bytes must arrive as they are. } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } while ( ob_get_level() ) { ob_end_clean(); } $handle = fopen( $chunk['path'], 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen if ( false === $handle || 0 !== fseek( $handle, $chunk['offset'] ) ) { status_header( 500 ); exit; } $prefix = self::framePrefix( $chunk ); // If something already printed (a notice, a stray blank line in a plugin file), headers can no longer // be sent. The frame still carries everything, so the transfer works either way. if ( ! headers_sent() ) { status_header( 200 ); header( 'Content-Type: application/octet-stream' ); header( 'Content-Length: ' . ( strlen( $prefix ) + $chunk['length'] ) ); header( 'Content-Encoding: identity' ); header( 'Cache-Control: private, no-store, no-transform' ); header( 'X-Accel-Buffering: no' ); header( 'X-LiteSpeed-Cache-Control: no-cache, no-transform' ); header( 'X-Content-Type-Options: nosniff' ); header( 'X-OM-Chunk-Index: ' . $chunk['index'] ); header( 'X-OM-Chunk-Total: ' . $chunk['total'] ); header( 'X-OM-Chunk-Hash: ' . $chunk['hash'] ); header( 'X-OM-Chunk-Signature: ' . $chunk['signature'] ); } echo $prefix; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary. $remaining = $chunk['length']; while ( $remaining > 0 && ! connection_aborted() ) { // Each block gets a fresh allowance, so a slow destination cannot cut the piece short. if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- renewed per block of one long-running transfer, and only where the host allows it. } $block = fread( $handle, (int) min( 1048576, $remaining ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- streams a multi-gigabyte archive in blocks. if ( false === $block || '' === $block ) { break; } echo $block; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary file contents. $remaining -= strlen( $block ); flush(); } fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose exit; } }