| 1 |
<?php |
| 2 |
/** |
| 3 |
* Responsible for handling ALTCHA. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component; |
| 9 |
|
| 10 |
use WP_Defender\Component\Altcha\Challenge; |
| 11 |
use WP_Defender\Component\Altcha\Challenge_Options; |
| 12 |
use WP_Defender\Component\Altcha\Altcha; |
| 13 |
use WP_Defender\Component\Altcha\Hasher\Algorithm; |
| 14 |
|
| 15 |
/** |
| 16 |
* Provides methods for creating and verifying Altcha's challenge. |
| 17 |
*/ |
| 18 |
class Altcha_Handler { |
| 19 |
|
| 20 |
/** |
| 21 |
* The log file name. |
| 22 |
*/ |
| 23 |
public const LOG_FILE_NAME = 'altcha.log'; |
| 24 |
|
| 25 |
/** |
| 26 |
* The HMAC key used for generating and verifying challenges. |
| 27 |
* |
| 28 |
* @var string |
| 29 |
*/ |
| 30 |
private $hmac_key; |
| 31 |
|
| 32 |
/** |
| 33 |
* The option name for the HMAC key. |
| 34 |
*/ |
| 35 |
public const HMAC_KEY_OPTION_NAME = 'wpdef_hmac_key'; |
| 36 |
|
| 37 |
/** |
| 38 |
* Constructor for Altcha_Handler class. |
| 39 |
*/ |
| 40 |
public function __construct() { |
| 41 |
$this->hmac_key = $this->get_hmac_key(); |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Generate or retrieve the HMAC key from the WordPress options. |
| 46 |
* |
| 47 |
* @return string The HMAC key. |
| 48 |
*/ |
| 49 |
private function get_hmac_key() { |
| 50 |
$hmac_key = get_option( self::HMAC_KEY_OPTION_NAME ); |
| 51 |
|
| 52 |
if ( ! is_string( $hmac_key ) || '' === trim( $hmac_key ) ) { |
| 53 |
// Generate a random key if it doesn't exist. |
| 54 |
$hmac_key = wp_generate_password( 64, true, true ); |
| 55 |
|
| 56 |
update_option( self::HMAC_KEY_OPTION_NAME, $hmac_key ); |
| 57 |
} |
| 58 |
|
| 59 |
return $hmac_key; |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Create a new ALTCHA challenge. |
| 64 |
* |
| 65 |
* @param int $max_number Maximum random number for the challenge. |
| 66 |
* |
| 67 |
* @return Challenge Challenge data. |
| 68 |
*/ |
| 69 |
public function create_challenge( $max_number = 100000 ): Challenge { |
| 70 |
$altcha = new Altcha( $this->hmac_key ); |
| 71 |
|
| 72 |
// Create a new challenge. |
| 73 |
$options = new Challenge_Options( |
| 74 |
Algorithm::SHA256, |
| 75 |
$max_number, |
| 76 |
( new \DateTimeImmutable() )->add( new \DateInterval( 'PT10S' ) ) |
| 77 |
); |
| 78 |
|
| 79 |
return $altcha->create_challenge( $options ); |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Verify the given solution against the challenge. |
| 84 |
* |
| 85 |
* @param array $payload Payload containing the solution details. |
| 86 |
* @param bool $strict_mode Enable or disable strict verification. |
| 87 |
* |
| 88 |
* @return bool Verification result. |
| 89 |
*/ |
| 90 |
public function verify_solution( array $payload, $strict_mode = true ) { |
| 91 |
$altcha = new Altcha( $this->hmac_key ); |
| 92 |
|
| 93 |
return $altcha->verify_solution( $payload, $strict_mode ); |
| 94 |
} |
| 95 |
} |
| 96 |
|