$samples One entry per 15 minutes: time, attempts, declines. * @param int $now Unix time. * @return float */ public static function baseline( array $samples, $now ) { $from = (int) $now - self::BASELINE_DAYS * 86400; $total = 0; $count = 0; foreach ( $samples as $sample ) { if ( isset( $sample[0], $sample[2] ) && (int) $sample[0] >= $from ) { $total += (int) $sample[2]; ++$count; } } return $count > 0 ? (float) ( $total / $count ) : 0.0; } /** * Which trigger, if any, says an attack is under way. * * @param array $s Numbers: declines15 and attempts15 (last 15 minutes), stopped5 (blocked or * challenged in the last 5 minutes) and baseline15 (normal declines per 15 minutes). * @return string '' or 'declines', 'decline_rate', 'blocked_burst'. */ public static function trigger( array $s ) { $declines = isset( $s['declines15'] ) ? (int) $s['declines15'] : 0; $attempts = isset( $s['attempts15'] ) ? (int) $s['attempts15'] : 0; $stopped = isset( $s['stopped5'] ) ? (int) $s['stopped5'] : 0; $baseline = isset( $s['baseline15'] ) ? (float) $s['baseline15'] : 0.0; // Declines in the last 15 minutes at least the larger of 10 and 5 × the baseline. if ( $declines >= max( 10, 5 * $baseline ) ) { return 'declines'; } // Decline rate of 60% or more with at least 8 attempts in 15 minutes. if ( $attempts >= 8 && $declines / $attempts >= 0.6 ) { return 'decline_rate'; } // 20 or more blocked or challenged requests in 5 minutes. if ( $stopped >= 20 ) { return 'blocked_burst'; } return ''; } /** * Whether an automatic lockdown should end: 60 straight minutes below every trigger. * * @param int $quiet_since Unix time since when every trigger has been quiet (0 = not quiet). * @param int $now Unix time. * @return bool */ public static function should_end( $quiet_since, $now ) { return $quiet_since > 0 && (int) $now - (int) $quiet_since >= self::QUIET_SECONDS; } }