Beispiel #1
0
 public function onAfterInitialise()
 {
     $ip = AtsystemUtilFilter::getIp();
     $continents = $this->cparams->getValue('geoblockcontinents', '');
     $continents = empty($continents) ? array() : explode(',', $continents);
     $countries = $this->cparams->getValue('geoblockcountries', '');
     $countries = empty($countries) ? array() : explode(',', $countries);
     $geoip = new AkeebaGeoipProvider();
     $country = $geoip->getCountryCode($ip);
     $continent = $geoip->getContinent($ip);
     if (empty($country)) {
         $country = '(unknown country)';
     }
     if (empty($continent)) {
         $continent = '(unknown continent)';
     }
     if ($continent && !empty($continents) && in_array($continent, $continents)) {
         $extraInfo = 'Continent : ' . $continent;
         $this->exceptionsHandler->blockRequest('geoblocking', null, $extraInfo);
     }
     if ($country && !empty($countries) && in_array($country, $countries)) {
         $extraInfo = 'Country : ' . $country;
         $this->exceptionsHandler->blockRequest('geoblocking', null, $extraInfo);
     }
 }
Beispiel #2
0
 /**
  * Filters back-end access by IP. If the IP of the visitor is not included
  * in the whitelist, he gets redirected to the home page
  */
 public function onAfterInitialise()
 {
     // Let's get a list of allowed IP ranges
     $db = $this->db;
     $sql = $db->getQuery(true)->select($db->qn('ip'))->from($db->qn('#__admintools_adminiplist'));
     $db->setQuery($sql);
     try {
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $ipTable = $db->loadColumn();
         } else {
             $ipTable = $db->loadResultArray();
         }
     } catch (Exception $e) {
         // Do nothing if the query fails
         $ipTable = null;
     }
     if (empty($ipTable)) {
         return;
     }
     $inList = AtsystemUtilFilter::IPinList($ipTable);
     if ($inList === false) {
         if (!$this->exceptionsHandler->logAndAutoban('ipwl')) {
             return;
         }
         $this->redirectAdminToHome();
     }
 }
 public function onUserAfterSave($user, $isnew, $success, $msg)
 {
     $process = true;
     // Only trigger on successful user creation
     if (!$success) {
         $process = false;
     }
     // Only trigger on new user creation, not subsequent edits
     if (!$isnew) {
         $process = false;
     }
     // Only trigger on front-end user creation.
     if (!F0FPlatform::getInstance()->isFrontend()) {
         $process = false;
     }
     if (!$process) {
         return;
     }
     // Create a new user note
     // Get the user's ID
     $user_id = (int) $user['id'];
     // Get the IP address
     $ip = AtsystemUtilFilter::getIp();
     if (strpos($ip, '::') === 0 && strstr($ip, '.') !== false) {
         $ip = substr($ip, strrpos($ip, ':') + 1);
     }
     // Get the user agent string
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
     // Get current date and time in database format
     JLoader::import('joomla.utilities.date');
     $now = new JDate();
     $now = $now->toSql();
     // Load the component's administrator translation files
     $jlang = JFactory::getLanguage();
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
     // Create and save the user note
     $userNote = (object) array('user_id' => $user_id, 'catid' => 0, 'subject' => JText::_('ATOOLS_LBL_WAF_SIGNUPIP_SUBJECT'), 'body' => JText::sprintf('ATOOLS_LBL_WAF_SIGNUPIP_BODY', $ip, $user_agent), 'state' => 1, 'created_user_id' => 42, 'created_time' => $now);
     try {
         $this->db->insertObject('#__user_notes', $userNote, 'id');
     } catch (Exception $e) {
         // Do nothing if the save fails
     }
 }
 /**
  * Sends an email upon a failed administrator login
  *
  * @param JAuthenticationResponse $response
  */
 public function onUserLoginFailure($response)
 {
     // Make sure we don't fire unless someone is still in the login page
     $user = JFactory::getUser();
     if (!$user->guest) {
         return;
     }
     $option = $this->input->getCmd('option');
     $task = $this->input->getCmd('task');
     if ($option != 'com_login' && $task != 'login') {
         return;
     }
     // If we are STILL in the login task WITHOUT a valid user, we had a login failure.
     // Load the component's administrator translation files
     $jlang = JFactory::getLanguage();
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
     // Fetch the username
     $username = JFactory::getApplication()->input->getString('username');
     // Get the site name
     $config = JFactory::getConfig();
     $sitename = $config->get('sitename');
     // Get the IP address
     $ip = AtsystemUtilFilter::getIp();
     if (strpos($ip, '::') === 0 && strstr($ip, '.') !== false) {
         $ip = substr($ip, strrpos($ip, ':') + 1);
     }
     // Send the email
     $mailer = JFactory::getMailer();
     $mailfrom = $config->get('mailfrom');
     $fromname = $config->get('fromname');
     $recipients = explode(',', $this->cparams->getValue('emailonfailedadminlogin', ''));
     $recipients = array_map('trim', $recipients);
     foreach ($recipients as $recipient) {
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($recipient);
         $mailer->setSubject(JText::sprintf('ATOOLS_LBL_WAF_EMAILADMINFAILEDLOGIN_SUBJECT', $username, $sitename));
         $mailer->setBody(JText::sprintf('ATOOLS_LBL_WAF_EMAILADMINFAILEDLOGIN_BODY', $username, $sitename, $ip, $sitename));
         $mailer->Send();
     }
 }
    /**
     * Runs the Project Honeypot HTTP:BL integration
     */
    public function onAfterInitialise()
    {
        // Load parameters
        $httpbl_key = $this->cparams->getValue('bbhttpblkey', '');
        $minthreat = $this->cparams->getValue('httpblthreshold', 25);
        $maxage = $this->cparams->getValue('httpblmaxage', 30);
        $suspicious = $this->cparams->getValue('httpblblocksuspicious', 0);
        // Make sure we have an HTTP:BL  key set
        if (empty($httpbl_key)) {
            return;
        }
        // Get the IP address
        $reqip = AtsystemUtilFilter::getIp();
        if ($reqip == '0.0.0.0') {
            return;
        }
        if (strpos($reqip, '::') === 0) {
            $reqip = substr($reqip, strrpos($reqip, ':') + 1);
        }
        // No point continuing if we can't get an address, right?
        if (empty($reqip)) {
            return;
        }
        // IPv6 addresses are not supported by HTTP:BL yet
        if (strpos($reqip, ":")) {
            return;
        }
        $find = implode('.', array_reverse(explode('.', $reqip)));
        $result = gethostbynamel($httpbl_key . ".{$find}.dnsbl.httpbl.org.");
        if (empty($result)) {
            return;
        }
        $ip = explode('.', $result[0]);
        // Make sure it's a valid response
        if ($ip[0] != 127) {
            return;
        }
        // Do not block search engines
        if ($ip[3] == 0) {
            return;
        }
        // Block harvesters and comment spammers
        $block = $ip[3] & 2 || $ip[3] & 4;
        // Do not block "suspicious" (not confirmed) IPs unless asked so
        if (!$suspicious && $ip[3] & 1) {
            $block = false;
        }
        $block = $block && $ip[1] <= $maxage;
        $block = $block && $ip[2] >= $minthreat;
        if ($block) {
            $classes = array();
            if ($ip[3] & 1) {
                $classes[] = 'Suspicious';
            }
            if ($ip[3] & 2) {
                $classes[] = 'Email Harvester';
            }
            if ($ip[3] & 4) {
                $classes[] = 'Comment Spammer';
            }
            $class = implode(', ', $classes);
            $extraInfo = <<<ENDINFO
HTTP:BL analysis for blocked spammer's IP address {$reqip}
\tAttacker class\t\t: {$class}
\tLast activity\t\t: {$ip['1']} days ago
\tThreat level\t\t: {$ip['2']} --> see http://is.gd/mAwMTo for more info

ENDINFO;
            $this->exceptionsHandler->blockRequest('httpbl', '', $extraInfo);
        }
    }
