Encryption.php 12.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
<?php
/**
 * Class Encryption
 *
 * @package ContentControl\Vendor\TrustedLogin\Client
 *
 * @copyright 2021 Katz Web Services, Inc.
 *
 * @license GPL-2.0-or-later
 * Modified by code-atlantic on 21-June-2024 using {@see https://github.com/BrianHenryIE/strauss}.
 */
namespace ContentControl\Vendor\TrustedLogin;

// Exit if accessed directly
if ( ! defined('ABSPATH') ) {
	exit;
}

use \Exception;
use \WP_Error;
use \Sodium;

final class Encryption {

	/**
	 * @var Config $config
	 */
	private $config;

	/**
	 * @var Remote $remote
	 */
	private $remote;

	/**
	 * @var Logging
	 */
	private $logging;

	/**
	 * @var string $vendor_public_key_option Where the plugin should store the public key for encrypting data
	 * @since 1.0.0
	 */
	private $vendor_public_key_option;

	/**
	 * @var string Endpoint path to Vendor public key.
	 */
	private $vendor_public_key_endpoint = '/trustedlogin/v1/public_key';

	/**
	 * @var int How long to store the Vendor public key in the database.
	 * @since 1.7.0
	 */
	const VENDOR_PUBLIC_KEY_EXPIRY = 60 * 10; // 10 minutes.

	/**
	 * Encryption constructor.
	 *
	 * @param Config $config
	 * @param Remote $remote
	 * @param Logging $logging
	 */
	public function __construct( Config $config, Remote $remote, Logging $logging ) {

		$this->config  = $config;
		$this->remote  = $remote;
		$this->logging = $logging;

		/**
		 * Filter: Sets the site option name for the Public Key for encryption functions
		 *
		 * @since 1.0.0
		 *
		 * @param string $vendor_public_key_option
		 * @param Config $config
		 */
		$this->vendor_public_key_option = apply_filters(
			'trustedlogin/' . $this->config->ns() . '/options/vendor_public_key',
			'tl_' . $this->config->ns() . '_vendor_public_key',
			$this->config
		);
	}

