get_secret( $user->ID ); if ( '' !== $secret ) { return $secret; } $secret = $this->generate_secret(); update_user_meta( $user->ID, self::META_KEY, $secret ); return $secret; } /** * Remove the stored OTP secret for a user. * * @param int $user_id User identifier. * * @return void */ public function delete_secret( int $user_id ): void { delete_user_meta( $user_id, self::META_KEY ); } /** * Verify an OTP code against the stored secret. * * @param WP_User $user User attempting to authenticate. * @param string $code Submitted verification code. * * @return bool */ public function verify_code( WP_User $user, string $code ): bool { $secret = $this->get_secret( $user->ID ); if ( '' === $secret ) { return false; } $code = preg_replace( '/[^0-9]/', '', $code ); if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) { return false; } $binary_secret = $this->base32_decode( $secret ); if ( '' === $binary_secret ) { return false; } $current_step = (int) floor( time() / self::TIME_STEP ); for ( $offset = -1; $offset <= 1; $offset++ ) { $otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset ); if ( hash_equals( $otp, $code ) ) { return true; } } return false; } /** * Retrieve the provisioning URI used by authenticator apps. * * @param WP_User $user User who owns the OTP secret. * * @return string */ public function get_provisioning_uri( WP_User $user ): string { $secret = $this->get_secret( $user->ID ); if ( '' === $secret ) { return ''; } $raw_blogname = get_option( 'blogname', '' ); $site_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES ); $site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' ); $label = '' !== $user->user_email ? $user->user_email : $user->user_login; $encoded_label = rawurlencode( sanitize_text_field( $label ) ); $encoded_site = rawurlencode( $site_name ); $encoded_secret = rawurlencode( $secret ); $parameters = array( 'issuer' => $encoded_site, 'period' => (string) self::TIME_STEP, ); $query = array(); foreach ( $parameters as $key => $value ) { $query[] = rawurlencode( $key ) . '=' . $value; } return sprintf( 'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s', $encoded_site, $encoded_label, $encoded_secret, implode( '&', $query ) ); } /** * Generate a QR code and return it as a data URI. * * @param WP_User $user User who owns the OTP secret. * * @return string Data URI containing an SVG image or an empty string when unavailable. */ public function get_qr_code_data_uri( WP_User $user ): string { $uri = $this->get_provisioning_uri( $user ); if ( '' === $uri ) { return ''; } $svg = $this->render_qr_svg( $uri ); if ( '' === $svg ) { return ''; } /* * Encode the SVG payload so it can be embedded safely as a data URI in the admin form. */ return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The QR SVG is encoded to embed it safely as a data URI. } /** * Generate a new secret encoded in Base32. * * @return string */ private function generate_secret(): string { $bytes = random_bytes( self::SECRET_LENGTH ); return $this->base32_encode( $bytes ); } /** * Render a QR code in SVG format using an available library. * * @param string $data Data encoded inside the QR code. * * @return string SVG markup or empty string on failure. */ private function render_qr_svg( string $data ): string { if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) { return ''; } try { $renderer = new \BaconQrCode\Renderer\ImageRenderer( new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ), new \BaconQrCode\Renderer\Image\SvgImageBackEnd() ); $writer = new \BaconQrCode\Writer( $renderer ); return $writer->writeString( $data ); } catch ( \Throwable $exception ) { /** * Fires when QR code SVG generation fails. * * @since 0.2.0 * * @param \Throwable $exception The caught exception. * @param string $data The provisioning URI that failed to render. */ do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data ); } return ''; } /** * Encode binary data using the Base32 alphabet. * * @param string $data Binary string to encode. * * @return string */ private function base32_encode( string $data ): string { $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $bits = ''; for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) { $bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT ); } $chunks = str_split( $bits, 5 ); $encoded = ''; foreach ( $chunks as $chunk ) { if ( strlen( $chunk ) < 5 ) { $chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT ); } $encoded .= $alphabet[ (int) bindec( $chunk ) ]; } return $encoded; } /** * Decode a Base32-encoded string. * * @param string $encoded Encoded secret. * * @return string */ private function base32_decode( string $encoded ): string { $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; $encoded = strtoupper( $encoded ); $encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded ); if ( null === $encoded || '' === $encoded ) { return ''; } $bits = ''; for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) { $position = strpos( $alphabet, $encoded[ $i ] ); if ( false === $position ) { return ''; } $bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT ); } $binary = ''; $chunks = str_split( $bits, 8 ); foreach ( $chunks as $chunk ) { if ( strlen( $chunk ) < 8 ) { continue; } $binary .= chr( (int) bindec( $chunk ) & 0xFF ); } return $binary; } /** * Generate an OTP value for a specific counter. * * @param string $secret Binary secret key. * @param int $counter Time-based counter value. * * @return string */ private function generate_otp_for_counter( string $secret, int $counter ): string { $counter = max( 0, $counter ); $binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter ); $hash = hash_hmac( 'sha1', $binary_counter, $secret, true ); $offset = ord( substr( $hash, -1 ) ) & 0x0F; $segment = substr( $hash, $offset, 4 ); $unpacked = unpack( 'N', $segment ); $raw_value = is_array( $unpacked ) && isset( $unpacked[1] ) && is_int( $unpacked[1] ) ? $unpacked[1] : 0; $value = $raw_value & 0x7FFFFFFF; $code = $value % ( 10 ** self::CODE_DIGITS ); return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT ); } }