Browse Source

added account_sentinel contrib module

Bachir Soussi Chiadmi 4 years ago
parent
commit
a7f0bb7650

+ 339 - 0
sites/all/modules/contrib/security/account_sentinel/LICENSE.txt

@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.

+ 102 - 0
sites/all/modules/contrib/security/account_sentinel/README.txt

@@ -0,0 +1,102 @@
+CONTENTS OF THIS FILE
+---------------------
+
+ * Introduction
+ * Requirements
+ * Recommended modules
+ * Installation
+ * Configuration
+ * Drush commands
+
+
+INTRODUCTION
+------------
+
+Account Sentinel perceives changes made to a configurable set of monitored
+roles' accounts, even those that are results of direct database modification
+(e.g. SQL injection). A set of e-mail addresses can be configured to be notified
+when such a change is detected, also a log of changes can be viewed in Drupal
+and via Drush for manual review.
+
+ * For a full description of the module, visit the project page:
+   https://www.drupal.org/project/account_sentinel
+
+ * To submit bug reports and feature suggestions, or to track changes:
+   https://www.drupal.org/project/issues/account_sentinel
+
+
+REQUIREMENTS
+------------
+
+No special requirements.
+
+
+RECOMMENDED MODULES
+-------------------
+
+ * Password Strength (https://www.drupal.org/project/password_strength):
+   When enabled, password change events will also store the strength of the
+   new password.
+
+
+INSTALLATION
+------------
+
+ * Install as you would normally install a contributed Drupal module. See:
+   https://drupal.org/documentation/install/modules-themes/modules-7
+   for further information.
+
+
+CONFIGURATION
+-------------
+
+ * Configure user permissions in Administration > People > Permissions:
+
+   - Access Account Sentinel logs
+     Users with this permission are able to access the logs of Account
+     Sentinel on Administration > Reports > Account Sentinel log.
+
+   - Change Account Sentinel's configuration
+     Users with this permission are able to change the configuration of Account
+     Sentinel on Administration > Configuration > System > Account Sentinel
+     settings.
+
+ * Configure the module in Administration > Configuration > System > Account
+   Sentinel settings:
+
+   - Monitored roles
+     Choose which roles' users should be monitored. Typically any administrative
+     roles should be checked.
+
+   - Recipient(s) of notification e-mails
+     You may provide e-mail addresses to send notifications to. The format
+     should be (if not empty):
+      * user@example.com
+      * user@example.com, anotheruser@example.com
+      * User <user@example.com>
+      * User <user@example.com>, Another User <anotheruser@example.com>
+
+   - Automatic DB check method
+     Account Sentinel periodically compares Drupal's data about users with its
+     own snapshots of monitored users. You can configure with this option what
+     the trigger for these audits should be.
+
+ * [Optional] Set last audit warning threshold
+     Account Sentinel will show a warning if it's been a while since the last
+     database audit. By default this warning is shown after 3 days. You can
+     change this value using Drush:
+
+     drush vset --yes account_sentinel_audit_warn_after NEW_VALUE
+
+     Where NEW_VALUE is the threshold in seconds.
+
+
+DRUSH COMMANDS
+--------------
+
+ * account-sentinel-audit (as-audit)
+   Runs the Account Sentinel database audit.
+
+ * account-sentinel-show (as-show)
+   Shows an event's details or a list of the most recent events.
+   Please consult "drush help as-show" for more information.

+ 247 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.audit.inc

@@ -0,0 +1,247 @@
+<?php
+
+/**
+ * @file
+ * Contains functions for the automatic database check.
+ */
+
+/**
+ * Runs a full database audit.
+ */
+function account_sentinel_audit() {
+  account_sentinel_audit_existence();
+  account_sentinel_audit_integrity();
+  account_sentinel_audit_changes();
+  watchdog('account_sentinel', 'Ran database audit.');
+  variable_set('account_sentinel_audit_last', REQUEST_TIME);
+}
+
+/**
+ * Checks whether stored snapshots are valid.
+ */
+function account_sentinel_audit_integrity() {
+  $hash_key = drupal_get_hash_salt();
+  $events = array();
+
+  // Check integrity in account_sentinel_users.
+  $query = db_select('account_sentinel_users', 'u')
+    ->fields('u', array('uid', 'name', 'pass', 'mail', 'status', 'checksum'));
+  $query->where('checksum <> sha2(concat(u.uid, u.name, u.pass, u.mail, u.status, :hash_key), 384)', array(':hash_key' => $hash_key));
+  $result = $query->execute();
+
+  while (($row = $result->fetchAssoc()) !== FALSE) {
+    $events[$row['uid']][] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID,
+      'data' => array(
+        'table' => 'users',
+        'row' => $row,
+      ),
+    );
+  }
+
+  // Check integrity in account_sentinel_users_roles.
+  $query = db_select('account_sentinel_users_roles', 'ur')
+    ->fields('ur', array('uid', 'rid', 'checksum'));
+  $query->where('checksum <> sha2(concat(ur.uid, ur.rid, :hash_key), 384)', array(':hash_key' => $hash_key));
+  $result = $query->execute();
+
+  while (($row = $result->fetchAssoc()) !== FALSE) {
+    $events[$row['uid']][] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID,
+      'data' => array(
+        'table' => 'users_roles',
+        'row' => $row,
+      ),
+    );
+  }
+
+  foreach ($events as $uid => $event_list) {
+    account_sentinel_record_events($uid, ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK, $event_list);
+    $user = user_load($uid, TRUE);
+    if ($user !== FALSE) {
+      $user = account_sentinel_monitored_account_data($user);
+      account_sentinel_update_snapshot($user);
+    }
+  }
+}
+
+/**
+ * Checks whether trusted users are the same as the users who have snapshots.
+ */
+function account_sentinel_audit_existence() {
+  $monitored_roles = account_sentinel_get_monitored_roles();
+
+  if (!empty($monitored_roles)) {
+    // Check for missing snapshots.
+    $missing = db_select('users', 'u');
+    $missing->fields('u', array('uid'));
+    $missing->rightJoin('users_roles', 'ur', 'u.uid = ur.uid');
+    $missing->condition('ur.rid', $monitored_roles);
+    $missing->leftJoin('account_sentinel_users', 'asu', 'u.uid = asu.uid');
+    $missing->fields('asu', array('uid'));
+    $missing->condition('asu.uid', NULL);
+
+    $result = $missing->execute();
+    while (($row = $result->fetchAssoc()) !== FALSE) {
+      $uid = $row['uid'];
+
+      // UID can be NULL if users_roles contains roles of a forcibly deleted
+      // user. That case will be handled in the second part of the function, so
+      // we only work with existing users now.
+      if (is_numeric($uid)) {
+        $changes = array();
+        $changes[] = array(
+          'type' => ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_MISSING,
+          'data' => array(),
+        );
+
+        // A missing snapshot means that the user was granted one or more
+        // monitored permissions, so it's also an event type of ROLE_ADD.
+        // Get the roles of the user.
+        $user = user_load($uid);
+        if ($user !== FALSE) {
+          $roles = array_intersect($monitored_roles, array_keys($user->roles));
+
+          // Current roles.
+          $new = array(
+            'uid' => $uid,
+            'roles' => $roles,
+          );
+
+          // Roles previously stored as snapshots.
+          $select_original = db_select('account_sentinel_users_roles', 'asur');
+          $select_original->fields('asur', array('rid'))
+            ->condition('uid', $uid);
+          $original_roles_queried = $select_original->execute();
+          $original_roles = $original_roles_queried->fetchAllAssoc('rid');
+          $original = array(
+            'uid' => $uid,
+            'roles' => array_keys($original_roles),
+          );
+
+          $changes = array_merge(
+            $changes,
+            account_sentinel_detect_changes($new, $original)
+          );
+        }
+
+        account_sentinel_record_events($uid, ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK, $changes);
+        if ($user !== FALSE) {
+          $user = account_sentinel_monitored_account_data($user);
+          account_sentinel_update_snapshot($user);
+        }
+      }
+    }
+  }
+
+  // Check for excess snapshots.
+  // Revoked roles are detected in account_sentinel_audit_changes(), so we only
+  // look for missing rows in the users table.
+  $excess = db_select('users', 'u');
+  $excess->fields('asu', array('uid', 'name', 'mail'))
+    ->condition('u.uid', NULL)
+    ->rightJoin('account_sentinel_users', 'asu', 'u.uid = asu.uid');
+  $result = $excess->execute();
+  while (($row = $result->fetchAssoc()) !== FALSE) {
+    $changes = array(
+      array(
+        'type' => ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE,
+        'data' => array(
+          'uid' => $row['uid'],
+          'name' => $row['name'],
+          'mail' => $row['mail'],
+        ),
+      ),
+    );
+    account_sentinel_record_events($row['uid'], ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK, $changes);
+    account_sentinel_delete_snapshot($row['uid']);
+  }
+}
+
+/**
+ * Scans the database for manual changes in users and users_roles.
+ *
+ * Compares the monitored users' actual data to Account Sentinel's stored
+ * snapshots.
+ */
+function account_sentinel_audit_changes() {
+  $accounts = array();
+  $monitored_roles = account_sentinel_get_monitored_roles();
+
+  // Look for changes in user details.
+  $query = db_select('users', 'u');
+  $query->fields('u', array('uid', 'name', 'pass', 'mail', 'status'))
+    ->fields('asu', array('name', 'pass', 'mail', 'status'))
+    ->where('u.name <> asu.name OR u.pass <> asu.pass OR u.mail <> asu.mail OR u.status <> asu.status')
+    ->rightJoin('account_sentinel_users', 'asu', 'u.uid = asu.uid');
+  $result = $query->execute();
+
+  while (($row = $result->fetchAssoc()) !== FALSE) {
+    $accounts[$row['uid']] = array(
+      'new' => array(
+        'name' => $row['name'],
+        'pass' => $row['pass'],
+        'mail' => $row['mail'],
+        'status' => $row['status'],
+      ),
+      'original' => array(
+        'name' => $row['asu_name'],
+        'pass' => $row['asu_pass'],
+        'mail' => $row['asu_mail'],
+        'status' => $row['asu_status'],
+      ),
+    );
+  }
+
+  if (!empty($monitored_roles)) {
+    // Look for added user roles.
+    $added = db_select('users_roles', 'ur');
+    $added->fields('ur', array('uid', 'rid'))
+      ->condition('ur.rid', $monitored_roles)
+      ->notExists(
+        db_select('account_sentinel_users_roles', 'asur')
+          ->fields('asur', array())
+          ->where('ur.rid = asur.rid')
+      );
+    $added_roles = $added->execute();
+    while (($row = $added_roles->fetchAssoc()) !== FALSE) {
+      $accounts[$row['uid']]['new']['roles'][] = $row['rid'];
+      if (!isset($accounts[$row['uid']]['original']['roles'])) {
+        $accounts[$row['uid']]['original']['roles'] = array();
+      }
+    }
+  }
+
+  // Look for removed user roles.
+  $removed = db_select('account_sentinel_users_roles', 'asur');
+  $removed->fields('asur', array('uid', 'rid'))
+    ->notExists(
+      db_select('users_roles', 'ur')
+        ->fields('ur', array())
+        ->where('ur.rid = asur.rid')
+    );
+  $removed_roles = $removed->execute();
+  while (($row = $removed_roles->fetchAssoc()) !== FALSE) {
+    $accounts[$row['uid']]['original']['roles'][] = $row['rid'];
+    if (!isset($accounts[$row['uid']]['new']['roles'])) {
+      $accounts[$row['uid']]['new']['roles'] = array();
+    }
+  }
+
+  // Evaluate changes.
+  foreach ($accounts as $uid => $account_states) {
+    $account_states['new']['uid'] = $uid;
+    $account_states['original']['uid'] = $uid;
+    $changes = account_sentinel_detect_changes(
+      $account_states['new'],
+      $account_states['original']
+    );
+
+    account_sentinel_record_events($uid, ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK, $changes);
+    $user = user_load($uid, TRUE);
+    if ($user !== FALSE) {
+      $user = account_sentinel_monitored_account_data($user);
+      account_sentinel_update_snapshot($user);
+    }
+  }
+}

