Including security review as a submodule - with patched for Yaffs.
authorJeff Veit <jeff.veit@gmail.com>
Tue, 27 Jun 2017 02:04:21 +0000 (03:04 +0100)
committerJeff Veit <jeff.veit@gmail.com>
Tue, 27 Jun 2017 02:04:21 +0000 (03:04 +0100)
59 files changed:
web/modules/contrib/security_review/API.txt [new file with mode: 0644]
web/modules/contrib/security_review/IGNOREME.txt [new file with mode: 0644]
web/modules/contrib/security_review/PATCHES.txt [new file with mode: 0644]
web/modules/contrib/security_review/README.txt [new file with mode: 0644]
web/modules/contrib/security_review/config/install/security_review.check.security_review-base_url_set.yml [new file with mode: 0644]
web/modules/contrib/security_review/config/install/security_review.settings.yml [new file with mode: 0644]
web/modules/contrib/security_review/config/schema/security_review.schema.yml [new file with mode: 0644]
web/modules/contrib/security_review/css/security_review.run_and_review.css [new file with mode: 0644]
web/modules/contrib/security_review/js/security_review.run_and_review.js [new file with mode: 0644]
web/modules/contrib/security_review/security_review.api.php [new file with mode: 0644]
web/modules/contrib/security_review/security_review.drush.inc [new file with mode: 0644]
web/modules/contrib/security_review/security_review.info.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.install [new file with mode: 0644]
web/modules/contrib/security_review/security_review.libraries.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.links.menu.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.links.task.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.module [new file with mode: 0644]
web/modules/contrib/security_review/security_review.permissions.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.routing.yml [new file with mode: 0644]
web/modules/contrib/security_review/security_review.services.yml [new file with mode: 0644]
web/modules/contrib/security_review/src/Check.php [new file with mode: 0644]
web/modules/contrib/security_review/src/CheckResult.php [new file with mode: 0644]
web/modules/contrib/security_review/src/CheckSettings.php [new file with mode: 0644]
web/modules/contrib/security_review/src/CheckSettings/TrustedHostSettings.php [new file with mode: 0644]
web/modules/contrib/security_review/src/CheckSettingsInterface.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checklist.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/AdminPermissions.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/ErrorReporting.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/ExecutablePhp.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/FailedLogins.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/Field.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/FilePermissions.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/InputFormats.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/PrivateFiles.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/QueryErrors.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/TemporaryFiles.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/TrustedHosts.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/UploadExtensions.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Checks/ViewsAccess.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Controller/ChecklistController.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Controller/HelpController.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Controller/ToggleController.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Form/RunForm.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Form/SettingsForm.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Security.php [new file with mode: 0644]
web/modules/contrib/security_review/src/SecurityReview.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Tests/CheckTest.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Tests/CheckWebTest.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Tests/ChecklistTest.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Tests/ChecklistWebTest.php [new file with mode: 0644]
web/modules/contrib/security_review/src/Tests/SecurityReviewTest.php [new file with mode: 0644]
web/modules/contrib/security_review/templates/check_evaluation.html.twig [new file with mode: 0644]
web/modules/contrib/security_review/templates/check_help.html.twig [new file with mode: 0644]
web/modules/contrib/security_review/templates/general_help.html.twig [new file with mode: 0644]
web/modules/contrib/security_review/templates/run_and_review.html.twig [new file with mode: 0644]
web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.info.yml [new file with mode: 0644]
web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.module [new file with mode: 0644]
web/modules/contrib/security_review/tests/modules/security_review_test/src/Test.php [new file with mode: 0644]
web/modules/contrib/security_review/tests/modules/security_review_test/src/TestNoStore.php [new file with mode: 0644]

