*/ private static $queue = array(); /** * Whether the shutdown handler is registered. * * @var bool */ private static $hooked = false; /** * Whether something happened that may start or end an attack. * * @var bool */ private static $check_attack = false; /** * Decides one payment attempt. Fails open. * * @param array $context See Context::build(). * @return array{decision:string,score:int,reasons:string[],signals:array,message:string,code:string,ms:float} */ public static function decide( $context = array() ) { $started = microtime( true ); try { $result = self::run( is_array( $context ) ? $context : array() ); } catch ( \Throwable $error ) { Util::log_error( 'Checkout decision failed, order allowed', $error ); $result = array( 'decision' => Score::ALLOW, 'score' => 0, 'reasons' => array(), 'signals' => array(), 'message' => '', 'code' => '', ); } $result['ms'] = round( ( microtime( true ) - $started ) * 1000, 2 ); return $result; } /** * The decision itself. * * @param array $context Context values. * @return array */ private static function run( array $context ) { $c = Context::build( $context ); $now = time(); $settings = Settings::get(); $secret = Settings::secret(); $lockdown = Lockdown::is_on(); $last = count( self::$queue ) - 1; // A block checkout is decided twice in one request: early, then again once the order is known. $previous = ( $last >= 0 && self::$queue[ $last ]['route'] === $c['route'] && empty( self::$queue[ $last ]['final'] ) ) ? self::$queue[ $last ] : null; $token = Token::verify( $c['token'], $secret, $c['prefix'], $c['ua_hash'], $now ); $device = $token['device']; $email_hash = '' !== $c['email_norm'] ? Settings::email_hash( $c['email_norm'] ) : ''; $guest = 0 === $c['user_id']; $pass_valid = $token['signed'] && '' !== $c['pass'] && Token::verify_pass( $c['pass'], $secret, $token['sid'], $c['prefix'], $c['ua_hash'], $now ); $keys = array( 'ip' => $c['ip'], 'prefix' => $c['prefix'], 'email' => $email_hash, 'device' => $device, 'order' => $c['order_id'] > 0 ? (string) $c['order_id'] : '', ); $marks = Blocks::lookup( $keys, $now ); // An email address typed at checkout proves nothing: anyone can type someone else's. It only // counts towards trust when it is the address of the account the visitor is signed in to. $email_proven = ! $guest && self::is_account_email( $c['user_id'], $c['email_norm'] ); // "Real customer" marks on an internet address or a device stand on their own: the address is // the connection itself and the device comes from a token this site signed. A mark on an // email address needs the proof above. $allow_mark = ! empty( array_diff( $marks['allow_types'], $email_proven ? array() : array( 'email' ) ) ); // Who is always allowed. $trusted = ''; if ( $settings['allowStaff'] && ! $guest && user_can( $c['user_id'], 'manage_woocommerce' ) ) { $trusted = 'staff'; } elseif ( '' !== $c['ip'] && \Brickmoat\Engine\Ip::in_list( $c['ip'], (array) $settings['allowIps'] ) ) { $trusted = 'allowlist'; } elseif ( $email_proven && self::email_allowed( $c['email_norm'], (array) $settings['allowEmails'] ) ) { $trusted = 'allowlist'; } elseif ( $allow_mark ) { $trusted = 'allowlist'; } elseif ( ! $marks['manual'] && $settings['allowReturningCustomers'] && ! $guest && self::has_completed_order( $c['user_id'] ) ) { $trusted = 'customer'; } // Count the attempt (once per request) and read this visitor's recent history. $counter_keys = array( 'ip' => Counters::key( 'ip', $c['ip'] ), 'prefix' => Counters::key( 'px', $c['prefix'] ), 'email' => '' !== $email_hash ? Counters::key( 'em', $email_hash ) : '', 'device' => '' !== $device ? Counters::key( 'dv', $device ) : '', 'order' => $c['order_id'] > 0 ? Counters::key( 'or', (string) $c['order_id'] ) : '', 'sid' => $token['signed'] ? Counters::key( 'tk', $token['sid'] ) : '', ); if ( null === $previous ) { $hits = array( 'g:a' ); if ( '' !== $c['ip'] ) { $hits[] = 'a:' . $counter_keys['ip']; } if ( $token['signed'] ) { $hits[] = 'u:' . $counter_keys['sid']; if ( $pass_valid ) { $hits[] = 'p:' . $counter_keys['sid']; } } Counters::hit( $hits, $now ); } $facts = array( 'trusted' => $trusted, 'guest' => $guest, 'total' => $c['total'], ); $hosting = Ip_Data::hosting( $c['ip'] ); $country = Geo::country( $c['ip'] ); $network = 0; $limits = self::limits(); if ( '' === $trusted ) { $wanted = array(); if ( '' !== $c['ip'] ) { $wanted['ip_attempts'] = array( 'a:' . $counter_keys['ip'], 600 ); $wanted['ip_declines'] = array( 'd:' . $counter_keys['ip'], 600 ); $wanted['prefix_declines'] = array( 'd:' . $counter_keys['prefix'], 600 ); } if ( '' !== $counter_keys['email'] ) { $wanted['email_declines'] = array( 'd:' . $counter_keys['email'], DAY_IN_SECONDS ); } if ( '' !== $counter_keys['device'] ) { $wanted['device_declines'] = array( 'd:' . $counter_keys['device'], HOUR_IN_SECONDS ); $wanted['device_declines_day'] = array( 'd:' . $counter_keys['device'], DAY_IN_SECONDS ); } if ( '' !== $counter_keys['order'] ) { $wanted['order_retries'] = array( 'd:' . $counter_keys['order'], DAY_IN_SECONDS ); } if ( '' !== $counter_keys['sid'] ) { $wanted['token_uses'] = array( 'u:' . $counter_keys['sid'], Token::MAX_AGE ); $wanted['pass_uses'] = array( 'p:' . $counter_keys['sid'], Token::PASS_TTL ); } $counts = Counters::sums( $wanted, $now ); $count = static function ( $name ) use ( $counts ) { return isset( $counts[ $name ] ) ? (int) $counts[ $name ] : 0; }; $has_pass = $pass_valid && $count( 'pass_uses' ) <= Token::PASS_MAX_USES; $token_age = $token['signed'] ? (int) $token['age'] : null; if ( ! $token['ok'] && 'young' === $token['reason'] && $has_pass ) { // Someone who just passed the "I'm human" check with a brand-new token is not "too fast". $token_state = 'ok'; $token_age = null; } elseif ( ! $token['ok'] ) { $token_state = 'missing' === $token['reason'] ? 'missing' : 'invalid'; } else { $token_state = $count( 'token_uses' ) > Token::MAX_USES ? 'reused' : 'ok'; } $identities = Events::identities_for_ip( $c['ip'], $now - HOUR_IN_SECONDS ); $emails = $identities['emails']; $names = $identities['names']; if ( '' !== $email_hash && ! in_array( $email_hash, $emails, true ) ) { $emails[] = $email_hash; } if ( '' !== $c['addr_hash'] && ! in_array( $c['addr_hash'], $names, true ) ) { $names[] = $c['addr_hash']; } // The list of bots seen on other stores, when the Brickmoat service has supplied one. $network = Network::lookup( $c['ip'], $c['prefix'], $device, $now ); /** * Filters the basket total (in the store currency) under which a one-item guest order * counts as the classic card-test basket. * * @param float $total Default 2.00. */ $small_total = (float) apply_filters( 'brickmoat_small_basket_total', 2.0 ); $small = $guest && 1 === $c['items'] && null !== $c['total'] && $c['total'] < $small_total; $facts = array_merge( $facts, array( 'honeypot' => '' !== $c['honeypot'], 'blocked' => $marks['block'] ? (string) $marks['block']['reason'] : '', 'token' => $token_state, 'token_age' => $token_age, 'network' => $network, 'headless' => (bool) $c['headless'], 'origin_unknown' => (bool) $c['origin_unknown'], 'ip_identities' => max( count( $emails ), count( $names ) ), 'hosting' => '' !== $hosting, 'small_basket' => $small, 'basket_text' => $small ? Util::money_text( $c['total'] ) : '', 'recent_decline' => $count( 'email_declines' ) > 0 || $count( 'device_declines_day' ) > 0, 'disposable' => '' !== $c['email_norm'] && Ip_Data::is_disposable( $c['email_norm'] ), 'ip_country' => $country, 'billing_country' => $c['billing_country'], 'account_age_days' => $guest ? null : self::account_age_days( $c['user_id'], $now ), 'paid_device' => $marks['trust'], 'velocity' => Limits::evaluate( $counts, $limits ), 'has_pass' => $has_pass, ) ); if ( '' === $facts['blocked'] && $marks['block'] ) { $facts['blocked'] = 'velocity_ip_declines'; } } $options = array( 'level' => $settings['level'], 'lockdown' => $lockdown, 'challenge_guests' => (bool) $settings['challengeGuestsInLockdown'], 'block_unknown' => (bool) $settings['blockUnknownInLockdown'], 'guest_minimum' => $settings['guestMinimumInLockdown'], 'identities_limit' => isset( $limits['ip_identities']['limit'] ) ? (int) $limits['ip_identities']['limit'] : 4, ); $result = Score::evaluate( $facts, $options ); // Stores connected to the Brickmoat service: one live question to the service about the email, // only for a guest who already looks a little risky. $email_checked = null !== $previous && ! empty( $previous['email_checked'] ); if ( '' === $trusted && $guest && '' !== $c['email_norm'] && 0 === $network && ! $email_checked && $result['score'] >= 15 && Score::BLOCK !== $result['decision'] && Licence::service_on() ) { $email_checked = true; $listed = Network::email_check( $c['email_norm'] ); if ( $listed > 0 ) { $network = $listed; $facts['network'] = $listed; $result = Score::evaluate( $facts, $options ); } } elseif ( null !== $previous && ! empty( $previous['email_listed'] ) && 0 === $network ) { $network = (int) $previous['email_listed']; $facts['network'] = $network; $result = Score::evaluate( $facts, $options ); } $attempt = array( 'ts' => $now, 'route' => $c['route'], 'decision' => $result['decision'], 'score' => $result['score'], 'reasons' => $result['reasons'], 'signals' => $result['signals'], 'ip' => $c['ip'], 'ip_prefix' => $c['prefix'], 'country' => $country, 'hosting' => substr( $hosting, 0, 40 ), 'email_hash' => $email_hash, 'device_hash' => $device, 'addr_hash' => $c['addr_hash'], 'sid' => $token['signed'] ? substr( $token['sid'], 0, 40 ) : '', 'user_id' => $c['user_id'], 'order_id' => $c['order_id'], 'outcome' => Score::BLOCK === $result['decision'] ? 'blocked' : 'unknown', 'passed' => $result['passed'] ? 1 : 0, 'network' => $network > 0 ? 1 : 0, 'policy' => $result['policy_only'] ? 1 : 0, 'gateway' => $c['gateway'], 'total' => $c['total'], 'items' => $c['items'], // Kept in memory only, for this request. 'final' => 'early' !== $c['stage'] || Score::ALLOW !== $result['decision'], 'trusted' => $trusted, 'email_norm' => $c['email_norm'], 'email_checked' => $email_checked, 'email_listed' => $network > 0 && $email_checked ? $network : 0, ); if ( null !== $previous ) { self::$queue[ $last ] = $attempt; } else { self::$queue[] = $attempt; } if ( ! self::$hooked ) { self::$hooked = true; // Late, so WooCommerce has finished with the order by the time the log is written. add_action( 'shutdown', array( __CLASS__, 'flush' ), 1000 ); } $message = ''; $code = ''; if ( Score::BLOCK === $result['decision'] ) { $code = 'brickmoat_blocked'; /** * Filters the message a blocked visitor sees. It must not say why they were blocked. * * @param string $message The message. */ $message = (string) apply_filters( 'brickmoat_block_message', __( 'Sorry, we could not process your order. Please try again later or contact us for help.', 'brickmoat' ) ); } elseif ( Score::CHALLENGE === $result['decision'] ) { $code = 'brickmoat_challenge_required'; /** * Filters the message a visitor sees when asked to prove they are human. * * @param string $message The message. */ $message = (string) apply_filters( 'brickmoat_challenge_message', __( 'One quick check before we take your payment: please tick “I’m human”, then place your order again.', 'brickmoat' ) ); } return array( 'decision' => $result['decision'], 'score' => $result['score'], 'reasons' => $result['reasons'], 'signals' => Signals::to_rest( $result['signals'] ), 'message' => $message, 'code' => $code, ); } /** * The velocity limits in force. * * @return array */ public static function limits() { /** * Filters the velocity limits. See Brickmoat\Engine\Limits::defaults() for the shape. * * @param array $limits Limits. */ $limits = apply_filters( 'brickmoat_limits', Limits::defaults() ); return is_array( $limits ) ? array_merge( Limits::defaults(), $limits ) : Limits::defaults(); } /** * Whether an email is on the merchant's always-allow list. * * @param string $normalised Normalised address. * @param string[] $allowed The list as saved. * @return bool */ private static function email_allowed( $normalised, array $allowed ) { foreach ( $allowed as $entry ) { if ( \Brickmoat\Engine\Email::normalise( $entry ) === $normalised ) { return true; } } return false; } /** * Whether an email address is the one on a signed-in visitor's own account. * * @param int $user_id User id (0 for a guest). * @param string $normalised Normalised address from the checkout. * @return bool */ private static function is_account_email( $user_id, $normalised ) { if ( (int) $user_id <= 0 || '' === (string) $normalised ) { return false; } $user = get_userdata( (int) $user_id ); if ( ! $user || empty( $user->user_email ) ) { return false; } return \Brickmoat\Engine\Email::normalise( (string) $user->user_email ) === $normalised; } /** * Whether a customer has at least one completed order. * * @param int $user_id User id. * @return bool */ public static function has_completed_order( $user_id ) { $user_id = (int) $user_id; if ( $user_id <= 0 ) { return false; } $known = get_user_meta( $user_id, '_brickmoat_completed', true ); if ( '1' === $known ) { return true; } $orders = wc_get_orders( array( 'customer_id' => $user_id, 'status' => array( 'wc-completed' ), 'limit' => 1, 'return' => 'ids', ) ); if ( ! empty( $orders ) ) { update_user_meta( $user_id, '_brickmoat_completed', '1' ); return true; } return false; } /** * Age of an account in days. * * @param int $user_id User id. * @param int $now Unix time. * @return int|null */ private static function account_age_days( $user_id, $now ) { $user = get_userdata( $user_id ); if ( ! $user || empty( $user->user_registered ) ) { return null; } $registered = strtotime( $user->user_registered . ' UTC' ); return false === $registered ? null : (int) floor( ( $now - $registered ) / DAY_IN_SECONDS ); } /** * The attempt decided most recently in this request. * * @return array|null */ public static function current() { $last = count( self::$queue ) - 1; return $last >= 0 ? self::$queue[ $last ] : null; } /** * Changes fields of the attempt decided most recently in this request. * * @param array $fields Fields to set. */ public static function update_current( array $fields ) { $last = count( self::$queue ) - 1; if ( $last >= 0 ) { self::$queue[ $last ] = array_merge( self::$queue[ $last ], $fields ); } } /** * Asks for the attack triggers to be checked once the response has been sent. */ public static function check_attack_later() { self::$check_attack = true; if ( ! self::$hooked ) { self::$hooked = true; add_action( 'shutdown', array( __CLASS__, 'flush' ), 1000 ); } } /** * After the response: writes the event log, counts what was stopped, and checks whether * an attack has started or ended. */ public static function flush() { if ( empty( self::$queue ) && ! self::$check_attack ) { return; } try { if ( function_exists( 'fastcgi_finish_request' ) ) { fastcgi_finish_request(); } elseif ( function_exists( 'litespeed_finish_request' ) ) { litespeed_finish_request(); } $queue = self::$queue; self::$queue = array(); $hits = array(); $needs_sweep = false; $check_attack = self::$check_attack; $pro = Licence::service_on(); $attack_id = Lockdown::attack_id(); foreach ( $queue as $attempt ) { // The order tells us how it ended when WooCommerce's hooks did not. if ( Score::ALLOW === $attempt['decision'] && 'unknown' === $attempt['outcome'] && $attempt['order_id'] > 0 ) { $attempt['outcome'] = Outcomes::outcome_from_order( $attempt['order_id'] ); if ( 'declined' === $attempt['outcome'] ) { Outcomes::count_decline( $attempt ); $check_attack = true; } } if ( Score::ALLOW !== $attempt['decision'] && ! $attempt['policy'] ) { $hits[] = 'g:s'; $check_attack = true; } if ( 'unknown' === $attempt['outcome'] ) { $needs_sweep = true; } $attempt['attack_id'] = $attack_id; if ( $pro && '' === $attempt['trusted'] ) { $type = ''; if ( Score::BLOCK === $attempt['decision'] ) { $type = 'block'; } elseif ( 'declined' === $attempt['outcome'] ) { $type = 'decline'; } if ( '' !== $type ) { $attempt['report_state'] = 1; $attempt['report_type'] = $type; $attempt['report_email'] = $attempt['email_norm']; } } $id = Events::insert( $attempt ); if ( $pro && 'paid' === $attempt['outcome'] && $id > 0 ) { Reporter::maybe_report_paid( $id, $attempt ); } } if ( ! empty( $hits ) ) { // One hit per stopped attempt. foreach ( $hits as $hit ) { Counters::hit( array( $hit ) ); } } self::$check_attack = false; if ( $check_attack ) { Lockdown::evaluate(); } if ( $needs_sweep ) { Scheduler::ensure_sweep(); } } catch ( \Throwable $error ) { Util::log_error( 'Writing the event log failed', $error ); } } /** * Forgets this request's attempts without writing them (tests, WP-CLI reset). */ public static function reset() { self::$queue = array(); self::$check_attack = false; } }