Beispiel #6
0
 /**
  * Sends an email upon accessing an administrator page other than the login screen
  */
 public function onAfterInitialise()
 {
     $user = JFactory::getUser();
     // Check if the session flag is set (avoid sending thousands of emails!)
     $session = JFactory::getSession();
     $flag = $session->get('waf.loggedin', 0, 'plg_admintools');
     if ($flag == 1) {
         return;
     }
     // Load the component's administrator translation files
     $jlang = JFactory::getLanguage();
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
     $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
     // Get the username
     $username = $user->username;
     // Get the site name
     $config = JFactory::getConfig();
     if (version_compare(JVERSION, '3.0', 'ge')) {
         $sitename = $config->get('sitename');
     } else {
         $sitename = $config->getValue('config.sitename');
     }
     // Get the IP address
     $ip = AtsystemUtilFilter::getIp();
     if (strpos($ip, '::') === 0 && strstr($ip, '.') !== false) {
         $ip = substr($ip, strrpos($ip, ':') + 1);
     }
     $country = '';
     $continent = '';
     if (class_exists('AkeebaGeoipProvider')) {
         $geoip = new AkeebaGeoipProvider();
         $country = $geoip->getCountryCode($ip);
         $continent = $geoip->getContinent($ip);
     }
     if (empty($country)) {
         $country = '(unknown country)';
     }
     if (empty($continent)) {
         $continent = '(unknown continent)';
     }
     // Construct the replacement table
     $substitutions = array('[SITENAME]' => $sitename, '[USERNAME]' => $username, '[IP]' => $ip, '[UASTRING]' => $_SERVER['HTTP_USER_AGENT'], '[COUNTRY]' => $country, '[CONTINENT]' => $continent);
     $subject = JText::_('ATOOLS_LBL_WAF_EMAILADMINLOGIN_SUBJECT_21');
     $body = JText::_('ATOOLS_LBL_WAF_EMAILADMINLOGIN_BODY_21');
     foreach ($substitutions as $k => $v) {
         $subject = str_replace($k, $v, $subject);
         $body = str_replace($k, $v, $body);
     }
     // Send the email
     $mailer = JFactory::getMailer();
     $mailfrom = $config->get('mailfrom');
     $fromname = $config->get('fromname');
     $recipients = explode(',', $this->cparams->getValue('emailonadminlogin', ''));
     $recipients = array_map('trim', $recipients);
     foreach ($recipients as $recipient) {
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($recipient);
         $mailer->setSubject($subject);
         $mailer->setBody($body);
         $mailer->Send();
     }
     // Set the flag to prevent sending more emails
     $session->set('waf.loggedin', 1, 'plg_admintools');
 }
 /**
  * Blocks visitors coming from an automatically banned IP.
  */
 public function onAfterInitialise()
 {
     // Get the visitor's IP address
     $ip = AtsystemUtilFilter::getIp();
     // Let's get a list of blocked IP ranges
     $db = $this->db;
     $sql = $db->getQuery(true)->select('*')->from($db->qn('#__admintools_ipautoban'))->where($db->qn('ip') . ' = ' . $db->q($ip));
     $db->setQuery($sql);
     try {
         $record = $db->loadObject();
     } catch (Exception $e) {
         $record = null;
     }
     if (empty($record)) {
         return;
     }
     // Is this record expired?
     JLoader::import('joomla.utilities.date');
     $jNow = new JDate();
     $jUntil = new JDate($record->until);
     $now = $jNow->toUnix();
     $until = $jUntil->toUnix();
     if ($now > $until) {
         // Ban expired. Move the entry and allow the request to proceed.
         $history = clone $record;
         $history->id = null;
         try {
             $db->insertObject('#__admintools_ipautobanhistory', $history, 'id');
         } catch (Exception $e) {
             // Oops...
         }
         $sql = $db->getQuery(true)->delete($db->qn('#__admintools_ipautoban'))->where($db->qn('ip') . ' = ' . $db->q($ip));
         $db->setQuery($sql);
         try {
             $db->execute();
         } catch (Exception $e) {
             // Oops...
         }
         return;
     }
     // Move old entries - The fastest way is to create a INSERT with a SELECT statement
     $sql = 'INSERT INTO ' . $db->qn('#__admintools_ipautobanhistory') . ' (' . $db->qn('id') . ', ' . $db->qn('ip') . ', ' . $db->qn('reason') . ', ' . $db->qn('until') . ')' . ' SELECT NULL, ' . $db->qn('ip') . ', ' . $db->qn('reason') . ', ' . $db->qn('until') . ' FROM ' . $db->qn('#__admintools_ipautoban') . ' WHERE ' . $db->qn('until') . ' < ' . $db->q($jNow->toSql());
     try {
         $r = $db->setQuery($sql)->execute();
     } catch (Exception $e) {
         // Oops...
     }
     $sql = $db->getQuery(true)->delete($db->qn('#__admintools_ipautoban'))->where($db->qn('until') . ' < ' . $db->q($jNow->toSql()));
     $db->setQuery($sql);
     try {
         $db->execute();
     } catch (Exception $e) {
         // Oops...
     }
     @ob_end_clean();
     header("HTTP/1.0 403 Forbidden");
     $spammerMessage = $this->cparams->getValue('spammermessage', '');
     $spammerMessage = str_replace('[IP]', $ip, $spammerMessage);
     echo $spammerMessage;
     $this->app->close();
 }
