0 ) { $started = $first; } } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom table. $wpdb->insert( Schema::table( 'attacks' ), array( 'started' => $started, 'detected' => $now, 'trigger_name' => $trigger, 'baseline' => $baseline, ) ); $id = (int) $wpdb->insert_id; if ( $id > 0 ) { $events = Schema::table( 'events' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $wpdb->query( $wpdb->prepare( 'UPDATE %i SET attack_id = %d WHERE ts >= %d AND attack_id = 0', $events, $id, $started ) ); } return $id; } /** * Changes fields of an attack. * * @param int $id Attack id. * @param array $fields Column => value. */ public static function update( $id, array $fields ) { global $wpdb; if ( $id > 0 && ! empty( $fields ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- Custom table. $wpdb->update( Schema::table( 'attacks' ), $fields, array( 'id' => (int) $id ) ); } } /** * Adds to a counter column of an attack. * * @param int $id Attack id. * @param string $column emails_held or junk_cleaned. * @param int $by How many to add (may be negative). */ public static function add( $id, $column, $by ) { global $wpdb; if ( $id <= 0 || ! in_array( $column, array( 'emails_held', 'junk_cleaned' ), true ) ) { return; } $table = Schema::table( 'attacks' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table; the column comes from a fixed list. $wpdb->query( $wpdb->prepare( 'UPDATE %i SET %i = GREATEST(0, CAST(%i AS SIGNED) + %d) WHERE id = %d', $table, $column, $column, (int) $by, (int) $id ) ); } /** * One attack. * * @param int $id Attack id. * @return array|null */ public static function get( $id ) { global $wpdb; $table = Schema::table( 'attacks' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, (int) $id ), ARRAY_A ); return $row ? $row : null; } /** * Attacks, newest first. * * @param int $limit How many. * @param int $since Only attacks that were still running at or after this unix time. * @return array */ public static function all( $limit = 50, $since = 0 ) { global $wpdb; $table = Schema::table( 'attacks' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE ended = 0 OR ended >= %d ORDER BY started DESC, id DESC LIMIT %d', $table, (int) $since, (int) $limit ), ARRAY_A ); } /** * The most recent attack that has ended. * * @return array|null */ public static function latest_ended() { global $wpdb; $table = Schema::table( 'attacks' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE ended > 0 ORDER BY ended DESC LIMIT 1', $table ), ARRAY_A ); return $row ? $row : null; } /** * Closes an attack: fixes its end time and saves its numbers, because the event log * is only kept for days while attacks are kept for a year. * * @param int $id Attack id. */ public static function close( $id ) { $attack = self::get( $id ); if ( ! $attack || (int) $attack['ended'] > 0 ) { return; } $now = time(); $attack['ended'] = $now; $numbers = Events::totals( (int) $attack['started'], $now ); $data = array( 'minutes' => self::minutes( $attack ), 'sources' => self::sources( $attack ), 'networks' => Events::networks( (int) $attack['started'], $now ), 'protections' => self::protections( $attack ), ); self::update( $id, array( 'ended' => $now, 'attempts' => $numbers['attempts'], 'declined' => $numbers['declined'], 'blocked' => $numbers['blocked'], 'challenged' => $numbers['challenged'], 'unique_ips' => $numbers['unique_ips'], 'unique_devices' => $numbers['unique_devices'], 'details' => wp_json_encode( $data ), ) ); // Counted after the end time is saved, so the cleanup sees the final window. self::update( $id, array( 'junk_orders' => Cleanup::count_junk( self::get( $id ) ) ) ); } /** * Saved details of a closed attack. * * @param array $attack Attack row. * @return array */ private static function data( array $attack ) { $data = isset( $attack['details'] ) && is_string( $attack['details'] ) ? json_decode( $attack['details'], true ) : null; return is_array( $data ) ? $data : array(); } /** * An attack as an AttackSummary. Numbers of a running attack are counted live. * * @param array $attack Attack row. * @return array */ public static function summary( array $attack ) { $running = 0 === (int) $attack['ended']; if ( $running ) { $numbers = Events::totals( (int) $attack['started'], time() ); $junk = (int) get_transient( 'brickmoat_cleanup_pending' ); } else { $numbers = array( 'attempts' => (int) $attack['attempts'], 'declined' => (int) $attack['declined'], 'blocked' => (int) $attack['blocked'], 'challenged' => (int) $attack['challenged'], 'unique_ips' => (int) $attack['unique_ips'], 'unique_devices' => (int) $attack['unique_devices'], ); $junk = (int) $attack['junk_orders']; } // Either the store's own numbers set it off, or an administrator pressed "Start lockdown". $automatic = in_array( $attack['trigger_name'], array( 'declines', 'decline_rate', 'blocked_burst' ), true ); $trigger = $automatic ? $attack['trigger_name'] : 'manual'; $detected = $automatic ? max( 0, (int) $attack['detected'] - (int) $attack['started'] ) : null; return array( 'id' => (int) $attack['id'], 'startedAt' => Util::iso( (int) $attack['started'] ), 'endedAt' => $running ? null : Util::iso( (int) $attack['ended'] ), 'trigger' => $trigger, 'detectedInSeconds' => $detected, 'attempts' => $numbers['attempts'], 'declined' => $numbers['declined'], 'blocked' => $numbers['blocked'], 'challenged' => $numbers['challenged'], 'uniqueIps' => $numbers['unique_ips'], 'uniqueDevices' => $numbers['unique_devices'], 'junkOrders' => max( $junk, (int) $attack['junk_cleaned'] ), 'junkCleaned' => (int) $attack['junk_cleaned'], ); } /** * An attack as an AttackDetail. * * @param array $attack Attack row. * @return array */ public static function detail( array $attack ) { $running = 0 === (int) $attack['ended']; $data = $running ? array() : self::data( $attack ); $minutes = isset( $data['minutes'] ) ? $data['minutes'] : self::minutes( $attack ); $sources = isset( $data['sources'] ) ? $data['sources'] : self::sources( $attack ); $protect = isset( $data['protections'] ) ? $data['protections'] : self::protections( $attack ); $out_minutes = array(); foreach ( (array) $minutes as $minute ) { $out_minutes[] = array( 't' => Util::iso( (int) $minute[0] ), 'declines' => (int) $minute[1], 'attempts' => (int) $minute[2], ); } $total = 0; $out_sources = array(); foreach ( (array) $sources as $source ) { $total += (int) $source[2]; } foreach ( (array) $sources as $source ) { $out_sources[] = array( 'countryCode' => (string) $source[0], 'country' => '' !== $source[0] ? Geo::name( (string) $source[0] ) : __( 'Unknown country', 'brickmoat' ), 'kind' => $source[1] ? __( 'Rented servers', 'brickmoat' ) : __( 'Home or phone connections', 'brickmoat' ), 'attempts' => (int) $source[2], 'share' => $total > 0 ? round( (int) $source[2] / $total, 4 ) : 0, ); } $out_protect = array(); foreach ( (array) $protect as $protection ) { $out_protect[] = array( 'label' => self::protection_label( (string) $protection[0], isset( $protection[2] ) ? (string) $protection[2] : '' ), 'on' => (bool) $protection[1], ); } return array_merge( self::summary( $attack ), array( 'lockdownAt' => Util::iso( (int) $attack['lockdown_at'] ), 'minutes' => $out_minutes, 'baselinePerMinute' => round( (float) $attack['baseline'] / 15, 4 ), 'protections' => $out_protect, 'sources' => $out_sources, // A page hosted by the Brickmoat service, for stores connected to it. The report anyone can // download from this site is Report::html(). 'reportUrl' => '' !== (string) $attack['report_url'] ? (string) $attack['report_url'] : null, 'sharedWithNetwork' => (int) $attack['shared'] > 0, ) ); } /** * Declines and attempts per minute, from 10 minutes before the start to 20 minutes after * it (or until the end, when the attack was shorter). * * @param array $attack Attack row. * @return array Minute start, declines, attempts. */ public static function minutes( array $attack ) { $start = (int) $attack['started']; $from = intdiv( $start - 600, 60 ) * 60; $to = $start + 1200; $end = (int) $attack['ended'] > 0 ? (int) $attack['ended'] : time(); $to = intdiv( min( $to, max( $end, $start + 60 ) ), 60 ) * 60; $found = array(); foreach ( Events::per_minute( $from, $to + 59 ) as $row ) { $found[ (int) $row['m'] * 60 ] = array( (int) $row['declines'], (int) $row['attempts'] ); } $out = array(); for ( $t = $from; $t <= $to; $t += 60 ) { $out[] = array( $t, isset( $found[ $t ] ) ? $found[ $t ][0] : 0, isset( $found[ $t ] ) ? $found[ $t ][1] : 0 ); } return $out; } /** * Where the attack's attempts came from. * * @param array $attack Attack row. * @return array Country code, rented server (1/0), attempts. */ public static function sources( array $attack ) { $end = (int) $attack['ended'] > 0 ? (int) $attack['ended'] : time(); $out = array(); foreach ( Events::sources( (int) $attack['started'], $end ) as $row ) { $out[] = array( (string) $row['country'], (int) $row['rented'], (int) $row['n'] ); } return $out; } /** * What lockdown changed during this attack. * * @param array $attack Attack row. * @return array Key, on, extra text. */ public static function protections( array $attack ) { $locked = (int) $attack['lockdown_at'] > 0; $settings = Settings::get(); $list = array( array( 'skip_shop', $locked, '' ), array( 'guests_human', $locked && (bool) $settings['challengeGuestsInLockdown'], '' ), array( 'suspicious', $locked, '' ), array( 'unknown_source', $locked && (bool) $settings['blockUnknownInLockdown'], '' ), array( 'emails_paused', $locked, '' ), array( 'times_noted', true, '' ), ); if ( null !== $settings['guestMinimumInLockdown'] ) { $list[] = array( 'guest_minimum', $locked, Util::money_text( (float) $settings['guestMinimumInLockdown'] ) ); } return $list; } /** * The sentence for one protection. * * @param string $key Protection key. * @param string $extra Extra text (an amount). * @return string */ public static function protection_label( $key, $extra = '' ) { switch ( $key ) { case 'skip_shop': return __( 'Anyone who skips your shop and goes straight to payment is stopped', 'brickmoat' ); case 'guests_human': return __( 'Guest shoppers answer a quick “I’m human” question', 'brickmoat' ); case 'suspicious': return __( 'Anything even a little suspicious is stopped', 'brickmoat' ); case 'unknown_source': return __( 'Payments from unknown sources are stopped', 'brickmoat' ); case 'emails_paused': return __( 'Failed-order emails paused; you get one summary instead', 'brickmoat' ); case 'guest_minimum': /* translators: %s: an amount of money, e.g. "$5.00". */ return sprintf( __( 'Guest orders under %s are stopped', 'brickmoat' ), $extra ); } return __( 'We noted the attack times so the junk orders can be cleaned up', 'brickmoat' ); } /** * Deletes attacks that ended more than a year ago. */ public static function prune() { global $wpdb; $table = Schema::table( 'attacks' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- The plugin's own table. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE ended > 0 AND ended < %d', $table, time() - YEAR_IN_SECONDS ) ); } }