Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

   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          $namefields = get_all_user_name_fields(true, 'u');
 119          $sql = "SELECT * FROM (
 120                          SELECT l.*, u.username, $namefields
 121                            FROM {" . $logtable . "} l
 122                            JOIN {cache_flags} cf ON l.ip = cf.name
 123                       LEFT JOIN {user} u         ON l.userid = u.id
 124                           WHERE l.eventname = ?
 125                                 AND l.timecreated > ?
 126                                 AND cf.flagtype = 'login_failure_by_ip'
 127                      UNION ALL
 128                          SELECT l.*, u.username, $namefields
 129                            FROM {" . $logtable . "} l
 130                            JOIN {cache_flags} cf ON l.userid = " . $DB->sql_cast_char2int('cf.name') . "
 131                       LEFT JOIN {user} u         ON l.userid = u.id
 132                           WHERE l.eventname = ?
 133                                 AND l.timecreated > ?
 134                                 AND cf.flagtype = 'login_failure_by_info') t
 135               ORDER BY t.timecreated DESC";
 136          $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, '\core\event\user_login_failed', $CFG->lastnotifyfailure);
 137  
 138          // Init some variables.
 139          $count = 0;
 140          $messages = '';
 141          // Iterate over the logs recordset.
 142          $rs = $DB->get_recordset_sql($sql, $params);
 143          foreach ($rs as $log) {
 144              $a = new \stdClass();
 145              $a->time = userdate($log->timecreated);
 146              if (empty($log->username)) {
 147                  // Entries with no valid username. We get attempted username from the event's other field.
 148                  $other = \tool_log\helper\reader::decode_other($log->other);
 149                  $a->info = empty($other['username']) ? '' : $other['username'];
 150                  $a->name = get_string('unknownuser');
 151              } else {
 152                  $a->info = $log->username;
 153                  $a->name = fullname($log);
 154              }
 155              $a->ip = $log->ip;
 156              $messages .= get_string('notifyloginfailuresmessage', '', $a)."\n";
 157              $count++;
 158          }
 159          $rs->close();
 160  
 161          // If we have something useful to report.
 162          if ($count > 0) {
 163              $site = get_site();
 164              $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
 165              // Calculate the complete body of notification (start + messages + end).
 166              $params = array('id' => 0, 'modid' => 'site_errors', 'chooselog' => '1', 'logreader' => $readername);
 167              $url = new \moodle_url('/report/log/index.php', $params);
 168              $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
 169                      (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
 170                      $messages .
 171                      "\n\n".get_string('notifyloginfailuresmessageend', '',  $url->out(false).' ')."\n\n";
 172  
 173              // For each destination, send mail.
 174              mtrace('Emailing admins about '. $count .' failed login attempts');
 175              foreach ($recip as $admin) {
 176                  // Emailing the admins directly rather than putting these through the messaging system.
 177                  email_to_user($admin, \core_user::get_noreply_user(), $subject, $body);
 178              }
 179          }
 180  
 181          // Update lastnotifyfailure with current time.
 182          set_config('lastnotifyfailure', time());
 183  
 184          // Finally, delete all the temp records we have created in cache_flags.
 185          $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
 186  
 187      }
 188  }