Beispiel #8
0
 /**
  * Filters visitor access by IP. If the IP of the visitor is included in the
  * blacklist, she gets a 403 error
  */
 public function onAfterInitialise()
 {
     // Let's get a list of blocked IP ranges
     $db = $this->db;
     $sql = $db->getQuery(true)->select($db->qn('ip'))->from($db->qn('#__admintools_ipblock'));
     $db->setQuery($sql);
     try {
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $ipTable = $db->loadColumn();
         } else {
             $ipTable = $db->loadResultArray();
         }
     } catch (Exception $e) {
         // Do nothing if the query fails
         $ipTable = null;
     }
     if (empty($ipTable)) {
         return;
     }
     $inList = AtsystemUtilFilter::IPinList($ipTable);
     if ($inList !== true) {
         return;
     }
     $message = $this->cparams->getValue('custom403msg', '');
     if (empty($message)) {
         $message = 'ADMINTOOLS_BLOCKED_MESSAGE';
     }
     // Merge the default translation with the current translation
     $jlang = JFactory::getLanguage();
     // Front-end translation
     $jlang->load('plg_system_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
     $jlang->load('plg_system_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
     $jlang->load('plg_system_admintools', JPATH_ADMINISTRATOR, null, true);
     // Do we have an override?
     $langOverride = $this->params->get('language_override', '');
     if (!empty($langOverride)) {
         $jlang->load('plg_system_admintools', JPATH_ADMINISTRATOR, $langOverride, true);
     }
     $message = JText::_($message);
     if ($message == 'ADMINTOOLS_BLOCKED_MESSAGE') {
         $message = "Access Denied";
     }
     // Show the 403 message
     if ($this->cparams->getValue('use403view', 0)) {
         $session = JFactory::getSession();
         // Using a view
         if (!$session->get('block', false, 'com_admintools') || F0FPlatform::getInstance()->isBackend()) {
             // This is inside an if-block so that we don't end up in an infinite redirection loop
             $session->set('block', true, 'com_admintools');
             $session->set('message', $message, 'com_admintools');
             $session->close();
             $base = JURI::base();
             if (F0FPlatform::getInstance()->isBackend()) {
                 $base = rtrim($base);
                 $base = substr($base, 0, -13);
             }
             $this->app->redirect($base);
         }
         return;
     }
     if (F0FPlatform::getInstance()->isBackend()) {
         // You can't use Joomla!'s error page in the admin area. Improvise!
         header('HTTP/1.1 403 Forbidden');
         echo $message;
         $this->app->close();
     }
     // Using Joomla!'s error page
     if (version_compare(JVERSION, '3.0', 'ge')) {
         throw new Exception($message, 403);
     }
     JError::raiseError(403, $message);
 }
Beispiel #9
0
 /**
  * Checks if an IP address should be automatically banned for raising too many security exceptions over a predefined
  * time period.
  *
  * @param   string $reason The reason of the ban
  *
  * @return  void
  */
 public function autoBan($reason = 'other')
 {
     // We need to be able to get our own IP, right?
     if (!function_exists('inet_pton')) {
         return;
     }
     // Get the IP
     $ip = AtsystemUtilFilter::getIp();
     // No point continuing if we can't get an address, right?
     if (empty($ip) || $ip == '0.0.0.0') {
         return;
     }
     // Check for repeat offenses
     $db = JFactory::getDBO();
     $strikes = $this->cparams->getValue('tsrstrikes', 3);
     $numfreq = $this->cparams->getValue('tsrnumfreq', 1);
     $frequency = $this->cparams->getValue('tsrfrequency', 'hour');
     $mindatestamp = 0;
     switch ($frequency) {
         case 'second':
             break;
         case 'minute':
             $numfreq *= 60;
             break;
         case 'hour':
             $numfreq *= 3600;
             break;
         case 'day':
             $numfreq *= 86400;
             break;
         case 'ever':
             $mindatestamp = 946706400;
             // January 1st, 2000
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jNow = new JDate();
     if ($mindatestamp == 0) {
         $mindatestamp = $jNow->toUnix() - $numfreq;
     }
     $jMinDate = new JDate($mindatestamp);
     $minDate = $jMinDate->toSql();
     $sql = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_log'))->where($db->qn('logdate') . ' >= ' . $db->q($minDate))->where($db->qn('ip') . ' = ' . $db->q($ip));
     $db->setQuery($sql);
     try {
         $numOffenses = $db->loadResult();
     } catch (Exception $e) {
         $numOffenses = 0;
     }
     if ($numOffenses < $strikes) {
         return;
     }
     // Block the IP
     $myIP = @inet_pton($ip);
     if ($myIP === false) {
         return;
     }
     $myIP = inet_ntop($myIP);
     $until = $jNow->toUnix();
     $numfreq = $this->cparams->getValue('tsrbannum', 1);
     $frequency = $this->cparams->getValue('tsrbanfrequency', 'hour');
     switch ($frequency) {
         case 'second':
             $until += $numfreq;
             break;
         case 'minute':
             $numfreq *= 60;
             $until += $numfreq;
             break;
         case 'hour':
             $numfreq *= 3600;
             $until += $numfreq;
             break;
         case 'day':
             $numfreq *= 86400;
             $until += $numfreq;
             break;
         case 'ever':
             $until = 2145938400;
             // January 1st, 2038 (mind you, UNIX epoch runs out on January 19, 2038!)
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jMinDate = new JDate($until);
     $minDate = $jMinDate->toSql();
     $record = (object) array('ip' => $myIP, 'reason' => $reason, 'until' => $minDate);
     // If I'm here it means that we have to ban the user. Let's see if this is a simple autoban or
     // we have to issue a permaban as a result of several attacks
     if ($this->cparams->getValue('permaban', 0)) {
         // Ok I have to check the number of autoban
         $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_ipautobanhistory'))->where($db->qn('ip') . ' = ' . $db->q($myIP));
         try {
             $bans = $db->setQuery($query)->loadResult();
         } catch (Exception $e) {
             $bans = 0;
         }
         $limit = (int) $this->cparams->getValue('permabannum', 0);
         if ($limit && $bans >= $limit) {
             $block = (object) array('ip' => $myIP, 'description' => 'IP automatically blocked after being banned automatically ' . $bans . ' times');
             $db->insertObject('#__admintools_ipblock', $block);
         }
     }
     $db->insertObject('#__admintools_ipautoban', $record);
     // Send an optional email
     if ($this->cparams->getValue('emailafteripautoban', '')) {
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         // Get the site name
         $config = JFactory::getConfig();
         $sitename = $config->get('sitename');
         $country = '';
         $continent = '';
         if (class_exists('AkeebaGeoipProvider')) {
             $geoip = new AkeebaGeoipProvider();
             $country = $geoip->getCountryCode($ip);
             $continent = $geoip->getContinent($ip);
         }
         if (empty($country)) {
             $country = '(unknown country)';
         }
         if (empty($continent)) {
             $continent = '(unknown continent)';
         }
         $uri = JURI::getInstance();
         $url = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment'));
         $ip_link = $this->cparams->getValue('iplookupscheme', 'http') . '://' . $this->cparams->getValue('iplookup', 'ip-lookup.net/index.php?ip={ip}');
         $ip_link = str_replace('{ip}', $ip, $ip_link);
         $substitutions = array('[SITENAME]' => $sitename, '[REASON]' => JText::_('COM_ADMINTOOLS_EMAILTEMPLATE_REASON_IPAUTOBAN'), '[DATE]' => gmdate('Y-m-d H:i:s') . " GMT", '[URL]' => $url, '[USER]' => '', '[IP]' => $ip, '[LOOKUP]' => '<a href="' . $ip_link . '">IP Lookup</a>', '[COUNTRY]' => $country, '[CONTINENT]' => $continent, '[UA]' => $_SERVER['HTTP_USER_AGENT'], '[UNTIL]' => $minDate);
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         // Let's get the most suitable email template
         $template = $this->getEmailTemplate('ipautoban');
         // Got no template, the user didn't published any email template, or the template doesn't want us to
         // send a notification email. Anyway, let's stop here.
         if (!$template) {
             return;
         } else {
             $subject = $template[0];
             $body = $template[1];
         }
         foreach ($substitutions as $k => $v) {
             $subject = str_replace($k, $v, $subject);
             $body = str_replace($k, $v, $body);
         }
         // Send the email
         $mailer = JFactory::getMailer();
         $mailfrom = $config->get('mailfrom');
         $fromname = $config->get('fromname');
         $mailer->isHtml(true);
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($this->cparams->getValue('emailafteripautoban', ''));
         $mailer->setSubject($subject);
         $mailer->setBody($body);
         $mailer->Send();
     }
 }
 /**
  * Checks if an IP address should be automatically banned for raising too many security exceptions over a predefined
  * time period.
  *
  * @param   string $reason The reason of the ban
  *
  * @return  void
  */
 public function autoBan($reason = 'other')
 {
     // We need to be able to get our own IP, right?
     if (!function_exists('inet_pton')) {
         return;
     }
     // Get the IP
     $ip = AtsystemUtilFilter::getIp();
     // No point continuing if we can't get an address, right?
     if (empty($ip) || $ip == '0.0.0.0') {
         return;
     }
     // Check for repeat offenses
     $db = JFactory::getDBO();
     $strikes = $this->cparams->getValue('tsrstrikes', 3);
     $numfreq = $this->cparams->getValue('tsrnumfreq', 1);
     $frequency = $this->cparams->getValue('tsrfrequency', 'hour');
     $mindatestamp = 0;
     switch ($frequency) {
         case 'second':
             break;
         case 'minute':
             $numfreq *= 60;
             break;
         case 'hour':
             $numfreq *= 3600;
             break;
         case 'day':
             $numfreq *= 86400;
             break;
         case 'ever':
             $mindatestamp = 946706400;
             // January 1st, 2000
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jNow = new JDate();
     if ($mindatestamp == 0) {
         $mindatestamp = $jNow->toUnix() - $numfreq;
     }
     $jMinDate = new JDate($mindatestamp);
     $minDate = $jMinDate->toSql();
     $sql = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_log'))->where($db->qn('logdate') . ' >= ' . $db->q($minDate))->where($db->qn('ip') . ' = ' . $db->q($ip));
     $db->setQuery($sql);
     try {
         $numOffenses = $db->loadResult();
     } catch (Exception $e) {
         $numOffenses = 0;
     }
     if ($numOffenses < $strikes) {
         return;
     }
     // Block the IP
     $myIP = @inet_pton($ip);
     if ($myIP === false) {
         return;
     }
     $myIP = inet_ntop($myIP);
     $until = $jNow->toUnix();
     $numfreq = $this->cparams->getValue('tsrbannum', 1);
     $frequency = $this->cparams->getValue('tsrbanfrequency', 'hour');
     switch ($frequency) {
         case 'second':
             $until += $numfreq;
             break;
         case 'minute':
             $numfreq *= 60;
             $until += $numfreq;
             break;
         case 'hour':
             $numfreq *= 3600;
             $until += $numfreq;
             break;
         case 'day':
             $numfreq *= 86400;
             $until += $numfreq;
             break;
         case 'ever':
             $until = 2145938400;
             // January 1st, 2038 (mind you, UNIX epoch runs out on January 19, 2038!)
             break;
     }
     JLoader::import('joomla.utilities.date');
     $jMinDate = new JDate($until);
     $minDate = $jMinDate->toSql();
     $record = (object) array('ip' => $myIP, 'reason' => $reason, 'until' => $minDate);
     // If I'm here it means that we have to ban the user. Let's see if this is a simple autoban or
     // we have to issue a permaban as a result of several attacks
     if ($this->cparams->getValue('permaban', 0)) {
         // Ok I have to check the number of autoban
         $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__admintools_ipautobanhistory'))->where($db->qn('ip') . ' = ' . $db->q($myIP));
         try {
             $bans = $db->setQuery($query)->loadResult();
         } catch (Exception $e) {
             $bans = 0;
         }
         $limit = (int) $this->cparams->getValue('permabannum', 0);
         if ($limit && $bans >= $limit) {
             $block = (object) array('ip' => $myIP, 'description' => 'IP automatically blocked after being banned automatically ' . $bans . ' times');
             $db->insertObject('#__admintools_ipblock', $block);
         }
     }
     $db->insertObject('#__admintools_ipautoban', $record);
     // Send an optional email
     if ($this->cparams->getValue('emailafteripautoban', '')) {
         // Get the site name
         $config = JFactory::getConfig();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $sitename = $config->get('sitename');
         } else {
             $sitename = $config->getValue('config.sitename');
         }
         $substitutions = array('[SITENAME]' => $sitename, '[IP]' => $myIP, '[UNTIL]' => $minDate);
         // Load the component's administrator translation files
         $jlang = JFactory::getLanguage();
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, 'en-GB', true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
         $jlang->load('com_admintools', JPATH_ADMINISTRATOR, null, true);
         $subject = JText::_('ATOOLS_LBL_WAF_AUTOIPBLOCKEMAIL_SUBJECT');
         $body = JText::_('ATOOLS_LBL_WAF_AUTOIPBLOCKEMAIL_BODY');
         foreach ($substitutions as $k => $v) {
             $subject = str_replace($k, $v, $subject);
             $body = str_replace($k, $v, $body);
         }
         // Send the email
         $mailer = JFactory::getMailer();
         if (version_compare(JVERSION, '3.0', 'ge')) {
             $mailfrom = $config->get('mailfrom');
             $fromname = $config->get('fromname');
         } else {
             $mailfrom = $config->getValue('config.mailfrom');
             $fromname = $config->getValue('config.fromname');
         }
         $mailer->setSender(array($mailfrom, $fromname));
         $mailer->addRecipient($this->cparams->getValue('emailafteripautoban', ''));
         $mailer->setSubject($subject);
         $mailer->setBody($body);
         $mailer->Send();
     }
 }
 /**
  * When the user is trying to access the administrator folder without being logged in make sure they had already
  * entered the custom administrator folder before coming here. Otherwise they are unauthorised and must be booted to
  * the site's front-end page.
  */
 protected function checkCustomAdminFolder()
 {
     // Initialise
     $seriesFound = false;
     $db = $this->db;
     // Get the series number from the cookie
     $series = $this->input->cookie->get('admintools', null);
     // If we are told that this is a user logging out redirect them to the front-end home page, do not log a
     // security exception, expire the cookie
     $logout = $this->input->cookie->get('admintools_logout', null, 'string');
     if ($logout == '!!!LOGOUT!!!') {
         $config = JFactory::getConfig();
         $cookie_domain = $config->get('cookie_domain', '');
         $cookie_path = $config->get('cookie_path', '/');
         $isSecure = $config->get('force_ssl', 0) ? true : false;
         setcookie('admintools_logout', null, 1, $cookie_path, $cookie_domain, $isSecure, true);
         $this->redirectAdminToHome();
         return;
     }
     // Do we have a series?
     $isValid = !empty($series);
     // Does the series exist in the db? If so, load it
     if ($isValid) {
         $query = $db->getQuery(true)->select('*')->from($db->qn('#__admintools_cookies'))->where($db->qn('series') . ' = ' . $db->q($series));
         $db->setQuery($query);
         $storedData = $db->loadObject();
         $seriesFound = true;
         if (!is_object($storedData)) {
             $isValid = false;
             $seriesFound = false;
         }
     }
     // Is the series still valid or did someone manipulate the cookie expiration?
     if ($isValid) {
         $jValid = strtotime($storedData->valid_to);
         if ($jValid < time()) {
             $isValid = false;
         }
     }
     // Does the UA match the stored series?
     if ($isValid) {
         $ip = AtsystemUtilFilter::getIp();
         if (version_compare(JVERSION, '3.2.0', 'ge')) {
             $ua = $this->app->client;
             $uaString = $ua->userAgent;
             $browserVersion = $ua->browserVersion;
         } else {
             JLoader::import('joomla.environment.browser');
             $browser = JBrowser::getInstance();
             $uaString = $browser->getAgentString();
             $browserVersion = $browser->getVersion();
         }
         $uaShort = str_replace($browserVersion, 'abcd', $uaString);
         $notSoSecret = $ip . $uaShort;
         JLoader::import('joomla.user.helper');
         if (version_compare(JVERSION, '3.2.1', 'ge')) {
             $isValid = JUserHelper::verifyPassword($notSoSecret, $storedData->client_hash);
         } else {
             $hash = md5($ip . $uaShort);
             $isValid = $hash == $storedData->client_hash;
         }
     }
     // Last check: session state variable
     if (JFactory::getSession()->get('adminlogindir', 0, 'com_admintools')) {
         $isValid = true;
     }
     // Delete the series cookie if found
     if ($seriesFound) {
         $query = $db->getQuery(true)->delete($db->qn('#__admintools_cookies'))->where($db->qn('series') . ' = ' . $db->q($series));
         $db->setQuery($query);
         $db->execute();
     }
     // Log an exception and redirect to homepage if we can't validate the user's cookie / session parameter
     if (!$isValid) {
         $this->exceptionsHandler->logAndAutoban('admindir');
         $this->redirectAdminToHome();
         return;
     }
     // Otherwise set the session parameter
     if ($seriesFound) {
         JFactory::getSession()->set('adminlogindir', 1, 'com_admintools');
     }
 }
 private function deactivateUser($username)
 {
     $userParams = JComponentHelper::getParams('com_users');
     // User registration disabled or no user activation - Let's stop here
     if (!$userParams->get('allowUserRegistration') || $userParams->get('useractivation') == 0) {
         return;
     }
     $ip = AtsystemUtilFilter::getIp();
     // If I can't detect the IP there's not point in continuing
     if (!$ip) {
         return;
     }
     $limit = $this->cparams->getValue('deactivateusers_num', 3);
     $numfreq = $this->cparams->getValue('deactivateusers_numfreq', 1);
     $frequency = $this->cparams->getValue('deactivateusers_frequency', 'hour');
     // The user didn't set any limit nor frequency value, let's stop here
     if (!$limit || !$numfreq) {
         return;
     }
     $userid = JUserHelper::getUserId($username);
     // The user doesn't exists, let's stop here
     if (!$userid) {
         return;
     }
     $user = JFactory::getUser($userid);
     // Username doesn't match, the user is blocked or is not active? Let's stop here
     if ($user->username != $username || $user->block || !empty($user->activation)) {
         return;
     }
     // If I'm here, it means that this is a valid user, let's see if I have to deactivate him
     $where = array('ip' => $ip, 'reason' => 'loginfailure');
     $deactivate = $this->checkLogFrequency($limit, $numfreq, $frequency, $where);
     if (!$deactivate) {
         return;
     }
     JPluginHelper::importPlugin('user');
     $db = $this->db;
     $data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
     $data['block'] = 1;
     $data['lastvisitDate'] = $db->getNullDate();
     // If an admin needs to activate the user, I have to set the activate flag
     if ($userParams->get('useractivation') == 2) {
         $user->setParam('activate', 1);
     }
     if (!$user->bind($data)) {
         return;
     }
     if (!$user->save()) {
         return;
     }
     // Ok, now it's time to send the activation email again
     $template = $this->exceptionsHandler->getEmailTemplate('user-reactivate');
     // Well, this should never happen...
     if (!$template) {
         return;
     }
     $subject = $template[0];
     $body = $template[1];
     $config = JFactory::getConfig();
     $mailer = JFactory::getMailer();
     $sitename = $config->get('sitename');
     $mailfrom = $config->get('mailfrom');
     $fromname = $config->get('fromname');
     $uri = JUri::getInstance();
     $base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
     $activate = $base . JRoute::_('index.php?option=com_users&task=registration.activate&token=' . $data['activation'], false);
     // Send e-mail to the user
     if ($userParams->get('useractivation') == 1) {
         $mailer->addRecipient($user->email);
     } elseif ($userParams->get('useractivation') == 2) {
         // get all admin users
         $query = $db->getQuery(true)->select($db->qn(array('name', 'email', 'sendEmail', 'id')))->from($db->qn('#__users'))->where($db->qn('sendEmail') . ' = ' . 1);
         $rows = $db->setQuery($query)->loadObjectList();
         // Send mail to all users with users creating permissions and receiving system emails
         foreach ($rows as $row) {
             $usercreator = JFactory::getUser($row->id);
             if ($usercreator->authorise('core.create', 'com_users')) {
                 $mailer->addRecipient($usercreator->email);
             }
         }
     } else {
         // Future-proof check
         return;
     }
     $tokens = array('[SITENAME]' => $sitename, '[DATE]' => gmdate('Y-m-d H:i:s') . " GMT", '[USER]' => $username, '[IP]' => $ip, '[ACTIVATE]' => '<a href="' . $activate . '">' . $activate . '</a>');
     $subject = str_replace(array_keys($tokens), array_values($tokens), $subject);
     $body = str_replace(array_keys($tokens), array_values($tokens), $body);
     $mailer->isHtml(true);
     $mailer->setSender(array($mailfrom, $fromname));
     $mailer->setSubject($subject);
     $mailer->setBody($body);
     $mailer->Send();
 }