__( 'Login', 'ai-guardwall' ), 'register' => __( 'Registration', 'ai-guardwall' ), 'lostpassword' => __( 'Lost password', 'ai-guardwall' ), 'comments' => __( 'Comments (visitors who are not logged in)', 'ai-guardwall' ), 'woo_login' => __( 'WooCommerce login', 'ai-guardwall' ), 'woo_register' => __( 'WooCommerce registration', 'ai-guardwall' ), 'woo_lostpassword' => __( 'WooCommerce lost password', 'ai-guardwall' ), 'woo_checkout' => __( 'WooCommerce checkout (guests)', 'ai-guardwall' ), 'cf7' => __( 'Contact Form 7 (reCAPTCHA v3)', 'ai-guardwall' ), 'wpforms' => __( 'WPForms (reCAPTCHA v3)', 'ai-guardwall' ), 'elementor' => __( 'Elementor Pro forms (reCAPTCHA v3)', 'ai-guardwall' ), ); } /** * The contact-form plugins: form id => whether the plugin is active, and the CSS selector of its forms. * * @return array */ public static function form_plugins() { return array( 'cf7' => array( class_exists( 'WPCF7' ) || defined( 'WPCF7_VERSION' ), 'form.wpcf7-form' ), 'wpforms' => array( function_exists( 'wpforms' ), 'form.wpforms-form' ), 'elementor' => array( defined( 'ELEMENTOR_PRO_VERSION' ), 'form.elementor-form' ), ); } /** * Whether any CAPTCHA is on: the rule on Security Wall › Brute force, or * the reCAPTCHA v3 feature on the Tools page. * * @return bool */ public static function active() { return Softvolt_Ai_Bodyguard_Settings::hardening_enabled( 'login_captcha' ) || ( class_exists( 'Softvolt_Ai_Bodyguard_Modules' ) && Softvolt_Ai_Bodyguard_Modules::enabled( 'recaptcha' ) ); } public static function keys_set() { return '' !== (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_site_key', '' ) && Softvolt_Ai_Bodyguard_Settings::has_secret( 'captcha_secret' ); } public static function providers() { return array( 'math' => __( 'Maths question (built in, no outside service)', 'ai-guardwall' ), 'turnstile' => __( 'Cloudflare Turnstile (free, private, usually invisible)', 'ai-guardwall' ), 'recaptcha_v2' => __( 'Google reCAPTCHA v2 ("I\'m not a robot" checkbox)', 'ai-guardwall' ), 'recaptcha_v3' => __( 'Google reCAPTCHA v3 (invisible score)', 'ai-guardwall' ), ); } public static function init() { // WooCommerce registration has its own error filter (the fields are printed with the login fields). add_filter( 'woocommerce_process_registration_errors', array( __CLASS__, 'check_woo_register' ), 10, 1 ); if ( ! self::active() ) { return; } $forms = (array) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_forms', array() ); if ( 'recaptcha_v3' === self::provider() ) { if ( in_array( 'cf7', $forms, true ) ) { add_filter( 'wpcf7_spam', array( __CLASS__, 'check_cf7' ), 9, 2 ); } if ( in_array( 'wpforms', $forms, true ) ) { add_action( 'wpforms_process', array( __CLASS__, 'check_wpforms' ), 9, 3 ); } if ( in_array( 'elementor', $forms, true ) ) { add_action( 'elementor_pro/forms/validation', array( __CLASS__, 'check_elementor' ), 9, 2 ); } add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_forms' ) ); if ( Softvolt_Ai_Bodyguard_Settings::get( 'captcha_hide_badge', 0 ) ) { add_action( 'wp_enqueue_scripts', array( __CLASS__, 'badge_css' ) ); add_action( 'login_enqueue_scripts', array( __CLASS__, 'badge_css' ) ); } } if ( in_array( 'comments', $forms, true ) ) { add_action( 'comment_form_after_fields', array( __CLASS__, 'print_comments' ) ); add_filter( 'preprocess_comment', array( __CLASS__, 'check_comment' ), 1 ); } if ( in_array( 'woo_checkout', $forms, true ) ) { add_action( 'woocommerce_review_order_before_submit', array( __CLASS__, 'print_woo_checkout' ) ); add_action( 'woocommerce_after_checkout_validation', array( __CLASS__, 'check_woo_checkout' ), 10, 2 ); } } /** * Whether the CAPTCHA is shown on a form. */ public static function on( $form ) { return self::active() && in_array( $form, (array) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_forms', array() ), true ); } public static function provider() { $p = (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_provider', 'math' ); // The reCAPTCHA v3 feature on the Tools page makes v3 the CAPTCHA everywhere. if ( class_exists( 'Softvolt_Ai_Bodyguard_Modules' ) && Softvolt_Ai_Bodyguard_Modules::enabled( 'recaptcha' ) ) { $p = 'recaptcha_v3'; } if ( 'math' !== $p && ! self::keys_set() ) { return 'math'; } return $p; } /** * The CAPTCHA markup for a form (empty when it is off for that form). * * @param string $form Form id. * @return string HTML. */ public static function widget( $form ) { if ( ! self::on( $form ) ) { return ''; } $key = esc_attr( (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_site_key', '' ) ); $html = ''; switch ( self::provider() ) { case 'turnstile': // phpcs:ignore PluginCheck.CodeAnalysis.Offloading.OffloadedContent -- the CAPTCHA service the site owner chose must be loaded from and checked by that service (see readme, External services). $html .= '
' . self::script( 'https://challenges.cloudflare.com/turnstile/v0/api.js' ); break; case 'recaptcha_v2': $html .= '
' . self::script( 'https://www.google.com/recaptcha/api.js' ); break; case 'recaptcha_v3': $id = 'svabg-rc3-' . wp_rand( 1000, 999999 ); $html .= '' . self::script( 'https://www.google.com/recaptcha/api.js?render=' . rawurlencode( (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_site_key', '' ) ) ); wp_add_inline_script( 'svabg-captcha-' . self::provider(), '(function(){var k=' . wp_json_encode( (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_site_key', '' ) ) . ',a=' . wp_json_encode( preg_replace( '/[^a-z_]/', '_', $form ) ) . ',el=document.getElementById(' . wp_json_encode( $id ) . ');function go(){if(!window.grecaptcha||!grecaptcha.ready){return setTimeout(go,300);}grecaptcha.ready(function(){grecaptcha.execute(k,{action:a}).then(function(t){el.value=t;});});}go();setInterval(go,90000);})();' ); if ( Softvolt_Ai_Bodyguard_Settings::get( 'captcha_hide_badge', 0 ) ) { $html .= '

' . self::google_notice() . '

'; } break; default: $a = wp_rand( 1, 9 ); $b = wp_rand( 1, 9 ); $token = wp_generate_password( 20, false, false ); set_transient( 'svabg_cap_' . $token, $a + $b, 15 * MINUTE_IN_SECONDS ); $html .= '

'; } return $html; } private static function script( $src ) { $handle = 'svabg-captcha-' . self::provider(); if ( ! wp_script_is( $handle, 'registered' ) ) { // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- the provider's own script; its URL carries no version. wp_register_script( $handle, $src, array(), null, array( 'in_footer' => true, 'strategy' => 'defer' ) ); } wp_enqueue_script( $handle ); return ''; } /** * Check the posted answer. * * @param string $form Form id. * @return true|WP_Error */ public static function verify( $form ) { if ( ! self::on( $form ) ) { return true; } $fail = new WP_Error( 'svabg_captcha', __( 'The security check was not passed. Please try again.', 'ai-guardwall' ) ); // phpcs:disable WordPress.Security.NonceVerification.Missing -- the CAPTCHA is the check. switch ( self::provider() ) { case 'turnstile': $token = isset( $_POST['cf-turnstile-response'] ) ? sanitize_text_field( wp_unslash( $_POST['cf-turnstile-response'] ) ) : ''; // phpcs:ignore PluginCheck.CodeAnalysis.Offloading.OffloadedContent -- the CAPTCHA service the site owner chose must be loaded from and checked by that service (see readme, External services). $res = self::remote( 'https://challenges.cloudflare.com/turnstile/v0/siteverify', $token ); return true === $res || ( is_array( $res ) && ! empty( $res['success'] ) ) ? true : $fail; case 'recaptcha_v2': $token = isset( $_POST['g-recaptcha-response'] ) ? sanitize_text_field( wp_unslash( $_POST['g-recaptcha-response'] ) ) : ''; $res = self::remote( 'https://www.google.com/recaptcha/api/siteverify', $token ); return true === $res || ( is_array( $res ) && ! empty( $res['success'] ) ) ? true : $fail; case 'recaptcha_v3': $token = isset( $_POST['svabg_recaptcha'] ) ? sanitize_text_field( wp_unslash( $_POST['svabg_recaptcha'] ) ) : ''; $res = self::remote( 'https://www.google.com/recaptcha/api/siteverify', $token ); if ( true === $res ) { return true; } $min = (int) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_v3_threshold', 5 ) / 10; if ( is_array( $res ) && ! empty( $res['success'] ) && isset( $res['score'] ) && (float) $res['score'] >= $min ) { return true; } if ( is_array( $res ) && isset( $res['score'] ) ) { Softvolt_Ai_Bodyguard_Logger::log_throttled( 'rc3' . Softvolt_Ai_Bodyguard_Helpers::client_ip(), 10, 'notice', 'captcha', sprintf( /* translators: 1: score, 2: form, 3: minutes */ __( 'reCAPTCHA v3 score %1$s on the %2$s form (needed %3$s).', 'ai-guardwall' ), $res['score'], $form, $min ) ); } return $fail; default: $token = isset( $_POST['svabg_captcha_token'] ) ? sanitize_key( wp_unslash( $_POST['svabg_captcha_token'] ) ) : ''; $answer = isset( $_POST['svabg_captcha'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['svabg_captcha'] ) ) : -1; $want = '' !== $token ? get_transient( 'svabg_cap_' . $token ) : false; if ( '' !== $token ) { delete_transient( 'svabg_cap_' . $token ); } return ( false !== $want && (int) $want === $answer ) ? true : new WP_Error( 'svabg_captcha', __( 'The answer to the security question was wrong. Please try again.', 'ai-guardwall' ) ); } // phpcs:enable } /** * Ask the provider. True when it could not be reached (never lock people out over an outage). * * @return array|true|false */ private static function remote( $url, $token ) { if ( '' === $token ) { return false; } $res = wp_remote_post( $url, array( 'timeout' => 8, 'body' => array( 'secret' => Softvolt_Ai_Bodyguard_Settings::secret( 'captcha_secret' ), 'response' => $token, 'remoteip' => Softvolt_Ai_Bodyguard_Helpers::client_ip(), ), ) ); if ( is_wp_error( $res ) || (int) wp_remote_retrieve_response_code( $res ) >= 500 ) { Softvolt_Ai_Bodyguard_Logger::log_throttled( 'capdown', 60, 'warning', 'captcha', sprintf( /* translators: %s: is WordPress error */ __( 'The CAPTCHA service could not be reached (%s); the form was let through.', 'ai-guardwall' ), is_wp_error( $res ) ? $res->get_error_message() : wp_remote_retrieve_response_code( $res ) ) ); return true; } $data = json_decode( (string) wp_remote_retrieve_body( $res ), true ); return is_array( $data ) ? $data : false; } /* --------------------------- the other forms -------------------------- */ public static function print_comments() { if ( ! is_user_logged_in() ) { echo self::widget( 'comments' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built from escaped parts. } } public static function check_comment( $data ) { if ( is_user_logged_in() || ( isset( $data['comment_type'] ) && in_array( $data['comment_type'], array( 'pingback', 'trackback' ), true ) ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) { return $data; } $ok = self::verify( 'comments' ); if ( is_wp_error( $ok ) ) { wp_die( esc_html( $ok->get_error_message() ), esc_html__( 'Comment not posted', 'ai-guardwall' ), array( 'response' => 403, 'back_link' => true ) ); } return $data; } public static function check_woo_register( $errors ) { $ok = Softvolt_Ai_Bodyguard_Login_Security::validate_form_fields( 'woo_register' ); if ( is_wp_error( $ok ) ) { $errors->add( $ok->get_error_code(), $ok->get_error_message() ); } return $errors; } public static function print_woo_checkout() { if ( ! is_user_logged_in() ) { echo self::widget( 'woo_checkout' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } } public static function check_woo_checkout( $data, $errors ) { if ( is_user_logged_in() ) { return; } $ok = self::verify( 'woo_checkout' ); if ( is_wp_error( $ok ) ) { $errors->add( $ok->get_error_code(), $ok->get_error_message() ); } } /* --------------------------- contact forms (reCAPTCHA v3) -------------------------- */ /** * The text Google asks for when the reCAPTCHA badge is hidden. * * @return string HTML. */ public static function google_notice() { return sprintf( /* translators: 1: privacy policy link, 2: terms link. */ esc_html__( 'This site is protected by reCAPTCHA and the Google %1$s and %2$s apply.', 'ai-guardwall' ), '' . esc_html__( 'Privacy Policy', 'ai-guardwall' ) . '', '' . esc_html__( 'Terms of Service', 'ai-guardwall' ) . '' ); } /** * Load reCAPTCHA v3 for the contact forms of the active plugins. */ public static function enqueue_forms() { if ( is_user_logged_in() && current_user_can( 'edit_posts' ) && ! apply_filters( 'svabg_recaptcha_for_editors', false ) ) { return; } $forms = (array) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_forms', array() ); $selectors = array(); foreach ( self::form_plugins() as $id => $plugin ) { if ( $plugin[0] && in_array( $id, $forms, true ) ) { $selectors[] = $plugin[1]; } } if ( ! $selectors ) { return; } $key = (string) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_site_key', '' ); wp_enqueue_script( 'svabg-recaptcha-api', 'https://www.google.com/recaptcha/api.js?render=' . rawurlencode( $key ), array(), null, array( 'in_footer' => true ) ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- Google's own script, versioned by Google. wp_enqueue_script( 'svabg-recaptcha', plugins_url( 'public/js/softvolt-ai-bodyguard-recaptcha.js', SOFTVOLT_AI_BODYGUARD_FILE ), array( 'svabg-recaptcha-api' ), SOFTVOLT_AI_BODYGUARD_VERSION, array( 'in_footer' => true ) ); wp_add_inline_script( 'svabg-recaptcha', 'window.svabgRecaptcha = ' . wp_json_encode( array( 'key' => $key, 'selectors' => $selectors, 'notice' => Softvolt_Ai_Bodyguard_Settings::get( 'captcha_hide_badge', 0 ) ? self::google_notice() : '', ) ) . ';', 'before' ); } public static function badge_css() { $handle = did_action( 'login_enqueue_scripts' ) ? 'login' : 'svabg-recaptcha-badge'; if ( 'login' !== $handle ) { wp_register_style( $handle, false, array(), SOFTVOLT_AI_BODYGUARD_VERSION ); wp_enqueue_style( $handle ); } wp_add_inline_style( $handle, '.grecaptcha-badge{visibility:hidden!important}' ); } /** * Contact Form 7: a failed check marks the message as spam. * * @param bool $spam Already spam. * @param mixed $submission WPCF7_Submission. * @return bool */ public static function check_cf7( $spam, $submission = null ) { if ( $spam ) { return $spam; } $ok = self::verify( 'cf7' ); if ( is_wp_error( $ok ) ) { if ( is_object( $submission ) && method_exists( $submission, 'add_spam_log' ) ) { $submission->add_spam_log( array( 'agent' => 'svabg_recaptcha', 'reason' => $ok->get_error_message(), ) ); } return true; } return $spam; } /** * WPForms: a failed check stops the entry with a message above the form. * * @param array $fields Fields. * @param array $entry Entry. * @param array $form_data Form. */ public static function check_wpforms( $fields, $entry, $form_data ) { $ok = self::verify( 'wpforms' ); if ( ! is_wp_error( $ok ) || ! function_exists( 'wpforms' ) ) { return; } $wpforms = wpforms(); $process = is_object( $wpforms ) && method_exists( $wpforms, 'get' ) ? $wpforms->get( 'process' ) : ( isset( $wpforms->process ) ? $wpforms->process : null ); if ( is_object( $process ) ) { $id = isset( $form_data['id'] ) ? $form_data['id'] : 0; $process->errors[ $id ]['header'] = $ok->get_error_message(); } } /** * Elementor Pro forms: a failed check is a form error. * * @param mixed $record Form record. * @param mixed $ajax_handler Ajax handler. */ public static function check_elementor( $record, $ajax_handler ) { $ok = self::verify( 'elementor' ); if ( ! is_wp_error( $ok ) || ! is_object( $ajax_handler ) ) { return; } if ( method_exists( $ajax_handler, 'add_error' ) ) { $ajax_handler->add_error( 'svabg_recaptcha', $ok->get_error_message() ); } if ( method_exists( $ajax_handler, 'add_error_message' ) ) { $ajax_handler->add_error_message( $ok->get_error_message() ); } } /** * Check a token from the "Test the keys" button. * * @param string $token Token made in the admin. * @return array|WP_Error success, score, hostname, action, errors. */ public static function test_token( $token ) { if ( ! self::keys_set() ) { return new WP_Error( 'svabg_captcha', __( 'Save the site key and the secret key first.', 'ai-guardwall' ) ); } $res = self::remote( 'https://www.google.com/recaptcha/api/siteverify', sanitize_text_field( (string) $token ) ); if ( true === $res ) { return new WP_Error( 'svabg_captcha', __( 'Google could not be reached from this server.', 'ai-guardwall' ) ); } if ( ! is_array( $res ) ) { return new WP_Error( 'svabg_captcha', __( 'Google did not answer.', 'ai-guardwall' ) ); } $errors = isset( $res['error-codes'] ) ? (array) $res['error-codes'] : array(); return array( 'success' => ! empty( $res['success'] ), 'score' => isset( $res['score'] ) ? (float) $res['score'] : null, 'hostname' => isset( $res['hostname'] ) ? (string) $res['hostname'] : '', 'errors' => $errors, 'message' => ! empty( $res['success'] ) ? sprintf( /* translators: 1: value, 2: value */ __( 'The keys work. Google scored this browser %1$s (forms need %2$s).', 'ai-guardwall' ), isset( $res['score'] ) ? $res['score'] : '?', (int) Softvolt_Ai_Bodyguard_Settings::get( 'captcha_v3_threshold', 5 ) / 10 ) : sprintf( /* translators: %s: value */ __( 'Google refused the check: %s. Make sure the keys are reCAPTCHA v3 keys and this domain is listed for them.', 'ai-guardwall' ), $errors ? implode( ', ', $errors ) : __( 'unknown reason', 'ai-guardwall' ) ), ); } }