diff --git a/web/modules/contrib/security_review/API.txt b/web/modules/contrib/security_review/API.txt
new file mode 100644 (file)
index 0000000..627e264
--- /dev/null
@@ -0,0 +1,198 @@
+For the latest documentation and code examples go to:
+https://www.drupal.org/node/2508415
+
+# Security Review API
+
+  * Defining a security check
+    * Identifiers
+    * Action and messages
+    * Help page
+    * Evaluation page (optional)
+    * Check-specific settings (optional)
+      * Form generation
+      * Configuration schema
+  * Hooks
+  * Alterable variables
+  * Drush usage
+
+## Defining a security check
+
+  This part of the documentation lets the developer understand the behavior of
+  the module. If anything's unclear it is recommended to look at the examples.
+
+  To define a security check for Security Review, one has to create a class that
+  extends Drupal\security_review\Check.
+  The functions that must be overridden are the following:
+    * getNamespace()
+    * getTitle()
+    * run()
+    * help()
+    * getMessage()
+
+  ### Identifiers
+
+    There are 5 kinds of identifiers for a given check:
+      * namespace
+      * machine namespace
+      * title
+      * machine title
+      * id
+
+    The 'namespace' must be manually set for each check by overriding the
+    getNamespace() method. This is the human-readable namespace of the check
+    (usually the module's name).
+
+    The 'machine namespace' is the version of namespace that is used internally.
+    If getMachineNamespace() isn't overridden, then it is produced from the
+    human-readable namespace by removing any non-alphanumeric characters and
+    replacing spaces with underscores. When overriding getMachineNamespace()
+    this rule must be followed.
+
+    The 'title' must be manually set for each check by overriding the getTitle()
+    method. This is the human-readable title of the check.
+
+    The 'machine title' has the same relationship to 'title' as 'machine
+    namespace' has to 'namespace'. The machine title should be unique to the
+    namespace. This might only be achievable by overriding getMachineTitle().
+
+    The 'id' is only used internally and cannot be overridden. It's constructed
+    by taking the 'machine namespace' and 'machine title' and putting a hyphen
+    between them.
+
+  ### Action and messages
+
+    The part where the actual security check happens is the run() method. This
+    method must be overridden, and should always return an instance of
+    Drupal\security_review\CheckResult.
+
+    Instantiating a CheckResult:
+
+    CheckResult defines one constructor:
+    (Check $check, $result, array $findings, $visible = TRUE, $time = NULL)
+      * $check
+        The Check that is responsible for the result
+      * $result
+        An integer that defines the outcome of the check:
+          * CheckResult::SUCCESS  - for a successful check
+          * CheckResult::FAIL     - for a failed check
+          * CheckResult::WARN     - for a check that only raised a warning
+          * CheckResult::INFO     - general result for providing information
+      * $findings
+        An array of findings that can be evaluated. It can be empty.
+      * $visible
+        Check results can be hidden from the user by setting $visible to FALSE.
+      * $time
+        Timestamp indicating the time when the result was produced. If left null
+        it will be the current time.
+
+    NOTE:
+    It's easier to instantiate a result with Check's createResult() method. It
+    has the same parameters as the constructor for CheckResult, except the
+    $check is left out (set to $this).
+
+    Human-readable messages for each result integer:
+
+    Must be defined by overriding the getMessage() method. The implementation is
+    usually a switch-case. For more details take a look at Security Review's own
+    Check implementations.
+
+  ### Help page
+
+    Every Check can have its own help page by overriding the help() method. This
+    should return a render array.
+    See https://www.drupal.org/developing/api/8/render/arrays
+
+  ### Evaluation page (optional)
+
+    The evaluation page is for providing an evaluation of a CheckResult produced
+    by the Check. Overriding this is optional, the default implementation
+    returns an empty array. If one chooses to override evaluate(), the function
+    must return a render array.
+    See https://www.drupal.org/developing/api/8/render/arrays
+
+  ### Check-specific settings (optional)
+
+    If the Check requires storage for settings, it can be accessed via
+    $this->settings(). This method returns a
+    Drupal\security_review\CheckSettingsInterface. It has get() and set()
+    methods for accessing the stored configuration, and buildForm(),
+    submitForm(), validateForm() for form building. By default Check's
+    implementation contains a Drupal\security_review\CheckSettings, which stores
+    the values in the Configuration system, and does nothing in its form
+    building methods. Usually it's enough to extend this class if the Check
+    needs separate settings on the Security Review settings page.
+
+    When using check-specific settings it's recommended to define a
+    configuration schema to store the values in their correct types. The schema
+    to declare is called security_review.check_settings.[id of check] .
+
+## Hooks
+
+  ### hook_security_review_checks()
+
+    To let Security Review know of the checks defined in the module it has to
+    implement hook_security_review_checks(). This hook is fairly simple. It has
+    to return an array of check instances.
+
+    For example implementations see security_review.api.php and
+    security_review.module and the examples.
+
+  ### hook_security_review_log()
+
+    Provides logging functions for various events:
+    Check skipped / enabled
+    Check ran
+    Check gave a NULL result
+
+    For example implementations see security_review.api.php and
+    security_review.module.
+
+## Alterable variables
+
+  To understand what alterable variables are, take a look at
+  https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Extension!ModuleHandler.php/function/ModuleHandler%3A%3Aalter/8
+  To modify an alterable variable you have to implement hook_[TYPE]_alter.
+  An example:
+
+  <?php
+  // ...
+  /**
+   * Implements hook_security_review_unsafe_extensions_alter().
+   */
+  function my_module_security_review_unsafe_extensions_alter(array &$variable) {
+    // Add the .reg file extension to the list of unsafe extensions.
+    $variable[] = 'reg';
+  }
+  ?>
+
+  ### security_review_unsafe_tags
+
+    The list of HTML tags considered to be unsafe.
+    See https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet .
+
+    Default variable content is at Security::unsafeTags().
+
+  ### security_review_unsafe_extensions
+
+    The list of file extensions considered to be unsafe for upload. Untrusted
+    users should not be allowed to upload files of these extensions.
+
+    Default variable content is at Security::unsafeExtensions().
+
+  ### security_review_file_ignore
+
+    The list of relative and absolute paths to ignore when running the File
+    permissions check.
+
+    Default variable content is at FilePermissions::run().
+
+  ### security_review_temporary_files
+
+    The list of files to check for the Temporary files security check.
+
+    Default variable definition is at TemporaryFiles::run().
+
+## Drush usage
+
+  Run the checklist via Drush with the "drush security-review" command.
+  Consult the Drush help on the security-review command for more information.
diff --git a/web/modules/contrib/security_review/IGNOREME.txt b/web/modules/contrib/security_review/IGNOREME.txt
new file mode 100644 (file)
index 0000000..72e8e13
--- /dev/null
@@ -0,0 +1,5 @@
+You should read the README.txt but can ignore this file. It is used as part of
+the test to see if files are writable on your site. If you see timestamps below
+this line those are security runs which were able to write to this file.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+20160608114206 - Your web server should not be able to write to your modules directory. This is a security vulnerable. Consult the Security Review file permissions check help for mitigation steps.
diff --git a/web/modules/contrib/security_review/PATCHES.txt b/web/modules/contrib/security_review/PATCHES.txt
new file mode 100644 (file)
index 0000000..3294fe1
--- /dev/null
@@ -0,0 +1,7 @@
+This file was automatically generated by Composer Patches (https://github.com/cweagans/composer-patches)
+Patches applied to this directory:
+
+Fix missing field review list
+Source: https://www.drupal.org/files/issues/security_review-dangerous-tags-list-2744805-2.patch
+
+
diff --git a/web/modules/contrib/security_review/README.txt b/web/modules/contrib/security_review/README.txt
new file mode 100644 (file)
index 0000000..03e7304
--- /dev/null
@@ -0,0 +1,91 @@
+
+-- ABOUT --
+
+Security Review automates checking many of the configuration errors that lead
+to an insecure Drupal site and looks for existing vulnerabilities and attack
+attempts.
+
+The primary goal of the module is to elevate your awareness of the importance of
+securing your Drupal site. The results of some checks may be incorrect depending
+on unique factors, this module does not make your site more secure. You should
+use the results of the checklist and its resources to manually secure your site.
+
+Refer to the support section below if you are interested in securing your Drupal
+site.
+
+-- INSTALLATION --
+
+Place the security_review directory and its contents under /modules or a
+subdirectory of /modules in the Drupal root directory.
+
+Enable the module at Administer >> Modules and refer to the
+following sections for configuration and usage.
+
+-- CONFIGURATION --
+
+Two permissions are provided and required to use the module. Navigate to
+Administer >> People >> Permissions to enable
+'access security review list' and 'run security checks' for trusted roles.
+
+NOTICE: This module provides information on the state of your site's security so
+it is imperative you grant these permissions to trusted roles and users only.
+For instance, if you have an admin role, be sure that all the users who have
+been granted this role are indeed users you trust if you grant them these
+permissions.
+
+After you have granted permissions to the module you should inform the system
+what roles are not trusted. Navigate to
+Administer >> Reports >> Security Review >> Settings to mark which roles are
+untrusted. Most checks only care if the resource is usable by
+untrusted roles.
+
+On this page you can also define the level of logging. The result
+of the last checklist is always stored but you can enable watchdog logging of
+each check if you like.
+
+-- USAGE --
+
+Navigate to Administer >> Reports >> Security Review to run the checklist.
+
+If a check is enabled it will be run. You can enable or skip a check on this
+page only after it has been run. Clicking on the 'Help' link beside each check
+will provide details on why the check exists and what was found on the last run.
+
+-- DRUSH USAGE --
+
+Running the Security Review checklist using Drush is a great way to build
+automated security audits of your site into your site development lifecycle and
+as part of continuous integration.
+
+With the module installed invoke 'drush secrev' from within your Drupal root.
+
+Call 'drush help secrev' to see available options.
+
+For running specific checks pass the '--check' option. Be sure to remove any
+whitespace characters separating check names.
+
+Consult implementations of hook_security_checks() for exact list of available
+check options. Standard Security Review checks are:
+
+file_perms, input_formats, field, error_reporting, private_files, query_errors,
+failed_logins, upload_extensions, admin_permissions, executable_php,
+trusted_hosts, temporary_files
+
+For custom checks you may prefix the check name with the module name and
+colon (:) character. For example:
+
+'drush secrev --check=my_module:my_check'
+
+Note, custom checks require that its module be enabled. Also, should you be
+skipping any check the 'store' option will not allow that check to be run.
+
+-- SUPPORT --
+
+Please use the issue queue at http://drupal.org/project/security_review for all
+module support. You can read more about securely configuring your site at
+http://drupal.org/security/secure-configuration and http://drupalscout.com
+
+-- CREDIT --
+
+Security Review module originally written by Benjamin Jeavons, drupal.org user
+coltrane. Ported to Drupal 8 by Viktor Bán.
diff --git a/web/modules/contrib/security_review/config/install/security_review.check.security_review-base_url_set.yml b/web/modules/contrib/security_review/config/install/security_review.check.security_review-base_url_set.yml
new file mode 100644 (file)
index 0000000..070f10a
--- /dev/null
@@ -0,0 +1,3 @@
+id: 'security_review-base_url_set'
+settings:
+  method: 'token'
diff --git a/web/modules/contrib/security_review/config/install/security_review.settings.yml b/web/modules/contrib/security_review/config/install/security_review.settings.yml
new file mode 100644 (file)
index 0000000..894cbe1
--- /dev/null
@@ -0,0 +1,4 @@
+configured: false
+untrusted_roles: []
+log: true
+last_run: 0
diff --git a/web/modules/contrib/security_review/config/schema/security_review.schema.yml b/web/modules/contrib/security_review/config/schema/security_review.schema.yml
new file mode 100644 (file)
index 0000000..86e3b18
--- /dev/null
@@ -0,0 +1,48 @@
+# The module's main settings.
+security_review.settings:
+  type: config_entity
+  mapping:
+    configured:
+      type: boolean
+      label: 'Has been configured'
+    untrusted_roles:
+      type: sequence
+      label: 'Untrusted roles'
+      sequence:
+        type: string
+        label: 'Role ID'
+    log:
+      type: boolean
+      label: 'Logging enabled'
+    last_run:
+      type: integer
+      label: 'Last run'
+
+# Defines a security check's skip informations and settings.
+security_review.check.*:
+  type: config_entity
+  mapping:
+    id:
+      type: string
+      label: 'Check ID'
+    skipped:
+      type: boolean
+      label: 'Is skipped'
+    skipped_by:
+      type: integer
+      label: 'Skipped by'
+    skipped_on:
+      type: integer
+      label: 'Skipped on'
+    settings:
+      # Checks that need storage for settings are advised to define their settings schema.
+      # This way type-strict per-check settings storage can be created.
+      type: security_review.check_settings.[%parent.id]
+
+# Setting storage for Base URL check.
+security_review.check_settings.security_review-base_url_set:
+  type: mapping
+  mapping:
+    method:
+      type: string
+      label: 'Base URL identification method'
diff --git a/web/modules/contrib/security_review/css/security_review.run_and_review.css b/web/modules/contrib/security_review/css/security_review.run_and_review.css
new file mode 100644 (file)
index 0000000..56ed396
--- /dev/null
@@ -0,0 +1,42 @@
+.security-review-run-and-review__table {
+  border: none;
+}
+
+.security-review-run-and-review__entry {
+  border-width: 1px 0 0 0;
+  border-style: solid;
+  border-color: #ccc;
+}
+
+.security-review-run-and-review__entry-icon {
+  width: 16px;
+}
+
+.security-review-run-and-review__entry:last-child {
+  border-bottom-width: 1px;
+}
+
+.security-review-run-and-review__entry.skipped {
+  color: #333333 !important;
+  background-color: #dddddd !important;
+}
+
+.security-review-run-and-review__entry.success {
+  color: #255b1e;
+  background-color: #e5ffe2;
+}
+
+.security-review-run-and-review__entry.fail {
+  color: #8c2e0b;
+  background-color: #fef5f1;
+}
+
+.security-review-run-and-review__entry.warning {
+  color: #734c00;
+  background-color: #fdf8ed;
+}
+
+.security-review-run-and-review__entry.info {
+  color: #000e6f;
+  background-color: #dfefff;
+}
diff --git a/web/modules/contrib/security_review/js/security_review.run_and_review.js b/web/modules/contrib/security_review/js/security_review.run_and_review.js
new file mode 100644 (file)
index 0000000..f249e41
--- /dev/null
@@ -0,0 +1,28 @@
+/**
+ * @file
+ * Implementation of check toggling using AJAX.
+ */
+
+(function ($) {
+  Drupal.behaviors.securityReview = {
+    attach: function (context) {
+      $(context).find('.security-review-toggle-link a').click(function () {
+        var link = $(this);
+        var url = link.attr('href');
+        var td = link.parent();
+        var tr = td.parent();
+        $.getJSON(url + '&js=1', function (data) {
+          if (data.skipped) {
+            tr.addClass('skipped');
+          }
+          else {
+            tr.removeClass('skipped');
+          }
+          link.text(data.toggle_text);
+          link.attr(data.toggle_href);
+        });
+        return false;
+      });
+    }
+  };
+})(jQuery);
diff --git a/web/modules/contrib/security_review/security_review.api.php b/web/modules/contrib/security_review/security_review.api.php
new file mode 100644 (file)
index 0000000..157689d
--- /dev/null
@@ -0,0 +1,48 @@
+<?php
+
+/**
+ * @file
+ * Defines the API for Security Review.
+ */
+
+/*
+use Drupal\mymodule\MyCheck;
+use Drupal\mymodule\MyOtherCheck;
+ */
+use Drupal\security_review\Check;
+
+/**
+ * Returns the array of security checks the module defines.
+ *
+ * The checks must extend \Drupal\security_review\Check.
+ *
+ * @return array
+ *   An array of security checks.
+ */
+function hook_security_review_checks() {
+  // Return instances of the defined Checks.
+  return [
+    /*
+    new MyCheck(),
+    new MyOtherCheck(),
+    */
+  ];
+}
+
+/**
+ * Provides logging capabilities.
+ *
+ * @param \Drupal\security_review\Check $check
+ *   The Check the event is related to.
+ * @param string $message
+ *   The message.
+ * @param array $context
+ *   The context of the message.
+ * @param int $level
+ *   Severity (RfcLogLevel).
+ */
+function hook_security_review_log(Check $check, $message, array $context, $level) {
+  if ($check->getNamespace() == "My Module") {
+    // Do something with the information.
+  }
+}
diff --git a/web/modules/contrib/security_review/security_review.drush.inc b/web/modules/contrib/security_review/security_review.drush.inc
new file mode 100644 (file)
index 0000000..6931887
--- /dev/null
@@ -0,0 +1,251 @@
+<?php
+
+/**
+ * @file
+ * Drush commands for Security Review module.
+ */
+
+use Drupal\security_review\CheckResult;
+
+/**
+ * Implements hook_drush_command().
+ */
+function security_review_drush_command() {
+  $items = [];
+
+  $items['security-review'] = [
+    'aliases' => ['secrev'],
+    'callback' => 'security_review_drush',
+    'description' => "Run the Security Review checklist",
+    'options' => [
+      'store' => 'Write results to the database',
+      'log' => 'Log results of each check to watchdog, defaults to off',
+      'lastrun' => 'Do not run the checklist, just print last results',
+      'check' => 'Comma-separated list of specified checks to run. See README.txt for list of options',
+      'skip' => 'Comma-separated list of specified checks not to run. This takes precedence over --check.',
+      'short' => "Short result messages instead of full description (e.g. 'Text formats')",
+      'results' => 'Show the incorrect settings for failed checks',
+    ],
+    'examples' => [
+      'secrev' => 'Run the checklist and output the results',
+      'secrev --store' => 'Run the checklist, store, and output the results',
+      'secrev --lastrun' => 'Output the stored results from the last run of the checklist',
+    ],
+    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
+    'outputformat' => [
+      'default' => 'table',
+      'pipe-format' => 'csv',
+      'fields-default' => ['message', 'status'],
+      'field-labels' => [
+        'message' => 'Message',
+        'status' => 'Status',
+        'findings' => 'Findings',
+      ],
+      'output-data-type' => 'format-table',
+    ],
+  ];
+
+  return $items;
+}
+
+/**
+ * Implements hook_drush_help().
+ */
+function security_review_drush_help($section) {
+  switch ($section) {
+    case 'drush:security-review':
+      return dt("Run configuration security checks on your Drupal site.");
+  }
+}
+
+/**
+ * Runs a checklist and displays results.
+ */
+function security_review_drush() {
+  /** @var \Drupal\security_review\SecurityReview $security_review */
+  $security_review = Drupal::service('security_review');
+
+  /** @var \Drupal\security_review\Checklist $checklist */
+  $checklist = Drupal::service('security_review.checklist');
+
+  $store = drush_get_option('store');
+  $log = drush_get_option('log');
+  $last_run = drush_get_option('lastrun');
+  $run_checks = drush_get_option_list('check');
+  $skip_checks = drush_get_option_list('skip');
+  $short_titles = drush_get_option('short');
+  $show_findings = drush_get_option('results');
+
+  // Set temporary logging.
+  $log = in_array($log, [TRUE, 1, 'TRUE']);
+  $security_review->setLogging($log, TRUE);
+
+  if (!empty($short_titles)) {
+    $short_titles = TRUE;
+  }
+  else {
+    $short_titles = FALSE;
+  }
+
+  $results = [];
+  if (!$last_run) {
+    // Do a normal security review run.
+    /** @var \Drupal\security_review\Check[] $checks */
+    $checks = [];
+    /** @var \Drupal\security_review\Check[] $to_skip */
+    $to_skip = [];
+
+    // Fill the $checks array.
+    if (!empty($run_checks)) {
+      // Get explicitly specified checks.
+      foreach ($run_checks as $check) {
+        $checks[] = _security_review_drush_get_check($check);
+      }
+    }
+    else {
+      // Get the whole checklist.
+      $checks = $checklist->getChecks();
+    }
+
+    // Mark checks listed after --skip for removal.
+    if (!empty($skip_checks)) {
+      foreach ($skip_checks as $skip_check) {
+        $to_skip[] = _security_review_drush_get_check($skip_check);
+      }
+    }
+
+    // If storing, mark skipped checks for removal.
+    if ($store) {
+      foreach ($checks as $check) {
+        if ($check->isSkipped()) {
+          $to_skip[] = $check;
+        }
+      }
+    }
+
+    // Remove the skipped checks from $checks.
+    foreach ($to_skip as $skip_check) {
+      foreach ($checks as $key => $check) {
+        if ($check->id() == $skip_check->id()) {
+          unset($checks[$key]);
+        }
+      }
+    }
+
+    // If $checks is empty at this point, return with an error.
+    if (empty($checks)) {
+      return drush_set_error('EMPTY_CHECKLIST', dt("No checks to run. Run 'drush help secrev' for option use or consult the drush section of API.txt for further help."));
+    }
+
+    // Run the checks.
+    $results = $checklist->runChecks($checks, TRUE);
+
+    // Store the results.
+    if ($store) {
+      $checklist->storeResults($results);
+    }
+  }
+  else {
+    // Show the latest stored results.
+    foreach ($checklist->getChecks() as $check) {
+      $last_result = $check->lastResult($show_findings);
+      if ($last_result instanceof CheckResult) {
+        $results[] = $last_result;
+      }
+    }
+  }
+
+  return _security_review_drush_format_results($results, $short_titles, $show_findings);
+}
+
+/**
+ * Helper function for parsing input check name strings.
+ *
+ * @param string $check_name
+ *   The check to get.
+ *
+ * @return \Drupal\security_review\Check|null
+ *   The found Check.
+ */
+function _security_review_drush_get_check($check_name) {
+  /** @var \Drupal\security_review\Checklist $checklist */
+  $checklist = Drupal::service('security_review.checklist');
+
+  // Default namespace is Security Review.
+  $namespace = 'security_review';
+  $title = $check_name;
+
+  // Set namespace and title if explicitly defined.
+  if (strpos($check_name, ':') !== FALSE) {
+    list($namespace, $title) = explode(':', $check_name);
+  }
+
+  // Return the found check if any.
+  return $checklist->getCheck($namespace, $title);
+}
+
+/**
+ * Helper function to compile Security Review results.
+ *
+ * @param \Drupal\security_review\CheckResult[] $results
+ *   An array of CheckResults.
+ * @param bool $short_titles
+ *   Whether to use short message (check title) or full check success or failure
+ *   message.
+ * @param bool $show_findings
+ *   Whether to print failed check results.
+ *
+ * @return array
+ *   The results of the security review checks.
+ */
+function _security_review_drush_format_results(array $results, $short_titles = FALSE, $show_findings = FALSE) {
+  $output = [];
+
+  foreach ($results as $result) {
+    if ($result instanceof CheckResult) {
+      if (!$result->isVisible()) {
+        // Continue with the next check.
+        continue;
+      }
+
+      $check = $result->check();
+      $message = $short_titles ? $check->getTitle() : $result->resultMessage();
+      $status = 'notice';
+
+      // Set log level according to check result.
+      switch ($result->result()) {
+        case CheckResult::SUCCESS:
+          $status = 'success';
+          break;
+
+        case CheckResult::FAIL:
+          $status = 'failed';
+          break;
+
+        case CheckResult::WARN:
+          $status = 'warning';
+          break;
+
+        case CheckResult::INFO:
+          $status = 'info';
+          break;
+      }
+
+      // Attach findings.
+      if ($show_findings) {
+        $findings = trim($result->check()->evaluatePlain($result));
+        if ($findings != '') {
+          $message .= "\n" . $findings;
+        }
+      }
+
+      $output[$check->id()] = [
+        'message' => (string) $message,
+        'status' => $status,
+        'findings' => $result->findings(),
+      ];
+    }
+  }
+
+  return $output;
+}
diff --git a/web/modules/contrib/security_review/security_review.info.yml b/web/modules/contrib/security_review/security_review.info.yml
new file mode 100644 (file)
index 0000000..5c810f8
--- /dev/null
@@ -0,0 +1,6 @@
+name: Security Review
+type: module
+description: 'Site security and configuration review module.'
+package: Security
+core: 8.x
+configure: security_review.settings
diff --git a/web/modules/contrib/security_review/security_review.install b/web/modules/contrib/security_review/security_review.install
new file mode 100644 (file)
index 0000000..9991149
--- /dev/null
@@ -0,0 +1,80 @@
+<?php
+
+/**
+ * @file
+ * Install, update and uninstall functions for the security_review module.
+ */
+
+use Drupal\Core\Url;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Implements hook_install().
+ */
+function security_review_install() {
+  // Remind the user to set the permissions.
+  drupal_set_message(
+    t(
+      'Security Review module enabled. You should first set the module access permissions at <a href=":url">admin/people/permissions</a>. Be sure to grant permissions to trusted users only as this module can show sensitive site information.',
+      [':url' => Url::fromRoute('user.admin_permissions')->toString()]
+    )
+  );
+}
+
+/**
+ * Implements hook_requirements().
+ */
+function security_review_requirements($phase) {
+  $requirements = [];
+
+  // Provides a Status Report entry.
+  if ($phase == 'runtime') {
+    /** @var \Drupal\security_review\Checklist $checklist */
+    $checklist = Drupal::service('security_review.checklist');
+
+    $failed_checks = FALSE;
+    $no_results = TRUE;
+
+    // Looks for failed checks.
+    foreach ($checklist->getEnabledChecks() as $check) {
+      $result = $check->lastResult();
+      if ($result instanceof CheckResult) {
+        $no_results = FALSE;
+        if ($result->result() === CheckResult::FAIL) {
+          $failed_checks = TRUE;
+          break;
+        }
+      }
+    }
+
+    $module_url = Url::fromRoute('security_review')->toString();
+    if ($no_results) {
+      $severity = REQUIREMENT_WARNING;
+      $value = t(
+        'The Security Review checklist has not been run. <a href=":url">Run the checklist</a>',
+        [':url' => $module_url]
+      );
+    }
+    elseif ($failed_checks) {
+      $severity = REQUIREMENT_WARNING;
+      $value = t(
+        'There are failed Security Review checks. <a href=":url">Review the checklist</a>',
+        [':url' => $module_url]
+      );
+    }
+    else {
+      $severity = REQUIREMENT_OK;
+      $value = t(
+        'Passing all non-ignored Security Review checks. <a href=":url">Review the checklist</a>',
+        [':url' => $module_url]
+      );
+    }
+    $requirements['security_review'] = [
+      'title' => t('Security Review'),
+      'severity' => $severity,
+      'value' => $value,
+    ];
+  }
+
+  return $requirements;
+}
diff --git a/web/modules/contrib/security_review/security_review.libraries.yml b/web/modules/contrib/security_review/security_review.libraries.yml
new file mode 100644 (file)
index 0000000..0eccdf9
--- /dev/null
@@ -0,0 +1,10 @@
+run_and_review:
+  version: VERSION
+  css:
+    theme:
+      css/security_review.run_and_review.css: {}
+  js:
+    js/security_review.run_and_review.js: {}
+  dependencies:
+    - core/jquery
+    - core/drupal
diff --git a/web/modules/contrib/security_review/security_review.links.menu.yml b/web/modules/contrib/security_review/security_review.links.menu.yml
new file mode 100644 (file)
index 0000000..89ec97a
--- /dev/null
@@ -0,0 +1,11 @@
+security_review:
+  route_name: security_review
+  title: 'Security review'
+  description: 'Perform a review of the security of your site.'
+  parent: system.admin_reports
+
+security_review.settings:
+  route_name: security_review.settings
+  title: 'Security Review'
+  description: 'Choose which roles are untrusted, set logging, skip or enable security checks and modify check-specific settings.'
+  parent: system.admin_config_system
diff --git a/web/modules/contrib/security_review/security_review.links.task.yml b/web/modules/contrib/security_review/security_review.links.task.yml
new file mode 100644 (file)
index 0000000..64278e8
--- /dev/null
@@ -0,0 +1,16 @@
+security_review:
+  route_name: security_review
+  title: 'Run & review'
+  base_route: security_review
+
+security_review.help:
+  route_name: security_review.help
+  title: 'Help'
+  weight: 10
+  base_route: security_review
+
+security_review.settings:
+  route_name: security_review.settings
+  title: 'Settings'
+  weight: 15
+  base_route: security_review
diff --git a/web/modules/contrib/security_review/security_review.module b/web/modules/contrib/security_review/security_review.module
new file mode 100644 (file)
index 0000000..cd640f6
--- /dev/null
@@ -0,0 +1,229 @@
+<?php
+
+/**
+ * @file
+ * Site security review and reporting Drupal module.
+ */
+
+use Drupal\Core\Logger\RfcLogLevel;
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Drupal\security_review\Checks\AdminPermissions;
+use Drupal\security_review\Checks\ErrorReporting;
+use Drupal\security_review\Checks\ExecutablePhp;
+use Drupal\security_review\Checks\FailedLogins;
+use Drupal\security_review\Checks\Field;
+use Drupal\security_review\Checks\FilePermissions;
+use Drupal\security_review\Checks\InputFormats;
+use Drupal\security_review\Checks\PrivateFiles;
+use Drupal\security_review\Checks\QueryErrors;
+use Drupal\security_review\Checks\TemporaryFiles;
+use Drupal\security_review\Checks\TrustedHosts;
+use Drupal\security_review\Checks\UploadExtensions;
+use Drupal\security_review\Checks\ViewsAccess;
+
+/**
+ * Implements hook_security_review_checks().
+ */
+function security_review_security_review_checks() {
+  return [
+    new AdminPermissions(),
+    new ErrorReporting(),
+    new ExecutablePhp(),
+    new FailedLogins(),
+    new Field(),
+    new FilePermissions(),
+    new InputFormats(),
+    new PrivateFiles(),
+    new QueryErrors(),
+    new TemporaryFiles(),
+    new TrustedHosts(),
+    new UploadExtensions(),
+    new ViewsAccess(),
+  ];
+}
+
+/**
+ * Implements hook_security_review_log().
+ */
+function security_review_security_review_log(Check $check, $message, array $context, $level) {
+  Drupal::logger('security_review')->log($level, $message, $context);
+}
+
+/**
+ * Implements hook_modules_uninstalled().
+ */
+function security_review_modules_uninstalled($modules) {
+  /** @var \Drupal\security_review\SecurityReview $security_review */
+  $security_review = Drupal::service('security_review');
+
+  // Clean orphaned checks.
+  $security_review->cleanStorage();
+}
+
+/**
+ * Implements hook_modules_installed().
+ */
+function security_review_modules_installed($modules) {
+  // Post-install hook.
+  if (in_array('security_review', $modules)) {
+
+    /** @var \Drupal\security_review\SecurityReview $security_review */
+    $security_review = Drupal::service('security_review');
+
+    // Clean orphaned checks.
+    $security_review->cleanStorage();
+
+    // Store the web server's user.
+    $security_review->setServerData();
+  }
+}
+
+/**
+ * Implements hook_theme().
+ */
+function security_review_theme($existing, $type, $theme, $path) {
+  return [
+    'check_evaluation' => [
+      'template' => 'check_evaluation',
+      'variables' => [
+        'paragraphs' => [],
+        'items' => [],
+      ],
+    ],
+    'check_help' => [
+      'template' => 'check_help',
+      'variables' => [
+        'title' => [],
+        'paragraphs' => [],
+      ],
+    ],
+    'general_help' => [
+      'template' => 'general_help',
+      'variables' => [
+        'paragraphs' => [],
+        'checks' => [],
+      ],
+    ],
+    'run_and_review' => [
+      'template' => 'run_and_review',
+      'variables' => [
+        'date' => [],
+        'checks' => [],
+      ],
+    ],
+  ];
+}
+
+/**
+ * Preprocesses variables for template 'run_and_review'.
+ */
+function template_preprocess_run_and_review(&$variables) {
+  // Get icon list.
+  $icons_root = '/core/misc/icons/';
+  $variables['icons'] = [
+    'success' => $icons_root . '73b355/check.svg',
+    'warning' => $icons_root . 'e29700/warning.svg',
+    'fail' => $icons_root . 'e32700/error.svg',
+  ];
+
+  // Generate full URLs.
+  foreach ($variables['icons'] as $icon => $path) {
+    $variables['icons'][$icon] = Url::fromUserInput($path)->setAbsolute()
+      ->toString();
+  }
+
+  // Format date.
+  $variables['date'] = format_date($variables['date']);
+
+  // Convert check result integers to strings.
+  foreach ($variables['checks'] as &$check) {
+    if (isset($check['result'])) {
+      switch ($check['result']) {
+        case CheckResult::SUCCESS:
+          $check['result'] = 'success';
+          break;
+
+        case CheckResult::FAIL:
+          $check['result'] = 'fail';
+          break;
+
+        case CheckResult::WARN:
+          $check['result'] = 'warning';
+          break;
+
+        case CheckResult::INFO:
+          $check['result'] = 'info';
+          break;
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_cron().
+ */
+function security_review_cron() {
+  // Store the web server's user.
+  Drupal::service('security_review')->setServerData();
+}
+
+/**
+ * Batch operation: runs a single check.
+ *
+ * @param \Drupal\security_review\Check $check
+ *   The check to run.
+ * @param array $context
+ *   The Batch context.
+ */
+function _security_review_batch_run_op(Check $check, array &$context) {
+  // Inform the user about the progress.
+  $context['message'] = $check->getTitle();
+
+  // Run the check.
+  $results = Drupal::service('security_review.checklist')
+    ->runChecks([$check]);
+
+  // Store the results.
+  $context['results'] = array_merge($context['results'], $results);
+}
+
+/**
+ * Callback for finishing the batch job of running the checklist.
+ *
+ * @param bool $success
+ *   Whether the batch job was successful.
+ * @param \Drupal\security_review\CheckResult[] $results
+ *   The results of the batch job.
+ * @param array $operations
+ *   The array of batch operations.
+ */
+function _security_review_batch_run_finished($success, array $results, array $operations) {
+  /** @var \Drupal\security_review\SecurityReview $security_review */
+  $security_review = Drupal::service('security_review');
+
+  /** @var \Drupal\security_review\Checklist $checklist */
+  $checklist = Drupal::service('security_review.checklist');
+
+  $security_review->setLastRun(time());
+  if ($success) {
+    if (!empty($results)) {
+      $checklist->storeResults($results);
+    }
+    drupal_set_message(t('Review complete'));
+  }
+  else {
+    // Show error information.
+    $error_operation = reset($operations);
+    $message = t(
+      'An error occurred while processing %error_operation with arguments: @arguments',
+      [
+        '%error_operation' => $error_operation[0],
+        '@arguments' => print_r($error_operation[1], TRUE),
+      ]
+    );
+    $security_review->log(NULL, $message, [], RfcLogLevel::ERROR);
+    drupal_set_message(t('The review did not store all results, please run again or check the logs for details.'));
+  }
+}
diff --git a/web/modules/contrib/security_review/security_review.permissions.yml b/web/modules/contrib/security_review/security_review.permissions.yml
new file mode 100644 (file)
index 0000000..9b1ea80
--- /dev/null
@@ -0,0 +1,7 @@
+access security review list:
+  title: 'Access security review pages'
+  description: 'View security review checks and output. Give only to trusted users.'
+
+run security checks:
+  title: 'Run security review checks'
+  description: 'Run the security review checks.'
diff --git a/web/modules/contrib/security_review/security_review.routing.yml b/web/modules/contrib/security_review/security_review.routing.yml
new file mode 100644 (file)
index 0000000..e7433e0
--- /dev/null
@@ -0,0 +1,29 @@
+security_review:
+  path: 'admin/reports/security-review'
+  defaults:
+    _controller: '\Drupal\security_review\Controller\ChecklistController::index'
+  requirements:
+    _permission: 'access security review list'
+
+security_review.help:
+  path: 'admin/reports/security-review/help/{namespace}/{title}'
+  defaults:
+    _controller: '\Drupal\security_review\Controller\HelpController::index'
+    namespace: ~
+    title: ~
+  requirements:
+    _permission: 'access security review list'
+
+security_review.settings:
+  path: 'admin/config/security-review'
+  defaults:
+    _form: '\Drupal\security_review\Form\SettingsForm'
+  requirements:
+    _permission: 'access security review list'
+
+security_review.toggle:
+  path: 'admin/reports/security-review/toggle/{check_id}'
+  defaults:
+    _controller: '\Drupal\security_review\Controller\ToggleController::index'
+  requirements:
+    _permission: 'access security review list'
diff --git a/web/modules/contrib/security_review/security_review.services.yml b/web/modules/contrib/security_review/security_review.services.yml
new file mode 100644 (file)
index 0000000..43827d7
--- /dev/null
@@ -0,0 +1,12 @@
+services:
+  security_review:
+    class: Drupal\security_review\SecurityReview
+    arguments: ['@config.factory', '@state', '@module_handler', '@current_user']
+
+  security_review.checklist:
+    class: Drupal\security_review\Checklist
+    arguments: ['@security_review', '@module_handler', '@current_user']
+
+  security_review.security:
+    class: Drupal\security_review\Security
+    arguments: ['@security_review', '@module_handler', '@config.factory', '@kernel']
diff --git a/web/modules/contrib/security_review/src/Check.php b/web/modules/contrib/security_review/src/Check.php
new file mode 100644 (file)
index 0000000..3b425cf
--- /dev/null
@@ -0,0 +1,551 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Check.
+ */
+
+namespace Drupal\security_review;
+
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
+use Drupal\Core\Logger\RfcLogLevel;
+use Drupal\Core\Routing\LinkGeneratorTrait;
+use Drupal\Core\Routing\UrlGeneratorTrait;
+use Drupal\Core\StringTranslation\StringTranslationTrait;
+use Drupal\user\Entity\User;
+
+/**
+ * Defines a security check.
+ */
+abstract class Check {
+
+  use DependencySerializationTrait;
+  use LinkGeneratorTrait;
+  use UrlGeneratorTrait;
+  use StringTranslationTrait;
+
+  /**
+   * The configuration storage for this check.
+   *
+   * @var \Drupal\Core\Config\Config $config
+   */
+  protected $config;
+
+  /**
+   * The service container.
+   *
+   * @var \Symfony\Component\DependencyInjection\ContainerInterface
+   */
+  protected $container;
+
+  /**
+   * Settings handler for this check.
+   *
+   * @var \Drupal\security_review\CheckSettingsInterface $settings
+   */
+  protected $settings;
+
+  /**
+   * The State system.
+   *
+   * @var \Drupal\Core\State\State
+   */
+  protected $state;
+
+  /**
+   * The check's prefix in the State system.
+   *
+   * @var string
+   */
+  protected $statePrefix;
+
+  /**
+   * Initializes the configuration storage and the settings handler.
+   */
+  public function __construct() {
+    $this->container = \Drupal::getContainer();
+
+    $this->config = $this->configFactory()
+      ->getEditable('security_review.check.' . $this->id());
+    $this->settings = new CheckSettings($this, $this->config);
+    $this->state = $this->container->get('state');
+    $this->statePrefix = 'security_review.check.' . $this->id() . '.';
+
+    // Set check ID in config.
+    if ($this->config->get('id') != $this->id()) {
+      $this->config->set('id', $this->id());
+      $this->config->save();
+    }
+  }
+
+  /**
+   * Returns the namespace of the check.
+   *
+   * Usually it's the same as the module's name.
+   *
+   * Naming rules (if overridden):
+   *   - All characters should be lowerspace.
+   *   - Use characters only from the english alphabet.
+   *   - Don't use spaces (use "_" instead).
+   *
+   * @return string
+   *   Machine namespace of the check.
+   */
+  public function getMachineNamespace() {
+    $namespace = strtolower($this->getNamespace());
+    $namespace = preg_replace("/[^a-z0-9 ]/", '', $namespace);
+    $namespace = str_replace(' ', '_', $namespace);
+
+    return $namespace;
+  }
+
+  /**
+   * Returns the namespace of the check.
+   *
+   * Usually it's the same as the module's name.
+   *
+   * @return string
+   *   Human-readable namespace of the check.
+   */
+  public abstract function getNamespace();
+
+  /**
+   * Returns the machine name of the check.
+   *
+   * Naming rules (if overridden):
+   *   - All characters should be lowerspace.
+   *   - Use characters only from the english alphabet.
+   *   - Don't use spaces (use "_" instead).
+   *
+   * @return string
+   *   ID of check.
+   */
+  public function getMachineTitle() {
+    $title = strtolower($this->getTitle());
+    $title = preg_replace("/[^a-z0-9 ]/", '', $title);
+    $title = str_replace(' ', '_', $title);
+
+    return $title;
+  }
+
+  /**
+   * Returns the human-readable title of the check.
+   *
+   * @return string
+   *   Title of check.
+   */
+  public abstract function getTitle();
+
+  /**
+   * Returns the identifier constructed using the namespace and title values.
+   *
+   * @return string
+   *   Unique identifier of the check.
+   */
+  public final function id() {
+    return $this->getMachineNamespace() . '-' . $this->getMachineTitle();
+  }
+
+  /**
+   * Returns whether the findings should be stored or reproduced when needed.
+   *
+   * The only case when this function should return false is if the check can
+   * generate a lot of findings (like the File permissions check for example).
+   * Turning this off for checks that don't generate findings at all or just a
+   * few of them actually means more overhead as the check has to be re-run
+   * in order to get its last result.
+   *
+   * @return bool
+   *   Boolean indicating whether findings will be stored.
+   */
+  public function storesFindings() {
+    return TRUE;
+  }
+
+  /**
+   * Returns the check-specific settings' handler.
+   *
+   * @return \Drupal\security_review\CheckSettingsInterface
+   *   The settings interface of the check.
+   */
+  public function settings() {
+    return $this->settings;
+  }
+
+  /**
+   * The actual procedure of carrying out the check.
+   *
+   * @return \Drupal\security_review\CheckResult
+   *   The result of running the check.
+   */
+  public abstract function run();
+
+  /**
+   * Same as run(), but used in CLI context such as Drush.
+   *
+   * @return \Drupal\security_review\CheckResult
+   *   The result of running the check.
+   */
+  public function runCli() {
+    return $this->run();
+  }
+
+  /**
+   * Returns the check-specific help page.
+   *
+   * @return array
+   *   The render array of the check's help page.
+   */
+  public abstract function help();
+
+  /**
+   * Returns the evaluation page of a result.
+   *
+   * Usually this is a list of the findings and an explanation.
+   *
+   * @param \Drupal\security_review\CheckResult $result
+   *   The check result to evaluate.
+   *
+   * @return array
+   *   The render array of the evaluation page.
+   */
+  public function evaluate(CheckResult $result) {
+    return [];
+  }
+
+  /**
+   * Evaluates a CheckResult and returns a plaintext output.
+   *
+   * @param \Drupal\security_review\CheckResult $result
+   *   The check result to evaluate.
+   *
+   * @return string
+   *   The evaluation string.
+   */
+  public function evaluatePlain(CheckResult $result) {
+    return '';
+  }
+
+  /**
+   * Converts a result integer to a human-readable result message.
+   *
+   * @param int $result_const
+   *   The result integer.
+   *
+   * @return string
+   *   The human-readable result message.
+   */
+  public abstract function getMessage($result_const);
+
+  /**
+   * Returns the last stored result of the check.
+   *
+   * Returns null if no results have been stored yet.
+   *
+   * @param bool $get_findings
+   *   Whether to get the findings too.
+   *
+   * @return \Drupal\security_review\CheckResult|null
+   *   The last stored result (or null).
+   */
+  public function lastResult($get_findings = FALSE) {
+    // Get stored data from State system.
+    $state_prefix = $this->statePrefix . 'last_result.';
+    $result = $this->state->get($state_prefix . 'result');
+    if ($get_findings) {
+      $findings = $this->state->get($state_prefix . 'findings');
+    }
+    else {
+      $findings = [];
+    }
+    $time = $this->state->get($state_prefix . 'time');
+    // Force boolean value.
+    $visible = $this->state->get($state_prefix . 'visible') == TRUE;
+
+    // Check validity of stored data.
+    $valid_result = is_int($result)
+      && $result >= CheckResult::SUCCESS
+      && $result <= CheckResult::INFO;
+    $valid_findings = is_array($findings);
+    $valid_time = is_int($time) && $time > 0;
+
+    // If invalid, return NULL.
+    if (!$valid_result || !$valid_findings || !$valid_time) {
+      return NULL;
+    }
+
+    // Construct the CheckResult.
+    $last_result = new CheckResult($this, $result, $findings, $visible, $time);
+
+    // Do a check run for acquiring findings if required.
+    if ($get_findings && !$this->storesFindings()) {
+      // Run the check to get the findings.
+      $fresh_result = $this->run();
+
+      // If it malfunctioned return the last known good result.
+      if (!($fresh_result instanceof CheckResult)) {
+        return $last_result;
+      }
+
+      if ($fresh_result->result() != $last_result->result()) {
+        // If the result is not the same store the new result and return it.
+        $this->storeResult($fresh_result);
+        $this->securityReview()->logCheckResult($fresh_result);
+        return $fresh_result;
+      }
+      else {
+        // Else return the old result with the fresh one's findings.
+        return CheckResult::combine($last_result, $fresh_result);
+      }
+    }
+
+    return $last_result;
+  }
+
+  /**
+   * Returns the timestamp the check was last run.
+   *
+   * Returns 0 if it has not been run yet.
+   *
+   * @return int
+   *   The timestamp of the last stored result.
+   */
+  public function lastRun() {
+    $last_result_time = $this->state
+      ->get($this->statePrefix . 'last_result.time');
+
+    if (!is_int($last_result_time)) {
+      return 0;
+    }
+    return $last_result_time;
+  }
+
+  /**
+   * Returns whether the check is skipped. Checks are not skipped by default.
+   *
+   * @return bool
+   *   Boolean indicating whether the check is skipped.
+   */
+  public function isSkipped() {
+    $is_skipped = $this->config->get('skipped');
+
+    if (!is_bool($is_skipped)) {
+      return FALSE;
+    }
+    return $is_skipped;
+  }
+
+  /**
+   * Returns the user the check was skipped by.
+   *
+   * Returns null if it hasn't been skipped yet or the user that skipped the
+   * check is not valid anymore.
+   *
+   * @return \Drupal\user\Entity\User|null
+   *   The user the check was last skipped by (or null).
+   */
+  public function skippedBy() {
+    $skipped_by = $this->config->get('skipped_by');
+
+    if (!is_int($skipped_by)) {
+      return NULL;
+    }
+    return User::load($skipped_by);
+  }
+
+  /**
+   * Returns the timestamp the check was last skipped on.
+   *
+   * Returns 0 if it hasn't been skipped yet.
+   *
+   * @return int
+   *   The UNIX timestamp the check was last skipped on (or 0).
+   */
+  public function skippedOn() {
+    $skipped_on = $this->config->get('skipped_on');
+
+    if (!is_int($skipped_on)) {
+      return 0;
+    }
+    return $skipped_on;
+  }
+
+  /**
+   * Enables the check. Has no effect if the check was not skipped.
+   */
+  public function enable() {
+    if ($this->isSkipped()) {
+      $this->config->set('skipped', FALSE);
+      $this->config->save();
+
+      // Log.
+      $context = ['@name' => $this->getTitle()];
+      $this->securityReview()->log($this, '@name check no longer skipped', $context, RfcLogLevel::NOTICE);
+    }
+  }
+
+  /**
+   * Marks the check as skipped.
+   *
+   * It still can be ran manually, but will remain skipped on the Run & Review
+   * page.
+   */
+  public function skip() {
+    if (!$this->isSkipped()) {
+      // Store skip data.
+      $this->config->set('skipped', TRUE);
+      $this->config->set('skipped_by', $this->currentUser()->id());
+      $this->config->set('skipped_on', time());
+      $this->config->save();
+
+      // Log.
+      $context = ['@name' => $this->getTitle()];
+      $this->securityReview()->log($this, '@name check skipped', $context, RfcLogLevel::NOTICE);
+    }
+  }
+
+  /**
+   * Stores a result in the state system.
+   *
+   * @param \Drupal\security_review\CheckResult $result
+   *   The result to store.
+   */
+  public function storeResult(CheckResult $result) {
+    if ($result == NULL) {
+      $context = [
+        '@reviewcheck' => $this->getTitle(),
+        '@namespace' => $this->getNamespace(),
+      ];
+      $this->securityReview()->log($this, 'Unable to store check @reviewcheck for @namespace', $context, RfcLogLevel::CRITICAL);
+      return;
+    }
+
+    $findings = $this->storesFindings() ? $result->findings() : [];
+    $this->state->setMultiple([
+      $this->statePrefix . 'last_result.result' => $result->result(),
+      $this->statePrefix . 'last_result.time' => $result->time(),
+      $this->statePrefix . 'last_result.visible' => $result->isVisible(),
+      $this->statePrefix . 'last_result.findings' => $findings,
+    ]);
+  }
+
+  /**
+   * Creates a new CheckResult for this Check.
+   *
+   * @param int $result
+   *   The result integer (see the constants defined in CheckResult).
+   * @param array $findings
+   *   The findings.
+   * @param bool $visible
+   *   The visibility of the result.
+   * @param int $time
+   *   The time the test was run.
+   *
+   * @return \Drupal\security_review\CheckResult
+   *   The created CheckResult.
+   */
+  public function createResult($result, array $findings = [], $visible = TRUE, $time = NULL) {
+    return new CheckResult($this, $result, $findings, $visible, $time);
+  }
+
+  /**
+   * Returns the Security Review Checklist service.
+   *
+   * @return \Drupal\security_review\Checklist
+   *   Security Review's Checklist service.
+   */
+  protected function checklist() {
+    return $this->container->get('security_review.checklist');
+  }
+
+  /**
+   * Returns the Config factory.
+   *
+   * @return \Drupal\Core\Config\ConfigFactory
+   *   Config factory.
+   */
+  protected function configFactory() {
+    return $this->container->get('config.factory');
+  }
+
+  /**
+   * Returns the service container.
+   *
+   * @return \Symfony\Component\DependencyInjection\ContainerInterface
+   *   Service container.
+   */
+  protected function container() {
+    return $this->container;
+  }
+
+  /**
+   * Returns the current Drupal user.
+   *
+   * @return \Drupal\Core\Session\AccountProxy
+   *   Current Drupal user.
+   */
+  protected function currentUser() {
+    return $this->container->get('current_user');
+  }
+
+  /**
+   * Returns the database connection.
+   *
+   * @return \Drupal\Core\Database\Connection
+   *   Database connection.
+   */
+  protected function database() {
+    return $this->container->get('database');
+  }
+
+  /**
+   * Returns the entity manager.
+   *
+   * @return \Drupal\Core\Entity\EntityManagerInterface
+   *   Entity manager.
+   */
+  protected function entityManager() {
+    return $this->container->get('entity.manager');
+  }
+
+  /**
+   * Returns the Drupal Kernel.
+   *
+   * @return \Drupal\Core\DrupalKernel
+   *   Drupal Kernel.
+   */
+  protected function kernel() {
+    return $this->container->get('kernel');
+  }
+
+  /**
+   * Returns the module handler.
+   *
+   * @return \Drupal\Core\Extension\ModuleHandler
+   *   Module handler.
+   */
+  protected function moduleHandler() {
+    return $this->container->get('module_handler');
+  }
+
+  /**
+   * Returns the Security Review Security service.
+   *
+   * @return \Drupal\security_review\Security
+   *   Security Review's Security service.
+   */
+  protected function security() {
+    return $this->container->get('security_review.security');
+  }
+
+  /**
+   * Returns the Security Review service.
+   *
+   * @return \Drupal\security_review\SecurityReview
+   *   Security Review service.
+   */
+  protected function securityReview() {
+    return $this->container->get('security_review');
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/CheckResult.php b/web/modules/contrib/security_review/src/CheckResult.php
new file mode 100644 (file)
index 0000000..7096430
--- /dev/null
@@ -0,0 +1,173 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\CheckResult.
+ */
+
+namespace Drupal\security_review;
+
+/**
+ * Used to define the result of a Check.
+ */
+class CheckResult {
+
+  const SUCCESS = 0;
+  const FAIL = 1;
+  const WARN = 2;
+  const INFO = 3;
+
+  /**
+   * Stores the parent Check.
+   *
+   * @var \Drupal\security_review\Check $check
+   */
+  private $check;
+
+  /**
+   * Stores the outcome of the check.
+   *
+   * @var int $result
+   */
+  private $result;
+
+  /**
+   * Stores findings.
+   *
+   * @var array $findings
+   */
+  private $findings;
+
+  /**
+   * Stores the timestamp of the check run.
+   *
+   * @var int $time
+   */
+  private $time;
+
+  /**
+   * Whether the result should be shown on the UI.
+   *
+   * @var bool $visible
+   */
+  private $visible;
+
+  /**
+   * Constructs an immutable CheckResult.
+   *
+   * @param \Drupal\security_review\Check $check
+   *   The Check that created this result.
+   * @param int $result
+   *   The result integer (see the constants defined above).
+   * @param array $findings
+   *   The findings.
+   * @param int $time
+   *   The timestamp of the check run.
+   * @param bool $visible
+   *   The visibility of the result.
+   */
+  public function __construct(Check $check, $result, array $findings, $visible = TRUE, $time = NULL) {
+    // Set the parent check.
+    $this->check = $check;
+
+    // Set the result value.
+    $result = intval($result);
+    if ($result < self::SUCCESS || $result > self::INFO) {
+      $result = self::INFO;
+    }
+    $this->result = $result;
+
+    // Set the findings.
+    $this->findings = $findings;
+
+    // Set the visibility.
+    $this->visible = $visible;
+
+    // Set the timestamp.
+    if (!is_int($time)) {
+      $this->time = time();
+    }
+    else {
+      $this->time = intval($time);
+    }
+  }
+
+  /**
+   * Combines two CheckResults.
+   *
+   * Combines two CheckResults and returns a new one with the old one's fields
+   * except for the findings which are copied from the fresh result.
+   *
+   * @param \Drupal\security_review\CheckResult $old
+   *   The old result to clone.
+   * @param \Drupal\security_review\CheckResult $fresh
+   *   The new result to copy the findings from.
+   *
+   * @return \Drupal\security_review\CheckResult
+   *   The combined result.
+   */
+  public static function combine(CheckResult $old, CheckResult $fresh) {
+    return new CheckResult($old->check, $old->result, $fresh->findings, $old->visible, $old->time);
+  }
+
+  /**
+   * Returns the parent Check.
+   *
+   * @return \Drupal\security_review\Check
+   *   The Check that created this result.
+   */
+  public function check() {
+    return $this->check;
+  }
+
+  /**
+   * Returns the outcome of the check.
+   *
+   * @return int
+   *   The result integer.
+   */
+  public function result() {
+    return $this->result;
+  }
+
+  /**
+   * Returns the findings.
+   *
+   * @return array
+   *   The findings. Contents of this depends on the actual check.
+   */
+  public function findings() {
+    return $this->findings;
+  }
+
+  /**
+   * Returns the timestamp.
+   *
+   * @return int
+   *   The timestamp the result was created on.
+   */
+  public function time() {
+    return $this->time;
+  }
+
+  /**
+   * Returns the visibility of the result.
+   *
+   * @return bool
+   *   Whether the result should be shown on the UI.
+   */
+  public function isVisible() {
+    return $this->visible;
+  }
+
+  /**
+   * Returns the result message.
+   *
+   * @return string
+   *   The result message for this result.
+   */
+  public function resultMessage() {
+    return $this->check->getMessage($this->result);
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/CheckSettings.php b/web/modules/contrib/security_review/src/CheckSettings.php
new file mode 100644 (file)
index 0000000..eadda42
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\CheckSettings.
+ */
+
+namespace Drupal\security_review;
+
+use Drupal\Core\Config\Config;
+
+/**
+ * Defines the default implementation of CheckSettingsInterface.
+ */
+class CheckSettings implements CheckSettingsInterface {
+
+  /**
+   * The parent check.
+   *
+   * @var \Drupal\security_review\Check
+   */
+  protected $check;
+
+  /**
+   * The configuration storage of the parent Check.
+   *
+   * @var \Drupal\Core\Config\Config $config
+   */
+  protected $config;
+
+  /**
+   * Creates a CheckSettings instance.
+   *
+   * @param \Drupal\security_review\Check $check
+   *   The parent Check.
+   * @param \Drupal\Core\Config\Config $config
+   *   The parent Check's configuration.
+   */
+  public function __construct(Check $check, Config &$config) {
+    $this->check = $check;
+    $this->config = $config;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function get($key, $default_value = NULL) {
+    $value = $this->config->get('settings.' . $key);
+
+    if ($value == NULL) {
+      return $default_value;
+    }
+    return $value;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function set($key, $value) {
+    $this->config->set('settings.' . $key, $value);
+    $this->config->save();
+    return $this;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm() {
+    return [];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function validateForm(array &$form, array $values) {
+    // Validation is optional.
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, array $values) {
+    // Handle submission.
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/CheckSettings/TrustedHostSettings.php b/web/modules/contrib/security_review/src/CheckSettings/TrustedHostSettings.php
new file mode 100644 (file)
index 0000000..23f22f8
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\CheckSettings\TrustedHostSettings.
+ */
+
+namespace Drupal\security_review\CheckSettings;
+
+use Drupal\security_review\CheckSettings;
+
+/**
+ * Provides the settings form for the TrustedHosts check.
+ */
+class TrustedHostSettings extends CheckSettings {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm() {
+    $form = [];
+    $form['method'] = [
+      '#type' => 'radios',
+      '#title' => t('Check method'),
+      '#description' => t('Detecting the $base_url in settings.php can be done via PHP tokenization (recommended) or including the file. Note that if you have custom functionality in your settings.php it will be executed if the file is included. Including the file can result in a more accurate $base_url check if you wrap the setting in conditional statements.'),
+      '#options' => [
+        'token' => t('Tokenize settings.php (recommended)'),
+        'include' => t('Include settings.php'),
+      ],
+      '#default_value' => $this->get('method', 'token'),
+    ];
+
+    return $form;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, array $values) {
+    $this->set('method', $values['method']);
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/CheckSettingsInterface.php b/web/modules/contrib/security_review/src/CheckSettingsInterface.php
new file mode 100644 (file)
index 0000000..5eccc2d
--- /dev/null
@@ -0,0 +1,69 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\CheckSettingsInterface.
+ */
+
+namespace Drupal\security_review;
+
+/**
+ * Interface for check-specific settings and forms for altering them.
+ */
+interface CheckSettingsInterface {
+
+  /**
+   * Gets a check-specific setting value identified by $key.
+   *
+   * @param string $key
+   *   The key.
+   * @param mixed $default_value
+   *   Default value to return in case $key does not exist.
+   *
+   * @return mixed
+   *   The value of the stored setting.
+   */
+  public function get($key, $default_value);
+
+  /**
+   * Sets a check-specific setting value identified by $key.
+   *
+   * @param string $key
+   *   The key.
+   * @param mixed $value
+   *   The new value.
+   *
+   * @return CheckSettingsInterface
+   *   Returns itself.
+   */
+  public function set($key, $value);
+
+  /**
+   * Form constructor.
+   *
+   * @return array
+   *   The form structure.
+   */
+  public function buildForm();
+
+  /**
+   * Form validation handler.
+   *
+   * @param array $form
+   *   An associative array containing the structure of the form.
+   * @param array $values
+   *   The current values of the form.
+   */
+  public function validateForm(array &$form, array $values);
+
+  /**
+   * Form submission handler.
+   *
+   * @param array $form
+   *   An associative array containing the structure of the form.
+   * @param array $values
+   *   The current values of the form.
+   */
+  public function submitForm(array &$form, array $values);
+
+}
diff --git a/web/modules/contrib/security_review/src/Checklist.php b/web/modules/contrib/security_review/src/Checklist.php
new file mode 100644 (file)
index 0000000..fe1d61a
--- /dev/null
@@ -0,0 +1,270 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checklist.
+ */
+
+namespace Drupal\security_review;
+
+use Drupal\Core\Access\AccessException;
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
+use Drupal\Core\Extension\ModuleHandlerInterface;
+use Drupal\Core\Session\AccountProxyInterface;
+
+/**
+ * Contains static functions for handling checks throughout every module.
+ */
+class Checklist {
+
+  use DependencySerializationTrait;
+
+  /**
+   * The current user.
+   *
+   * @var \Drupal\Core\Session\AccountProxyInterface
+   */
+  protected $currentUser;
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+  /**
+   * The module handler.
+   *
+   * @var \Drupal\Core\Extension\ModuleHandlerInterface
+   */
+  protected $moduleHandler;
+
+  /**
+   * Constructs a Checklist instance.
+   *
+   * @param \Drupal\security_review\SecurityReview $security_review
+   *   The SecurityReview service.
+   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
+   *   The module handler.
+   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
+   *   The current user.
+   */
+  public function __construct(SecurityReview $security_review, ModuleHandlerInterface $module_handler, AccountProxyInterface $current_user) {
+    $this->securityReview = $security_review;
+    $this->moduleHandler = $module_handler;
+    $this->currentUser = $current_user;
+  }
+
+  /**
+   * Array of cached Checks.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  private static $cachedChecks = [];
+
+  /**
+   * Clears the cached checks.
+   */
+  public static function clearCache() {
+    static::$cachedChecks = [];
+  }
+
+  /**
+   * Returns every Check.
+   *
+   * @return \Drupal\security_review\Check[]
+   *   Array of Checks.
+   */
+  public function getChecks() {
+    $checks = &static::$cachedChecks;
+    if (!empty($checks)) {
+      return $checks;
+    }
+
+    // Get checks.
+    $raw_checks = $this->moduleHandler->invokeAll('security_review_checks');
+
+    // Filter invalid checks.
+    $checks = [];
+    foreach ($raw_checks as $raw_check) {
+      if ($raw_check instanceof Check) {
+        $checks[] = $raw_check;
+      }
+    }
+
+    // Sort the checks.
+    usort($checks, [$this, 'compareChecks']);
+
+    return $checks;
+  }
+
+  /**
+   * Returns the enabled Checks.
+   *
+   * @return \Drupal\security_review\Check[]
+   *   Array of enabled Checks.
+   */
+  public function getEnabledChecks() {
+    $enabled = [];
+
+    foreach (static::getChecks() as $check) {
+      if (!$check->isSkipped()) {
+        $enabled[] = $check;
+      }
+    }
+
+    return $enabled;
+  }
+
+  /**
+   * Groups an array of checks by their namespaces.
+   *
+   * @param \Drupal\security_review\Check[] $checks
+   *   The array of Checks to group.
+   *
+   * @return array
+   *   Array containing Checks grouped by their namespaces.
+   */
+  public function groupChecksByNamespace(array $checks) {
+    $output = [];
+
+    foreach ($checks as $check) {
+      $output[$check->getMachineNamespace()][] = $check;
+    }
+
+    return $output;
+  }
+
+  /**
+   * Runs enabled checks and stores their results.
+   */
+  public function runChecklist() {
+    if ($this->currentUser->hasPermission('run security checks')) {
+      $checks = $this->getEnabledChecks();
+      $results = $this->runChecks($checks);
+      $this->storeResults($results);
+      $this->securityReview->setLastRun(time());
+    }
+    else {
+      throw new AccessException();
+    }
+  }
+
+  /**
+   * Runs an array of checks.
+   *
+   * @param \Drupal\security_review\Check[] $checks
+   *   The array of Checks to run.
+   * @param bool $cli
+   *   Whether to call runCli() instead of run().
+   *
+   * @return \Drupal\security_review\CheckResult[]
+   *   The array of CheckResults generated.
+   */
+  public function runChecks(array $checks, $cli = FALSE) {
+    $results = [];
+
+    foreach ($checks as $check) {
+      if ($cli) {
+        $result = $check->runCli();
+      }
+      else {
+        $result = $check->run();
+      }
+      $this->securityReview->logCheckResult($result);
+      $results[] = $result;
+    }
+
+    return $results;
+  }
+
+  /**
+   * Stores an array of CheckResults.
+   *
+   * @param \Drupal\security_review\CheckResult[] $results
+   *   The CheckResults to store.
+   */
+  public function storeResults(array $results) {
+    foreach ($results as $result) {
+      $result->check()->storeResult($result);
+    }
+  }
+
+  /**
+   * Finds a check by its namespace and title.
+   *
+   * @param string $namespace
+   *   The machine namespace of the requested check.
+   * @param string $title
+   *   The machine title of the requested check.
+   *
+   * @return null|\Drupal\security_review\Check
+   *   The Check or null if it doesn't exist.
+   */
+  public function getCheck($namespace, $title) {
+    foreach (static::getChecks() as $check) {
+      $same_namespace = $check->getMachineNamespace() == $namespace;
+      $same_title = $check->getMachineTitle() == $title;
+      if ($same_namespace && $same_title) {
+        return $check;
+      }
+    }
+
+    return NULL;
+  }
+
+  /**
+   * Finds a Check by its id.
+   *
+   * @param string $id
+   *   The machine namespace of the requested check.
+   *
+   * @return null|\Drupal\security_review\Check
+   *   The Check or null if it doesn't exist.
+   */
+  public function getCheckById($id) {
+    foreach (static::getChecks() as $check) {
+      if ($check->id() == $id) {
+        return $check;
+      }
+    }
+
+    return NULL;
+  }
+
+  /**
+   * Helper function for sorting checks.
+   *
+   * @param \Drupal\security_review\Check $a
+   *   Check A.
+   * @param \Drupal\security_review\Check $b
+   *   Check B.
+   *
+   * @return int
+   *   The comparison's result.
+   */
+  public function compareChecks(Check $a, Check $b) {
+    // If one comes from security_review and the other doesn't, prefer the one
+    // with the security_review namespace.
+    $a_is_local = $a->getMachineNamespace() == 'security_review';
+    $b_is_local = $b->getMachineNamespace() == 'security_review';
+    if ($a_is_local && !$b_is_local) {
+      return -1;
+    }
+    elseif (!$a_is_local && $b_is_local) {
+      return 1;
+    }
+    else {
+      if ($a->getNamespace() == $b->getNamespace()) {
+        // If the namespaces match, sort by title.
+        return strcmp($a->getTitle(), $b->getTitle());
+      }
+      else {
+        // If the namespaces don't mach, sort by namespace.
+        return strcmp($a->getNamespace(), $b->getNamespace());
+      }
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/AdminPermissions.php b/web/modules/contrib/security_review/src/Checks/AdminPermissions.php
new file mode 100644 (file)
index 0000000..1b663ad
--- /dev/null
@@ -0,0 +1,155 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\AdminPermissions.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Drupal\user\Entity\Role;
+
+/**
+ * Checks whether untrusted roles have restricted permissions.
+ */
+class AdminPermissions extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Drupal permissions';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMachineTitle() {
+    return 'admin_permissions';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    // Get every permission.
+    $all_permissions = $this->security()->permissions(TRUE);
+    $all_permission_strings = array_keys($all_permissions);
+
+    // Get permissions for untrusted roles.
+    $untrusted_permissions = $this->security()->untrustedPermissions(TRUE);
+    foreach ($untrusted_permissions as $rid => $permissions) {
+      $intersect = array_intersect($all_permission_strings, $permissions);
+      foreach ($intersect as $permission) {
+        if (isset($all_permissions[$permission]['restrict access'])) {
+          $findings[$rid][] = $permission;
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t("Drupal's permission system is extensive and allows for varying degrees of control. Certain permissions would allow a user total control, or the ability to escalate their control, over your site and should only be granted to trusted users.");
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Admin and trusted Drupal permissions'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $output = [];
+
+    foreach ($result->findings() as $rid => $permissions) {
+      $role = Role::load($rid);
+      /** @var Role $role */
+      $paragraphs = [];
+      $paragraphs[] = $this->t(
+        "@role has the following restricted permissions:",
+        [
+          '@role' => $this->l(
+            $role->label(),
+            Url::fromRoute(
+              'entity.user_role.edit_permissions_form',
+              ['user_role' => $role->id()]
+            )
+          ),
+        ]
+      );
+
+      $output[] = [
+        '#theme' => 'check_evaluation',
+        '#paragraphs' => $paragraphs,
+        '#items' => $permissions,
+      ];
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $output = '';
+
+    foreach ($result->findings() as $rid => $permissions) {
+      $role = Role::load($rid);
+      /** @var Role $role */
+
+      $output .= $this->t(
+        '@role has @permissions',
+        [
+          '@role' => $role->label(),
+          '@permissions' => implode(', ', $permissions),
+        ]
+      );
+      $output .= "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Untrusted roles do not have administrative or trusted Drupal permissions.');
+
+      case CheckResult::FAIL:
+        return $this->t('Untrusted roles have been granted administrative or trusted Drupal permissions.');
+
+      default:
+        return $this->t("Unexpected result.");
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/ErrorReporting.php b/web/modules/contrib/security_review/src/Checks/ErrorReporting.php
new file mode 100644 (file)
index 0000000..c6d0141
--- /dev/null
@@ -0,0 +1,120 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\BaseUrl.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Defines a security check that checks the error reporting setting.
+ */
+class ErrorReporting extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Error reporting';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // Get the error level.
+    $error_level = $this->configFactory()->get('system.logging')
+      ->get('error_level');
+
+    // Determine the result.
+    if (is_null($error_level) || $error_level != 'hide') {
+      $result = CheckResult::FAIL;
+    }
+    else {
+      $result = CheckResult::SUCCESS;
+    }
+
+    return $this->createResult($result, ['level' => $error_level]);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('As a form of hardening your site you should avoid information disclosure. Drupal by default prints errors to the screen and writes them to the log. Error messages disclose the full path to the file where the error occurred.');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Error reporting'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    if ($result->result() == CheckResult::SUCCESS) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('You have error reporting set to both the screen and the log.');
+    $paragraphs[] = $this->l(
+      $this->t('Alter error reporting settings.'),
+      Url::fromRoute('system.logging_settings')
+    );
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => [],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    if ($result->result() == CheckResult::SUCCESS) {
+      return '';
+    }
+
+    if (isset($result->findings()['level'])) {
+      return $this->t('Error level: @level', [
+        '@level' => $result->findings()['level'],
+      ]);
+    }
+    return '';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Error reporting set to log only.');
+
+      case CheckResult::FAIL:
+        return $this->t('Errors are written to the screen.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/ExecutablePhp.php b/web/modules/contrib/security_review/src/Checks/ExecutablePhp.php
new file mode 100644 (file)
index 0000000..b237722
--- /dev/null
@@ -0,0 +1,231 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\ExecutablePhp.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Component\PhpStorage\FileStorage;
+use Drupal\Core\StreamWrapper\PublicStream;
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use GuzzleHttp\Exception\RequestException;
+
+/**
+ * Checks if PHP files written to the files directory can be executed.
+ */
+class ExecutablePhp extends Check {
+
+  /**
+   * Drupal's HTTP Client.
+   *
+   * @var \Drupal\Core\Http\Client
+   */
+  protected $httpClient;
+
+  /**
+   * {@inheritdoc}
+   */
+  public function __construct() {
+    parent::__construct();
+    $this->httpClient = $this->container->get('http_client');
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Executable PHP';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run($cli = FALSE) {
+    global $base_url;
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    // Set up test file data.
+    $message = 'Security review test ' . date('Ymdhis');
+    $content = "<?php\necho '" . $message . "';";
+    $file_path = PublicStream::basePath() . '/security_review_test.php';
+
+    // Create the test file.
+    if ($test_file = @fopen('./' . $file_path, 'w')) {
+      fwrite($test_file, $content);
+      fclose($test_file);
+    }
+
+    // Try to access the test file.
+    try {
+      $response = $this->httpClient->get($base_url . '/' . $file_path);
+      if ($response->getStatusCode() == 200 && $response->getBody() === $message) {
+        $result = CheckResult::FAIL;
+        $findings[] = 'executable_php';
+      }
+    }
+    catch (RequestException $e) {
+      // Access was denied to the file.
+    }
+
+    // Remove the test file.
+    if (file_exists('./' . $file_path)) {
+      @unlink('./' . $file_path);
+    }
+
+    // Check for presence of the .htaccess file and if the contents are correct.
+    $htaccess_path = PublicStream::basePath() . '/.htaccess';
+    if (!file_exists($htaccess_path)) {
+      $result = CheckResult::FAIL;
+      $findings[] = 'missing_htaccess';
+    }
+    else {
+      // Check whether the contents of .htaccess are correct.
+      $contents = file_get_contents($htaccess_path);
+      $expected = FileStorage::htaccessLines(FALSE);
+
+      // Trim each line separately then put them back together.
+      $contents = implode("\n", array_map('trim', explode("\n", trim($contents))));
+      $expected = implode("\n", array_map('trim', explode("\n", trim($expected))));
+
+      if ($contents !== $expected) {
+        $result = CheckResult::FAIL;
+        $findings[] = 'incorrect_htaccess';
+      }
+
+      // Check whether .htaccess is writable.
+      if (!$cli) {
+        $writable_htaccess = is_writable($htaccess_path);
+      }
+      else {
+        $writable = $this->security()->findWritableFiles([$htaccess_path], TRUE);
+        $writable_htaccess = !empty($writable);
+      }
+
+      if ($writable_htaccess) {
+        $findings[] = 'writable_htaccess';
+        if ($result !== CheckResult::FAIL) {
+          $result = CheckResult::WARN;
+        }
+      }
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function runCli() {
+    return $this->run(TRUE);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The Drupal files directory is for user-uploaded files and by default provides some protection against a malicious user executing arbitrary PHP code against your site.');
+    $paragraphs[] = $this->t('Read more about the <a href="https://drupal.org/node/615888">risk of PHP code execution on Drupal.org</a>.');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Executable PHP in files directory'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $paragraphs = [];
+    foreach ($result->findings() as $label) {
+      switch ($label) {
+        case 'executable_php':
+          $paragraphs[] = $this->t('Security Review was able to execute a PHP file written to your files directory.');
+          break;
+
+        case 'missing_htaccess':
+          $directory = PublicStream::basePath();
+          $paragraphs[] = $this->t("The .htaccess file is missing from the files directory at @path", ['@path' => $directory]);
+          $paragraphs[] = $this->t("Note, if you are using a webserver other than Apache you should consult your server's documentation on how to limit the execution of PHP scripts in this directory.");
+          break;
+
+        case 'incorrect_htaccess':
+          $paragraphs[] = $this->t("The .htaccess file exists but does not contain the correct content. It is possible it's been maliciously altered.");
+          break;
+
+        case 'writable_htaccess':
+          $paragraphs[] = $this->t("The .htaccess file is writable which poses a risk should a malicious user find a way to execute PHP code they could alter the .htaccess file to allow further PHP code execution.");
+          break;
+      }
+    }
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => [],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $paragraphs = [];
+    $directory = PublicStream::basePath();
+    foreach ($result->findings() as $label) {
+      switch ($label) {
+        case 'executable_php':
+          $paragraphs[] = $this->t('PHP file executed in @path', ['@path' => $directory]);
+          break;
+
+        case 'missing_htaccess':
+          $paragraphs[] = $this->t('.htaccess is missing from @path', ['@path' => $directory]);
+          break;
+
+        case 'incorrect_htaccess':
+          $paragraphs[] = $this->t('.htaccess wrong content');
+          break;
+
+        case 'writable_htaccess':
+          $paragraphs[] = $this->t('.htaccess writable');
+          break;
+      }
+    }
+
+    return implode("\n", $paragraphs);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('PHP files in the Drupal files directory cannot be executed.');
+
+      case CheckResult::FAIL:
+        return $this->t('PHP files in the Drupal files directory can be executed.');
+
+      case CheckResult::WARN:
+        return $this->t('The .htaccess file in the files directory is writable.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/FailedLogins.php b/web/modules/contrib/security_review/src/Checks/FailedLogins.php
new file mode 100644 (file)
index 0000000..42c545a
--- /dev/null
@@ -0,0 +1,160 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\FailedLogins.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Logger\RfcLogLevel;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Checks for abundant failed logins.
+ */
+class FailedLogins extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Failed logins';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // If dblog is not enabled return with hidden INFO.
+    if (!$this->moduleHandler()->moduleExists('dblog')) {
+      return $this->createResult(CheckResult::INFO, [], FALSE);
+    }
+
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+    $last_result = $this->lastResult();
+    $visible = FALSE;
+
+    // Prepare the query.
+    $query = $this->database()->select('watchdog', 'w');
+    $query->fields('w', [
+      'severity',
+      'type',
+      'timestamp',
+      'message',
+      'variables',
+      'hostname',
+    ]);
+    $query->condition('type', 'user')
+      ->condition('severity', RfcLogLevel::NOTICE)
+      ->condition('message', 'Login attempt failed from %ip.');
+    if ($last_result instanceof CheckResult) {
+      // Only check entries that got recorded since the last run of the check.
+      $query->condition('timestamp', $last_result->time(), '>=');
+    }
+
+    // Execute the query.
+    $db_result = $query->execute();
+
+    // Count the number of failed logins per IP.
+    $entries = [];
+    foreach ($db_result as $row) {
+      $ip = unserialize($row->variables)['%ip'];
+      $entry_for_ip = &$entries[$ip];
+
+      if (!isset($entry_for_ip)) {
+        $entry_for_ip = 0;
+      }
+      $entry_for_ip++;
+    }
+
+    // Filter the IPs with more than 10 failed logins.
+    if (!empty($entries)) {
+      foreach ($entries as $ip => $count) {
+        if ($count > 10) {
+          $findings[] = $ip;
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+      $visible = TRUE;
+    }
+
+    return $this->createResult($result, $findings, $visible);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('Failed login attempts from the same IP may be an artifact of a malicious user attempting to brute-force their way onto your site as an authenticated user to carry out nefarious deeds.');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Abundant failed logins from the same IP'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following IPs were observed with an abundance of failed login attempts.');
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $result->findings(),
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = $this->t('Suspicious IP addresses:') . ":\n";
+    foreach ($findings as $ip) {
+      $output .= "\t" . $ip . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::FAIL:
+        return $this->t('Failed login attempts from the same IP. These may be a brute-force attack to gain access to your site.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/Field.php b/web/modules/contrib/security_review/src/Checks/Field.php
new file mode 100644 (file)
index 0000000..5ca3067
--- /dev/null
@@ -0,0 +1,217 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\Field.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Entity\Entity;
+use Drupal\Core\Entity\FieldableEntityInterface;
+use Drupal\Core\TypedData\TypedDataInterface;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Drupal\text\Plugin\Field\FieldType\TextItemBase;
+
+/**
+ * Checks for Javascript and PHP in submitted content.
+ */
+class Field extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Content';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMachineTitle() {
+    return 'field';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    $tags = [
+      'Javascript' => 'script',
+      'PHP' => '?php',
+    ];
+
+    // Load all of the entities.
+    $entities = [];
+    $bundle_info = $this->entityManager()->getAllBundleInfo();
+    foreach ($bundle_info as $entity_type_id => $bundles) {
+      $current = $this->entityManager()
+        ->getStorage($entity_type_id)
+        ->loadMultiple();
+      $entities = array_merge($entities, $current);
+    }
+
+    // Search for text fields.
+    $text_items = [];
+    foreach ($entities as $entity) {
+      if ($entity instanceof FieldableEntityInterface) {
+        /** @var FieldableEntityInterface $entity */
+        foreach ($entity->getFields() as $field_list) {
+          foreach ($field_list as $field_item) {
+            if ($field_item instanceof TextItemBase) {
+              /** @var TextItemBase $item */
+              // Text field found.
+              $text_items[] = $field_item;
+            }
+          }
+        }
+      }
+    }
+
+    // Scan the text items for vulnerabilities.
+    foreach ($text_items as $item) {
+      $entity = $item->getEntity();
+      foreach ($item->getProperties() as $property) {
+        /** @var TypedDataInterface $property */
+        $value = $property->getValue();
+        if (is_string($value)) {
+          $field_name = $item->getFieldDefinition()->getLabel();
+          foreach ($tags as $vulnerability => $tag) {
+            if (strpos($value, '<' . $tag) !== FALSE) {
+              // Vulnerability found.
+              $findings[$entity->getEntityTypeId()][$entity->id()][$field_name][] = $vulnerability;
+            }
+          }
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('Script and PHP code in content does not align with Drupal best practices and may be a vulnerability if an untrusted user is allowed to edit such content. It is recommended you remove such contents.');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Dangerous tags in content'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following items potentially have dangerous tags.');
+
+    $items = [];
+    foreach ($findings as $entity_type_id => $entities) {
+      foreach ($entities as $entity_id => $fields) {
+        $entity = $this->entityManager()
+          ->getStorage($entity_type_id)
+          ->load($entity_id);
+
+        foreach ($fields as $field => $finding) {
+          $url = $entity->toUrl('edit-form')->toString();
+          if ($url === NULL) {
+            $url = $entity->toUrl()->toString();
+          }
+          $items[] = $this->t(
+            '@vulnerabilities found in <em>@field</em> field of <a href=":url">@label</a>',
+            [
+              '@vulnerabilities' => implode(' and ', $finding),
+              '@field' => $field,
+              '@label' => $entity->label(),
+              ':url' => $url,
+            ]
+          );
+        }
+      }
+    }
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $items,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = '';
+    foreach ($findings as $entity_type_id => $entities) {
+      foreach ($entities as $entity_id => $fields) {
+        $entity = $this->entityManager()
+          ->getStorage($entity_type_id)
+          ->load($entity_id);
+
+        foreach ($fields as $field => $finding) {
+          $url = $entity->urlInfo('edit-form');
+          if ($url === NULL) {
+            $url = $entity->url();
+          }
+          $output .= "\t" . $this->t(
+              '@vulnerabilities in @field of :link',
+              [
+                '@vulnerabilities' => implode(' and ', $finding),
+                '@field' => $field,
+                ':link' => $url->toString(),
+              ]
+            ) . "\n";
+        }
+      }
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Dangerous tags were not found in any submitted content (fields).');
+
+      case CheckResult::FAIL:
+        return $this->t('Dangerous tags were found in submitted content (fields).');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/FilePermissions.php b/web/modules/contrib/security_review/src/Checks/FilePermissions.php
new file mode 100644 (file)
index 0000000..8641747
--- /dev/null
@@ -0,0 +1,246 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\FilePermissions.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\StreamWrapper\PrivateStream;
+use Drupal\Core\StreamWrapper\PublicStream;
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Check that files aren't writeable by the server.
+ */
+class FilePermissions extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'File permissions';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMachineTitle() {
+    return 'file_perms';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function storesFindings() {
+    return FALSE;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run($cli = FALSE) {
+    $result = CheckResult::SUCCESS;
+
+    $file_list = $this->getFileList('.');
+    $writable = $this->security()->findWritableFiles($file_list, $cli);
+
+    // Try creating or appending files.
+    // Assume it doesn't work.
+    $create_status = FALSE;
+    $append_status = FALSE;
+
+    if (!$cli) {
+      $append_message = $this->t("Your web server should not be able to write to your modules directory. This is a security vulnerable. Consult the Security Review file permissions check help for mitigation steps.");
+      $directory = $this->moduleHandler()
+        ->getModule('security_review')
+        ->getPath();
+
+      // Write a file with the timestamp.
+      $file = './' . $directory . '/file_write_test.' . date('Ymdhis');
+      if ($file_create = @fopen($file, 'w')) {
+        $create_status = fwrite($file_create, date('Ymdhis') . ' - ' . $append_message . "\n");
+        fclose($file_create);
+      }
+
+      // Try to append to our IGNOREME file.
+      $file = './' . $directory . '/IGNOREME.txt';
+      if ($file_append = @fopen($file, 'a')) {
+        $append_status = fwrite($file_append, date('Ymdhis') . ' - ' . $append_message . "\n");
+        fclose($file_append);
+      }
+    }
+
+    if (!empty($writable) || $create_status || $append_status) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $writable);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function runCli() {
+    if (!$this->securityReview()->isServerPosix()) {
+      return $this->createResult(CheckResult::INFO);
+    }
+
+    return $this->run(TRUE);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('It is dangerous to allow the web server to write to files inside the document root of your server. Doing so could allow Drupal to write files that could then be executed. An attacker might use such a vulnerability to take control of your site. An exception is the Drupal files, private files, and temporary directories which Drupal needs permission to write to in order to provide features like file attachments.');
+    $paragraphs[] = $this->t('In addition to inspecting existing directories, this test attempts to create and write to your file system. Look in your security_review module directory on the server for files named file_write_test.YYYYMMDDHHMMSS and for a file called IGNOREME.txt which gets a timestamp appended to it if it is writeable.');
+    $paragraphs[] = $this->l(
+      $this->t('Read more about file system permissions in the handbooks.'),
+      Url::fromUri('http://drupal.org/node/244924')
+    );
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Web server file system permissions'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    if ($result->result() == CheckResult::SUCCESS) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following files and directories appear to be writeable by your web server. In most cases you can fix this by simply altering the file permissions or ownership. If you have command-line access to your host try running "chmod 644 [file path]" where [file path] is one of the following paths (relative to your webroot). For more information consult the <a href="http://drupal.org/node/244924">Drupal.org handbooks on file permissions</a>.');
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $result->findings(),
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    if ($result->result() == CheckResult::SUCCESS) {
+      return '';
+    }
+
+    $output = $this->t('Writable files:') . "\n";
+    foreach ($result->findings() as $file) {
+      $output .= "\t" . $file . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Drupal installation files and directories (except required) are not writable by the server.');
+
+      case CheckResult::FAIL:
+        return $this->t('Some files and directories in your install are writable by the server.');
+
+      case CheckResult::INFO:
+        return $this->t('The test cannot be run on this system.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+  /**
+   * Scans a directory recursively and returns the files and directories inside.
+   *
+   * @param string $directory
+   *   The directory to scan.
+   * @param string[] $parsed
+   *   Array of already parsed real paths.
+   * @param string[] $ignore
+   *   Array of file names to ignore.
+   *
+   * @return string[]
+   *   The items found.
+   */
+  protected function getFileList($directory, array &$parsed = NULL, array &$ignore = NULL) {
+    // Initialize $parsed and $ignore arrays.
+    if ($parsed === NULL) {
+      $parsed = [realpath($directory)];
+    }
+    if ($ignore === NULL) {
+      $ignore = $this->getIgnoreList();
+    }
+
+    // Start scanning.
+    $items = [];
+    if ($handle = opendir($directory)) {
+      while (($file = readdir($handle)) !== FALSE) {
+        // Don't check hidden files or ones we said to ignore.
+        $path = $directory . "/" . $file;
+        if ($file[0] != "." && !in_array($file, $ignore) && !in_array(realpath($path), $ignore)) {
+          if (is_dir($path) && !in_array(realpath($path), $parsed)) {
+            $parsed[] = realpath($path);
+            $items = array_merge($items, $this->getFileList($path, $parsed, $ignore));
+          }
+          $items[] = preg_replace("/\/\//si", "/", $path);
+        }
+      }
+      closedir($handle);
+    }
+
+    return $items;
+  }
+
+  /**
+   * Returns an array of relative and canonical paths to ignore.
+   *
+   * @return string[]
+   *   List of relative and canonical file paths to ignore.
+   */
+  protected function getIgnoreList() {
+    $file_path = PublicStream::basePath();
+    $ignore = ['..', 'CVS', '.git', '.svn', '.bzr', realpath($file_path)];
+
+    // Add temporary files directory if it's set.
+    $temp_path = file_directory_temp();
+    if (!empty($temp_path)) {
+      $ignore[] = realpath('./' . rtrim($temp_path, '/'));
+    }
+
+    // Add private files directory if it's set.
+    $private_files = PrivateStream::basePath();
+    if (!empty($private_files)) {
+      // Remove leading slash if set.
+      if (strrpos($private_files, '/') !== FALSE) {
+        $private_files = substr($private_files, strrpos($private_files, '/') + 1);
+      }
+      $ignore[] = $private_files;
+    }
+
+    $this->moduleHandler()->alter('security_review_file_ignore', $ignore);
+    return $ignore;
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/InputFormats.php b/web/modules/contrib/security_review/src/Checks/InputFormats.php
new file mode 100644 (file)
index 0000000..79d1e1f
--- /dev/null
@@ -0,0 +1,194 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\InputFormats.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Checks for vulnerabilities related to input formats.
+ *
+ * Checks for formats that either do not have HTML filter that can be used by
+ * untrusted users, or if they do check if unsafe tags are allowed.
+ */
+class InputFormats extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Text formats';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMachineTitle() {
+    return 'input_formats';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // If filter is not enabled return with INFO.
+    if (!$this->moduleHandler()->moduleExists('filter')) {
+      return $this->createResult(CheckResult::INFO);
+    }
+
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    $formats = filter_formats();
+    $untrusted_roles = $this->security()->untrustedRoles();
+    $unsafe_tags = $this->security()->unsafeTags();
+
+    foreach ($formats as $format) {
+      $format_roles = array_keys(filter_get_roles_by_format($format));
+      $intersect = array_intersect($format_roles, $untrusted_roles);
+
+      if (!empty($intersect)) {
+        // Untrusted users can use this format.
+        // Check format for enabled HTML filter.
+        $filter_html_enabled = FALSE;
+        if ($format->filters()->has('filter_html')) {
+          $filter_html_enabled = $format->filters('filter_html')
+            ->getConfiguration()['status'];
+        }
+        $filter_html_escape_enabled = FALSE;
+        if ($format->filters()->has('filter_html_escape')) {
+          $filter_html_escape_enabled = $format->filters('filter_html_escape')
+            ->getConfiguration()['status'];
+        }
+
+        if ($filter_html_enabled) {
+          $filter = $format->filters('filter_html');
+
+          // Check for unsafe tags in allowed tags.
+          $allowed_tags = array_keys($filter->getHTMLRestrictions()['allowed']);
+          foreach (array_intersect($allowed_tags, $unsafe_tags) as $tag) {
+            // Found an unsafe tag.
+            $findings['tags'][$format->id()] = $tag;
+          }
+        }
+        elseif (!$filter_html_escape_enabled) {
+          // Format is usable by untrusted users but does not contain the HTML
+          // Filter or the HTML escape.
+          $findings['formats'][$format->id()] = $format->label();
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t("Certain HTML tags can allow an attacker to take control of your site. Drupal's input format system makes use of a set filters to run on incoming text. The 'HTML Filter' strips out harmful tags and Javascript events and should be used on all formats accessible by untrusted users.");
+    $paragraphs[] = $this->l(
+      $this->t("Read more about Drupal's input formats in the handbooks."),
+      Url::fromUri('http://drupal.org/node/224921')
+    );
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Allowed HTML tags in text formats'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $output = [];
+
+    if (!empty($result->findings()['tags'])) {
+      $paragraphs = [];
+      $paragraphs[] = $this->l(
+        $this->t('Review your text formats.'),
+        Url::fromRoute('filter.admin_overview')
+      );
+      $paragraphs[] = $this->t('It is recommended you remove the following tags from roles accessible by untrusted users.');
+      $output[] = [
+        '#theme' => 'check_evaluation',
+        '#paragraphs' => $paragraphs,
+        '#items' => $result->findings()['tags'],
+      ];
+    }
+
+    if (!empty($result->findings()['formats'])) {
+      $paragraphs = [];
+      $paragraphs[] = $this->t('The following formats are usable by untrusted roles and do not filter or escape allowed HTML tags.');
+      $output[] = [
+        '#theme' => 'check_evaluation',
+        '#paragraphs' => $paragraphs,
+        '#items' => $result->findings()['formats'],
+      ];
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $output = '';
+
+    if (!empty($result->findings()['tags'])) {
+      $output .= $this->t('Tags') . "\n";
+      foreach ($result->findings()['tags'] as $tag) {
+        $output .= "\t$tag\n";
+      }
+    }
+
+    if (!empty($result->findings()['formats'])) {
+      $output .= $this->t('Formats') . "\n";
+      foreach ($result->findings()['formats'] as $format) {
+        $output .= "\t$format\n";
+      }
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Untrusted users are not allowed to input dangerous HTML tags.');
+
+      case CheckResult::FAIL:
+        return $this->t('Untrusted users are allowed to input dangerous HTML tags.');
+
+      case CheckResult::INFO:
+        return $this->t('Module filter is not enabled.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/PrivateFiles.php b/web/modules/contrib/security_review/src/Checks/PrivateFiles.php
new file mode 100644 (file)
index 0000000..e19fb9f
--- /dev/null
@@ -0,0 +1,119 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\PrivateFiles.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\StreamWrapper\PrivateStream;
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Checks whether the private files' directory is under the web root.
+ */
+class PrivateFiles extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Private files';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $file_directory_path = PrivateStream::basePath();
+    $visible = TRUE;
+    if (empty($file_directory_path)) {
+      // Private files feature is not enabled.
+      $result = CheckResult::SUCCESS;
+      $visible = FALSE;
+    }
+    elseif (strpos(realpath($file_directory_path), DRUPAL_ROOT) === 0) {
+      // Path begins at root.
+      $result = CheckResult::FAIL;
+    }
+    else {
+      // The private files directory is placed correctly.
+      $result = CheckResult::SUCCESS;
+    }
+    return $this->createResult($result, ['path' => $file_directory_path], $visible);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t("If you have Drupal's private files feature enabled you should move the files directory outside of the web server's document root. Drupal will secure access to files that it renders the link to, but if a user knows the actual system path they can circumvent Drupal's private files feature. You can protect against this by specifying a files directory outside of the webserver root.");
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Private files'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    if ($result->result() != CheckResult::FAIL) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('Your files directory is not outside of the server root.');
+    $paragraphs[] = $this->l(
+      $this->t('Edit the files directory path.'),
+      Url::fromRoute('system.file_system_settings')
+    );
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => [],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    if ($result->result() != CheckResult::FAIL) {
+      return '';
+    }
+
+    return $this->t('Private files directory: @path', ['@path' => $result->findings()['path']]);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Private files directory is outside the web server root.');
+
+      case CheckResult::FAIL:
+        return $this->t('Private files is enabled but the specified directory is not secure outside the web server root.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/QueryErrors.php b/web/modules/contrib/security_review/src/Checks/QueryErrors.php
new file mode 100644 (file)
index 0000000..ba83e4f
--- /dev/null
@@ -0,0 +1,173 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\QueryErrors.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Logger\RfcLogLevel;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Checks for abundant query errors.
+ */
+class QueryErrors extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Query errors';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // If dblog is not enabled return with hidden INFO.
+    if (!$this->moduleHandler()->moduleExists('dblog')) {
+      return $this->createResult(CheckResult::INFO, [], FALSE);
+    }
+
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+    $last_result = $this->lastResult();
+    $visible = FALSE;
+
+    // Prepare the query.
+    $query = $this->database()->select('watchdog', 'w');
+    $query->fields('w', [
+      'severity',
+      'type',
+      'timestamp',
+      'message',
+      'variables',
+      'hostname',
+    ]);
+    $query->condition('type', 'php')->condition('severity', RfcLogLevel::ERROR);
+    if ($last_result instanceof CheckResult) {
+      // Only check entries that got recorded since the last run of the check.
+      $query->condition('timestamp', $last_result->time(), '>=');
+    }
+
+    // Execute the query.
+    $db_result = $query->execute();
+
+    // Count the number of query errors per IP.
+    $entries = [];
+    foreach ($db_result as $row) {
+      // Get the message.
+      if ($row->variables === 'N;') {
+        $message = $row->message;
+      }
+      else {
+        $message = $this->t($row->message, unserialize($row->variables));
+      }
+
+      // Get the IP.
+      $ip = $row->hostname;
+
+      // Search for query errors.
+      $message_contains_sql = strpos($message, 'SQL') !== FALSE;
+      $message_contains_select = strpos($message, 'SELECT') !== FALSE;
+      if ($message_contains_sql && $message_contains_select) {
+        $entry_for_ip = &$entries[$ip];
+
+        if (!isset($entry_for_ip)) {
+          $entry_for_ip = 0;
+        }
+        $entry_for_ip++;
+      }
+    }
+
+    // Filter the IPs with more than 10 query errors.
+    if (!empty($entries)) {
+      foreach ($entries as $ip => $count) {
+        if ($count > 10) {
+          $findings[] = $ip;
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+      $visible = TRUE;
+    }
+
+    return $this->createResult($result, $findings, $visible);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('Database errors triggered from the same IP may be an artifact of a malicious user attempting to probe the system for weaknesses like SQL injection or information disclosure.');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Abundant query errors from the same IP'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following IPs were observed with an abundance of query errors.');
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $result->findings(),
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = $this->t('Suspicious IP addresses:') . ":\n";
+    foreach ($findings as $ip) {
+      $output .= "\t" . $ip . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::FAIL:
+        return $this->t('Query errors from the same IP. These may be a SQL injection attack or an attempt at information disclosure.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/TemporaryFiles.php b/web/modules/contrib/security_review/src/Checks/TemporaryFiles.php
new file mode 100644 (file)
index 0000000..24700c1
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\TemporaryFiles.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * Check for sensitive temporary files like settings.php~.
+ */
+class TemporaryFiles extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Temporary files';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    // Get list of files from the site directory.
+    $files = [];
+    $site_path = $this->security()->sitePath() . '/';
+    $dir = scandir($site_path);
+    foreach ($dir as $file) {
+      // Set full path to only files.
+      if (!is_dir($file)) {
+        $files[] = $site_path . $file;
+      }
+    }
+    $this->moduleHandler()->alter('security_review_temporary_files', $files);
+
+    // Analyze the files' names.
+    foreach ($files as $path) {
+      $matches = [];
+      if (file_exists($path) && preg_match('/.*(~|\.sw[op]|\.bak|\.orig|\.save)$/', $path, $matches) !== FALSE && !empty($matches)) {
+        // Found a temporary file.
+        $findings[] = $path;
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t("Some file editors create temporary copies of a file that can be left on the file system. A copy of a sensitive file like Drupal's settings.php may be readable by a malicious user who could use that information to further attack a site.");
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Sensitive temporary files'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t("The following are extraneous files in your Drupal installation that can probably be removed. You should confirm you have saved any of your work in the original files prior to removing these.");
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $findings,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = $this->t('Temporary files:') . "\n";
+    foreach ($findings as $file) {
+      $output .= "\t" . $file . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('No sensitive temporary files were found.');
+
+      case CheckResult::FAIL:
+        return $this->t('Sensitive temporary files were found on your files system.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/TrustedHosts.php b/web/modules/contrib/security_review/src/Checks/TrustedHosts.php
new file mode 100644 (file)
index 0000000..fe105fc
--- /dev/null
@@ -0,0 +1,171 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\TrustedHosts.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Drupal\security_review\CheckSettings\TrustedHostSettings;
+
+/**
+ * Checks for base_url and trusted_host_patterns settings in settings.php.
+ */
+class TrustedHosts extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function __construct() {
+    parent::__construct();
+    $this->settings = new TrustedHostSettings($this, $this->config);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Trusted hosts';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $result = CheckResult::FAIL;
+    $base_url_set = FALSE;
+    $trusted_host_patterns_set = FALSE;
+    $findings = [];
+    $settings_php = $this->security()->sitePath() . '/settings.php';
+
+    if (!file_exists($settings_php)) {
+      return $this->createResult(CheckResult::INFO, [], FALSE);
+    }
+
+    if ($this->settings()->get('method', 'token') === 'token') {
+      // Use tokenization.
+      $content = file_get_contents($settings_php);
+      $tokens = token_get_all($content);
+
+      $prev_settings_line = -1;
+      foreach ($tokens as $token) {
+        if (is_array($token)) {
+          // Get information about the current token.
+          $line = $token[2];
+          $is_variable = $token[0] === T_VARIABLE;
+          $is_string = $token[0] === T_CONSTANT_ENCAPSED_STRING;
+          $is_settings = $is_variable ? $token[1] == '$settings' : FALSE;
+          $is_base_url = $token[1] == '$base_url';
+          $is_thp = trim($token[1], "\"'") == 'trusted_host_patterns';
+          $is_after_settings = $line == $prev_settings_line;
+
+          // Check for $base_url.
+          if ($is_variable && $is_base_url) {
+            $base_url_set = TRUE;
+            $result = CheckResult::SUCCESS;
+          }
+
+          // Check for $settings['trusted_host_patterns'].
+          if ($is_after_settings && $is_string && $is_thp) {
+            $trusted_host_patterns_set = TRUE;
+            $result = CheckResult::SUCCESS;
+          }
+
+          // If found both settings stop the review.
+          if ($base_url_set && $trusted_host_patterns_set) {
+            // Got everything we need.
+            break;
+          }
+
+          // Store last $settings line.
+          if ($is_settings) {
+            $prev_settings_line = $line;
+          }
+        }
+      }
+    }
+    else {
+      // Use inclusion.
+      include $settings_php;
+      $base_url_set = isset($base_url);
+      $trusted_host_patterns_set = isset($settings['trusted_host_patterns']);
+    }
+
+    if ($result === CheckResult::FAIL) {
+      // Provide information if the check failed.
+      global $base_url;
+      $findings['base_url'] = $base_url;
+      $findings['settings'] = $settings_php;
+      $findings['base_url_set'] = $base_url_set;
+      $findings['trusted_host_patterns_set'] = $trusted_host_patterns_set;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t('Often Drupal needs to know the URL(s) it is responding from in order to build full links back to itself (e.g. password reset links sent via email). Until you explicitly tell Drupal what full or partial URL(s) it should respond for it must dynamically detect it based on the incoming request, something that can be malicously spoofed in order to trick someone into unknowningly visiting an attacker\'s site (known as a HTTP host header attack).');
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Drupal trusted hosts'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    global $base_url;
+    if ($result->result() !== CheckResult::FAIL) {
+      return [];
+    }
+
+    $settings_php = $this->security()->sitePath() . '/settings.php';
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('This site is responding from the URL: :url.', [':url' => $base_url]);
+    $paragraphs[] = $this->t('If the site should be available only at that URL it is recommended that you set it as the $base_url variable in the settings.php file at @file.', ['@file' => $settings_php]);
+    $paragraphs[] = $this->t('If the site has multiple URLs it can respond from you should whitelist host patterns with trusted_host_patterns in settings.php.');
+    $paragraphs[] = $this->l($this->t('Read more about HTTP Host Header attacks and setting trusted_host_patterns.'), Url::fromUri('https://www.drupal.org/node/1992030'));
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => [],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Either $base_url or trusted_host_patterns is set.');
+
+      case CheckResult::FAIL:
+        return $this->t('Neither $base_url nor trusted_host_patterns is set.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/UploadExtensions.php b/web/modules/contrib/security_review/src/Checks/UploadExtensions.php
new file mode 100644 (file)
index 0000000..488fa28
--- /dev/null
@@ -0,0 +1,191 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\UploadExtensions.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Entity\Entity;
+use Drupal\Core\Url;
+use Drupal\field\Entity\FieldConfig;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Symfony\Component\Routing\Exception\RouteNotFoundException;
+
+/**
+ * Checks for unsafe extensions in the allowed extensions settings of fields.
+ */
+class UploadExtensions extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Allowed upload extensions';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMachineTitle() {
+    return 'upload_extensions';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // If field is not enabled return with INFO.
+    if (!$this->moduleHandler()->moduleExists('field')) {
+      return $this->createResult(CheckResult::INFO);
+    }
+
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    // Check field configuration entities.
+    foreach (FieldConfig::loadMultiple() as $entity) {
+      /** @var FieldConfig $entity */
+      $extensions = $entity->getSetting('file_extensions');
+      if ($extensions != NULL) {
+        $extensions = explode(' ', $extensions);
+        $intersect = array_intersect($extensions, $this->security()->unsafeExtensions());
+        // $intersect holds the unsafe extensions this entity allows.
+        foreach ($intersect as $unsafe_extension) {
+          $findings[$entity->id()][] = $unsafe_extension;
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t(
+      'File and image fields allow for uploaded files. Some extensions are considered dangerous because the files can be evaluated and then executed in the browser. A malicious user could use this opening to gain control of your site. Review <a href=":url">all fields on your site</a>.',
+      [':url' => Url::fromRoute('entity.field_storage_config.collection')->toString()]
+    );
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => 'Allowed upload extensions',
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following extensions are considered unsafe and should be removed or limited from use. Or, be sure you are not granting untrusted users the ability to upload files.');
+
+    $items = [];
+    foreach ($findings as $entity_id => $unsafe_extensions) {
+      $entity = FieldConfig::load($entity_id);
+      /** @var FieldConfig $entity */
+
+      foreach ($unsafe_extensions as $extension) {
+        $item = $this->t(
+          'Review @type in <em>@field</em> field on @bundle',
+          [
+            '@type' => $extension,
+            '@field' => $entity->label(),
+            '@bundle' => $entity->getTargetBundle(),
+          ]
+        );
+
+        // Try to get an edit url.
+        try {
+          $url_params = ['field_config' => $entity->id()];
+          if ($entity->getTargetEntityTypeId() == 'node') {
+            $url_params['node_type'] = $entity->getTargetBundle();
+          }
+          $url = Url::fromRoute(
+            'entity.field_config.' . $entity->getTargetEntityTypeId() . '_field_edit_form',
+            $url_params
+          );
+          $items[] = $this->l($item, $url);
+        }
+        catch (RouteNotFoundException $e) {
+          $items[] = $item;
+        }
+      }
+    }
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $items,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = '';
+    foreach ($findings as $entity_id => $unsafe_extensions) {
+      $entity = FieldConfig::load($entity_id);
+      /** @var FieldConfig $entity */
+
+      $output .= $this->t(
+        '@bundle: field @field',
+        [
+          '@bundle' => $entity->getTargetBundle(),
+          '@field' => $entity->label(),
+        ]
+      );
+      $output .= "\n\t" . implode(', ', $unsafe_extensions) . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Only safe extensions are allowed for uploaded files and images.');
+
+      case CheckResult::FAIL:
+        return $this->t('Unsafe file extensions are allowed in uploads.');
+
+      case CheckResult::INFO:
+        return $this->t('Module field is not enabled.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Checks/ViewsAccess.php b/web/modules/contrib/security_review/src/Checks/ViewsAccess.php
new file mode 100644 (file)
index 0000000..3d7cf01
--- /dev/null
@@ -0,0 +1,157 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Checks\ViewsAccess.
+ */
+
+namespace Drupal\security_review\Checks;
+
+use Drupal\Core\Url;
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+use Drupal\views\Entity\View;
+
+/**
+ * Checks for Views that do not check access.
+ */
+class ViewsAccess extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Views access';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    // If views is not enabled return with INFO.
+    if (!$this->moduleHandler()->moduleExists('views')) {
+      return $this->createResult(CheckResult::INFO);
+    }
+
+    $result = CheckResult::SUCCESS;
+    $findings = [];
+
+    $views = View::loadMultiple();
+    /** @var View[] $views */
+
+    // Iterate through views and their displays.
+    foreach ($views as $view) {
+      if ($view->status()) {
+        foreach ($view->get('display') as $display_name => $display) {
+          $access = &$display['display_options']['access'];
+          if (isset($access) && $access['type'] == 'none') {
+            // Access is not controlled for this display.
+            $findings[$view->id()][] = $display_name;
+          }
+        }
+      }
+    }
+
+    if (!empty($findings)) {
+      $result = CheckResult::FAIL;
+    }
+
+    return $this->createResult($result, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    $paragraphs = [];
+    $paragraphs[] = $this->t("Views can check if the user is allowed access to the content. It is recommended that all Views implement some amount of access control, at a minimum checking for the permission 'access content'.");
+
+    return [
+      '#theme' => 'check_help',
+      '#title' => $this->t('Views access'),
+      '#paragraphs' => $paragraphs,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluate(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return [];
+    }
+
+    $paragraphs = [];
+    $paragraphs[] = $this->t('The following View displays do not check access.');
+
+    $items = [];
+    foreach ($findings as $view_id => $displays) {
+      $view = View::load($view_id);
+      /** @var View $view */
+
+      foreach ($displays as $display) {
+        $items[] = $this->l(
+          $view->label() . ': ' . $display,
+          Url::fromRoute(
+            'entity.view.edit_display_form',
+            [
+              'view' => $view_id,
+              'display_id' => $display,
+            ]
+          )
+        );
+      }
+    }
+
+    return [
+      '#theme' => 'check_evaluation',
+      '#paragraphs' => $paragraphs,
+      '#items' => $items,
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function evaluatePlain(CheckResult $result) {
+    $findings = $result->findings();
+    if (empty($findings)) {
+      return '';
+    }
+
+    $output = $this->t('Views without access check:') . ":\n";
+    foreach ($findings as $view_id => $displays) {
+      $output .= "\t" . $view_id . ": " . implode(', ', $displays) . "\n";
+    }
+
+    return $output;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    switch ($result_const) {
+      case CheckResult::SUCCESS:
+        return $this->t('Views are access controlled.');
+
+      case CheckResult::FAIL:
+        return $this->t('There are Views that do not provide any access checks.');
+
+      case CheckResult::INFO:
+        return $this->t('Module views is not enabled.');
+
+      default:
+        return $this->t('Unexpected result.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Controller/ChecklistController.php b/web/modules/contrib/security_review/src/Controller/ChecklistController.php
new file mode 100644 (file)
index 0000000..3883522
--- /dev/null
@@ -0,0 +1,175 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Controller\ChecklistController.
+ */
+
+namespace Drupal\security_review\Controller;
+
+use Drupal\Core\Access\CsrfTokenGenerator;
+use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Url;
+use Drupal\security_review\Checklist;
+use Drupal\security_review\CheckResult;
+use Drupal\security_review\SecurityReview;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * The class of the 'Run & Review' page's controller.
+ */
+class ChecklistController extends ControllerBase {
+
+  /**
+   * The CSRF Token generator.
+   *
+   * @var \Drupal\Core\Access\CsrfTokenGenerator $csrfToken
+   */
+  protected $csrfToken;
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+
+  /**
+   * Constructs a ChecklistController.
+   *
+   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token_generator
+   *   The CSRF Token generator.
+   * @param \Drupal\security_review\SecurityReview $security_review
+   *   The security_review service.
+   * @param \Drupal\security_review\Checklist $checklist
+   *   The security_review.checklist service.
+   */
+  public function __construct(CsrfTokenGenerator $csrf_token_generator, SecurityReview $security_review, Checklist $checklist) {
+    $this->csrfToken = $csrf_token_generator;
+    $this->checklist = $checklist;
+    $this->securityReview = $security_review;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('csrf_token'),
+      $container->get('security_review'),
+      $container->get('security_review.checklist')
+    );
+  }
+
+  /**
+   * Creates the Run & Review page.
+   *
+   * @return array
+   *   The 'Run & Review' page's render array.
+   */
+  public function index() {
+    $run_form = [];
+
+    // If the user has the required permissions, show the RunForm.
+    if ($this->currentUser()->hasPermission('run security checks')) {
+      // Get the Run form.
+      $run_form = $this->formBuilder()
+        ->getForm('Drupal\security_review\Form\RunForm');
+
+      // Close the Run form if there are results.
+      if ($this->securityReview->getLastRun() > 0) {
+        $run_form['run_form']['#open'] = FALSE;
+      }
+    }
+
+    // Print the results if any.
+    if ($this->securityReview->getLastRun() <= 0) {
+      // If they haven't configured the site, prompt them to do so.
+      if (!$this->securityReview->isConfigured()) {
+        drupal_set_message($this->t('It appears this is your first time using the Security Review checklist. Before running the checklist please review the settings page at <a href=":url">admin/reports/security-review/settings</a> to set which roles are untrusted.',
+          [':url' => Url::fromRoute('security_review.settings')->toString()]
+        ), 'warning');
+      }
+    }
+
+    return [$run_form, $this->results()];
+  }
+
+  /**
+   * Creates the results' table.
+   *
+   * @return array
+   *   The render array for the result table.
+   */
+  public function results() {
+    // If there are no results return.
+    if ($this->securityReview->getLastRun() <= 0) {
+      return [];
+    }
+
+    $checks = [];
+    foreach ($this->checklist->getChecks() as $check) {
+      // Initialize with defaults.
+      $check_info = [
+        'message' => $this->t(
+          'The check "@name" hasn\'t been run yet.',
+          ['@name' => $check->getTitle()]
+        ),
+        'skipped' => $check->isSkipped(),
+      ];
+
+      // Get last result.
+      $last_result = $check->lastResult();
+      if ($last_result != NULL) {
+        if (!$last_result->isVisible()) {
+          continue;
+        }
+        $check_info['result'] = $last_result->result();
+        $check_info['message'] = $last_result->resultMessage();
+      }
+
+      // Determine help link.
+      $check_info['help_link'] = $this->l(
+        'Details',
+        Url::fromRoute(
+          'security_review.help',
+          [
+            'namespace' => $check->getMachineNamespace(),
+            'title' => $check->getMachineTitle(),
+          ]
+        )
+      );
+
+      // Add toggle button.
+      $toggle_text = $check->isSkipped() ? 'Enable' : 'Skip';
+      $check_info['toggle_link'] = $this->l($toggle_text,
+        Url::fromRoute(
+          'security_review.toggle',
+          ['check_id' => $check->id()],
+          ['query' => ['token' => $this->csrfToken->get($check->id())]]
+        )
+      );
+
+      // Add to array of completed checks.
+      $checks[] = $check_info;
+    }
+
+    return [
+      '#theme' => 'run_and_review',
+      '#date' => $this->securityReview->getLastRun(),
+      '#checks' => $checks,
+      '#attached' => [
+        'library' => ['security_review/run_and_review'],
+      ],
+    ];
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Controller/HelpController.php b/web/modules/contrib/security_review/src/Controller/HelpController.php
new file mode 100644 (file)
index 0000000..89f1043
--- /dev/null
@@ -0,0 +1,198 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Controller\HelpController.
+ */
+
+namespace Drupal\security_review\Controller;
+
+use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Url;
+use Drupal\security_review\Checklist;
+use Drupal\security_review\CheckResult;
+use Drupal\security_review\SecurityReview;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+
+/**
+ * The class of the Help pages' controller.
+ */
+class HelpController extends ControllerBase {
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+  /**
+   * Constructs a HelpController.
+   *
+   * @param \Drupal\security_review\SecurityReview $security_review
+   *   The security_review service.
+   * @param \Drupal\security_review\Checklist $checklist
+   *   The security_review.checklist service.
+   */
+  public function __construct(SecurityReview $security_review, Checklist $checklist) {
+    // Store the dependencies.
+    $this->checklist = $checklist;
+    $this->securityReview = $security_review;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('security_review'),
+      $container->get('security_review.checklist')
+    );
+  }
+
+  /**
+   * Serves as an entry point for the help pages.
+   *
+   * @param string|NULL $namespace
+   *   The namespace of the check (null if general page).
+   * @param string $title
+   *   The name of the check.
+   *
+   * @return array
+   *   The requested help page.
+   */
+  public function index($namespace, $title) {
+    // If no namespace is set, print the general help page.
+    if ($namespace === NULL) {
+      return $this->generalHelp();
+    }
+
+    // Print check-specific help.
+    return $this->checkHelp($namespace, $title);
+  }
+
+  /**
+   * Returns the general help page.
+   *
+   * @return array
+   *   The general help page.
+   */
+  private function generalHelp() {
+    $paragraphs = [];
+
+    // Print the general help.
+    $paragraphs[] = $this->t('You should take the security of your site very seriously. Fortunately, Drupal is fairly secure by default. The Security Review module automates many of the easy-to-make mistakes that render your site insecure, however it does not automatically make your site impenetrable. You should give care to what modules you install and how you configure your site and server. Be mindful of who visits your site and what features you expose for their use.');
+    $paragraphs[] = $this->t('You can read more about securing your site in the <a href="http://drupal.org/security/secure-configuration">drupal.org handbooks</a> and on <a href="http://crackingdrupal.com">CrackingDrupal.com</a>. There are also additional modules you can install to secure or protect your site. Be aware though that the more modules you have running on your site the greater (usually) attack area you expose.');
+    $paragraphs[] = $this->t('<a href="http://drupal.org/node/382752">Drupal.org Handbook: Introduction to security-related contrib modules</a>');
+
+    // Print the list of security checks with links to their help pages.
+    $checks = [];
+    foreach ($this->checklist->getChecks() as $check) {
+      // Get the namespace array's reference.
+      $check_namespace = &$checks[$check->getMachineNamespace()];
+
+      // Set up the namespace array if not set.
+      if (!isset($check_namespace)) {
+        $check_namespace['namespace'] = $check->getNamespace();
+        $check_namespace['check_links'] = [];
+      }
+
+      // Add the link pointing to the check-specific help.
+      $check_namespace['check_links'][] = $this->l(
+        $this->t('@title', ['@title' => $check->getTitle()]),
+        Url::fromRoute('security_review.help', [
+          'namespace' => $check->getMachineNamespace(),
+          'title' => $check->getMachineTitle(),
+        ])
+      );
+    }
+
+    return [
+      '#theme' => 'general_help',
+      '#paragraphs' => $paragraphs,
+      '#checks' => $checks,
+    ];
+  }
+
+  /**
+   * Returns a check-specific help page.
+   *
+   * @param string $namespace
+   *   The namespace of the check.
+   * @param string $title
+   *   The name of the check.
+   *
+   * @return array
+   *   The check's help page.
+   *
+   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
+   *   If the check is not found.
+   */
+  private function checkHelp($namespace, $title) {
+    // Get the requested check.
+    $check = $this->checklist->getCheck($namespace, $title);
+
+    // If the check doesn't exist, throw 404.
+    if ($check == NULL) {
+      throw new NotFoundHttpException();
+    }
+
+    // Print the help page.
+    $output = [];
+    $output[] = $check->help();
+
+    // If the check is skipped print the skip message, else print the
+    // evaluation.
+    if ($check->isSkipped()) {
+
+      if ($check->skippedBy() != NULL) {
+        $user = $this->l(
+          $check->skippedBy()->getUsername(),
+          $check->skippedBy()->urlInfo()
+        );
+      }
+      else {
+        $user = 'Anonymous';
+      }
+
+      $skip_message = $this->t(
+        'Check marked for skipping on @date by @user',
+        [
+          '@date' => format_date($check->skippedOn()),
+          '@user' => $user,
+        ]
+      );
+
+      $output[] = [
+        '#type' => 'markup',
+        '#markup' => "<p>$skip_message</p>",
+      ];
+    }
+    else {
+      // Evaluate last result, if any.
+      $last_result = $check->lastResult(TRUE);
+      if ($last_result instanceof CheckResult) {
+        // Separator.
+        $output[] = [
+          '#type' => 'markup',
+          '#markup' => '<div />',
+        ];
+
+        // Evaluation page.
+        $output[] = $check->evaluate($last_result);
+      }
+    }
+
+    // Return the completed page.
+    return $output;
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Controller/ToggleController.php b/web/modules/contrib/security_review/src/Controller/ToggleController.php
new file mode 100644 (file)
index 0000000..4aca297
--- /dev/null
@@ -0,0 +1,139 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Controller\ToggleController.
+ */
+
+namespace Drupal\security_review\Controller;
+
+use Drupal\Core\Access\CsrfTokenGenerator;
+use Drupal\Core\Controller\ControllerBase;
+use Drupal\Core\Url;
+use Drupal\security_review\Checklist;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpFoundation\JsonResponse;
+use Symfony\Component\HttpFoundation\RequestStack;
+
+/**
+ * Responsible for handling the toggle links on the Run & Review page.
+ */
+class ToggleController extends ControllerBase {
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * The CSRF Token generator.
+   *
+   * @var \Drupal\Core\Access\CsrfTokenGenerator $csrfToken
+   */
+  protected $csrfToken;
+
+  /**
+   * The request stack.
+   *
+   * @var \Symfony\Component\HttpFoundation\Request $request
+   */
+  protected $request;
+
+  /**
+   * Constructs a ToggleController.
+   *
+   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token_generator
+   *   The CSRF Token generator.
+   * @param \Symfony\Component\HttpFoundation\RequestStack $request
+   *   The request stack.
+   * @param \Drupal\security_review\Checklist $checklist
+   *   The security_review.checklist service.
+   */
+  public function __construct(CsrfTokenGenerator $csrf_token_generator, RequestStack $request, Checklist $checklist) {
+    $this->checklist = $checklist;
+    $this->csrfToken = $csrf_token_generator;
+    $this->request = $request->getCurrentRequest();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('csrf_token'),
+      $container->get('request_stack'),
+      $container->get('security_review.checklist')
+    );
+  }
+
+  /**
+   * Handles check toggling.
+   *
+   * @param string $check_id
+   *   The ID of the check.
+   *
+   * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
+   *   The response.
+   */
+  public function index($check_id) {
+    // Determine access type.
+    $ajax = $this->request->query->get('js') == 1;
+
+    // Validate token.
+    $token = $this->request->query->get('token');
+    if ($this->csrfToken->validate($token, $check_id)) {
+      // Toggle.
+      $check = $this->checklist->getCheckById($check_id);
+      if ($check != NULL) {
+        if ($check->isSkipped()) {
+          $check->enable();
+        }
+        else {
+          $check->skip();
+        }
+      }
+
+      // Output.
+      if ($ajax) {
+        return new JsonResponse([
+          'skipped' => $check->isSkipped(),
+          'toggle_text' => $check->isSkipped() ? $this->t('Enable') : $this->t('Skip'),
+          'toggle_href' => Url::fromRoute(
+            'security_review.toggle',
+            ['check_id' => $check->id()],
+            [
+              'query' => [
+                'token' => $this->csrfToken->get($check->id()),
+                'js' => 1,
+              ],
+            ]
+          )->toString(),
+        ]);
+      }
+      else {
+        // Set message.
+        if ($check->isSkipped()) {
+          drupal_set_message($this->t(
+            '@name check skipped.',
+            ['@name' => $check->getTitle()]
+          ));
+        }
+        else {
+          drupal_set_message($this->t(
+            '@name check no longer skipped.',
+            ['@name' => $check->getTitle()]
+          ));
+        }
+
+        // Redirect back to Run & Review.
+        return $this->redirect('security_review');
+      }
+    }
+
+    // Go back to Run & Review if the access was wrong.
+    return $this->redirect('security_review');
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Form/RunForm.php b/web/modules/contrib/security_review/src/Form/RunForm.php
new file mode 100644 (file)
index 0000000..8eeeba9
--- /dev/null
@@ -0,0 +1,100 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Form\RunForm.
+ */
+
+namespace Drupal\security_review\Form;
+
+use Drupal\Core\Form\FormBase;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\security_review\Checklist;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Provides implementation for the Run form.
+ */
+class RunForm extends FormBase {
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * Constructs a RunForm.
+   *
+   * @param \Drupal\security_review\Checklist $checklist
+   *   The security_review.checklist service.
+   */
+  public function __construct(Checklist $checklist) {
+    $this->checklist = $checklist;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('security_review.checklist')
+    );
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getFormId() {
+    return 'security-review-run';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm(array $form, FormStateInterface $form_state) {
+    if (!$this->currentUser()->hasPermission('run security checks')) {
+      return [];
+    }
+
+    $form['run_form'] = [
+      '#type' => 'details',
+      '#title' => $this->t('Run'),
+      '#description' => $this->t('Click the button below to run the security checklist and review the results.') . '<br />',
+      '#open' => TRUE,
+    ];
+
+    $form['run_form']['submit'] = [
+      '#type' => 'submit',
+      '#value' => $this->t('Run checklist'),
+    ];
+
+    // Return the finished form.
+    return $form;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, FormStateInterface $form_state) {
+    $batch = [
+      'operations' => [],
+      'finished' => '_security_review_batch_run_finished',
+      'title' => $this->t('Performing Security Review'),
+      'init_message' => $this->t('Security Review is starting.'),
+      'progress_message' => $this->t('Progress @current out of @total.'),
+      'error_message' => $this->t('An error occurred. Rerun the process or consult the logs.'),
+    ];
+
+    foreach ($this->checklist->getEnabledChecks() as $check) {
+      $batch['operations'][] = [
+        '_security_review_batch_run_op',
+        [$check],
+      ];
+    }
+
+    batch_set($batch);
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Form/SettingsForm.php b/web/modules/contrib/security_review/src/Form/SettingsForm.php
new file mode 100644 (file)
index 0000000..bd6dc9c
--- /dev/null
@@ -0,0 +1,276 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Form\SettingsForm.
+ */
+
+namespace Drupal\security_review\Form;
+
+use Drupal\Component\Utility\SafeMarkup;
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\Form\ConfigFormBase;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\security_review\Checklist;
+use Drupal\security_review\Security;
+use Drupal\security_review\SecurityReview;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Settings page for Security Review.
+ */
+class SettingsForm extends ConfigFormBase {
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * The security_review.security service.
+   *
+   * @var \Drupal\security_review\Security
+   */
+  protected $security;
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+  /**
+   * Constructs a SettingsForm.
+   *
+   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
+   *   The config factory.
+   * @param \Drupal\security_review\Checklist $checklist
+   *   The security_review.checklist service.
+   * @param \Drupal\security_review\Security $security
+   *   The security_review.security service.
+   * @param \Drupal\security_review\SecurityReview $security_review
+   *   The security_review service.
+   */
+  public function __construct(ConfigFactoryInterface $config_factory, Checklist $checklist, Security $security, SecurityReview $security_review) {
+    parent::__construct($config_factory);
+    $this->checklist = $checklist;
+    $this->security = $security;
+    $this->securityReview = $security_review;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('config.factory'),
+      $container->get('security_review.checklist'),
+      $container->get('security_review.security'),
+      $container->get('security_review')
+    );
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getFormId() {
+    return 'security-review-settings';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function buildForm(array $form, FormStateInterface $form_state) {
+    // Get the list of checks.
+    $checks = $this->checklist->getChecks();
+
+    // Get the user roles.
+    $roles = user_roles();
+    $options = [];
+    foreach ($roles as $rid => $role) {
+      $options[$rid] = SafeMarkup::checkPlain($role->label());
+    }
+
+    // Notify the user if anonymous users can create accounts.
+    $message = '';
+    if (in_array(AccountInterface::AUTHENTICATED_ROLE, $this->security->defaultUntrustedRoles())) {
+      $message = $this->t('You have allowed anonymous users to create accounts without approval so the authenticated role defaults to untrusted.');
+    }
+
+    // Show the untrusted roles form element.
+    $form['untrusted_roles'] = [
+      '#type' => 'checkboxes',
+      '#title' => $this->t('Untrusted roles'),
+      '#description' => $this->t(
+        'Define which roles are for less trusted users. The anonymous role defaults to untrusted. @message Most Security Review checks look for resources usable by untrusted roles.',
+        ['@message' => $message]
+      ),
+      '#options' => $options,
+      '#default_value' => $this->security->untrustedRoles(),
+    ];
+
+    $form['advanced'] = [
+      '#type' => 'details',
+      '#title' => $this->t('Advanced'),
+      '#open' => TRUE,
+    ];
+
+    // Show the logging setting.
+    $form['advanced']['logging'] = [
+      '#type' => 'checkbox',
+      '#title' => $this->t('Log checklist results and skips'),
+      '#description' => $this->t('The result of each check and skip can be logged to watchdog for tracking.'),
+      '#default_value' => $this->securityReview->isLogging(),
+    ];
+
+    // Skipped checks.
+    $values = [];
+    $options = [];
+    foreach ($checks as $check) {
+      // Determine if check is being skipped.
+      if ($check->isSkipped()) {
+        $values[] = $check->id();
+        $label = $this->t(
+          '@name <em>skipped by UID @uid on @date</em>',
+          [
+            '@name' => $check->getTitle(),
+            '@uid' => $check->skippedBy()->id(),
+            '@date' => format_date($check->skippedOn()),
+          ]
+        );
+      }
+      else {
+        $label = $check->getTitle();
+      }
+      $options[$check->id()] = $label;
+    }
+    $form['advanced']['skip'] = [
+      '#type' => 'checkboxes',
+      '#title' => $this->t('Checks to skip'),
+      '#description' => $this->t('Skip running certain checks. This can also be set on the <em>Run & review</em> page. It is recommended that you do not skip any checks unless you know the result is wrong or the process times out while running.'),
+      '#options' => $options,
+      '#default_value' => $values,
+    ];
+
+    // Iterate through checklist and get check-specific setting pages.
+    foreach ($checks as $check) {
+      // Get the check's setting form.
+      $check_form = $check->settings()->buildForm();
+
+      // If not empty, add it to the form.
+      if (!empty($check_form)) {
+        // If this is the first non-empty setting page initialize the 'details'
+        if (!isset($form['advanced']['check_specific'])) {
+          $form['advanced']['check_specific'] = [
+            '#type' => 'details',
+            '#title' => $this->t('Check-specific settings'),
+            '#open' => FALSE,
+            '#tree' => TRUE,
+          ];
+        }
+
+        // Add the form.
+        $sub_form = &$form['advanced']['check_specific'][$check->id()];
+
+        $title = $check->getTitle();
+        // If it's an external check, show its namespace.
+        if ($check->getMachineNamespace() != 'security_review') {
+          $title .= $this->t('%namespace', [
+            '%namespace' => $check->getNamespace(),
+          ]);
+        }
+        $sub_form = [
+          '#type' => 'details',
+          '#title' => $title,
+          '#open' => TRUE,
+          '#tree' => TRUE,
+          'form' => $check_form,
+        ];
+      }
+    }
+
+    // Return the finished form.
+    return parent::buildForm($form, $form_state);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function validateForm(array &$form, FormStateInterface $form_state) {
+    // Run validation for check-specific settings.
+    if (isset($form['advanced']['check_specific'])) {
+      $check_specific_values = $form_state->getValue('check_specific');
+      foreach ($this->checklist->getChecks() as $check) {
+        $check_form = &$form['advanced']['check_specific'][$check->id()];
+        if (isset($check_form)) {
+          $check->settings()
+            ->validateForm($check_form, $check_specific_values[$check->id()]);
+        }
+      }
+    }
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function submitForm(array &$form, FormStateInterface $form_state) {
+    // Frequently used configuration items.
+    $check_settings = $this->config('security_review.checks');
+
+    // Save that the module has been configured.
+    $this->securityReview->setConfigured(TRUE);
+
+    // Save the new untrusted roles.
+    $untrusted_roles = array_keys(array_filter($form_state->getValue('untrusted_roles')));
+    $this->securityReview->setUntrustedRoles($untrusted_roles);
+
+    // Save the new logging setting.
+    $logging = $form_state->getValue('logging') == 1;
+    $this->securityReview->setLogging($logging);
+
+    // Skip selected checks.
+    $skipped = array_keys(array_filter($form_state->getValue('skip')));
+    foreach ($this->checklist->getChecks() as $check) {
+      if (in_array($check->id(), $skipped)) {
+        $check->skip();
+      }
+      else {
+        $check->enable();
+      }
+    }
+
+    // Save the check-specific settings.
+    if (isset($form['advanced']['check_specific'])) {
+      $check_specific_values = $form_state->getValue('check_specific');
+      foreach ($check_specific_values as $id => $values) {
+        // Get corresponding Check.
+        $check = $this->checklist->getCheckById($id);
+
+        // Submit parameters.
+        $check_form = &$form['advanced']['check_specific'][$id]['form'];
+        $check_form_values = $check_specific_values[$id]['form'];
+
+        // Submit.
+        $check->settings()->submitForm($check_form, $check_form_values);
+      }
+    }
+
+    // Commit the settings.
+    $check_settings->save();
+
+    // Finish submitting the form.
+    parent::submitForm($form, $form_state);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function getEditableConfigNames() {
+    return ['security_review.checks'];
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Security.php b/web/modules/contrib/security_review/src/Security.php
new file mode 100644 (file)
index 0000000..bf280f3
--- /dev/null
@@ -0,0 +1,383 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Security.
+ */
+
+namespace Drupal\security_review;
+
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
+use Drupal\Core\DrupalKernelInterface;
+use Drupal\Core\Extension\ModuleHandlerInterface;
+use Drupal\Core\Session\AccountInterface;
+use Drupal\user\Entity\Role;
+
+/**
+ * Provides frequently used security-related data.
+ */
+class Security {
+
+  use DependencySerializationTrait;
+
+  /**
+   * The config factory.
+   *
+   * @var \Drupal\Core\Config\ConfigFactoryInterface
+   */
+  protected $configFactory;
+
+  /**
+   * The Drupal kernel.
+   *
+   * @var \Drupal\Core\DrupalKernelInterface
+   */
+  protected $kernel;
+
+  /**
+   * The module handler.
+   *
+   * @var \Drupal\Core\Extension\ModuleHandlerInterface
+   */
+  protected $moduleHandler;
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+  /**
+   * Constructs a Security instance.
+   *
+   * @param \Drupal\security_review\SecurityReview $security_review
+   *   The SecurityReview service.
+   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
+   *   The module handler.
+   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
+   *   The config factory.
+   * @param \Drupal\Core\DrupalKernelInterface $kernel
+   *   The Drupal kernel.
+   */
+  public function __construct(SecurityReview $security_review, ModuleHandlerInterface $module_handler, ConfigFactoryInterface $config_factory, DrupalKernelInterface $kernel) {
+    // Store the dependencies.
+    $this->securityReview = $security_review;
+    $this->moduleHandler = $module_handler;
+    $this->configFactory = $config_factory;
+    $this->kernel = $kernel;
+  }
+
+  /**
+   * Returns the IDs of untrusted roles.
+   *
+   * If the module hasn't been configured yet, it returns the default untrusted
+   * roles.
+   *
+   * @return string[]
+   *   Untrusted roles' IDs.
+   */
+  public function untrustedRoles() {
+    // If the module hasn't been manually configured yet, return the untrusted
+    // roles depending on Drupal's actual configuration.
+    if (!$this->securityReview->isConfigured()) {
+      return static::defaultUntrustedRoles();
+    }
+
+    // Else return the stored untrusted roles.
+    return $this->securityReview->getUntrustedRoles();
+  }
+
+  /**
+   * Returns the default untrusted roles.
+   *
+   * The default untrusted roles are:
+   *   Anonymous      : always
+   *   Authenticated  : if visitors are allowed to create accounts.
+   *
+   * @return string[]
+   *   Default untrusted roles' IDs.
+   */
+  public function defaultUntrustedRoles() {
+    // Add the Anonymous role to the output array.
+    $roles = [AccountInterface::ANONYMOUS_ROLE];
+
+    // Check whether visitors can create accounts.
+    $user_register = $this->configFactory->get('user.settings')
+      ->get('register');
+    if ($user_register !== USER_REGISTER_ADMINISTRATORS_ONLY) {
+      // If visitors are allowed to create accounts they are considered
+      // untrusted.
+      $roles[] = AccountInterface::AUTHENTICATED_ROLE;
+    }
+
+    // Return the untrusted roles.
+    return $roles;
+  }
+
+  /**
+   * Returns the permission strings that a group of roles have.
+   *
+   * @param string[] $role_ids
+   *   The array of roleIDs to check.
+   * @param bool $group_by_role_id
+   *   Choose whether to group permissions by role ID.
+   *
+   * @return array
+   *   An array of the permissions untrusted roles have. If $groupByRoleId is
+   *   true, the array key is the role ID, the value is the array of permissions
+   *   the role has.
+   */
+  public function rolePermissions(array $role_ids, $group_by_role_id = FALSE) {
+    // Get the permissions the given roles have, grouped by roles.
+    $permissions_grouped = user_role_permissions($role_ids);
+
+    // Fill up the administrative roles' permissions too.
+    foreach ($role_ids as $role_id) {
+      $role = Role::load($role_id);
+      /** @var Role $role */
+      if ($role->isAdmin()) {
+        $permissions_grouped[$role_id] = $this->permissions();
+      }
+    }
+
+    if ($group_by_role_id) {
+      // If the result should be grouped, we have nothing else to do.
+      return $permissions_grouped;
+    }
+    else {
+      // Merge the grouped permissions into $untrusted_permissions.
+      $untrusted_permissions = [];
+      foreach ($permissions_grouped as $permissions) {
+        $untrusted_permissions = array_merge($untrusted_permissions, $permissions);
+      }
+
+      // Remove duplicate elements and fix indexes.
+      $untrusted_permissions = array_values(array_unique($untrusted_permissions));
+      return $untrusted_permissions;
+    }
+  }
+
+  /**
+   * Returns the permission strings that untrusted roles have.
+   *
+   * @param bool $group_by_role_id
+   *   Choose whether to group permissions by role ID.
+   *
+   * @return array
+   *   An array of the permissions untrusted roles have. If $groupByRoleId is
+   *   true, the array key is the role ID, the value is the array of permissions
+   *   the role has.
+   */
+  public function untrustedPermissions($group_by_role_id = FALSE) {
+    return $this->rolePermissions($this->untrustedRoles(), $group_by_role_id);
+  }
+
+  /**
+   * Returns the trusted roles.
+   *
+   * @return array
+   *   Trusted roles' IDs.
+   */
+  public function trustedRoles() {
+    // Get the stored/default untrusted roles.
+    $untrusted_roles = $this->untrustedRoles();
+
+    // Iterate through all the roles, and store which are not untrusted.
+    $trusted = [];
+    foreach (user_roles() as $role) {
+      if (!in_array($role->id(), $untrusted_roles)) {
+        $trusted[] = $role->id();
+      }
+    }
+
+    // Return the trusted roles.
+    return $trusted;
+  }
+
+  /**
+   * Returns the permission strings that trusted roles have.
+   *
+   * @param bool $group_by_role_id
+   *   Choose whether to group permissions by role ID.
+   *
+   * @return array
+   *   An array of the permissions trusted roles have. If $groupByRoleId is
+   *   true, the array key is the role ID, the value is the array of permissions
+   *   the role has.
+   */
+  public function trustedPermissions($group_by_role_id = FALSE) {
+    return $this->rolePermissions($this->trustedRoles(), $group_by_role_id);
+  }
+
+
+  /**
+   * Gets all the permissions.
+   *
+   * @param bool $meta
+   *   Whether to return only permission strings or metadata too.
+   *
+   * @see \Drupal\user\PermissionHandlerInterface::getPermissions()
+   *
+   * @return array
+   *   Array of every permission.
+   */
+  public function permissions($meta = FALSE) {
+    // Not injected because of hard testability.
+    $permissions = \Drupal::service('user.permissions')->getPermissions();
+
+    if (!$meta) {
+      return array_keys($permissions);
+    }
+    return $permissions;
+  }
+
+  /**
+   * Gets the list of unsafe HTML tags.
+   *
+   * @return string[]
+   *   List of unsafe tags.
+   */
+  public function unsafeTags() {
+    $unsafe_tags = [
+      'applet',
+      'area',
+      'audio',
+      'base',
+      'basefont',
+      'body',
+      'button',
+      'comment',
+      'embed',
+      'eval',
+      'form',
+      'frame',
+      'frameset',
+      'head',
+      'html',
+      'iframe',
+      'image',
+      'img',
+      'input',
+      'isindex',
+      'label',
+      'link',
+      'map',
+      'math',
+      'meta',
+      'noframes',
+      'noscript',
+      'object',
+      'optgroup',
+      'option',
+      'param',
+      'script',
+      'select',
+      'style',
+      'svg',
+      'table',
+      'td',
+      'textarea',
+      'title',
+      'video',
+      'vmlframe',
+    ];
+
+    // Alter data.
+    $this->moduleHandler->alter('security_review_unsafe_tags', $unsafe_tags);
+
+    return $unsafe_tags;
+  }
+
+  /**
+   * Gets the list of unsafe file extensions.
+   *
+   * @return string[]
+   *   List of unsafe extensions.
+   */
+  public function unsafeExtensions() {
+    $unsafe_ext = [
+      'swf',
+      'exe',
+      'html',
+      'htm',
+      'php',
+      'phtml',
+      'py',
+      'js',
+      'vb',
+      'vbe',
+      'vbs',
+    ];
+
+    // Alter data.
+    $this->moduleHandler
+      ->alter('security_review_unsafe_extensions', $unsafe_ext);
+
+    return $unsafe_ext;
+  }
+
+  /**
+   * Returns the site path.
+   *
+   * @return string
+   *   Absolute site path.
+   */
+  public function sitePath() {
+    return DRUPAL_ROOT . '/' . $this->kernel->getSitePath();
+  }
+
+  /**
+   * Finds files and directories that are writable by the web server.
+   *
+   * @param string[] $files
+   *   The files to iterate through.
+   * @param bool $cli
+   *   Whether it is being invoked in CLI context.
+   *
+   * @return string[]
+   *   The files that are writable.
+   */
+  public function findWritableFiles(array $files, $cli = FALSE) {
+    $writable = [];
+    if (!$cli) {
+      // Running from UI.
+      foreach ($files as $file) {
+        if (is_writable($file)) {
+          $writable[] = $file;
+        }
+      }
+    }
+    else {
+      // Get the web server's user data.
+      $uid = $this->securityReview->getServerUid();
+      $gids = $this->securityReview->getServerGids();
+
+      foreach ($files as $file) {
+        $perms = 0777 & fileperms($file);
+        // Check write permissions for others.
+        $ow = ($perms >> 1) & 1;
+        if ($ow === 1) {
+          $writable[] = $file;
+          continue;
+        }
+
+        // Check write permissions for owner.
+        $uw = ($perms >> 7) & 1;
+        if ($uw === 1 && fileowner($file) == $uid) {
+          $writable[] = $file;
+          continue;
+        }
+
+        // Check write permissions for group.
+        $gw = ($perms >> 4) & 1;
+        if ($gw === 1 && in_array(filegroup($file), $gids)) {
+          $writable[] = $file;
+        }
+      }
+    }
+    return $writable;
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/SecurityReview.php b/web/modules/contrib/security_review/src/SecurityReview.php
new file mode 100644 (file)
index 0000000..03c48fe
--- /dev/null
@@ -0,0 +1,335 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\SecurityReview.
+ */
+
+namespace Drupal\security_review;
+
+use Drupal\Core\Config\ConfigFactoryInterface;
+use Drupal\Core\DependencyInjection\DependencySerializationTrait;
+use Drupal\Core\Extension\ModuleHandlerInterface;
+use Drupal\Core\Logger\RfcLogLevel;
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\Core\State\StateInterface;
+
+/**
+ * A class containing static methods regarding the module's configuration.
+ */
+class SecurityReview {
+
+  use DependencySerializationTrait;
+
+  /**
+   * Temporary logging setting.
+   *
+   * @var null|bool
+   */
+  protected static $temporaryLogging = NULL;
+
+  /**
+   * The config factory.
+   *
+   * @var \Drupal\Core\Config\ConfigFactoryInterface
+   */
+  protected $configFactory;
+
+  /**
+   * The config storage.
+   *
+   * @var \Drupal\Core\Config\Config
+   */
+  protected $config;
+
+  /**
+   * The state storage.
+   *
+   * @var \Drupal\Core\State\StateInterface
+   */
+  protected $state;
+
+  /**
+   * The module handler.
+   *
+   * @var \Drupal\Core\Extension\ModuleHandlerInterface
+   */
+  protected $moduleHandler;
+
+  /**
+   * The current user.
+   *
+   * @var \Drupal\Core\Session\AccountProxyInterface
+   */
+  protected $currentUser;
+
+  /**
+   * Constructs a SecurityReview instance.
+   *
+   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
+   *   The config factory.
+   * @param \Drupal\Core\State\StateInterface $state
+   *   The state storage.
+   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
+   *   The module handler.
+   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
+   *   The current user.
+   */
+  public function __construct(ConfigFactoryInterface $config_factory, StateInterface $state, ModuleHandlerInterface $module_handler, AccountProxyInterface $current_user) {
+    // Store the dependencies.
+    $this->configFactory = $config_factory;
+    $this->config = $config_factory->getEditable('security_review.settings');
+    $this->state = $state;
+    $this->moduleHandler = $module_handler;
+    $this->currentUser = $current_user;
+  }
+
+  /**
+   * Returns whether the module has been configured.
+   *
+   * If the module has been configured on the settings page this function
+   * returns true. Otherwise it returns false.
+   *
+   * @return bool
+   *   A boolean indicating whether the module has been configured.
+   */
+  public function isConfigured() {
+    return $this->config->get('configured') === TRUE;
+  }
+
+  /**
+   * Returns true if logging is enabled, otherwise returns false.
+   *
+   * @return bool
+   *   A boolean indicating whether logging is enabled.
+   */
+  public function isLogging() {
+    // Check for temporary logging.
+    if (static::$temporaryLogging !== NULL) {
+      return static::$temporaryLogging;
+    }
+
+    return $this->config->get('log') === TRUE;
+  }
+
+  /**
+   * Returns the last time Security Review has been run.
+   *
+   * @return int
+   *   The last time Security Review has been run.
+   */
+  public function getLastRun() {
+    return $this->config->get('last_run');
+  }
+
+  /**
+   * Returns the IDs of the stored untrusted roles.
+   *
+   * @return string[]
+   *   Stored untrusted roles' IDs.
+   */
+  public function getUntrustedRoles() {
+    return $this->config->get('untrusted_roles');
+  }
+
+  /**
+   * Sets the 'configured' flag.
+   *
+   * @param bool $configured
+   *   The new value of the 'configured' setting.
+   */
+  public function setConfigured($configured) {
+    $this->config->set('configured', $configured);
+    $this->config->save();
+  }
+
+  /**
+   * Sets the 'logging' flag.
+   *
+   * @param bool $logging
+   *   The new value of the 'logging' setting.
+   * @param bool $temporary
+   *   Whether to set only temporarily.
+   */
+  public function setLogging($logging, $temporary = FALSE) {
+    if (!$temporary) {
+      $this->config->set('log', $logging);
+      $this->config->save();
+    }
+    else {
+      static::$temporaryLogging = ($logging == TRUE);
+    }
+  }
+
+  /**
+   * Sets the 'last_run' value.
+   *
+   * @param int $last_run
+   *   The new value for 'last_run'.
+   */
+  public function setLastRun($last_run) {
+    $this->config->set('last_run', $last_run);
+    $this->config->save();
+  }
+
+  /**
+   * Stores the given 'untrusted_roles' setting.
+   *
+   * @param string[] $untrusted_roles
+   *   The new untrusted roles' IDs.
+   */
+  public function setUntrustedRoles(array $untrusted_roles) {
+    $this->config->set('untrusted_roles', $untrusted_roles);
+    $this->config->save();
+  }
+
+  /**
+   * Logs an event.
+   *
+   * @param \Drupal\security_review\Check $check
+   *   The Check the message is about.
+   * @param string $message
+   *   The message.
+   * @param array $context
+   *   The context of the message.
+   * @param int $level
+   *   Severity (RfcLogLevel).
+   */
+  public function log(Check $check, $message, array $context, $level) {
+    if (static::isLogging()) {
+      $this->moduleHandler->invokeAll(
+        'security_review_log',
+        [
+          'check' => $check,
+          'message' => $message,
+          'context' => $context,
+          'level' => $level,
+        ]
+      );
+    }
+  }
+
+  /**
+   * Logs a check result.
+   *
+   * @param \Drupal\security_review\CheckResult $result
+   *   The result to log.
+   */
+  public function logCheckResult(CheckResult $result = NULL) {
+    if ($this->isLogging()) {
+      if ($result == NULL) {
+        $check = $result->check();
+        $context = [
+          '@check' => $check->getTitle(),
+          '@namespace' => $check->getNamespace(),
+        ];
+        $this->log($check, '@check of @namespace produced a null result', $context, RfcLogLevel::CRITICAL);
+        return;
+      }
+
+      $check = $result->check();
+
+      // Fallback log message.
+      $level = RfcLogLevel::NOTICE;
+      $message = '@name check invalid result';
+
+      // Set log message and level according to result.
+      switch ($result->result()) {
+        case CheckResult::SUCCESS:
+          $level = RfcLogLevel::INFO;
+          $message = '@name check succeeded';
+          break;
+
+        case CheckResult::FAIL:
+          $level = RfcLogLevel::ERROR;
+          $message = '@name check failed';
+          break;
+
+        case CheckResult::WARN:
+          $level = RfcLogLevel::WARNING;
+          $message = '@name check raised a warning';
+          break;
+
+        case CheckResult::INFO:
+          $level = RfcLogLevel::INFO;
+          $message = '@name check returned info';
+          break;
+      }
+
+      $context = ['@name' => $check->getTitle()];
+      $this->log($check, $message, $context, $level);
+    }
+  }
+
+  /**
+   * Deletes orphaned check data.
+   */
+  public function cleanStorage() {
+    /** @var \Drupal\security_review\Checklist $checklist */
+    $checklist = \Drupal::service('security_review.checklist');
+
+    // Get list of check configuration names.
+    $orphaned = $this->configFactory->listAll('security_review.check.');
+
+    // Remove items that are used by the checks.
+    foreach ($checklist->getChecks() as $check) {
+      $key = array_search('security_review.check.' . $check->id(), $orphaned);
+      if ($key !== FALSE) {
+        unset($orphaned[$key]);
+      }
+    }
+
+    // Delete orphaned configuration data.
+    foreach ($orphaned as $config_name) {
+      $config = $this->configFactory->getEditable($config_name);
+      $config->delete();
+    }
+  }
+
+  /**
+   * Stores information about the server into the State system.
+   */
+  public function setServerData() {
+    if (!static::isServerPosix() || PHP_SAPI === 'cli') {
+      return;
+    }
+    // Determine web server's uid and groups.
+    $uid = posix_getuid();
+    $groups = posix_getgroups();
+
+    // Store the data in the State system.
+    $this->state->set('security_review.server.uid', $uid);
+    $this->state->set('security_review.server.groups', $groups);
+  }
+
+  /**
+   * Returns whether the server is POSIX.
+   *
+   * @return bool
+   *   Whether the web server is POSIX based.
+   */
+  public function isServerPosix() {
+    return function_exists('posix_getuid');
+  }
+
+  /**
+   * Returns the UID of the web server.
+   *
+   * @return int
+   *   UID of the web server's user.
+   */
+  public function getServerUid() {
+    return $this->state->get('security_review.server.uid');
+  }
+
+  /**
+   * Returns the GIDs of the web server.
+   *
+   * @return int[]
+   *   GIDs of the web server's user.
+   */
+  public function getServerGids() {
+    return $this->state->get('security_review.server.groups');
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Tests/CheckTest.php b/web/modules/contrib/security_review/src/Tests/CheckTest.php
new file mode 100644 (file)
index 0000000..1ac1b1c
--- /dev/null
@@ -0,0 +1,142 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Tests\CheckTest.
+ */
+
+namespace Drupal\security_review\Tests;
+
+use Drupal\security_review\CheckResult;
+use Drupal\simpletest\KernelTestBase;
+
+/**
+ * Contains tests for Checks.
+ *
+ * @group security_review
+ */
+class CheckTest extends KernelTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['security_review', 'security_review_test'];
+
+  /**
+   * The security checks defined by Security Review and Security Review Test.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $checks;
+
+  /**
+   * The security checks defined by Security Review.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $realChecks;
+
+  /**
+   * The security checks defined by Security Review Test.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $testChecks;
+
+  /**
+   * Sets up the environment, populates the $checks variable.
+   */
+  protected function setUp() {
+    parent::setUp();
+    $this->realChecks = security_review_security_review_checks();
+    $this->testChecks = security_review_test_security_review_checks();
+    $this->checks = array_merge($this->realChecks, $this->testChecks);
+  }
+
+  /**
+   * Tests whether $checks is empty.
+   */
+  protected function testChecksExist() {
+    $this->assertFalse(empty($this->checks), 'Checks found.');
+  }
+
+  /**
+   * Every check should be enabled by default.
+   */
+  public function testEnabledByDefault() {
+    foreach ($this->checks as $check) {
+      $this->assertFalse($check->isSkipped(), $check->getTitle() . ' is enabled by default.');
+    }
+  }
+
+  /**
+   * Tests some check's results on a clean install of Drupal.
+   */
+  public function testDefaultResults() {
+    $defaults = [
+      'security_review-field' => CheckResult::SUCCESS,
+    ];
+
+    foreach ($this->checks as $check) {
+      if (array_key_exists($check->id(), $defaults)) {
+        $result = $check->run();
+        $this->assertEqual($result->result(), $defaults[$check->id()], $check->getTitle() . ' produced the right result.');
+      }
+    }
+  }
+
+  /**
+   * Tests the storing of a check result on every test check.
+   */
+  public function testStoreResult() {
+    foreach ($this->testChecks as $check) {
+      // Run the check and store its result.
+      $result = $check->run();
+      $check->storeResult($result);
+
+      // Compare lastResult() with $result.
+      $last_result = $check->lastResult(TRUE);
+      $this->assertEqual($result->result(), $last_result->result(), 'Result stored.');
+      $this->assertEqual($result->time(), $last_result->time(), 'Time stored.');
+      if ($check->storesFindings()) {
+        // If storesFindings() is set to FALSE, then these could differ.
+        $this->assertEqual($result->findings(), $last_result->findings(), 'Findings stored.');
+      }
+    }
+  }
+
+  /**
+   * Tests stored result correction on lastResult() call.
+   *
+   * Tests the case when the check doesn't store its findings, and the new
+   * result that lastResult() returns overwrites the old one if the result
+   * integer is not the same.
+   */
+  public function testLastResultUpdate() {
+    foreach ($this->testChecks as $check) {
+      if (!$check->storesFindings()) {
+        // Get the real result.
+        $result = $check->run();
+
+        // Build the fake result.
+        $new_result_result = $result->result() == CheckResult::SUCCESS ? CheckResult::FAIL : CheckResult::SUCCESS;
+        $new_result = new CheckResult(
+          $check,
+          $new_result_result,
+          [],
+          TRUE
+        );
+
+        // Store it.
+        $check->storeResult($new_result);
+
+        // Check if lastResult()'s result integer is the same as $result's.
+        $last_result = $check->lastResult(TRUE);
+        $this->assertEqual($last_result->result(), $result->result(), 'Invalid result got updated.');
+      }
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Tests/CheckWebTest.php b/web/modules/contrib/security_review/src/Tests/CheckWebTest.php
new file mode 100644 (file)
index 0000000..94ccf86
--- /dev/null
@@ -0,0 +1,79 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Tests\CheckWebTest.
+ */
+
+namespace Drupal\security_review\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Contains tests for Check that don't suffice with KernelTestBase.
+ *
+ * @group security_review
+ */
+class CheckWebTest extends WebTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['security_review'];
+
+  /**
+   * The security checks defined by Security Review.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $checks;
+
+  /**
+   * The test user.
+   *
+   * @var \Drupal\user\Entity\User
+   */
+  protected $user;
+
+  /**
+   * Sets up the testing environment, logs the user in, populates $check.
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    // Login.
+    $this->user = $this->drupalCreateUser(
+      [
+        'run security checks',
+        'access security review list',
+        'access administration pages',
+        'administer site configuration',
+      ]
+    );
+    $this->drupalLogin($this->user);
+
+    // Get checks.
+    $this->checks = security_review_security_review_checks();
+  }
+
+  /**
+   * Tests Check::skip().
+   *
+   * Checks whether skip() marks the check as skipped, and checks the
+   * skippedBy() value.
+   */
+  public function testSkipCheck() {
+    foreach ($this->checks as $check) {
+      $check->skip();
+
+      $is_skipped = $check->isSkipped();
+      $skipped_by = $check->skippedBy();
+
+      $this->assertTrue($is_skipped, $check->getTitle() . ' skipped.');
+      $this->assertEqual($this->user->id(), $skipped_by->id(), 'Skipped by ' . $skipped_by->label());
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Tests/ChecklistTest.php b/web/modules/contrib/security_review/src/Tests/ChecklistTest.php
new file mode 100644 (file)
index 0000000..7d32f6a
--- /dev/null
@@ -0,0 +1,129 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Tests\ChecklistTest.
+ */
+
+namespace Drupal\security_review\Tests;
+
+use Drupal\security_review\Checklist;
+use Drupal\simpletest\KernelTestBase;
+
+/**
+ * Contains test for Checklist.
+ *
+ * @group security_review
+ */
+class ChecklistTest extends KernelTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['security_review', 'security_review_test'];
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * The security checks defined by Security Review and Security Review Test.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $checks;
+
+  /**
+   * The security checks defined by Security Review.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $realChecks;
+
+  /**
+   * The security checks defined by Security Review Test.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $testChecks;
+
+  /**
+   * Array of the IDs of $checks.
+   *
+   * @var array
+   */
+  protected $checkIDs;
+
+  /**
+   * Sets up the environment, populates the $checks variable.
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    $this->checklist = \Drupal::getContainer()
+      ->get('security_review.checklist');
+    $this->realChecks = security_review_security_review_checks();
+    $this->testChecks = security_review_test_security_review_checks();
+    $this->checks = array_merge($this->realChecks, $this->testChecks);
+
+    Checklist::clearCache();
+    $this->checkIDs = [];
+    foreach ($this->checks as $check) {
+      $this->checkIDs[] = $check->id();
+    }
+  }
+
+  /**
+   * Tests Checklist::getChecks().
+   *
+   * Tests whether getChecks() contains all the checks that
+   * security_review_security_review_checks() and
+   * security_review_test_security_review_checks() returns.
+   */
+  public function testChecksProvided() {
+    foreach ($this->checklist->getChecks() as $check) {
+      $this->assertTrue(in_array($check->id(), $this->checkIDs), $check->getTitle() . ' found.');
+    }
+  }
+
+  /**
+   * Tests whether checks returned by getEnabledChecks() are all enabled.
+   */
+  public function testEnabledChecks() {
+    foreach ($this->checklist->getEnabledChecks() as $check) {
+      $this->assertFalse($check->isSkipped(), $check->getTitle() . ' is enabled.');
+
+      // Disable check.
+      $check->skip();
+    }
+    Checklist::clearCache();
+    $this->assertEqual(count($this->checklist->getEnabledChecks()), 0, 'Disabled all checks.');
+  }
+
+  /**
+   * Tests Checklist's Check search functions.
+   *
+   * Tests the search functions of Checklist:
+   *   getCheck().
+   *   getCheckById().
+   */
+  public function testCheckSearch() {
+    foreach ($this->checklist->getChecks() as $check) {
+      // getCheck().
+      $found = $this->checklist->getCheck($check->getMachineNamespace(), $check->getMachineTitle());
+      $this->assertNotNull($found, 'Found a check.');
+      $this->assertEqual($check->id(), $found->id(), 'Found ' . $check->getTitle() . '.');
+
+      // getCheckById().
+      $found = $this->checklist->getCheckById($check->id());
+      $this->assertNotNull($found, 'Found a check.');
+      $this->assertEqual($check->id(), $found->id(), 'Found ' . $check->getTitle() . '.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Tests/ChecklistWebTest.php b/web/modules/contrib/security_review/src/Tests/ChecklistWebTest.php
new file mode 100644 (file)
index 0000000..87fa679
--- /dev/null
@@ -0,0 +1,104 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Tests\ChecklistWebTest.
+ */
+
+namespace Drupal\security_review\Tests;
+
+use Drupal\security_review\Checklist;
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Contains tests related to the SecurityReview class.
+ *
+ * @group security_review
+ */
+class ChecklistWebTest extends WebTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['security_review'];
+
+  /**
+   * The test user.
+   *
+   * @var \Drupal\user\Entity\User
+   */
+  protected $user;
+
+  /**
+   * The security checks defined by Security Review.
+   *
+   * @var \Drupal\security_review\Check[]
+   */
+  protected $checks;
+
+  /**
+   * The security_review.checklist service.
+   *
+   * @var \Drupal\security_review\Checklist
+   */
+  protected $checklist;
+
+  /**
+   * Sets up the testing environment.
+   */
+  protected function setUp() {
+    parent::setUp();
+
+    $this->checklist = \Drupal::getContainer()
+      ->get('security_review.checklist');
+
+    // Login.
+    $this->user = $this->drupalCreateUser(
+      [
+        'run security checks',
+        'access security review list',
+        'access administration pages',
+        'administer site configuration',
+      ]
+    );
+    $this->drupalLogin($this->user);
+
+    // Populate $checks.
+    $this->checks = security_review_security_review_checks();
+
+    // Clear cache.
+    Checklist::clearCache();
+  }
+
+  /**
+   * Tests a full checklist run.
+   *
+   * Tests whether the checks hasn't been run yet, then runs them and checks
+   * that their lastRun value is not 0.
+   */
+  public function testRun() {
+    foreach ($this->checks as $check) {
+      $this->assertEqual(0, $check->lastRun(), $check->getTitle() . ' has not been run yet.');
+    }
+    $this->checklist->runChecklist();
+    foreach ($this->checks as $check) {
+      $this->assertNotEqual(0, $check->lastRun(), $check->getTitle() . ' has been run.');
+    }
+  }
+
+  /**
+   * Skips all checks then runs the checklist. No checks should be ran.
+   */
+  public function testSkippedRun() {
+    foreach ($this->checks as $check) {
+      $check->skip();
+    }
+    $this->checklist->runChecklist();
+    foreach ($this->checks as $check) {
+      $this->assertEqual(0, $check->lastRun(), $check->getTitle() . ' has not been run.');
+    }
+  }
+
+}
diff --git a/web/modules/contrib/security_review/src/Tests/SecurityReviewTest.php b/web/modules/contrib/security_review/src/Tests/SecurityReviewTest.php
new file mode 100644 (file)
index 0000000..8beb0ee
--- /dev/null
@@ -0,0 +1,81 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review\Tests\SecurityReviewTest.
+ */
+
+namespace Drupal\security_review\Tests;
+
+use Drupal\simpletest\KernelTestBase;
+
+/**
+ * Contains tests related to the SecurityReview class.
+ *
+ * @group security_review
+ */
+class SecurityReviewTest extends KernelTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = ['security_review'];
+
+  /**
+   * The security_review service.
+   *
+   * @var \Drupal\security_review\SecurityReview
+   */
+  protected $securityReview;
+
+  /**
+   * Sets up the testing environment.
+   */
+  protected function setUp() {
+    parent::setUp();
+    $this->installConfig(static::$modules);
+    $this->securityReview = \Drupal::getContainer()->get('security_review');
+  }
+
+  /**
+   * Tests the 'logging' setting.
+   */
+  public function testConfigLogging() {
+    $this->assertTrue($this->securityReview->isLogging(), 'Logging enabled by default.');
+    $this->securityReview->setLogging(FALSE);
+    $this->assertFalse($this->securityReview->isLogging(), 'Logging disabled.');
+  }
+
+  /**
+   * Tests the 'configured' setting.
+   */
+  public function testConfigConfigured() {
+    $this->assertFalse($this->securityReview->isConfigured(), 'Not configured by default.');
+    $this->securityReview->setConfigured(TRUE);
+    $this->assertTrue($this->securityReview->isConfigured(), 'Set to configured.');
+  }
+
+  /**
+   * Tests the 'untrusted_roles' setting.
+   */
+  public function testConfigUntrustedRoles() {
+    $this->assertEqual($this->securityReview->getUntrustedRoles(), [], 'untrusted_roles empty by default.');
+
+    $roles = [0, 1, 2, 3, 4];
+    $this->securityReview->setUntrustedRoles($roles);
+    $this->assertEqual($roles, $this->securityReview->getUntrustedRoles(), 'untrusted_roles set to test array.');
+  }
+
+  /**
+   * Tests the 'last_run' setting.
+   */
+  public function testConfigLastRun() {
+    $this->assertEqual(0, $this->securityReview->getLastRun(), 'last_run is 0 by default.');
+    $time = time();
+    $this->securityReview->setLastRun($time);
+    $this->assertEqual($time, $this->securityReview->getLastRun(), 'last_run set to now.');
+  }
+
+}
diff --git a/web/modules/contrib/security_review/templates/check_evaluation.html.twig b/web/modules/contrib/security_review/templates/check_evaluation.html.twig
new file mode 100644 (file)
index 0000000..77f4509
--- /dev/null
@@ -0,0 +1,23 @@
+{#
+/**
+ * @file
+ * Default evaluation page template for checks.
+ *
+ * Available variables:
+ * - paragraphs: Array of paragraphs (strings) to show before the list.
+ * - items: Array of items (strings) to show in an unordered list after the paragraphs.
+ */
+#}
+
+{% for paragraph in paragraphs %}
+    <p>
+        {{ paragraph }}
+    </p>
+{% endfor %}
+{% if items is not empty %}
+    <ul>
+        {% for item in items %}
+            <li>{{ item }}</li>
+        {% endfor %}
+    </ul>
+{% endif %}
diff --git a/web/modules/contrib/security_review/templates/check_help.html.twig b/web/modules/contrib/security_review/templates/check_help.html.twig
new file mode 100644 (file)
index 0000000..8b491cf
--- /dev/null
@@ -0,0 +1,19 @@
+{#
+/**
+ * @file
+ * Default check-specific help page template for checks.
+ *
+ * Available variables:
+ * - title: The title to show on the top of the page.
+ * - paragraphs: Array of paragraphs (strings) to show after the title.
+ */
+#}
+
+<h3>
+    {{ title }}
+</h3>
+{% for paragraph in paragraphs %}
+    <p>
+        {{ paragraph }}
+    </p>
+{% endfor %}
diff --git a/web/modules/contrib/security_review/templates/general_help.html.twig b/web/modules/contrib/security_review/templates/general_help.html.twig
new file mode 100644 (file)
index 0000000..0b0168e
--- /dev/null
@@ -0,0 +1,42 @@
+{#
+/**
+ * @file
+ * Default general help page of Security Review.
+ *
+ * Available variables:
+ * - paragraphs: Array of paragraphs (strings) to show as an introduction.
+ * - items: Array of items (strings) to show in an unordered list after the
+ *   paragraphs.
+ * - checks: Array of check links grouped by their namespaces.
+ */
+#}
+
+{% for paragraph in paragraphs %}
+    <p>
+        {{ paragraph }}
+    </p>
+{% endfor %}
+<h3>
+    {% trans %}
+    Check-specific help
+    {% endtrans %}
+</h3>
+<p>
+    {% trans %}
+    Details and help on the security review checks. Checks are not always
+    perfectly correct in their procedure and result. Refer to drupal.org
+    handbook documentation if you are unsure how to make the recommended
+    alterations to your configuration or consult the module's README.txt for
+    support.
+    {% endtrans %}
+</p>
+{% if checks is not empty %}
+    {% for check_namespace in checks %}
+        <h4>{{ check_namespace.namespace }}</h4>
+        <ul>
+            {% for check_link in check_namespace.check_links %}
+                <li>{{ check_link }}</li>
+            {% endfor %}
+        </ul>
+    {% endfor %}
+{% endif %}
diff --git a/web/modules/contrib/security_review/templates/run_and_review.html.twig b/web/modules/contrib/security_review/templates/run_and_review.html.twig
new file mode 100644 (file)
index 0000000..e6eac92
--- /dev/null
@@ -0,0 +1,52 @@
+{#
+/**
+ * @file
+ * Default template for the Run & Review page.
+ *
+ * Available variables:
+ * - checks: Array of check informations.
+ *   A check information consists of:
+ *   - result: The check's result (string).
+ *   - message: The result message.
+ *   - help_link: The link to the check's help page.
+ *   - toggle_link: The toggle link for the check.
+ *   - skipped: Whether the check is skipped.
+ */
+#}
+
+<h3>
+    {% trans %}
+    Review results from last run {{ date }}
+    {% endtrans %}
+</h3>
+<p>
+    {% trans %}
+    Here you can review the results from the last run of the checklist. Checks
+    are not always perfectly correct in their procedure and result. You can keep
+    a check from running by clicking the 'Skip' link beside it. You can run the
+    checklist again by expanding the fieldset above.
+    {% endtrans %}
+</p>
+<table class="security-review-run-and-review__table">
+    <tbody>
+    {% for check in checks %}
+        {% set style = '' %}
+        {% if check.result is defined %}
+            {% set style = style ~ ' ' ~ check.result %}
+        {% endif %}
+        {% if check.skipped %}
+            {% set style = style ~ ' skipped' %}
+        {% endif %}
+        <tr class="security-review-run-and-review__entry{{ style }}">
+            <td class="security-review-run-and-review__entry-icon">
+                {% if icons[check.result] is defined %}
+                    <img src="{{ icons[check.result] }}"/>
+                {% endif %}
+            </td>
+            <td>{{ check.message }}</td>
+            <td>{{ check.help_link }}</td>
+            <td class="security-review-toggle-link">{{ check.toggle_link }}</td>
+        </tr>
+    {% endfor %}
+    </tbody>
+</table>
diff --git a/web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.info.yml b/web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.info.yml
new file mode 100644 (file)
index 0000000..5aeb68c
--- /dev/null
@@ -0,0 +1,6 @@
+name: security_review_test
+type: module
+core: 8.x
+package: Testing
+dependencies:
+  - security_review
diff --git a/web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.module b/web/modules/contrib/security_review/tests/modules/security_review_test/security_review_test.module
new file mode 100644 (file)
index 0000000..ae4400f
--- /dev/null
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * @file
+ * Module that defines testable security checks for Security Review.
+ */
+
+use Drupal\security_review_test\Test;
+use Drupal\security_review_test\TestNoStore;
+
+/**
+ * Implements hook_security_review_checks().
+ */
+function security_review_test_security_review_checks() {
+  return [
+    new Test(),
+    new TestNoStore(),
+  ];
+}
diff --git a/web/modules/contrib/security_review/tests/modules/security_review_test/src/Test.php b/web/modules/contrib/security_review/tests/modules/security_review_test/src/Test.php
new file mode 100644 (file)
index 0000000..873c99a
--- /dev/null
@@ -0,0 +1,58 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review_test\Test.
+ */
+
+namespace Drupal\security_review_test;
+
+use Drupal\security_review\Check;
+use Drupal\security_review\CheckResult;
+
+/**
+ * A test security check for testing extensibility.
+ */
+class Test extends Check {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getNamespace() {
+    return 'Security Review Test';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Test';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function run() {
+    $findings = [];
+    for ($i = 0; $i < 20; ++$i) {
+      $findings[] = rand(0, 1) ? rand(0, 10) : 'string';
+    }
+
+    return $this->createResult(CheckResult::INFO, $findings);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function help() {
+    return [];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getMessage($result_const) {
+    return 'The test ran.';
+  }
+
+}
diff --git a/web/modules/contrib/security_review/tests/modules/security_review_test/src/TestNoStore.php b/web/modules/contrib/security_review/tests/modules/security_review_test/src/TestNoStore.php
new file mode 100644 (file)
index 0000000..db158e1
--- /dev/null
@@ -0,0 +1,31 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\security_review_test\TestNoStore.
+ */
+
+namespace Drupal\security_review_test;
+
+/**
+ * A test security check for testing extensibility.
+ *
+ * Same as Test, but doesn't store findings.
+ */
+class TestNoStore extends Test {
+
+  /**
+   * {@inheritdoc}
+   */
+  public function getTitle() {
+    return 'Test without storing findings';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function storesFindings() {
+    return FALSE;
+  }
+
+}