|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CrowdSecBouncer; |
| 4 | + |
| 5 | +require_once __DIR__.'/templates/captcha.php'; |
| 6 | +require_once __DIR__.'/templates/access-forbidden.php'; |
| 7 | + |
| 8 | +use IPLib\Factory; |
| 9 | +use Monolog\Formatter\LineFormatter; |
| 10 | +use Monolog\Handler\RotatingFileHandler; |
| 11 | +use Monolog\Logger; |
| 12 | +use Psr\Log\LoggerInterface; |
| 13 | + |
| 14 | +/** |
| 15 | + * The class that apply a bounce. |
| 16 | + * |
| 17 | + * @author CrowdSec team |
| 18 | + * |
| 19 | + * @see https://crowdsec.net CrowdSec Official Website |
| 20 | + * |
| 21 | + * @copyright Copyright (c) 2021+ CrowdSec |
| 22 | + * @license MIT License |
| 23 | + */ |
| 24 | +abstract class AbstractBounce |
| 25 | +{ |
| 26 | + /** @var array */ |
| 27 | + protected $settings = []; |
| 28 | + |
| 29 | + /** @var bool */ |
| 30 | + protected $debug = false; |
| 31 | + |
| 32 | + /** @var LoggerInterface */ |
| 33 | + protected $logger; |
| 34 | + |
| 35 | + /** @var Bouncer */ |
| 36 | + protected $bouncer; |
| 37 | + |
| 38 | + protected function getStringSettings(string $name): string |
| 39 | + { |
| 40 | + return $this->settings[$name]; |
| 41 | + } |
| 42 | + |
| 43 | + protected function getArraySettings(string $name): array |
| 44 | + { |
| 45 | + return $this->settings[$name]; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Run a bounce. |
| 50 | + */ |
| 51 | + public function run( |
| 52 | + ): void { |
| 53 | + if ($this->shouldBounceCurrentIp()) { |
| 54 | + $this->bounceCurrentIp(); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public function setDebug(bool $debug) |
| 59 | + { |
| 60 | + $this->debug = $debug; |
| 61 | + } |
| 62 | + |
| 63 | + protected function initLoggerHelper($logDirectoryPath, $loggerName): void |
| 64 | + { |
| 65 | + // Singleton for this function |
| 66 | + if ($this->logger) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + $this->logger = new Logger($loggerName); |
| 71 | + $logPath = $logDirectoryPath.'/prod.log'; |
| 72 | + $fileHandler = new RotatingFileHandler($logPath, 0, Logger::INFO); |
| 73 | + $fileHandler->setFormatter(new LineFormatter("%datetime%|%level%|%context%\n")); |
| 74 | + $this->logger->pushHandler($fileHandler); |
| 75 | + |
| 76 | + // Set custom readable logger when debug=true |
| 77 | + if ($this->debug) { |
| 78 | + $debugLogPath = $logDirectoryPath.'/debug.log'; |
| 79 | + $debugFileHandler = new RotatingFileHandler($debugLogPath, 0, Logger::DEBUG); |
| 80 | + if (class_exists('\Bramus\Monolog\Formatter\ColoredLineFormatter')) { |
| 81 | + $debugFileHandler->setFormatter(new \Bramus\Monolog\Formatter\ColoredLineFormatter(null, "[%datetime%] %message% %context%\n", 'H:i:s')); |
| 82 | + $this->logger->pushHandler($debugFileHandler); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + protected function bounceCurrentIp() |
| 88 | + { |
| 89 | + $ip = $this->getRemoteIp(); |
| 90 | + |
| 91 | + // X-Forwarded-For override |
| 92 | + $XForwardedForHeader = $this->getHttpRequestHeader('X-Forwarded-For'); |
| 93 | + if (null !== $XForwardedForHeader) { |
| 94 | + $ipList = array_map('trim', array_values(array_filter(explode(',', $XForwardedForHeader)))); |
| 95 | + $forwardedIp = end($ipList); |
| 96 | + if ($this->shouldTrustXforwardedFor($ip)) { |
| 97 | + $ip = $forwardedIp; |
| 98 | + } else { |
| 99 | + $this->logger->warning('', [ |
| 100 | + 'type' => 'NON_AUTHORIZED_X_FORWARDED_FOR_USAGE', |
| 101 | + 'original_ip' => $ip, |
| 102 | + 'x_forwarded_for_ip' => $forwardedIp, |
| 103 | + ]); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + try { |
| 108 | + $this->getBouncerInstance(); |
| 109 | + $remediation = $this->bouncer->getRemediationForIp($ip); |
| 110 | + $this->handleRemediation($remediation, $ip); |
| 111 | + } catch (\Exception $e) { |
| 112 | + $this->logger->warning('', [ |
| 113 | + 'type' => 'UNKNOWN_EXCEPTION_WHILE_BOUNCING', |
| 114 | + 'ip' => $ip, |
| 115 | + 'messsage' => $e->getMessage(), |
| 116 | + 'code' => $e->getCode(), |
| 117 | + 'file' => $e->getFile(), |
| 118 | + 'line' => $e->getLine(), |
| 119 | + ]); |
| 120 | + if ($this->debug) { |
| 121 | + throw $e; |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + protected function shouldTrustXforwardedFor(string $ip): bool |
| 127 | + { |
| 128 | + $comparableAddress = Factory::addressFromString($ip)->getComparableString(); |
| 129 | + foreach ($this->getTrustForwardedIpBoundsList() as $comparableIpBounds) { |
| 130 | + if ($comparableAddress >= $comparableIpBounds[0] && $comparableAddress <= $comparableIpBounds[1]) { |
| 131 | + return true; |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + return false; |
| 136 | + } |
| 137 | + |
| 138 | + protected function displayCaptchaWall() |
| 139 | + { |
| 140 | + $options = $this->getCaptchaWallOptions(); |
| 141 | + $body = Bouncer::getCaptchaHtmlTemplate( |
| 142 | + $this->getSessionVariable('crowdsec_captcha_resolution_failed'), |
| 143 | + $this->getSessionVariable('crowdsec_captcha_inline_image'), |
| 144 | + '', |
| 145 | + $options |
| 146 | + ); |
| 147 | + $this->sendResponse($body, 401); |
| 148 | + } |
| 149 | + |
| 150 | + protected function handleBanRemediation() |
| 151 | + { |
| 152 | + $options = $this->getBanWallOptions(); |
| 153 | + $body = Bouncer::getAccessForbiddenHtmlTemplate($options); |
| 154 | + $this->sendResponse($body, 403); |
| 155 | + } |
| 156 | + |
| 157 | + protected function storeNewCaptchaCoupleInSession() |
| 158 | + { |
| 159 | + $captchaCouple = Bouncer::buildCaptchaCouple(); |
| 160 | + $this->setSessionVariable('crowdsec_captcha_phrase_to_guess', $captchaCouple['phrase']); |
| 161 | + $this->setSessionVariable('crowdsec_captcha_inline_image', $captchaCouple['inlineImage']); |
| 162 | + } |
| 163 | + |
| 164 | + protected function clearCaptchaSessionContext() |
| 165 | + { |
| 166 | + $this->unsetSessionVariable('crowdsec_captcha_has_to_be_resolved'); |
| 167 | + $this->unsetSessionVariable('crowdsec_captcha_phrase_to_guess'); |
| 168 | + $this->unsetSessionVariable('crowdsec_captcha_inline_image'); |
| 169 | + $this->unsetSessionVariable('crowdsec_captcha_resolution_failed'); |
| 170 | + } |
| 171 | + |
| 172 | + protected function handleCaptchaResolutionForm(string $ip) |
| 173 | + { |
| 174 | + // Early return if no captcha has to be resolved or if captcha already resolved. |
| 175 | + if (\in_array($this->getSessionVariable('crowdsec_captcha_has_to_be_resolved'), [null, false])) { |
| 176 | + return; |
| 177 | + } |
| 178 | + |
| 179 | + // Early return if no form captcha form has been filled. |
| 180 | + if ('POST' !== $this->getHttpMethod() || null === $this->getPostedVariable('crowdsec_captcha')) { |
| 181 | + return; |
| 182 | + } |
| 183 | + |
| 184 | + // Handle image refresh. |
| 185 | + if (null !== $this->getPostedVariable('refresh') && (bool) (int) $this->getPostedVariable('refresh')) { |
| 186 | + // Generate new captcha image for the user |
| 187 | + $this->storeNewCaptchaCoupleInSession(); |
| 188 | + $this->setSessionVariable('crowdsec_captcha_resolution_failed', false); |
| 189 | + |
| 190 | + return; |
| 191 | + } |
| 192 | + |
| 193 | + // Handle a captcha resolution try |
| 194 | + if (null !== $this->getPostedVariable('phrase') && null !== $this->getSessionVariable('crowdsec_captcha_phrase_to_guess')) { |
| 195 | + $this->getBouncerInstance(); |
| 196 | + if ($this->bouncer->checkCaptcha( |
| 197 | + $this->getSessionVariable('crowdsec_captcha_phrase_to_guess'), |
| 198 | + $this->getPostedVariable('phrase'), |
| 199 | + $ip)) { |
| 200 | + // User has correctly fill the captcha |
| 201 | + |
| 202 | + $this->setSessionVariable('crowdsec_captcha_has_to_be_resolved', false); |
| 203 | + $this->unsetSessionVariable('crowdsec_captcha_phrase_to_guess'); |
| 204 | + $this->unsetSessionVariable('crowdsec_captcha_inline_image'); |
| 205 | + $this->unsetSessionVariable('crowdsec_captcha_resolution_failed'); |
| 206 | + } else { |
| 207 | + // The user failed to resolve the captcha. |
| 208 | + $this->setSessionVariable('crowdsec_captcha_resolution_failed', true); |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + protected function handleCaptchaRemediation($ip) |
| 214 | + { |
| 215 | + // Check captcha resolution form |
| 216 | + $this->handleCaptchaResolutionForm($ip); |
| 217 | + |
| 218 | + if (null === $this->getSessionVariable('crowdsec_captcha_has_to_be_resolved')) { |
| 219 | + // Setup the first captcha remediation. |
| 220 | + |
| 221 | + $this->storeNewCaptchaCoupleInSession(); |
| 222 | + $this->setSessionVariable('crowdsec_captcha_has_to_be_resolved', true); |
| 223 | + $this->setSessionVariable('crowdsec_captcha_resolution_failed', false); |
| 224 | + } |
| 225 | + |
| 226 | + // Display captcha page if this is required. |
| 227 | + if ($this->getSessionVariable('crowdsec_captcha_has_to_be_resolved')) { |
| 228 | + $this->displayCaptchaWall(); |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + protected function handleRemediation(string $remediation, string $ip) |
| 233 | + { |
| 234 | + if (Constants::REMEDIATION_CAPTCHA !== $remediation && null !== $this->getSessionVariable('crowdsec_captcha_has_to_be_resolved')) { |
| 235 | + $this->clearCaptchaSessionContext(); |
| 236 | + } |
| 237 | + switch ($remediation) { |
| 238 | + case Constants::REMEDIATION_BYPASS: |
| 239 | + return; |
| 240 | + case Constants::REMEDIATION_CAPTCHA: |
| 241 | + $this->handleCaptchaRemediation($ip); |
| 242 | + break; |
| 243 | + case Constants::REMEDIATION_BAN: |
| 244 | + $this->handleBanRemediation(); |
| 245 | + break; |
| 246 | + default: |
| 247 | + return; |
| 248 | + } |
| 249 | + } |
| 250 | +} |
0 commit comments