Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Scheduled task class.
  19   *
  20   * @package    core
  21   * @copyright  2013 onwards Martin Dougiamas  http://dougiamas.com
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  namespace core\task;
  25  
  26  /**
  27   * Simple task to send notifications about failed login attempts.
  28   */
  29  class send_failed_login_notifications_task extends scheduled_task {
  30  
  31      /** The maximum time period to look back (30 days = 30 * 24 * 3600) */
  32      const NOTIFY_MAXIMUM_TIME = 2592000;
  33  
  34      /**
  35       * Get a descriptive name for this task (shown to admins).
  36       *
  37       * @return string
  38       */
  39      public function get_name() {
  40          return get_string('tasksendfailedloginnotifications', 'admin');
  41      }
  42  
  43      /**
  44       * Do the job.
  45       * Throw exceptions on errors (the job will be retried).
  46       */
  47      public function execute() {
  48          global $CFG, $DB;
  49  
  50          if (empty($CFG->notifyloginfailures)) {
  51              return;
  52          }
  53  
  54          $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');
  55  
  56          // Do not look back more than 1 month to avoid crashes due to huge number of records.
  57          $maximumlastnotifytime = time() - self::NOTIFY_MAXIMUM_TIME;
  58          if (empty($CFG->lastnotifyfailure) || ($CFG->lastnotifyfailure < $maximumlastnotifytime)) {
  59              $CFG->lastnotifyfailure = $maximumlastnotifytime;
  60          }
  61  
  62          // If it has been less than an hour, or if there are no recipients, don't execute.
  63          if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
  64              return;
  65          }
  66  
  67          // We need to deal with the threshold stuff first.
  68          if (empty($CFG->notifyloginthreshold)) {
  69              $CFG->notifyloginthreshold = 10; // Default to something sensible.
  70          }
  71  
  72          // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
  73          // and insert them into the cache_flags temp table.
  74          $logmang = get_log_manager();
  75          $readers = $logmang->get_readers('\core\log\sql_internal_table_reader');
  76          $reader = reset($readers);
  77          $readername = key($readers);
  78          if (empty($reader) || empty($readername)) {
  79              // No readers, no processing.
  80              return true;
  81          }
  82          $logtable = $reader->get_internal_log_table_name();
  83  
  84          $sql = "SELECT ip, COUNT(*)
  85                    FROM {" . $logtable . "}
  86                   WHERE eventname = ?
  87                         AND timecreated > ?
  88                 GROUP BY ip
  89                   HAVING COUNT(*) >= ?";
  90          $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
  91          $rs = $DB->get_recordset_sql($sql, $params);
  92          foreach ($rs as $iprec) {
  93              if (!empty($iprec->ip)) {
  94                  set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
  95              }
  96          }
  97          $rs->close();
  98  
  99          // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
 100          // and insert them into the cache_flags temp table.
 101          $sql = "SELECT userid, count(*)
 102                    FROM {" . $logtable . "}
 103                   WHERE eventname = ?
 104                         AND timecreated > ?
 105                GROUP BY userid
 106                  HAVING count(*) >= ?";
 107          $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
 108          $rs = $DB->get_recordset_sql($sql, $params);
 109          foreach ($rs as $inforec) {
 110              if (!empty($inforec->info)) {
 111                  set_cache_flag('login_failure_by_id', $inforec->userid, '1', 0);
 112              }
 113          }
 114          $rs->close();
 115  
 116          // Now, select all the login error logged records belonging to the ips and infos
 117          // since lastnotifyfailure, that we have stored in the cache_flags table.
 118          $userfieldsapi = \core_user\fields::for_name();
 119          $namefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 120          $sql = "SELECT * FROM (
 121                          SELECT l.*, u.username, $namefields
 122                            FROM {" . $logtable . "} l
 123                            JOIN {cache_flags} cf ON l.ip = cf.name
 124                       LEFT JOIN {user} u         ON l.userid = u.id
 125                           WHERE l.eventname = ?
 126                                 AND l.timecreated > ?
 127                                 AND cf.flagtype = 'login_failure_by_ip'
 128                      UNION ALL
 129                          SELECT l.*, u.username, $namefields
 130                            FROM {" . $logtable . "} l
 131                            JOIN {cache_flags} cf ON l.userid = " . $DB->sql_cast_char2int('cf.name') . "
 132                       LEFT JOIN {user} u         ON l.userid = u.id
 133                           WHERE l.eventname = ?
 134                                 AND l.timecreated > ?
 135                                 AND cf.flagtype = 'login_failure_by_info') t
 136               ORDER BY t.timecreated DESC";
 137          $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, '\core\event\user_login_failed', $CFG->lastnotifyfailure);
 138  
 139          // Init some variables.
 140          $count = 0;
 141          $messages = '';
 142          // Iterate over the logs recordset.
 143          $rs = $DB->get_recordset_sql($sql, $params);
 144          foreach ($rs as $log) {
 145              $a = new \stdClass();
 146              $a->time = userdate($log->timecreated);
 147              if (empty($log->username)) {
 148                  // Entries with no valid username. We get attempted username from the event's other field.
 149                  $other = \tool_log\helper\reader::decode_other($log->other);
 150                  $a->info = empty($other['username']) ? '' : $other['username'];
 151                  $a->name = get_string('unknownuser');
 152              } else {
 153                  $a->info = $log->username;
 154                  $a->name = fullname($log);
 155              }
 156              $a->ip = $log->ip;
 157              $messages .= get_string('notifyloginfailuresmessage', '', $a)."\n";
 158              $count++;
 159          }
 160          $rs->close();
 161  
 162          // If we have something useful to report.
 163          if ($count > 0) {
 164              $site = get_site();
 165              $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
 166              // Calculate the complete body of notification (start + messages + end).
 167              $params = array('id' => 0, 'modid' => 'site_errors', 'chooselog' => '1', 'logreader' => $readername);
 168              $url = new \moodle_url('/report/log/index.php', $params);
 169              $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
 170                      (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
 171                      $messages .
 172                      "\n\n".get_string('notifyloginfailuresmessageend', '',  $url->out(false).' ')."\n\n";
 173  
 174              // For each destination, send mail.
 175              mtrace('Emailing admins about '. $count .' failed login attempts');
 176              foreach ($recip as $admin) {
 177                  // Emailing the admins directly rather than putting these through the messaging system.
 178                  email_to_user($admin, \core_user::get_noreply_user(), $subject, $body);
 179              }
 180          }
 181  
 182          // Update lastnotifyfailure with current time.
 183          set_config('lastnotifyfailure', time());
 184  
 185          // Finally, delete all the temp records we have created in cache_flags.
 186          $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
 187  
 188      }
 189  }