123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489 |
- <?php
- /**
- * @file
- * Honeypot module, for deterring spam bots from completing Drupal forms.
- */
- /**
- * Implements hook_menu().
- */
- function honeypot_menu() {
- $items['admin/config/content/honeypot'] = array(
- 'title' => 'Honeypot configuration',
- 'description' => 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('honeypot_admin_form'),
- 'access arguments' => array('administer honeypot'),
- 'file' => 'honeypot.admin.inc',
- );
- return $items;
- }
- /**
- * Implements hook_permission().
- */
- function honeypot_permission() {
- return array(
- 'administer honeypot' => array(
- 'title' => t('Administer Honeypot'),
- 'description' => t('Administer Honeypot-protected forms and settings'),
- ),
- 'bypass honeypot protection' => array(
- 'title' => t('Bypass Honeypot protection'),
- 'description' => t('Bypass Honeypot form protection.'),
- ),
- );
- }
- /**
- * Implements hook_cron().
- */
- function honeypot_cron() {
- // Delete {honeypot_user} entries older than the value of honeypot_expire.
- db_delete('honeypot_user')
- ->condition('timestamp', REQUEST_TIME - variable_get('honeypot_expire', 300), '<')
- ->execute();
- // Regenerate the honeypot css file if it does not exist or is outdated.
- $honeypot_css = honeypot_get_css_file_path();
- $honeypot_element_name = variable_get('honeypot_element_name', 'url');
- if (!file_exists($honeypot_css) || !honeypot_check_css($honeypot_element_name)) {
- honeypot_create_css($honeypot_element_name);
- }
- }
- /**
- * Implements hook_form_alter().
- *
- * Add Honeypot features to forms enabled in the Honeypot admin interface.
- */
- function honeypot_form_alter(&$form, &$form_state, $form_id) {
- // Don't use for maintenance mode forms (install, update, etc.).
- if (defined('MAINTENANCE_MODE')) {
- return;
- }
- $unprotected_forms = array(
- 'user_login',
- 'user_login_block',
- 'search_form',
- 'search_block_form',
- 'views_exposed_form',
- 'honeypot_admin_form',
- );
- // If configured to protect all forms, add protection to every form.
- if (variable_get('honeypot_protect_all_forms', 0) && !in_array($form_id, $unprotected_forms)) {
- // Don't protect system forms - only admins should have access, and system
- // forms may be programmatically submitted by drush and other modules.
- if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
- honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
- }
- }
- // Otherwise add form protection to admin-configured forms.
- elseif ($forms_to_protect = honeypot_get_protected_forms()) {
- foreach ($forms_to_protect as $protect_form_id) {
- // For most forms, do a straight check on the form ID.
- if ($form_id == $protect_form_id) {
- honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
- }
- // For webforms use a special check for variable form ID.
- elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
- honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
- }
- }
- }
- }
- /**
- * Implements hook_trigger_info().
- */
- function honeypot_trigger_info() {
- return array(
- 'honeypot' => array(
- 'honeypot_reject' => array(
- 'label' => t('Honeypot rejection'),
- ),
- ),
- );
- }
- /**
- * Implements hook_rules_event_info().
- */
- function honeypot_rules_event_info() {
- return array(
- 'honeypot_reject' => array(
- 'label' => t('Honeypot rejection'),
- 'group' => t('Honeypot'),
- 'variables' => array(
- 'form_id' => array(
- 'type' => 'text',
- 'label' => t('Form ID of the form the user was disallowed from submitting.'),
- ),
- // Don't provide 'uid' in context because it is available as
- // site:current-user:uid.
- 'type' => array(
- 'type' => 'text',
- 'label' => t('String indicating the reason the submission was blocked.'),
- ),
- ),
- ),
- );
- }
- /**
- * Build an array of all the protected forms on the site, by form_id.
- *
- * @todo - Add in API call/hook to allow modules to add to this array.
- */
- function honeypot_get_protected_forms() {
- $forms = &drupal_static(__FUNCTION__);
- // If the data isn't already in memory, get from cache or look it up fresh.
- if (!isset($forms)) {
- if ($cache = cache_get('honeypot_protected_forms')) {
- $forms = $cache->data;
- }
- else {
- $forms = array();
- // Look up all the honeypot forms in the variables table.
- $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
- // Add each form that's enabled to the $forms array.
- foreach ($result as $variable) {
- if (variable_get($variable, 0)) {
- $forms[] = substr($variable, 14);
- }
- }
- // Save the cached data.
- cache_set('honeypot_protected_forms', $forms, 'cache');
- }
- }
- return $forms;
- }
- /**
- * Form builder function to add different types of protection to forms.
- *
- * @param array $options
- * Array of options to be added to form. Currently accepts 'honeypot' and
- * 'time_restriction'.
- *
- * @return array
- * Returns elements to be placed in a form's elements array to prevent spam.
- */
- function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
- global $user;
- // Allow other modules to alter the protections applied to this form.
- drupal_alter('honeypot_form_protections', $options, $form);
- // Don't add any protections if the user can bypass the Honeypot.
- if (user_access('bypass honeypot protection')) {
- return;
- }
- // Build the honeypot element.
- if (in_array('honeypot', $options)) {
- // Get the element name (default is generic 'url').
- $honeypot_element = variable_get('honeypot_element_name', 'url');
- // Add 'autocomplete="off"' if configured.
- $attributes = array();
- if (variable_get('honeypot_autocomplete_attribute', 1)) {
- $attributes = array('autocomplete' => 'off');
- }
- // Get the path to the honeypot css file.
- $honeypot_css = honeypot_get_css_file_path();
- // Build the honeypot element.
- $honeypot_class = $honeypot_element . '-textfield';
- $form[$honeypot_element] = array(
- '#type' => 'textfield',
- '#title' => t('Leave this field blank'),
- '#size' => 20,
- '#weight' => 100,
- '#attributes' => $attributes,
- '#element_validate' => array('_honeypot_honeypot_validate'),
- '#prefix' => '<div class="' . $honeypot_class . '">',
- '#suffix' => '</div>',
- // Hide honeypot using CSS.
- '#attached' => array(
- 'css' => array(
- 'data' => $honeypot_css,
- ),
- ),
- );
- }
- // Build the time restriction element (if it's not disabled).
- if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
- // Set the current time in a hidden value to be checked later.
- $form['honeypot_time'] = array(
- '#type' => 'hidden',
- '#title' => t('Timestamp'),
- '#default_value' => honeypot_get_signed_timestamp(REQUEST_TIME),
- '#element_validate' => array('_honeypot_time_restriction_validate'),
- );
- // Disable page caching to make sure timestamp isn't cached.
- if (user_is_anonymous()) {
- drupal_page_is_cacheable(FALSE);
- }
- }
- // Allow other modules to react to addition of form protection.
- if (!empty($options)) {
- module_invoke_all('honeypot_add_form_protection', $options, $form);
- }
- }
- /**
- * Validate honeypot field.
- */
- function _honeypot_honeypot_validate($element, &$form_state) {
- // Get the honeypot field value.
- $honeypot_value = $element['#value'];
- // Make sure it's empty.
- if (!empty($honeypot_value)) {
- _honeypot_log($form_state['values']['form_id'], 'honeypot');
- form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
- }
- }
- /**
- * Validate honeypot's time restriction field.
- */
- function _honeypot_time_restriction_validate($element, &$form_state) {
- if (!empty($form_state['programmed'])) {
- // Don't do anything if the form was submitted programmatically.
- return;
- }
- // Don't do anything if the triggering element is a preview button.
- if ($form_state['triggering_element']['#value'] == t('Preview')) {
- return;
- }
- // Get the time value.
- $honeypot_time = honeypot_get_time_from_signed_timestamp($form_state['values']['honeypot_time']);
- // Get the honeypot_time_limit.
- $time_limit = honeypot_get_time_limit($form_state['values']);
- // Make sure current time - (time_limit + form time value) is greater than 0.
- // If not, throw an error.
- if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) {
- _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
- // Get the time limit again, since it increases after first failure.
- $time_limit = honeypot_get_time_limit($form_state['values']);
- $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
- form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
- }
- }
- /**
- * Log blocked form submissions.
- *
- * @param string $form_id
- * Form ID for the form on which submission was blocked.
- * @param string $type
- * String indicating the reason the submission was blocked. Allowed values:
- * - honeypot: If honeypot field was filled in.
- * - honeypot_time: If form was completed before the configured time limit.
- */
- function _honeypot_log($form_id, $type) {
- honeypot_log_failure($form_id, $type);
- if (variable_get('honeypot_log', 0)) {
- $variables = array(
- '%form' => $form_id,
- '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
- );
- watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
- }
- }
- /**
- * Look up the time limit for the current user.
- *
- * @param array $form_values
- * Array of form values (optional).
- */
- function honeypot_get_time_limit($form_values = array()) {
- global $user;
- $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
- // Only calculate time limit if honeypot_time_limit has a value > 0.
- if ($honeypot_time_limit) {
- $expire_time = variable_get('honeypot_expire', 300);
- // Query the {honeypot_user} table to determine the number of failed
- // submissions for the current user.
- $query = db_select('honeypot_user', 'hs')
- ->condition('uid', $user->uid)
- ->condition('timestamp', REQUEST_TIME - $expire_time, '>');
- // For anonymous users, take the hostname into account.
- if ($user->uid === 0) {
- $query->condition('hostname', ip_address());
- }
- $number = $query->countQuery()->execute()->fetchField();
- // Don't add more than 30 days' worth of extra time.
- $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
- $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
- if (count($additions)) {
- $honeypot_time_limit += array_sum($additions);
- }
- }
- return $honeypot_time_limit;
- }
- /**
- * Log the failed submision with timestamp and hostname.
- *
- * @param string $form_id
- * Form ID for the rejected form submission.
- * @param string $type
- * String indicating the reason the submission was blocked. Allowed values:
- * - honeypot: If honeypot field was filled in.
- * - honeypot_time: If form was completed before the configured time limit.
- */
- function honeypot_log_failure($form_id, $type) {
- global $user;
- db_insert('honeypot_user')
- ->fields(array(
- 'uid' => $user->uid,
- 'hostname' => ip_address(),
- 'timestamp' => REQUEST_TIME,
- ))
- ->execute();
- // Allow other modules to react to honeypot rejections.
- module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
- // Trigger honeypot_reject action.
- if (module_exists('trigger')) {
- $aids = trigger_get_assigned_actions('honeypot_reject');
- $context = array(
- 'group' => 'honeypot',
- 'hook' => 'honeypot_reject',
- 'form_id' => $form_id,
- // Do not provide $user in context because it is available as a global.
- 'type' => $type,
- );
- // Honeypot does not act on any specific object.
- $object = NULL;
- actions_do(array_keys($aids), $object, $context);
- }
- // Trigger rules honeypot_reject event.
- if (module_exists('rules')) {
- rules_invoke_event('honeypot_reject', $form_id, $type);
- }
- }
- /**
- * Retrieve the location of the Honeypot CSS file.
- *
- * @return string
- * The path to the honeypot.css file.
- */
- function honeypot_get_css_file_path() {
- return variable_get('file_public_path', conf_path() . '/files') . '/honeypot/honeypot.css';
- }
- /**
- * Create CSS file to hide the Honeypot field.
- *
- * @param string $element_name
- * The honeypot element class name (e.g. 'url').
- */
- function honeypot_create_css($element_name) {
- $path = 'public://honeypot';
- if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
- drupal_set_message(t('Unable to create Honeypot CSS directory, %path. Check the permissions on your files directory.', array('%path' => file_uri_target($path))), 'error');
- }
- else {
- $filename = $path . '/honeypot.css';
- $data = '.' . $element_name . '-textfield { display: none !important; }';
- file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
- }
- }
- /**
- * Check Honeypot's CSS file for a given Honeypot element name.
- *
- * This function assumes the Honeypot CSS file already exists.
- *
- * @param string $element_name
- * The honeypot element class name (e.g. 'url').
- *
- * @return bool
- * TRUE if CSS is has element class name, FALSE if not.
- */
- function honeypot_check_css($element_name) {
- $path = honeypot_get_css_file_path();
- $handle = fopen($path, 'r');
- $contents = fread($handle, filesize($path));
- fclose($handle);
- if (strpos($contents, $element_name) === 1) {
- return TRUE;
- }
- return FALSE;
- }
- /**
- * Sign the timestamp $time.
- *
- * @param mixed $time
- * The timestamp to sign.
- *
- * @return string
- * A signed timestamp in the form timestamp|HMAC.
- */
- function honeypot_get_signed_timestamp($time) {
- return $time . '|' . drupal_hmac_base64($time, drupal_get_private_key());
- }
- /**
- * Validate a signed timestamp.
- *
- * @param string $signed_timestamp
- * A timestamp concateneted with the signature
- *
- * @return int
- * The timestamp if the signature is correct, 0 otherwise.
- */
- function honeypot_get_time_from_signed_timestamp($signed_timestamp) {
- $honeypot_time = 0;
- // Fail fast if timestamp was forged or saved with an older Honeypot version.
- if (strpos($signed_timestamp, '|') === FALSE) {
- return $honeypot_time;
- }
- list($timestamp, $received_hmac) = explode('|', $signed_timestamp);
- if ($timestamp && $received_hmac) {
- $calculated_hmac = drupal_hmac_base64($timestamp, drupal_get_private_key());
- // Prevent leaking timing information, compare second order hmacs.
- $random_key = drupal_random_bytes(32);
- if (drupal_hmac_base64($calculated_hmac, $random_key) === drupal_hmac_base64($received_hmac, $random_key)) {
- $honeypot_time = $timestamp;
- }
- }
- return $honeypot_time;
- }
|