	/**
	 * Returns true if the site supports encryption using the required Sodium functions.
	 *
	 * These functions are available by extension in PHP 7.0 & 7.1, built-in to PHP 7.2+ and WordPress 5.2+.
	 *
	 * @since 1.4.0
	 *
	 * @return bool True: supports encryption. False: does not support encryption.
	 */
	static public function meets_requirements() {

		$required_functions = array(
			'random_bytes',
			'sodium_hex2bin',
			'sodium_crypto_box',
			'sodium_crypto_secretbox',
			'sodium_crypto_generichash',
			'sodium_crypto_box_keypair_from_secretkey_and_publickey',
		);

		foreach ( $required_functions as $function ) {
			if ( ! function_exists( $function ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Generates a random hash 64 characters long.
	 *
	 * If random_bytes() and openssl_random_pseudo_bytes() don't exist, returns WP_Error with code generate_hash_failed.
	 *
	 * If random_bytes() does not exist and openssl_random_pseudo_bytes() is unable to return a strong result,
	 * returns a WP_Error with code `openssl_not_strong_crypto`.
	 *
	 * @uses random_bytes
	 * @uses openssl_random_pseudo_bytes Only used if random_bytes() does not exist.
	 *
	 * @param Logging The logging object to use
	 *
	 * @return string|WP_Error 64-character random hash or a WP_Error object explaining what went wrong. See docblock.
	 */
	static public function get_random_hash( $logging ) {

		$byte_length = 64;

		$hash = false;

		if ( function_exists( 'random_bytes' ) ) {
			try {
				$bytes = random_bytes( $byte_length );
				$hash  = bin2hex( $bytes );
			} catch ( \TypeError $e ) {
				$logging->log( $e->getMessage(), __METHOD__, 'error' );
			} catch ( \Error $e ) {
				$logging->log( $e->getMessage(), __METHOD__, 'error' );
			} catch ( \Exception $e ) {
				$logging->log( $e->getMessage(), __METHOD__, 'error' );
			}
		} else {
			$logging->log( 'This site does not have the random_bytes() function.', __METHOD__, 'debug' );
		}

		if ( $hash ) {
			return $hash;
		}

		if ( ! function_exists( 'openssl_random_pseudo_bytes' ) ) {
			return new \WP_Error( 'generate_hash_failed', 'Could not generate a secure hash with random_bytes or openssl.' );
		}

		$crypto_strong = false;
		$hash          = openssl_random_pseudo_bytes( $byte_length, $crypto_strong );

		if ( ! $crypto_strong ) {
			return new \WP_Error( 'openssl_not_strong_crypto', 'Site could not generate a secure hash with OpenSSL.' );
		}

		return $hash;
	}

	/**
	 * @param $string
	 *
	 * @return string|WP_Error
	 */
	static public function hash( $string, $length = 16 ) {

		if ( ! function_exists( 'sodium_crypto_generichash' ) ) {
			return new \WP_Error( 'sodium_crypto_generichash_not_available', 'sodium_crypto_generichash not available' );
		}

		try {
			$hash_bin = sodium_crypto_generichash( $string, '', (int) $length );
			$hash     = sodium_bin2hex( $hash_bin );
		} catch ( \TypeError $e ) {
			return new \WP_Error(
				'encryption_failed_generichash_typeerror',
				sprintf( 'Error while generating hash: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		} catch ( \Error $e ) {
			return new \WP_Error(
				'encryption_failed_generichash_error',
				sprintf( 'Error while generating hash: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		} catch ( \SodiumException $e ) {
			return new \WP_Error(
				'encryption_failed_generichash_sodium',
				sprintf( 'Error while generating hash: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		} catch ( \Exception $e ) {
			return new \WP_Error(
				'encryption_failed_generichash',
				sprintf( 'Error while generating hash: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		}

		return $hash;
	}

	/**
	 * Fetches the Public Key from local or db
	 *
	 * @since 1.0.0
	 *
	 * @return string|WP_Error  If found, it returns the publicKey, if not a WP_Error
	 */
	public function get_vendor_public_key() {

		// Already stored as transient
		$public_key = Utils::get_transient( $this->vendor_public_key_option );

		if ( $public_key ) {
			// Documented below
			return apply_filters( 'trustedlogin/' . $this->config->ns() . '/vendor_public_key', $public_key, $this->config );
		}

		// Fetch a key from Vendor site
		$remote_key = $this->get_remote_encryption_key();

		if ( is_wp_error( $remote_key ) ) {

			$this->logging->log( sprintf( '(%s) %s', $remote_key->get_error_code(), $remote_key->get_error_message() ), __METHOD__, 'error' );

			return $remote_key;
		}

		// Store Vendor public key in the DB for ten minutes.
		$saved = Utils::set_transient( $this->vendor_public_key_option, $remote_key, self::VENDOR_PUBLIC_KEY_EXPIRY );

		if ( ! $saved ) {
			$this->logging->log( 'Public key not saved after being fetched remotely.', __METHOD__, 'warning' );
		}

		/**
		 * Filter: Override the public key functions.
		 *
		 * @since 1.0.0
		 *
		 * @param string $vendor_public_key
		 * @param Config $config
		 */
		return apply_filters( 'trustedlogin/' . $this->config->ns() . '/vendor_public_key', $remote_key, $this->config );
	}

	/**
	 * Returns the URL for the vendor public key endpoint.
	 *
	 * @since 1.5.0
	 *
	 * @return string URL for the vendor public key endpoint, after being filtered.
	 */
	public function get_remote_encryption_key_url() {

		$vendor_website = $this->config->get_setting( 'vendor/website', '' );

		/**
		 * @see https://docs.trustedlogin.com/Client/hooks#trustedloginnamespacevendorpublic_keywebsite
		 * @since 1.3.2
		 * @param string $public_key_website Root URL of the website from where the vendor's public key is fetched. May be different than the vendor/website configuration setting.
		 */
		$public_key_website = apply_filters( 'trustedlogin/' . $this->config->ns() . '/vendor/public_key/website', $vendor_website );

		/**
		 * @see https://docs.trustedlogin.com/Client/hooks#trustedloginnamespacevendorpublic_keyendpoint
		 * @param string $key_endpoint Endpoint path on vendor (software vendor's) site.
		 */
		$key_endpoint = apply_filters( 'trustedlogin/' . $this->config->ns() . '/vendor/public_key/endpoint', $this->vendor_public_key_endpoint );

		$public_key_url = add_query_arg( array( 'rest_route' => $key_endpoint ), trailingslashit( $public_key_website ) );

		return $public_key_url;
	}

	/**
	 * Fetches the Public Key from the `TrustedLogin-vendor` plugin on support website.
	 *
	 * @since 1.0.0
	 *
	 * @return string|WP_Error  If successful, will return the Public Key string. Otherwise WP_Error on failure.
	 */
	private function get_remote_encryption_key() {

		$headers = array(
			'Accept'       => 'application/json',
			'Content-Type' => 'application/json',
		);

		$request_options = array(
			'method'      => 'GET',
			'timeout'     => 45,
			'httpversion' => '1.1',
			'headers'     => $headers
		);

		$url = $this->get_remote_encryption_key_url();

		$response = wp_remote_request( $url, $request_options );

		$response_json = $this->remote->handle_response( $response, array( 'publicKey' ) );

		if ( is_wp_error( $response_json ) ) {

			if ( 'not_found' == $response_json->get_error_code() ){
				return new \WP_Error( 'not_found', __( 'Encryption key could not be fetched, Vendor site returned 404.', 'trustedlogin' ) );
			}

			return $response_json;
		}

		return $response_json['publicKey'];
	}

	/**
	 * Encrypts a string using the Public Key provided by the plugin/theme developers' server.
	 *
	 * @since 1.0.0
	 * @uses \sodium_crypto_box_keypair_from_secretkey_and_publickey() to generate key.
	 * @uses \sodium_crypto_secretbox() to encrypt.
	 *
	 * @param string $data Data to encrypt.
	 * @param string $nonce The nonce generated for this encryption.
	 * @param string $alice_secret_key The key to use when generating the encryption key.
	 *
	 * @return string|WP_Error  Encrypted envelope or WP_Error on failure.
	 */
	public function encrypt( $data, $nonce, $alice_secret_key ) {

		if ( empty( $data ) ) {
			return new \WP_Error( 'no_data', 'No data provided.' );
		}

		if ( ! function_exists( 'sodium_crypto_secretbox' ) ) {
			return new \WP_Error( 'sodium_crypto_secretbox_not_available', 'lib_sodium not available' );
		}

		$bob_public_key = $this->get_vendor_public_key();

		if ( is_wp_error( $bob_public_key ) ) {
			return $bob_public_key;
		}

		try {

			$alice_to_bob_kp = sodium_crypto_box_keypair_from_secretkey_and_publickey( $alice_secret_key, \sodium_hex2bin( $bob_public_key ) );
			$encrypted       = sodium_crypto_box( $data, $nonce, $alice_to_bob_kp );

		} catch ( \SodiumException $e ) {
			return new \WP_Error(
				'encryption_failed_cryptobox',
				sprintf( 'Error while encrypting the envelope: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		} catch ( \RangeException $e ) {
			return new \WP_Error(
				'encryption_failed_cryptobox_rangeexception',
				sprintf( 'Error while encrypting the envelope: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		} catch ( \TypeError $e ) {
			return new \WP_Error(
				'encryption_failed_cryptobox_typeerror',
				sprintf( 'Error while encrypting the envelope: %s (%s)', $e->getMessage(), $e->getCode() )
			);
		}

		return base64_encode( $encrypted );
	}

	/**
	 * Gets and returns a random nonce.
	 *
	 * @since 1.0.0
	 *
	 * @return string|WP_Error  Nonce if created, otherwise WP_Error
	 */
	public function get_nonce() {

		if ( ! function_exists( 'random_bytes' ) ) {
			return new \WP_Error( 'missing_function', 'No random_bytes function installed.' );
		}

		try {
			$nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
		} catch ( \Exception $e ) {
			return new \WP_Error( 'encryption_failed_randombytes', sprintf( 'Unable to generate encryption nonce: %s (%s)', $e->getMessage(), $e->getCode() ) );
		}

		return $nonce;
	}

	/**
	 * Generate unique Client encryption keys.
	 *
	 * @since 1.0.0
	 *
	 * @uses sodium_crypto_box_keypair()
	 * @uses sodium_crypto_box_publickey()
	 * @uses sodium_crypto_box_secretkey()
	 *
	 * @return object|WP_Error $alice_keys or WP_Error if there's any issues.
	 *   $alice_keys = [
	 *      'publicKey'  =>  (string)  The public key.
	 *      'privateKey' =>  (string)  The private key.
	 *   ]
	 */
	public function generate_keys() {

		if ( ! function_exists( 'sodium_crypto_box_keypair' ) ) {
			return new \WP_Error( 'sodium_crypto_secretbox_not_available', 'lib_sodium not available' );
		}

		// In our build Alice = Client & Bob = Vendor.
		$aliceKeypair = sodium_crypto_box_keypair();

		$alice_keys = array(
			'publicKey'  => sodium_crypto_box_publickey( $aliceKeypair ),
			'privateKey' => sodium_crypto_box_secretkey( $aliceKeypair )
		);

		return (object) $alice_keys;
	}
}