+ 249 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.drush.inc

@@ -0,0 +1,249 @@
+<?php
+
+/**
+ * @file
+ * Drush interface of Account Sentinel.
+ */
+
+/**
+ * Implements hook_drush_command().
+ */
+function account_sentinel_drush_command() {
+  $items['account-sentinel-show'] = array(
+    'callback' => 'account_sentinel_drush_show',
+    'description' => 'Shows the latest events Account Sentinel recorded.',
+    'aliases' => array('as-show'),
+    'arguments' => array(
+      'eid' => 'Optional id of Account Sentinel event to show in detail. If not set, the most recent events will be shown.',
+    ),
+    'options' => array(
+      'count' => 'Number of events to show. Defaults to 15.',
+      'uid' => "Filter by the subject's UID.",
+      'by_uid' => "Filter by the invoker's UID.",
+      'origin' => "Filter by the event's origin.",
+      'type' => "Filter by the event's type.",
+      'ip' => "Filter by the invoker's IP address.",
+      'before' => 'Show events occurred before given date. Supports a wide range of date formats (see http://php.net/manual/en/datetime.formats.php).',
+      'after' => 'Show events occurred after given date. Supports a wide range of date formats (see http://php.net/manual/en/datetime.formats.php).',
+    ),
+    'outputformat' => array(
+      'default' => 'table',
+      'pipe-format' => 'var_export',
+      'field-labels' => array(
+        'eid' => 'ID',
+        'uid' => 'UID',
+        'origin' => 'Origin',
+        'type' => 'Type',
+        'data' => 'Raw data',
+        'message' => 'Message',
+        'by_uid' => 'By UID',
+        'ip' => 'IP address',
+        'date' => 'Date',
+      ),
+      'fields-default' => array('eid', 'date', 'uid', 'message', 'by_uid', 'ip'),
+      'output-data-type' => 'format-table',
+    ),
+  );
+
+  $items['account-sentinel-audit'] = array(
+    'callback' => 'account_sentinel_drush_audit',
+    'description' => "Runs Account Sentinel's database audit.",
+    'aliases' => array('as-audit'),
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_drush_help().
+ */
+function account_sentinel_drush_help($section) {
+  switch ($section) {
+    case 'account-sentinel-show':
+      return dt('');
+
+    case 'account-sentinel-audit':
+      return dt('');
+  }
+}
+
+
+/**
+ * Implements the account-sentinel-show Drush command.
+ *
+ * @param int|null $eid
+ *   EID of the event, or NULL if multiple events should be shown.
+ *
+ * @return array|bool|null
+ *   Output for Drush.
+ */
+function account_sentinel_drush_show($eid = NULL) {
+  drush_include_engine('drupal', 'environment');
+
+  if (is_numeric($eid)) {
+    return account_sentinel_drush_show_one($eid);
+  }
+  else {
+    return account_sentinel_drush_show_many();
+  }
+}
+
+/**
+ * Shows a single event's details.
+ *
+ * @param int $eid
+ *   EID of the event.
+ *
+ * @return array|bool
+ *   Output for Drush.
+ */
+function account_sentinel_drush_show_one($eid) {
+  // Show a nicer output than a single-row table.
+  drush_set_default_outputformat('key-value-list');
+
+  // Query the event.
+  $rsc = drush_db_select('account_sentinel_logs', '*', 'eid = :eid', array(':eid' => $eid), 0, 1);
+  $result = drush_db_fetch_object($rsc);
+  if (!$result) {
+    return drush_set_error(dt('Account Sentinel event #!eid not found.', array('!eid' => $eid)));
+  }
+  $event = account_sentinel_drush_format_event($result);
+  return array($event->eid => (array) $event);
+}
+
+/**
+ * Shows multiple events' details.
+ *
+ * @return array
+ *   Output for drush.
+ */
+function account_sentinel_drush_show_many() {
+  $where = account_sentinel_drush_show_many_where();
+  $count = drush_get_option('count', 15);
+  $rsc = drush_db_select('account_sentinel_logs', '*', $where['expr'], $where['args'], 0, $count, 'eid', 'DESC');
+  $table = array();
+  while ($result = drush_db_fetch_object($rsc)) {
+    $row = account_sentinel_drush_format_event($result);
+    $table[$row->eid] = (array) $row;
+  }
+  if (empty($table)) {
+    drush_log(dt('No log events available.'), 'ok');
+    return array();
+  }
+  return $table;
+}
+
+/**
+ * Constructs the WHERE expression for the show command.
+ *
+ * @see account_sentinel_drush_show_many()
+ *
+ * @return array
+ *   An associative array containing:
+ *   - expr: The WHERE expression.
+ *   - args: Values of the named placeholders.
+ */
+function account_sentinel_drush_show_many_where() {
+  // Collect filter values from options.
+  $filters = array(
+    array('uid', drush_get_option('uid')),
+    array('by_uid', drush_get_option('by_uid')),
+    array('origin', drush_get_option('origin')),
+    array('type', drush_get_option('type')),
+    array('ip', drush_get_option('ip')),
+    array('timestamp', drush_get_option('before'), '<='),
+    array('timestamp', drush_get_option('after'), '>='),
+  );
+
+  // Convert some filter values.
+  foreach ($filters as $key => $filter) {
+    // Dates should be converted to UNIX timestamps.
+    if ($filter[0] == 'timestamp' && $filter[1] !== NULL) {
+      if (($time = strtotime($filter[1])) !== FALSE) {
+        $filters[$key][1] = $time;
+      }
+      else {
+        $filters[$key][1] = NULL;
+      }
+    }
+  }
+
+  // Build the expression.
+  $where = array(
+    'expr' => array(),
+    'args' => array(),
+  );
+  $placeholder_cnt = 0;
+  foreach ($filters as $filter) {
+    $col = $filter[0];
+    $val = $filter[1];
+    $op = isset($filter[2]) ? $filter[2] : '=';
+    if ($val !== NULL) {
+      $placeholder_cnt++;
+      $expr = "($col $op :ph_$placeholder_cnt)";
+      $where['expr'][] = $expr;
+      $where['args'][":ph_$placeholder_cnt"] = $val;
+    }
+  }
+
+  $where['expr'] = implode(' AND ', $where['expr']);
+
+  // Return the WHERE expression.
+  return $where;
+}
+
+/**
+ * Formats an event row for output.
+ *
+ * @param object $event
+ *   A row object of account_sentinel_logs.
+ *
+ * @return object
+ *   The event with formatted data.
+ */
+function account_sentinel_drush_format_event($event) {
+  // Collect and construct additional information.
+  $type = $event->type;
+  $origin = $event->origin;
+  $data = unserialize($event->data);
+  $message = account_sentinel_get_event_message($type, $data);
+  $message = account_sentinel_drush_html_to_text($message);
+
+  // Set formatted information.
+  $event->date = format_date($event->timestamp, 'short');
+  $event->data = print_r($data, TRUE);
+  $event->message = $message;
+  $event->type = account_sentinel_event_type_get_string($type);
+  $event->origin = account_sentinel_event_origin_get_string($origin);
+
+  // Return formatted event.
+  return $event;
+}
+
+/**
+ * Converts an HTML message to plain text.
+ *
+ * Uses drush_html_to_text(), but also removes some unwanted whitespace that the
+ * said command leaves in its output.
+ *
+ * @param string $message
+ *   The input HTML message.
+ *
+ * @see drush_html_to_text()
+ *
+ * @return string
+ *   The plaintext message.
+ */
+function account_sentinel_drush_html_to_text($message) {
+  return str_replace(' .', '.', drush_html_to_text($message));
+}
+
+/**
+ * Implements the account-sentinel-audit Drush command.
+ */
+function account_sentinel_drush_audit() {
+  watchdog('account_sentinel', 'Invoked database audit from Drush.');
+  module_load_include('inc', 'account_sentinel', 'account_sentinel.audit');
+  account_sentinel_audit();
+  drush_log(dt('Account Sentinel audit run successful.'), 'success');
+}

+ 11 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.info

@@ -0,0 +1,11 @@
+name = Account Sentinel
+description = "Detects changes made to selected roles' accounts."
+core = 7.x
+files[] = account_sentinel.test
+configure = admin/config/system/account-sentinel
+
+; Information added by Drupal.org packaging script on 2018-06-02
+version = "7.x-1.3"
+core = "7.x"
+project = "account_sentinel"
+datestamp = "1527932587"

+ 249 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.install

@@ -0,0 +1,249 @@
+<?php
+
+/**
+ * @file
+ * Installation and requirements for Account Sentinel module.
+ */
+
+/**
+ * Implements hook_schema().
+ */
+function account_sentinel_schema() {
+  $schema['account_sentinel_logs'] = array(
+    'description' => "Stores Account Sentinel's events.",
+    'fields' => array(
+      'eid' => array(
+        'description' => 'The primary identifier for an event.',
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'uid' => array(
+        'description' => "Subject account's {users}.uid.",
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'origin' => array(
+        'description' => 'From where the event was detected.',
+        'type' => 'varchar',
+        'length' => 32,
+        'not null' => TRUE,
+      ),
+      'type' => array(
+        'description' => 'Type of the event.',
+        'type' => 'varchar',
+        'length' => 32,
+        'not null' => TRUE,
+      ),
+      'data' => array(
+        'description' => 'Additional event data.',
+        'type' => 'blob',
+        'not null' => FALSE,
+        'size' => 'big',
+        'serialize' => TRUE,
+      ),
+      'by_uid' => array(
+        'description' => 'The {users}.uid of the user who triggered the event.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'ip' => array(
+        'description' => 'The IP of the user who triggered the event.',
+        'type' => 'varchar',
+        'length' => 45,
+        'default' => NULL,
+      ),
+      'timestamp' => array(
+        'description' => 'Unix timestamp of when the event occurred.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+    ),
+    'indexes' => array(
+      'uid' => array('uid'),
+      'origin' => array('origin'),
+      'type' => array('type'),
+      'by_uid' => array('by_uid'),
+      'ip' => array('ip'),
+      'timestamp' => array('timestamp'),
+    ),
+    'primary key' => array('eid'),
+  );
+
+  $schema['account_sentinel_users'] = array(
+    'description' => "Stores a copy of monitored users' data from the users table.",
+    'fields' => array(
+      'uid' => array(
+        'description' => 'Primary Key: Unique user ID.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'name' => array(
+        'description' => 'Unique user name.',
+        'type' => 'varchar',
+        'length' => 60,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'pass' => array(
+        'description' => "User's password (hashed).",
+        'type' => 'varchar',
+        'length' => 128,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'mail' => array(
+        'description' => "User's e-mail address.",
+        'type' => 'varchar',
+        'length' => 254,
+        'not null' => FALSE,
+        'default' => '',
+      ),
+      'status' => array(
+        'description' => 'Whether the user is active(1) or blocked(0).',
+        'type' => 'int',
+        'size' => 'tiny',
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'checksum' => array(
+        'description' => "Checksum calculated with site-specific hash-key.",
+        'type' => 'varchar',
+        'length' => 96,
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('uid'),
+  );
+
+  $schema['account_sentinel_users_roles'] = array(
+    'description' => 'Maps monitored users to monitored roles.',
+    'fields' => array(
+      'uid' => array(
+        'description' => 'Primary Key: {users}.uid for user.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'rid' => array(
+        'description' => 'Primary Key: {role}.rid for role.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'checksum' => array(
+        'description' => "Checksum calculated with site-specific hash-key.",
+        'type' => 'varchar',
+        'length' => 96,
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('uid', 'rid'),
+  );
+
+  return $schema;
+}
+
+/**
+ * Implements hook_requirements().
+ */
+function account_sentinel_requirements($phase) {
+  $t = get_t();
+
+  $requirements = array();
+  if ($phase == 'runtime') {
+    // Warn if it's been a while since the last database audit.
+    $warn_after = variable_get('account_sentinel_audit_warn_after', 3 * 24 * 60 * 60);
+    $last = variable_get('account_sentinel_audit_last', 0);
+    $enabled_on = variable_get('account_sentinel_enabled_on', 0);
+    if (REQUEST_TIME - max($last, $enabled_on) > $warn_after) {
+      $requirements[] = array(
+        'title' => $t('Account Sentinel database audit'),
+        'value' => $t(
+          'Last run @ago ago',
+          array('@ago' => format_interval(REQUEST_TIME - $last))
+        ),
+        'description' => $t("It's been a while since the last database audit run of Account Sentinel. It is highly recommended that you run it frequently either via cron or Drush. For more information check README.txt in the module's directory."),
+        'severity' => REQUIREMENT_WARNING,
+      );
+    }
+  }
+  return $requirements;
+}
+
+/**
+ * Implements hook_install().
+ */
+function account_sentinel_install() {
+  $t = get_t();
+  account_sentinel_reset_cron_key();
+  drupal_set_message($t(
+    'Account Sentinel successfully installed! Please head over <a href="!configure">here</a> to configure it.',
+    array('!configure' => url('admin/config/system/account-sentinel'))
+  ));
+}
+
+/**
+ * Implements hook_enable().
+ */
+function account_sentinel_enable() {
+  variable_set('account_sentinel_enabled_on', REQUEST_TIME);
+
+  // Reset snapshot tables to prevent false detections after enabling the
+  // module.
+  db_truncate('account_sentinel_users')->execute();
+  db_truncate('account_sentinel_users_roles')->execute();
+  $roles = account_sentinel_get_monitored_roles();
+  account_sentinel_rebuild_snapshots(array(), $roles);
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function account_sentinel_uninstall() {
+  variable_del('account_sentinel_audit_last');
+  variable_del('account_sentinel_audit_warn_after');
+  variable_del('account_sentinel_cron_key');
+  variable_del('account_sentinel_cron_method');
+  variable_del('account_sentinel_email_to');
+  variable_del('account_sentinel_enabled_on');
+  variable_del('account_sentinel_monitored_roles');
+}
+
+/**
+ * Change checksums to use SHA384.
+ */
+function account_sentinel_update_1() {
+  $checksum_field = array(
+    'description' => "Checksum calculated with site-specific hash-key.",
+    'type' => 'varchar',
+    'length' => 96,
+    'not null' => TRUE,
+  );
+
+  // Update checksum columns.
+  db_change_field('account_sentinel_users', 'checksum', 'checksum', $checksum_field);
+  db_change_field('account_sentinel_users_roles', 'checksum', 'checksum', $checksum_field);
+
+  // Regenerate valid checksums.
+  $hash_key = drupal_get_hash_salt();
+  $args = array(':hash_key' => $hash_key);
+  db_update('account_sentinel_users')
+    ->where('checksum = md5(concat(uid, name, pass, mail, status, :hash_key))', $args)
+    ->expression('checksum', 'sha2(concat(uid, name, pass, mail, status, :hash_key), 384)', $args)
+    ->execute();
+  db_update('account_sentinel_users_roles')
+    ->where('checksum = md5(concat(uid, rid, :hash_key))', $args)
+    ->expression('checksum', 'sha2(concat(uid, rid, :hash_key), 384)', $args)
+    ->execute();
+}

+ 922 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.module

@@ -0,0 +1,922 @@
+<?php
+
+/**
+ * @file
+ * Detects changes made to selected roles' accounts.
+ */
+
+/**
+ * Indicates that the username was changed.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_NAME', 'name');
+
+/**
+ * Indicates that the password was changed.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_PASS', 'pass');
+
+/**
+ * Indicates that the e-mail address was changed.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_MAIL', 'mail');
+
+/**
+ * Indicates that a monitored role was added.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD', 'role_add');
+
+/**
+ * Indicates that a monitored role was revoked.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE', 'role_remove');
+
+/**
+ * Indicates that the snapshot of the user was not valid.
+ *
+ * This is a critical event.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID', 'snapshot_invalid');
+
+/**
+ * Indicates that the snapshot of the user should already exist but it does not.
+ *
+ * This is a critical event.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_MISSING', 'snapshot_missing');
+
+/**
+ * Indicates that a new user was created with one or more monitored permissions.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_USER_ADD', 'user_add');
+
+/**
+ * Indicates that the user was deleted.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE', 'user_delete');
+
+/**
+ * Indicates that the user got blocked.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK', 'user_block');
+
+/**
+ * Indicates that the user got unblocked.
+ */
+define('ACCOUNT_SENTINEL_EVENT_TYPE_USER_UNBLOCK', 'user_unblock');
+
+/**
+ * Indicates that the change was caught via hooks inside Drupal.
+ */
+define('ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK', 'drupal');
+
+/**
+ * Indicates that the change was caught by checking the database.
+ *
+ * This is a critical event.
+ */
+define('ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK', 'database');
+
+/**
+ * Implements hook_help().
+ */
+function account_sentinel_help($path, $arg) {
+  switch ($path) {
+    case 'admin/help#account_sentinel':
+      $help = t("Account Sentinel perceives changes made to a configurable set of monitored roles' accounts, even those that are results of direct database modification (e.g. SQL injection). A set of e-mail addresses can be configured to be notified when such a change is detected, also a log of changes can be viewed in Drupal and via Drush for manual review.");
+      return '<p>' . $help . '</p>';
+  }
+}
+
+/**
+ * Implements hook_permission().
+ */
+function account_sentinel_permission() {
+  return array(
+    'access account sentinel logs' => array(
+      'title' => t('Access Account Sentinel logs'),
+    ),
+    'administer account sentinel' => array(
+      'title' => t("Change Account Sentinel's configuration"),
+    ),
+  );
+}
+
+/**
+ * Implements hook_menu().
+ */
+function account_sentinel_menu() {
+  // Report page.
+  $items['admin/reports/account-sentinel'] = array(
+    'title' => 'Account Sentinel log',
+    'description' => 'List of changes to monitored roles\' accounts perceived by Account Sentinel.',
+    'page callback' => 'account_sentinel_page_report',
+    'access arguments' => array('access account sentinel logs'),
+    'file' => 'account_sentinel.pages.inc',
+    'type' => MENU_NORMAL_ITEM,
+  );
+
+  // Settings page.
+  $items['admin/config/system/account-sentinel'] = array(
+    'title' => 'Account Sentinel settings',
+    'description' => 'Manage Account Sentinel settings.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('account_sentinel_page_settings'),
+    'access arguments' => array('administer account sentinel'),
+    'file' => 'account_sentinel.pages.inc',
+  );
+
+  // Cron handler.
+  $items['system/account-sentinel-cron'] = array(
+    'title' => 'Run Account Sentinel DB check',
+    'page callback' => 'account_sentinel_callback_cron',
+    'access callback' => TRUE,
+    'file' => 'account_sentinel.pages.inc',
+    'type' => MENU_CALLBACK,
+  );
+
+  // Cron key reset handler.
+  $items['system/account-sentinel-reset-cron-key'] = array(
+    'title' => "Reset Account Sentinel's cron key",
+    'page callback' => 'account_sentinel_callback_reset_cron_key',
+    'access callback' => TRUE,
+    'access arguments' => array('administer account sentinel'),
+    'file' => 'account_sentinel.pages.inc',
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
+}
+
+/**
+ * Implements hook_theme().
+ */
+function account_sentinel_theme($existing, $type, $theme, $path) {
+  return array(
+    'account_sentinel_username' => array(
+      'variables' => array(
+        'uid' => 0,
+      ),
+      'file' => 'account_sentinel.themes.inc',
+    ),
+  );
+}
+
+/**
+ * Implements hook_user_update().
+ */
+function account_sentinel_user_update(&$edit, $account, $category) {
+  $new = account_sentinel_monitored_account_data($account);
+  $original = account_sentinel_monitored_account_data($account->original);
+
+  if ($new['monitored'] || $original['monitored']) {
+    $changes = account_sentinel_detect_changes($new, $original);
+    if (!empty($changes)) {
+      account_sentinel_record_events($account->uid, ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK, $changes);
+      account_sentinel_update_snapshot($new);
+    }
+  }
+}
+
+/**
+ * Implements hook_password_strength_change().
+ */
+function account_sentinel_password_strength_change($account, $strength) {
+  // Store password strength for $account for later use.
+  account_sentinel_password_strength($account->uid, password_strength_get_score($strength['score']));
+}
+
+/**
+ * Provides static storage for password strengths.
+ *
+ * @param int $uid
+ *   UID of the user.
+ * @param string $score
+ *   Password's strength.
+ *
+ * @return mixed
+ *   Returns the score for UID's new password or FALSE if not set.
+ */
+function account_sentinel_password_strength($uid, $score = NULL) {
+  static $strengths = array();
+
+  // Update score.
+  if (isset($score)) {
+    $strengths[$uid] = $score;
+  }
+
+  // Return score.
+  if (isset($strengths[$uid])) {
+    return $strengths[$uid];
+  }
+
+  // Return FALSE if score is not available.
+  return FALSE;
+}
+
+/**
+ * Implements hook_account_sentinel_changes_alter().
+ */
+function account_sentinel_account_sentinel_changes_alter(array &$changes, array &$new, array &$original) {
+  // Include password strength information if available.
+  $strength = account_sentinel_password_strength($original['uid']);
+  if ($strength) {
+    foreach ($changes as &$change) {
+      if ($change['type'] == ACCOUNT_SENTINEL_EVENT_TYPE_PASS && !isset($change['data']['strength'])) {
+        $change['data']['strength'] = $strength;
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_user_insert().
+ */
+function account_sentinel_user_insert(&$edit, $account, $category) {
+  $account = account_sentinel_monitored_account_data($account);
+  if ($account['monitored']) {
+    $events[] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_USER_ADD,
+      'data' => array(
+        'uid' => $account['uid'],
+        'name' => $account['name'],
+        'mail' => $account['mail'],
+      ),
+    );
+    foreach ($account['roles'] as $rid) {
+      $events[] = array(
+        'type' => ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD,
+        'data' => array('rid' => $rid),
+      );
+    }
+    account_sentinel_record_events($account['uid'], ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK, $events);
+    account_sentinel_update_snapshot($account);
+  }
+}
+
+/**
+ * Implements hook_user_delete().
+ */
+function account_sentinel_user_delete($account) {
+  $account = account_sentinel_monitored_account_data($account);
+  if ($account['monitored']) {
+    $events[] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE,
+      'data' => array(
+        'uid' => $account['uid'],
+        'name' => $account['name'],
+        'mail' => $account['mail'],
+      ),
+    );
+    account_sentinel_record_events($account['uid'], ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK, $events);
+    account_sentinel_delete_snapshot($account['uid']);
+  }
+}
+
+/**
+ * Implements hook_cron().
+ */
+function account_sentinel_cron() {
+  if (variable_get('account_sentinel_cron_method', 'drupal') == 'drupal') {
+    watchdog('account_sentinel', "Invoked database audit from Drupal's cron.");
+    module_load_include('inc', 'account_sentinel', 'account_sentinel.audit');
+    account_sentinel_audit();
+  }
+}
+
+/**
+ * Implements hook_mail().
+ */
+function account_sentinel_mail($key, &$message, $params) {
+  switch ($key) {
+    // Compose notification e-mail.
+    case 'notification':
+      // Collect information parameters.
+      $origin = $params['origin'];
+      $events = $params['events'];
+
+      // Collect users' data.
+      $users = array(
+        'changed' => array('uid' => $params['uid']),
+        'by' => array('uid' => $params['meta_data']['by_uid']),
+      );
+      foreach ($users as &$user) {
+        $uid = $user['uid'];
+        $user_object = user_load($uid);
+        if ($user_object !== FALSE) {
+          $user['name'] = $user_object->name;
+          $user['link'] = l($user_object->name, 'user/' . $uid, array(
+            'absolute' => TRUE,
+          ));
+        }
+        else {
+          $user['name'] = t('Unknown');
+          $user['link'] = $user['name'];
+        }
+      }
+
+      // Compose e-mail.
+      if (!empty($events)) {
+        $message['subject'] = t(
+          '[AS] User #@uid (@name) was changed',
+          array(
+            '@uid' => $users['changed']['uid'],
+            '@name' => $users['changed']['name'],
+          )
+        );
+        if ($origin != ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK) {
+          $message['body'][] = '<strong>' . t('Warning: these changes were made outside of Drupal!') . '</strong>';
+        }
+        $message['body'][] = t(
+          'User #@uid (!user) was changed by user #@by_uid (!by_user) (@ip) at @timestamp.',
+          array(
+            '@uid' => $users['changed']['uid'],
+            '!user' => $users['changed']['link'],
+            '@by_uid' => $users['by']['uid'],
+            '!by_user' => $users['by']['link'],
+            '@ip' => $params['meta_data']['ip'],
+            '@timestamp' => format_date($params['meta_data']['timestamp']),
+          )
+        );
+        $message['body'][] = t('The following changes were made to the account:');
+        $event_list = '<ul>';
+        foreach ($events as $event) {
+          $event_list .= '<li>' . account_sentinel_get_event_message($event['type'], $event['data']) . '</li>';
+        }
+        $event_list .= '</ul>';
+        $message['body'][] = $event_list;
+        $message['body'][] = '-- <br/>' . t(
+          'Sent by Account Sentinel on <a href="!site_url">@site_name</a>.',
+          array(
+            '@site_name' => variable_get('site_name'),
+            '!site_url' => url('', array('absolute' => TRUE)),
+          )
+        );
+      }
+      break;
+  }
+}
+
+/**
+ * Returns the ID's of monitored roles.
+ *
+ * If the monitored roles have not been set yet, it will return the
+ * administrator role.
+ *
+ * @return int[]
+ *   Array of monitored roles' ids.
+ */
+function account_sentinel_get_monitored_roles() {
+  $roles = variable_get('account_sentinel_monitored_roles', NULL);
+  if ($roles === NULL) {
+    return array(
+      variable_get('user_admin_role', 3),
+    );
+  }
+  return $roles;
+}
+
+/**
+ * Returns the module's cron key.
+ *
+ * @return string
+ *   The cron key.
+ */
+function account_sentinel_get_cron_key() {
+  $key = variable_get('account_sentinel_cron_key', NULL);
+  if ($key === NULL) {
+    return account_sentinel_reset_cron_key();
+  }
+  return $key;
+}
+
+/**
+ * Returns the relevant monitored data of an $account object.
+ *
+ * The output is an associative array which only stores data needed by Account
+ * Sentinel.
+ *
+ * @param object $account
+ *   A user entity.
+ *
+ * @return array
+ *   An associative array containing the monitored data.
+ */
+function account_sentinel_monitored_account_data($account) {
+  // Only work with role IDs.
+  $roles = array_keys($account->roles);
+
+  // Only work with monitored roles.
+  $monitored = account_sentinel_get_monitored_roles();
+  $roles = array_intersect($monitored, $roles);
+
+  $output = array(
+    'uid' => $account->uid,
+    'name' => $account->name,
+    'pass' => $account->pass,
+    'mail' => $account->mail,
+    'status' => $account->status,
+    'roles' => $roles,
+    'monitored' => !empty($roles),
+  );
+
+  return $output;
+}
+
+/**
+ * Returns an array of event type string - human-readable string associations.
+ *
+ * @return array
+ *   Array of translatable strings mapped by their event type constants.
+ */
+function account_sentinel_event_type_strings() {
+  return array(
+    ACCOUNT_SENTINEL_EVENT_TYPE_NAME => t('name changed'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_PASS => t('password changed'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_MAIL => t('mail changed'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD => t('role added'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE => t('role removed'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID => t('invalid snapshot'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_MISSING => t('missing snapshot'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_USER_ADD => t('user added'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE => t('user deleted'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK => t('blocked'),
+    ACCOUNT_SENTINEL_EVENT_TYPE_USER_UNBLOCK => t('unblocked'),
+  );
+}
+
+/**
+ * Returns an array of event origin string - human-readable string associations.
+ *
+ * @return array
+ *   Array of translatable strings mapped by their event origin constants.
+ */
+function account_sentinel_event_origin_strings() {
+  return array(
+    ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK => t('Drupal'),
+    ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK => t('database'),
+  );
+}
+
+/**
+ * Gets the human-readable name of a given event type.
+ *
+ * @param string $event_type
+ *   The event's type.
+ *
+ * @return string
+ *   The event type's human-readable name.
+ */
+function account_sentinel_event_type_get_string($event_type) {
+  $event_type_strings = account_sentinel_event_type_strings();
+  if (isset($event_type_strings[$event_type])) {
+    return $event_type_strings[$event_type];
+  }
+  return t('unknown');
+}
+
+/**
+ * Gets the human-readable name of a given event origin.
+ *
+ * @param string $event_origin
+ *   The event's origin.
+ *
+ * @return string
+ *   The event origin's human-readable name.
+ */
+function account_sentinel_event_origin_get_string($event_origin) {
+  $event_origin_strings = account_sentinel_event_origin_strings();
+  if (isset($event_origin_strings[$event_origin])) {
+    return $event_origin_strings[$event_origin];
+  }
+  return t('unknown');
+}
+
+/**
+ * Generates an event's detailed human-readable message.
+ *
+ * @param string $event_type
+ *   The event's type.
+ * @param array $data
+ *   Additional data from the database used to generate informative messages.
+ *
+ * @return string
+ *   The generated detailed event message.
+ */
+function account_sentinel_get_event_message($event_type, array $data) {
+  switch ($event_type) {
+    case ACCOUNT_SENTINEL_EVENT_TYPE_NAME:
+      return t('Changed name from <strong>@name_old</strong> to <strong>@name_new</strong>.', array(
+        '@name_old' => $data['old'],
+        '@name_new' => $data['new'],
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_PASS:
+      $msg = t('Changed password.');
+      // Append strength information if set.
+      if (isset($data['strength'])) {
+        $msg .= ' ' . t('New strength: @strength.', array(
+          '@strength' => $data['strength'],
+        ));
+      }
+      return $msg;
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_MAIL:
+      return t('Changed mail from <strong>@mail_old</strong> to <strong>@mail_new</strong>.', array(
+        '@mail_old' => $data['old'],
+        '@mail_new' => $data['new'],
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD:
+      $role = user_role_load($data['rid']);
+      return t('Granted role <strong>@role</strong>.', array(
+        '@role' => $role->name,
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE:
+      $role = user_role_load($data['rid']);
+      return t('Revoked role <strong>@role</strong>.', array(
+        '@role' => $role->name,
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID:
+      return t("The user's snapshot was altered.");
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_MISSING:
+      return t("The user's snapshot is missing.");
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_USER_ADD:
+      return t('Created user <em>#@uid</em> <strong>@name</strong> (<strong>@mail</strong>).', array(
+        '@uid' => $data['uid'],
+        '@name' => $data['name'],
+        '@mail' => $data['mail'],
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE:
+      return t('Deleted user <em>#@uid</em> <strong>@name</strong> (<strong>@mail</strong>).', array(
+        '@uid' => $data['uid'],
+        '@name' => $data['name'],
+        '@mail' => $data['mail'],
+      ));
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK:
+      return t('Blocked user.');
+
+    case ACCOUNT_SENTINEL_EVENT_TYPE_USER_UNBLOCK:
+      return t('Unblocked user.');
+
+    default:
+      return t('Unknown event.');
+  }
+}
+
+/**
+ * Resets the cron key.
+ *
+ * @return string
+ *   Returns the new cron key.
+ */
+function account_sentinel_reset_cron_key() {
+  $new_key = drupal_random_key();
+  variable_set('account_sentinel_cron_key', $new_key);
+  watchdog('account_sentinel', 'Cron key reset.');
+  return $new_key;
+}
+
+/**
+ * Compares a user account's two states and returns the list of differences.
+ *
+ * @param array $new
+ *   The new state of the user.
+ * @param array $original
+ *   The original state of the user.
+ *
+ * @return array
+ *   Array of changes.
+ *
+ * @see account_sentinel_monitored_account_data($account)
+ */
+function account_sentinel_detect_changes(array $new, array $original) {
+  $changes = array();
+
+  // Check whether name was changed.
+  if (isset($new['name']) && $new['name'] != $original['name']) {
+    $changes[] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_NAME,
+      'data' => array(
+        'old' => $original['name'],
+        'new' => $new['name'],
+      ),
+    );
+  }
+
+  // Check whether pass was changed.
+  if (isset($new['pass']) && $new['pass'] != $original['pass']) {
+    $changes[] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_PASS,
+      'data' => array(),
+    );
+  }
+
+  // Check whether mail was changed.
+  if (isset($new['mail']) && $new['mail'] != $original['mail']) {
+    $changes[] = array(
+      'type' => ACCOUNT_SENTINEL_EVENT_TYPE_MAIL,
+      'data' => array(
+        'old' => $original['mail'],
+        'new' => $new['mail'],
+      ),
+    );
+  }
+
+  // Check whether status was changed.
+  if (isset($new['status']) && $new['status'] != $original['status']) {
+    if ($original['status']) {
+      $type = ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK;
+    }
+    else {
+      $type = ACCOUNT_SENTINEL_EVENT_TYPE_USER_UNBLOCK;
+    }
+    $changes[] = array(
+      'type' => $type,
+      'data' => array(),
+    );
+  }
+
+  if (isset($new['roles'])) {
+    // Check whether roles were changed.
+    $roles_added = array_diff($new['roles'], $original['roles']);
+    $roles_removed = array_diff($original['roles'], $new['roles']);
+
+    foreach ($roles_added as $rid) {
+      $changes[] = array(
+        'type' => ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD,
+        'data' => array('rid' => $rid),
+      );
+    }
+
+    foreach ($roles_removed as $rid) {
+      $changes[] = array(
+        'type' => ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE,
+        'data' => array('rid' => $rid),
+      );
+    }
+  }
+
+  drupal_alter('account_sentinel_changes', $changes, $new, $original);
+
+  return $changes;
+}
+
+/**
+ * Records events.
+ *
+ * Stores account changes in the database, sets the new snapshot, sends an email
+ * notification and invokes hook_account_sentinel_change().
+ *
+ * @param int $uid
+ *   The UID of the account.
+ * @param string $origin
+ *   The origin of the event.
+ * @param array $events
+ *   The array of changes.
+ */
+function account_sentinel_record_events($uid, $origin, array $events) {
+  global $user;
+  $by_uid = ($origin == ACCOUNT_SENTINEL_EVENT_ORIGIN_HOOK) ? $user->uid : 0;
+
+  $meta_data = array(
+    'uid' => $uid,
+    'origin' => $origin,
+    'by_uid' => $by_uid,
+    'ip' => ip_address(),
+    'timestamp' => REQUEST_TIME,
+  );
+
+  // Store changes.
+  foreach ($events as $event_key => $event) {
+    $record = $meta_data;
+    $record['type'] = $event['type'];
+    $record['data'] = $event['data'];
+
+    // Log to database.
+    drupal_write_record('account_sentinel_logs', $record);
+
+    // Inform other modules.
+    module_invoke_all('account_sentinel_change', $record);
+  }
+
+  // Send one e-mail notification per account.
+  account_sentinel_send_notification($uid, $origin, $events, $meta_data);
+}
+
+/**
+ * Sends e-mail notification about events.
+ *
+ * @param int $uid
+ *   The UID of the account.
+ * @param string $origin
+ *   The origin of the event.
+ * @param array $events
+ *   The array of changes.
+ * @param array $meta_data
+ *   Additional meta data about the change events.
+ */
+function account_sentinel_send_notification($uid, $origin, array $events, array $meta_data) {
+  if (!empty($events)) {
+    $to = variable_get('account_sentinel_email_to', '');
+    if ($to != '') {
+      drupal_mail(
+          'account_sentinel',
+          'notification',
+          $to,
+          language_default(),
+          array(
+              'uid' => $uid,
+              'origin' => $origin,
+              'events' => $events,
+              'meta_data' => $meta_data,
+          )
+      );
+    }
+  }
+}
+
+/**
+ * Rebuilds the snapshot tables.
+ *
+ * Invoked after changing which roles are monitored.
+ *
+ * @param array $roles_old
+ *   Array of previously monitored role IDs.
+ * @param array $roles_new
+ *   Array of monitored role IDs.
+ */
+function account_sentinel_rebuild_snapshots(array $roles_old, array $roles_new) {
+  $roles_added = array_diff($roles_new, $roles_old);
+  $roles_removed = array_diff($roles_old, $roles_new);
+  $auth_in_old = array_search(DRUPAL_AUTHENTICATED_RID, $roles_old) !== FALSE;
+  $auth_in_new = array_search(DRUPAL_AUTHENTICATED_RID, $roles_new) !== FALSE;
+  $hash_key = drupal_get_hash_salt();
+
+  // Check if we don't have to modify anything.
+  if ($auth_in_old && $auth_in_new) {
+    // Every user is in the database, and will remain there.
+    return;
+  }
+
+  // Check if we have to create new user snapshots.
+  if (!$auth_in_old && !empty($roles_added)) {
+    // Select users' data.
+    $select = db_select('users', 'u')
+      ->fields('u', array('uid', 'name', 'pass', 'mail', 'status'))
+      ->condition('u.uid', '0', '<>')
+      ->groupBy('u.uid');
+
+    // Filter by users of added roles.
+    if (!$auth_in_new) {
+      $select_include = db_select('users_roles', 'ur')
+        ->fields('ur', array('uid'))
+        ->condition('rid', $roles_added);
+      $select->condition('uid', $select_include, 'IN');
+    }
+
+    // Exclude users of previous roles.
+    if (!empty($roles_old)) {
+      $select_exclude = db_select('users_roles', 'ur')
+        ->fields('ur', array('uid'))
+        ->condition('rid', $roles_old);
+      $select->condition('uid', $select_exclude, 'NOT IN');
+    }
+
+    // Add checksum.
+    $select->addExpression(
+      'sha2(concat(u.uid, u.name, u.pass, u.mail, u.status, :hash_key), 384)', 'checksum',
+      array(':hash_key' => $hash_key)
+    );
+
+    // Insert.
+    $insert = db_insert('account_sentinel_users')
+      ->fields(array('uid', 'name', 'pass', 'mail', 'status', 'checksum'))
+      ->from($select);
+    $insert->execute();
+  }
+
+  // Check if we have to remove users snapshots.
+  if (!$auth_in_new && !empty($roles_removed)) {
+    // Delete records.
+    $delete = db_delete('account_sentinel_users');
+
+    // Exclude users of monitored roles.
+    if (!empty($roles_new)) {
+      $delete_exclude = db_select('users_roles', 'ur')
+        ->fields('ur', array('uid'))
+        ->condition('rid', $roles_new);
+      $delete->condition('uid', $delete_exclude, 'NOT IN');
+    }
+
+    // Execute query.
+    $delete->execute();
+  }
+
+  // Check if we have to create new users_roles snapshots.
+  $roles_added = array_diff($roles_added, array(DRUPAL_AUTHENTICATED_RID));
+  if (!empty($roles_added)) {
+    // Select added roles' records.
+    $select = db_select('users_roles', 'ur');
+    $select->fields('ur', array('uid', 'rid'))
+      ->condition('rid', $roles_added);
+
+    // Add checksum.
+    $select->addExpression(
+      'sha2(concat(ur.uid, ur.rid, :hash_key), 384)', 'checksum',
+      array(':hash_key' => $hash_key)
+    );
+
+    // Insert.
+    $insert = db_insert('account_sentinel_users_roles')
+      ->fields(array('uid', 'rid', 'checksum'))
+      ->from($select);
+    $insert->execute();
+  }
+
+  // Check if we have to remove users_roles snapshots.
+  $roles_removed = array_diff($roles_removed, array(DRUPAL_AUTHENTICATED_RID));
+  if (!empty($roles_removed)) {
+    // Delete removed roles' records.
+    $delete = db_delete('account_sentinel_users_roles');
+    $delete->condition('rid', $roles_removed);
+    $delete->execute();
+  }
+}
+
+/**
+ * Updates a modified user's snapshot.
+ *
+ * @param array $account
+ *   Account details.
+ *
+ * @see account_sentinel_monitored_account_data($account)
+ */
+function account_sentinel_update_snapshot(array $account) {
+  $uid = $account['uid'];
+  account_sentinel_delete_snapshot($uid);
+  account_sentinel_create_snapshot($account);
+}
+
+/**
+ * Deletes a user's snapshots from the database.
+ *
+ * @param int $uid
+ *   UID of user.
+ */
+function account_sentinel_delete_snapshot($uid) {
+  // Reset user's snapshot.
+  db_delete('account_sentinel_users')
+    ->condition('uid', $uid)
+    ->execute();
+
+  // Reset users_roles snapshots.
+  db_delete('account_sentinel_users_roles')
+    ->condition('uid', $uid)
+    ->execute();
+}
+
+/**
+ * Creates a snapshot of the given account's state in the database.
+ *
+ * @param array $account
+ *   The account.
+ *
+ * @see account_sentinel_monitored_account_data($account)
+ */
+function account_sentinel_create_snapshot(array $account) {
+  $uid = $account['uid'];
+  $hash_key = drupal_get_hash_salt();
+
+  // Update account_sentinel_users.
+  if ($account['monitored']) {
+    $checksum = hash('sha384', $uid . $account['name'] . $account['pass'] . $account['mail'] . $account['status'] . $hash_key);
+    db_insert('account_sentinel_users')
+      ->fields(array(
+        'uid' => $uid,
+        'name' => $account['name'],
+        'pass' => $account['pass'],
+        'mail' => $account['mail'],
+        'status' => $account['status'],
+        'checksum' => $checksum,
+      ))
+      ->execute();
+  }
+
+  // Fill users_roles snapshots.
+  foreach ($account['roles'] as $rid) {
+    $checksum = hash('sha384', $uid . $rid . $hash_key);
+    db_insert('account_sentinel_users_roles')
+      ->fields(array(
+        'uid' => $uid,
+        'rid' => $rid,
+        'checksum' => $checksum,
+      ))
+      ->execute();
+  }
+}

+ 524 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.pages.inc

@@ -0,0 +1,524 @@
+<?php
+
+/**
+ * @file
+ * Contains pages, forms and callbacks for Account Sentinel.
+ */
+
+/**
+ * Generates the settings page.
+ *
+ * @return array
+ *   The settings form.
+ */
+function account_sentinel_page_settings() {
+  $roles = array();
+  foreach (user_roles(TRUE) as $rid => $role) {
+    $roles[$rid] = check_plain($role);
+  }
+
+  // Monitored roles.
+  $form['account_sentinel_monitored_roles'] = array(
+    '#type' => 'checkboxes',
+    '#title' => t('Monitored roles'),
+    '#description' => t("Mark which roles' accounts should be monitored."),
+    '#options' => $roles,
+    '#default_value' => account_sentinel_get_monitored_roles(),
+  );
+
+  // E-mail notification recipients.
+  $form['account_sentinel_email_to'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Recipient(s) of notification e-mails'),
+    '#description' => t('Comma separated list of e-mail addresses to notify of changes to monitored accounts.'),
+    '#default_value' => variable_get('account_sentinel_email_to', ''),
+  );
+
+  // Cron settings.
+  $cron_key = account_sentinel_get_cron_key();
+  $cron_url = url(
+    'system/account-sentinel-cron',
+    array(
+      'absolute' => TRUE,
+      'query' => array('key' => $cron_key),
+    )
+  );
+  $cron_reset_url = url(
+    'system/account-sentinel-reset-cron-key',
+    array('query' => array('token' => drupal_get_token($cron_key)))
+  );
+  if (($cron_last = variable_get('account_sentinel_audit_last', 0)) != 0) {
+    $cron_status = t('Last run: %audit-last ago.', array('%audit-last' => format_interval(REQUEST_TIME - $cron_last)));
+  }
+  else {
+    $cron_status = t('The audit has not been run yet!');
+  }
+
+  $form['account_sentinel_cron_method'] = array(
+    '#type' => 'radios',
+    '#title' => t('Automatic DB check method'),
+    '#description' => $cron_status,
+    '#options' => array(
+      'drupal' => t("Run with Drupal's inbuilt cron"),
+      'custom' => t("Use Account Sentinel's own cron handler"),
+    ),
+    '#default_value' => variable_get('account_sentinel_cron_method', 'drupal'),
+  );
+
+  $form['account_sentinel_custom_cron_info'] = array(
+    '#type' => 'container',
+    '#states' => array(
+      'visible' => array(
+        ':input[name="account_sentinel_cron_method"]' => array('value' => 'custom'),
+      ),
+    ),
+  );
+
+  $form['account_sentinel_custom_cron_info']['content'] = array(
+    '#type' => 'markup',
+    '#markup' => t(
+      'The custom cron URL is <a href="!cron_url" id="cron-link">!cron_url</a>.<br />You can request a new URL by clicking <a href="!cron_reset_url" id="cron-reset-link">here</a>. This will invalidate the current URL!',
+      array(
+        '!cron_url' => $cron_url,
+        '!cron_reset_url' => $cron_reset_url,
+      )
+    ),
+  );
+
+  // Attach JavaScript.
+  $form['#attached']['js'] = array(
+    drupal_get_path('module', 'account_sentinel') . '/js/settings.js',
+  );
+
+  // Add submit handler.
+  $form['#submit'][] = 'account_sentinel_page_settings_submit';
+
+  return system_settings_form($form);
+}
+
+/**
+ * Handles the settings form's validation.
+ *
+ * @param array $form
+ *   The form's structure.
+ * @param array $form_state
+ *   The array containing the form's state.
+ */
+function account_sentinel_page_settings_validate(array $form, array &$form_state) {
+  // E-mail notification recipient validation.
+  $to = $form_state['values']['account_sentinel_email_to'];
+  $to_valid = TRUE;
+  $addresses = explode(',', $to);
+  foreach ($addresses as $address) {
+    $address = trim($address);
+    if (strpos($address, '<') !== FALSE) {
+      $start = strpos($address, '<') + 1;
+      $end = strpos($address, '>');
+      if ($end === FALSE) {
+        $to_valid = FALSE;
+        break;
+      }
+      $address = substr($address, $start, $end - $start);
+    }
+    if ($address != '' && !valid_email_address($address)) {
+      $to_valid = FALSE;
+      break;
+    }
+  }
+  if (!$to_valid) {
+    form_set_error('account_sentinel_email_to', t('Invalid e-mail address!'));
+  }
+}
+
+/**
+ * Handles the settings form's submission.
+ *
+ * @param array $form
+ *   The form's structure.
+ * @param array $form_state
+ *   The array containing the form's state.
+ */
+function account_sentinel_page_settings_submit(array $form, array &$form_state) {
+  // Only store IDs of monitored roles.
+  $roles_new = &$form_state['values']['account_sentinel_monitored_roles'];
+  $roles_new = array_keys(array_filter($roles_new));
+  $roles_old = account_sentinel_get_monitored_roles();
+  $roles_added = array_diff($roles_new, $roles_old);
+  $roles_removed = array_diff($roles_old, $roles_new);
+
+  // Check whether roles have changed.
+  if (!empty($roles_added) || !empty($roles_removed)) {
+    watchdog('account_sentinel', 'Monitored roles modified.');
+
+    // Invoke snapshot integrity check.
+    module_load_include('inc', 'account_sentinel', 'account_sentinel.audit');
+    account_sentinel_audit_existence();
+    account_sentinel_audit_integrity();
+
+    // Delete unmonitored snapshots, create newly monitored users' snapshots.
+    account_sentinel_rebuild_snapshots($roles_old, $roles_new);
+  }
+}
+
+/**
+ * Generates the report page.
+ *
+ * @return array
+ *   The report page.
+ */
+function account_sentinel_page_report() {
+  $filters = isset($_SESSION['account_sentinel_report_filter']) ? $_SESSION['account_sentinel_report_filter'] : array();
+
+  $output = array();
+  $output['account_sentinel_report_description'] = array(
+    '#type' => 'markup',
+    '#markup' => '<p>' . t(
+      'Here you can review the changes that were made to accounts monitored by Account Sentinel. To configure Account Sentinel <a href="!configure">click here</a>.',
+      array('!configure' => url('admin/config/system/account-sentinel'))
+    ) . '</p>',
+  );
+  $output['account_sentinel_report_filter'] = drupal_get_form('account_sentinel_page_report_filter_form');
+
+  // Query the events.
+  $events_per_page = 15;
+  $fields = array(
+    'eid',
+    'uid',
+    'origin',
+    'type',
+    'data',
+    'by_uid',
+    'ip',
+    'timestamp',
+  );
+  $select = db_select('account_sentinel_logs', 'l')->extend('PagerDefault');
+  $select->fields('l', $fields)
+    ->orderBy('timestamp', 'DESC')
+    ->orderBy('eid', 'DESC')
+    ->limit($events_per_page);
+
+  foreach ($filters as $filter => $filter_value) {
+    if (in_array($filter, $fields)) {
+      $select->condition($filter, $filter_value);
+    }
+    elseif ($filter == 'before') {
+      $select->condition('timestamp', $filter_value, '<=');
+    }
+    elseif ($filter == 'after') {
+      $select->condition('timestamp', $filter_value, '>=');
+    }
+  }
+
+  $events_queried = $select->execute();
+
+  // Fill the rows.
+  $rows = array();
+  while (($row = $events_queried->fetchAssoc()) !== FALSE) {
+    // Format date.
+    $row['timestamp'] = format_date($row['timestamp']);
+
+    // Format account names.
+    if ($row['origin'] == ACCOUNT_SENTINEL_EVENT_ORIGIN_DB_CHECK) {
+      $row['by'] = '<strong>' . t('DB alteration') . '</strong>';
+    }
+    else {
+      $row['by'] = theme('account_sentinel_username', array('uid' => $row['by_uid']));
+    }
+    $row['account'] = theme('account_sentinel_username', array('uid' => $row['uid']));
+
+    // Add event message.
+    $row['data'] = unserialize($row['data']);
+    $row['message'] = account_sentinel_get_event_message($row['type'], $row['data']);
+
+    // Add classes.
+    $origin_class = 'origin--' . str_replace('_', '-', $row['origin']);
+    $type_class = 'type--' . str_replace('_', '-', $row['type']);
+
+    // Insert row.
+    $rows[] = array(
+      'data' => array(
+        $row['account'],
+        $row['message'],
+        $row['timestamp'],
+        array(
+          'data' => $row['by'],
+          'class' => array('col--by'),
+        ),
+        $row['ip'],
+      ),
+      'class' => array($type_class, $origin_class),
+    );
+  }
+
+  $output['account_sentinel_report_table'] = array(
+    '#theme' => 'table',
+    '#header' => array(
+      t('Account'),
+      t('Event details'),
+      t('Date'),
+      t('By'),
+      t('IP'),
+    ),
+    '#rows' => $rows,
+    '#attributes' => array(
+      'class' => array('account-sentinel-table'),
+    ),
+  );
+  $output['account_sentinel_report_pager'] = array('#theme' => 'pager');
+  $output['#attached']['css'] = array(
+    drupal_get_path('module', 'account_sentinel') . '/css/report.css',
+  );
+  return $output;
+}
+
+/**
+ * Generates the filter form for the report page.
+ *
+ * @return array
+ *   The filter form.
+ */
+function account_sentinel_page_report_filter_form() {
+  $session = isset($_SESSION['account_sentinel_report_filter']) ? $_SESSION['account_sentinel_report_filter'] : array();
+
+  $form['account_sentinel_filter'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Filter events'),
+    '#collapsible' => TRUE,
+    '#collapsed' => empty($session),
+  );
+  $filter = &$form['account_sentinel_filter'];
+
+  $event_types = account_sentinel_event_type_strings();
+  $origin_types = account_sentinel_event_origin_strings();
+  $event_types = array_map('ucfirst', $event_types);
+  $origin_types = array_map('ucfirst', $origin_types);
+  asort($event_types);
+  asort($origin_types);
+
+  $weight = 0;
+  $filter['fields'] = array(
+    '#type' => 'container',
+    '#attributes' => array('class' => array('account-sentinel-filter-fields')),
+  );
+  $filter['fields']['subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subject'),
+    '#description' => t("The changed user's name, or alternatively their UID in \"#UID\" format."),
+    '#size' => 20,
+    '#maxlength' => 60,
+    '#autocomplete_path' => 'user/autocomplete',
+    '#default_value' => isset($session['subject']) ? $session['subject'] : '',
+    '#weight' => $weight++,
+  );
+
+  $filter['fields']['ip'] = array(
+    '#type' => 'textfield',
+    '#title' => t('IP address'),
+    '#description' => t('This field is irrelevant in cases when the database was modified.'),
+    '#size' => 20,
+    '#maxlength' => 45,
+    '#default_value' => isset($session['ip']) ? $session['ip'] : '',
+    '#weight' => $weight++,
+  );
+
+  $filter['fields']['origin'] = array(
+    '#type' => 'select',
+    '#multiple' => TRUE,
+    '#title' => t('Event origin'),
+    '#required' => FALSE,
+    '#options' => $origin_types,
+    '#size' => min(5, count($origin_types)),
+    '#weight' => $weight++,
+    '#default_value' => isset($session['origin']) ? $session['origin'] : array(),
+  );
+
+  $filter['fields']['type'] = array(
+    '#type' => 'select',
+    '#multiple' => TRUE,
+    '#title' => t('Type of event'),
+    '#required' => FALSE,
+    '#options' => $event_types,
+    '#size' => min(5, count($event_types)),
+    '#weight' => $weight++,
+    '#default_value' => isset($session['type']) ? $session['type'] : array(),
+  );
+
+  $filter['fields']['after'] = array(
+    '#type' => 'date',
+    '#title' => t('Occurred after'),
+    '#required' => FALSE,
+    '#weight' => $weight++,
+    '#default_value' => isset($session['after']) ? account_sentinel_time_to_array($session['after']) : account_sentinel_time_to_array(0),
+  );
+
+  $filter['fields']['before'] = array(
+    '#type' => 'date',
+    '#title' => t('Occurred before'),
+    '#required' => FALSE,
+    '#weight' => $weight++,
+    '#default_value' => isset($session['before']) ? account_sentinel_time_to_array($session['before']) : account_sentinel_time_to_array(time()),
+  );
+
+  $filter['actions'] = array(
+    '#type' => 'actions',
+    '#attributes' => array('class' => array('account-sentinel-filter-actions')),
+  );
+  $filter['actions']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => (!empty($session) ? t('Refine') : t('Filter')),
+  );
+
+  if (!empty($session)) {
+    $filter['actions']['reset'] = array(
+      '#type' => 'submit',
+      '#value' => t('Reset'),
+    );
+  }
+
+  return $form;
+}
+
+/**
+ * Converts a UNIX timestamp to a Form API date array.
+ *
+ * @param int $time
+ *   UNIX timestamp.
+ *
+ * @return array
+ *   Date array.
+ */
+function account_sentinel_time_to_array($time = 0) {
+  return array(
+    'year' => date('Y', $time),
+    'month' => date('m', $time),
+    'day' => date('d', $time),
+  );
+}
+
+/**
+ * Converts a Form API's date field's value to UNIX timestamp.
+ *
+ * @param array $date
+ *   Date array.
+ * @param bool $end_of_day
+ *   If set to true, the last second of the day will be returned.
+ *
+ * @return int
+ *   UNIX timestamp.
+ */
+function account_sentinel_array_to_time(array $date, $end_of_day = FALSE) {
+  $time_of_day = $end_of_day ? '23:59:59' : '00:00:00';
+  return strtotime($date['year'] . '-' . $date['month'] . '-' . $date['day'] . ' ' . $time_of_day);
+}
+
+/**
+ * Handles the filter form's submission.
+ *
+ * @param array $form
+ *   The form's structure.
+ * @param array $form_state
+ *   The array containing the form's state.
+ */
+function account_sentinel_page_report_filter_form_submit(array $form, array &$form_state) {
+  $session = &$_SESSION['account_sentinel_report_filter'];
+  $values = $form_state['values'];
+
+  switch ($values['op']) {
+    case t('Refine'):
+    case t('Filter'):
+      if (($subject = trim($values['subject'])) != '') {
+        $session['subject'] = $subject;
+        $matches = array();
+        if (preg_match('/\\#([0-9]+)/', $subject, $matches)) {
+          // Store UID.
+          $session['uid'] = $matches[1];
+        }
+        else {
+          // Load by name.
+          $user = user_load_by_name($subject);
+          if ($user !== FALSE) {
+            $session['uid'] = $user->uid;
+          }
+        }
+      }
+      if (($ip = trim($values['ip'])) != '') {
+        $session['ip'] = $ip;
+      }
+      if (!empty($values['origin'])) {
+        $session['origin'] = array_keys($values['origin']);
+      }
+      if (!empty($values['type'])) {
+        $session['type'] = array_keys($values['type']);
+      }
+      if (!empty($values['after'])) {
+        $session['after'] = account_sentinel_array_to_time($values['after']);
+      }
+      if (!empty($values['before'])) {
+        $session['before'] = account_sentinel_array_to_time($values['before'], TRUE);
+      }
+      break;
+
+    case t('Reset'):
+      $session = array();
+      break;
+  }
+
+}
+
+/**
+ * Handler for the module's own cron URL.
+ */
+function account_sentinel_callback_cron() {
+  // Only handle if the cron_method is set to custom.
+  if (variable_get('account_sentinel_cron_method', 'drupal') == 'custom') {
+    // Validate access.
+    $query = drupal_get_query_parameters();
+    $cron_key = account_sentinel_get_cron_key();
+    if (isset($query['key']) && $query['key'] == $cron_key) {
+      watchdog('account_sentinel', 'Invoked database audit from URL.');
+      module_load_include('inc', 'account_sentinel', 'account_sentinel.audit');
+      account_sentinel_audit();
+    }
+    else {
+      watchdog('account_sentinel', 'Invalid access to audit URL.', array(), WATCHDOG_WARNING);
+    }
+  }
+}
+
+/**
+ * Handler for the cron key resetting URL.
+ */
+function account_sentinel_callback_reset_cron_key() {
+  $output = array();
+
+  // Validate access.
+  $query = drupal_get_query_parameters();
+  $cron_key = account_sentinel_get_cron_key();
+  if (isset($query['token']) && drupal_valid_token($query['token'], $cron_key)) {
+    // Reset cron key.
+    $cron_key = account_sentinel_reset_cron_key();
+
+    // Return the new URL.
+    $output['url_cron'] = url(
+      'system/account-sentinel-cron',
+      array(
+        'absolute' => TRUE,
+        'query' => array('key' => $cron_key),
+      )
+    );
+    $output['url_reset'] = url(
+      'system/account-sentinel-reset-cron-key',
+      array(
+        'query' => array('token' => drupal_get_token($cron_key)),
+      )
+    );
+  }
+
+  // Output JSON if JavaScript is enabled, otherwise refresh the page.
+  if (isset($query['js'])) {
+    drupal_json_output($output);
+  }
+  else {
+    drupal_goto('admin/config/system/account-sentinel');
+  }
+}

+ 241 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.test

@@ -0,0 +1,241 @@
+<?php
+
+/**
+ * @file
+ * Contains automated tests for Account Sentinel.
+ */
+
+/**
+ * Provides test cases for Account Sentinel.
+ */
+class AccountSentinelTest extends DrupalWebTestCase {
+
+  /**
+   * Returns the test's metadata.
+   *
+   * @return array
+   *   Information about the test.
+   */
+  public static function getInfo() {
+    return array(
+      'name' => 'Account Sentinel tests',
+      'description' => 'Test the Account Sentinel module.',
+      'group' => 'Account Sentinel',
+    );
+  }
+
+  protected $admin;
+  protected $subject;
+  protected $role;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp('account_sentinel');
+
+    // Create an administrator and log in.
+    $this->admin = $this->drupalCreateUser(array(
+      'administer permissions',
+      'administer users',
+      'access account sentinel logs',
+      'administer account sentinel',
+    ));
+    $this->drupalLogin($this->admin);
+
+    // Create subject user.
+    $this->subject = $this->drupalCreateUser();
+
+    // Create role to monitor.
+    $this->role = $this->drupalCreateRole(array());
+
+    // Grant role to subject user.
+    user_save($this->subject, array(
+      'name' => 'name',
+      'pass' => 'pass',
+      'mail' => 'mail@example.com',
+      'roles' => array($this->role => TRUE),
+    ));
+
+    // Configure the module.
+    $edit = array(
+      'account_sentinel_cron_method' => 'custom',
+    );
+    foreach (user_roles(TRUE) as $rid => $role) {
+      $edit['account_sentinel_monitored_roles[' . $rid . ']'] = ($rid == $this->role);
+    }
+    $this->drupalPost('admin/config/system/account-sentinel', $edit, t('Save configuration'));
+  }
+
+  /**
+   * User modification detection for changes made in Drupal.
+   */
+  public function testModifyInDrupal() {
+    // Change name, pass and email of user, also block it and remove its roles.
+    user_save($this->subject, array(
+      'name' => 'name_',
+      'pass' => 'pass_',
+      'mail' => 'mail_@example.com',
+      'status' => 0,
+      'roles' => array(),
+    ));
+    // Update the $subject variable too.
+    $this->subject = user_load($this->subject->uid);
+
+    // Check the log for the changes made.
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_NAME, array(
+      'old' => 'name',
+      'new' => 'name_',
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_PASS, array()));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_MAIL, array(
+      'old' => 'mail@example.com',
+      'new' => 'mail_@example.com',
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE, array(
+      'rid' => $this->role,
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK, array(
+      'rid' => $this->role,
+    )));
+
+    // Unblock the user and grant the monitored role.
+    user_save($this->subject, array(
+      'status' => 1,
+      'roles' => array($this->role => TRUE),
+    ));
+
+    // Check the log for the changes made.
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_UNBLOCK, array(
+      'rid' => $this->role,
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD, array(
+      'rid' => $this->role,
+    )));
+
+    // Delete the user.
+    user_delete($this->subject->uid);
+
+    // Check the log for the changes made.
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE, array(
+      'uid' => $this->subject->uid,
+      'name' => $this->subject->name,
+      'mail' => $this->subject->mail,
+    )));
+
+    // Readd the user.
+    $this->subject->is_new = TRUE;
+    user_save($this->subject);
+
+    // Check the log for the changes made.
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_ADD, array(
+      'uid' => $this->subject->uid,
+      'name' => $this->subject->name,
+      'mail' => $this->subject->mail,
+    )));
+  }
+
+  /**
+   * Runs the database audit by accessing the custom cron URL.
+   */
+  protected function runAudit() {
+    $this->drupalGet('system/account-sentinel-cron', array(
+      'query' => array('key' => account_sentinel_get_cron_key()),
+    ));
+  }
+
+  /**
+   * User modification detection for changes made via database modification.
+   */
+  public function testModifyInDatabase() {
+    // Change name, pass and mail of user, also block it.
+    $update = db_update('users');
+    $update->fields(array(
+      'name' => 'name_',
+      'pass' => 'pass_',
+      'mail' => 'mail_@example.com',
+      'status' => 0,
+    ));
+    $update->condition('uid', $this->subject->uid);
+    $update->execute();
+    // Update the $subject variable too.
+    $this->subject = user_load($this->subject->uid);
+
+    // Run the audit and check the log for the changes made.
+    $this->runAudit();
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_NAME, array(
+      'old' => 'name',
+      'new' => 'name_',
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_PASS, array()));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_MAIL, array(
+      'old' => 'mail@example.com',
+      'new' => 'mail_@example.com',
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_BLOCK, array(
+      'rid' => $this->role,
+    )));
+
+    // Remove the monitored role from the user.
+    $remove_role = db_delete('users_roles');
+    $remove_role->condition('uid', $this->subject->uid)
+      ->condition('rid', $this->role);
+    $remove_role->execute();
+
+    // Run the audit and check the log for the changes made.
+    $this->runAudit();
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_REMOVE, array(
+      'rid' => $this->role,
+    )));
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_MISSING, array()));
+
+    // Grant the role to the user.
+    $add_role = db_insert('users_roles');
+    $add_role->fields(array(
+      'uid' => $this->subject->uid,
+      'rid' => $this->role,
+    ));
+    $add_role->execute();
+
+    // Run the audit and check the log for the changes made.
+    $this->runAudit();
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_ROLE_ADD, array(
+      'rid' => $this->role,
+    )));
+
+    // Unblock the user.
+    $update = db_update('account_sentinel_users');
+    $update->fields(array(
+      'status' => 1,
+    ));
+    $update->condition('uid', $this->subject->uid);
+    $update->execute();
+
+    // Run the audit and check the log for the changes made.
+    $this->runAudit();
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_SNAPSHOT_INVALID, array()));
+
+    // Delete the user.
+    $remove_user = db_delete('users');
+    $remove_user->condition('uid', $this->subject->uid);
+    $remove_user->execute();
+
+    // Run the audit and check the log for the changes made.
+    $this->runAudit();
+    $this->drupalGet('admin/reports/account-sentinel');
+    $this->assertRaw(account_sentinel_get_event_message(ACCOUNT_SENTINEL_EVENT_TYPE_USER_DELETE, array(
+      'uid' => $this->subject->uid,
+      'name' => $this->subject->name,
+      'mail' => $this->subject->mail,
+    )));
+  }
+
+}

+ 34 - 0
sites/all/modules/contrib/security/account_sentinel/account_sentinel.themes.inc

@@ -0,0 +1,34 @@
+<?php
+
+/**
+ * @file
+ * Contains Account Sentinel's templates and template preprocessors.
+ */
+
+/**
+ * Formats a username by its UID.
+ *
+ * Almost the same as the "username" theme, but if the UID is not 0 and
+ * user_load returns FALSE, it will return the UID of the (probably) deleted
+ * user.
+ *
+ * @param array $variables
+ *   An associative array containing:
+ *   - uid: The UID of the user.
+ *
+ * @see theme_username()
+ *
+ * @return string
+ *   The HTML for a username.
+ */
+function theme_account_sentinel_username(array $variables) {
+  $uid = $variables['uid'];
+  $user = user_load($uid);
+
+  if ($uid != 0 && $user === FALSE) {
+    return t('#@uid (deleted)', array('@uid' => $uid));
+  }
+  else {
+    return theme('username', array('account' => $user));
+  }
+}

+ 31 - 0
sites/all/modules/contrib/security/account_sentinel/css/report.css

@@ -0,0 +1,31 @@
+/* Filter styles. */
+.account-sentinel-filter-fields {
+  float: none;
+  clear: both;
+}
+
+.account-sentinel-filter-actions {
+  float: none;
+  clear: both;
+}
+
+/* Table styles */
+.account-sentinel-table tr {
+  border-bottom: 1px solid #dbdbdb;
+}
+
+.account-sentinel-table tr:last-of-type {
+  border-bottom: none;
+}
+
+.account-sentinel-table tr.origin--database td.col--by {
+  color: #680308;
+}
+
+.account-sentinel-table tr.origin--database.odd td.col--by {
+  background-color: #ffe1e1 !important;
+}
+
+.account-sentinel-table tr.origin--database.even td.col--by {
+  background-color: #f6d8d8 !important;
+}

+ 19 - 0
sites/all/modules/contrib/security/account_sentinel/js/settings.js

@@ -0,0 +1,19 @@
+/**
+ * @file
+ * Provides an AJAX handler for the cron URL reset functionality.
+ */
+
+(function ($) {
+  'use strict';
+  Drupal.behaviors.AccountSentinelSettings = {
+    attach: function (context, settings) {
+      $('#cron-reset-link').click(function () {
+        $.getJSON(this.getAttribute('href') + '&js=1', function (data) {
+          $('#cron-link').html(data.url_cron).attr('href', data.url_cron);
+          $('#cron-reset-link').attr('href', data.url_reset);
+        });
+        return false;
+      });
+    }
+  };
+})(jQuery);