honeypot.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. /**
  3. * @file
  4. * Honeypot module, for deterring spam bots from completing Drupal forms.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function honeypot_menu() {
  10. $items['admin/config/content/honeypot'] = array(
  11. 'title' => 'Honeypot configuration',
  12. 'description' => 'Configure Honeypot spam prevention and the forms on which Honeypot will be used.',
  13. 'page callback' => 'drupal_get_form',
  14. 'page arguments' => array('honeypot_admin_form'),
  15. 'access arguments' => array('administer honeypot'),
  16. 'file' => 'honeypot.admin.inc',
  17. );
  18. return $items;
  19. }
  20. /**
  21. * Implements hook_permission().
  22. */
  23. function honeypot_permission() {
  24. return array(
  25. 'administer honeypot' => array(
  26. 'title' => t('Administer Honeypot'),
  27. 'description' => t('Administer Honeypot-protected forms and settings'),
  28. ),
  29. 'bypass honeypot protection' => array(
  30. 'title' => t('Bypass Honeypot protection'),
  31. 'description' => t('Bypass Honeypot form protection.'),
  32. ),
  33. );
  34. }
  35. /**
  36. * Implements hook_cron().
  37. */
  38. function honeypot_cron() {
  39. // Delete {honeypot_user} entries older than the value of honeypot_expire.
  40. db_delete('honeypot_user')
  41. ->condition('timestamp', REQUEST_TIME - variable_get('honeypot_expire', 300), '<')
  42. ->execute();
  43. // Regenerate the honeypot css file if it does not exist or is outdated.
  44. $honeypot_css = honeypot_get_css_file_path();
  45. $honeypot_element_name = variable_get('honeypot_element_name', 'url');
  46. if (!file_exists($honeypot_css) || !honeypot_check_css($honeypot_element_name)) {
  47. honeypot_create_css($honeypot_element_name);
  48. }
  49. }
  50. /**
  51. * Implements hook_form_alter().
  52. *
  53. * Add Honeypot features to forms enabled in the Honeypot admin interface.
  54. */
  55. function honeypot_form_alter(&$form, &$form_state, $form_id) {
  56. // Don't use for maintenance mode forms (install, update, etc.).
  57. if (defined('MAINTENANCE_MODE')) {
  58. return;
  59. }
  60. $unprotected_forms = array(
  61. 'user_login',
  62. 'user_login_block',
  63. 'search_form',
  64. 'search_block_form',
  65. 'views_exposed_form',
  66. 'honeypot_admin_form',
  67. );
  68. // If configured to protect all forms, add protection to every form.
  69. if (variable_get('honeypot_protect_all_forms', 0) && !in_array($form_id, $unprotected_forms)) {
  70. // Don't protect system forms - only admins should have access, and system
  71. // forms may be programmatically submitted by drush and other modules.
  72. if (preg_match('/[^a-zA-Z]system_/', $form_id) === 0 && preg_match('/[^a-zA-Z]search_/', $form_id) === 0 && preg_match('/[^a-zA-Z]views_exposed_form_/', $form_id) === 0) {
  73. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  74. }
  75. }
  76. // Otherwise add form protection to admin-configured forms.
  77. elseif ($forms_to_protect = honeypot_get_protected_forms()) {
  78. foreach ($forms_to_protect as $protect_form_id) {
  79. // For most forms, do a straight check on the form ID.
  80. if ($form_id == $protect_form_id) {
  81. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  82. }
  83. // For webforms use a special check for variable form ID.
  84. elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
  85. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  86. }
  87. }
  88. }
  89. }
  90. /**
  91. * Implements hook_trigger_info().
  92. */
  93. function honeypot_trigger_info() {
  94. return array(
  95. 'honeypot' => array(
  96. 'honeypot_reject' => array(
  97. 'label' => t('Honeypot rejection'),
  98. ),
  99. ),
  100. );
  101. }
  102. /**
  103. * Implements hook_rules_event_info().
  104. */
  105. function honeypot_rules_event_info() {
  106. return array(
  107. 'honeypot_reject' => array(
  108. 'label' => t('Honeypot rejection'),
  109. 'group' => t('Honeypot'),
  110. 'variables' => array(
  111. 'form_id' => array(
  112. 'type' => 'text',
  113. 'label' => t('Form ID of the form the user was disallowed from submitting.'),
  114. ),
  115. // Don't provide 'uid' in context because it is available as
  116. // site:current-user:uid.
  117. 'type' => array(
  118. 'type' => 'text',
  119. 'label' => t('String indicating the reason the submission was blocked.'),
  120. ),
  121. ),
  122. ),
  123. );
  124. }
  125. /**
  126. * Implements hook_library().
  127. */
  128. function honeypot_library() {
  129. $info = system_get_info('module', 'honeypot');
  130. $version = $info['version'];
  131. // Library for Honeypot JS.
  132. $libraries['timestamp.js'] = array(
  133. 'title' => 'Javascript to support timelimit on cached pages.',
  134. 'version' => $version,
  135. 'js' => array(
  136. array(
  137. 'type' => 'setting',
  138. 'data' => array(
  139. 'honeypot' => array(
  140. 'jsToken' => honeypot_get_signed_timestamp('js_token:' . mt_rand(0, 2147483647)),
  141. ),
  142. ),
  143. ),
  144. drupal_get_path('module', 'honeypot') . '/js/honeypot.js' => array(
  145. 'group' => JS_LIBRARY,
  146. 'weight' => 3,
  147. ),
  148. ),
  149. );
  150. return $libraries;
  151. }
  152. /**
  153. * Build an array of all the protected forms on the site, by form_id.
  154. *
  155. * @todo - Add in API call/hook to allow modules to add to this array.
  156. */
  157. function honeypot_get_protected_forms() {
  158. $forms = &drupal_static(__FUNCTION__);
  159. // If the data isn't already in memory, get from cache or look it up fresh.
  160. if (!isset($forms)) {
  161. if ($cache = cache_get('honeypot_protected_forms')) {
  162. $forms = $cache->data;
  163. }
  164. else {
  165. $forms = array();
  166. // Look up all the honeypot forms in the variables table.
  167. $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
  168. // Add each form that's enabled to the $forms array.
  169. foreach ($result as $variable) {
  170. if (variable_get($variable, 0)) {
  171. $forms[] = substr($variable, 14);
  172. }
  173. }
  174. // Save the cached data.
  175. cache_set('honeypot_protected_forms', $forms, 'cache');
  176. }
  177. }
  178. return $forms;
  179. }
  180. /**
  181. * Form builder function to add different types of protection to forms.
  182. *
  183. * @param array $options
  184. * Array of options to be added to form. Currently accepts 'honeypot' and
  185. * 'time_restriction'.
  186. *
  187. * @return array
  188. * Returns elements to be placed in a form's elements array to prevent spam.
  189. */
  190. function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
  191. global $user;
  192. // Allow other modules to alter the protections applied to this form.
  193. drupal_alter('honeypot_form_protections', $options, $form);
  194. // Don't add any protections if the user can bypass the Honeypot.
  195. if (user_access('bypass honeypot protection')) {
  196. return;
  197. }
  198. // Build the honeypot element.
  199. if (in_array('honeypot', $options)) {
  200. // Get the element name (default is generic 'url').
  201. $honeypot_element = variable_get('honeypot_element_name', 'url');
  202. // Add 'autocomplete="off"' if configured.
  203. $attributes = array();
  204. if (variable_get('honeypot_autocomplete_attribute', 1)) {
  205. $attributes = array('autocomplete' => 'off');
  206. }
  207. // Get the path to the honeypot css file.
  208. $honeypot_css = honeypot_get_css_file_path();
  209. // Build the honeypot element.
  210. $honeypot_class = $honeypot_element . '-textfield';
  211. $form[$honeypot_element] = array(
  212. '#type' => 'textfield',
  213. '#title' => t('Leave this field blank'),
  214. '#size' => 20,
  215. '#weight' => 100,
  216. '#attributes' => $attributes,
  217. '#element_validate' => array('_honeypot_honeypot_validate'),
  218. '#prefix' => '<div class="' . $honeypot_class . '">',
  219. '#suffix' => '</div>',
  220. // Hide honeypot using CSS.
  221. '#attached' => array(
  222. 'css' => array(
  223. 'data' => $honeypot_css,
  224. ),
  225. ),
  226. );
  227. }
  228. // Build the time restriction element (if it's not disabled).
  229. if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
  230. // Set the current time in a hidden value to be checked later.
  231. $form['honeypot_time'] = array(
  232. '#type' => 'hidden',
  233. '#title' => t('Timestamp'),
  234. '#default_value' => honeypot_get_signed_timestamp(REQUEST_TIME),
  235. '#element_validate' => array('_honeypot_time_restriction_validate'),
  236. );
  237. // Disable page caching to make sure timestamp isn't cached.
  238. if (user_is_anonymous() && drupal_page_is_cacheable()) {
  239. // Use javascript implementation if this page should be cached.
  240. if (variable_get('honeypot_use_js_for_cached_pages', FALSE)) {
  241. $form['honeypot_time']['#default_value'] = 'no_js_available';
  242. $form['honeypot_time']['#attached']['library'][] = array('honeypot', 'timestamp.js');
  243. $form['#attributes']['class'][] = 'honeypot-timestamp-js';
  244. }
  245. else {
  246. drupal_page_is_cacheable(FALSE);
  247. }
  248. }
  249. }
  250. // Allow other modules to react to addition of form protection.
  251. if (!empty($options)) {
  252. module_invoke_all('honeypot_add_form_protection', $options, $form);
  253. }
  254. }
  255. /**
  256. * Validate honeypot field.
  257. */
  258. function _honeypot_honeypot_validate($element, &$form_state) {
  259. // Get the honeypot field value.
  260. $honeypot_value = $element['#value'];
  261. // Make sure it's empty.
  262. if (!empty($honeypot_value)) {
  263. _honeypot_log($form_state['values']['form_id'], 'honeypot');
  264. form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
  265. }
  266. }
  267. /**
  268. * Validate honeypot's time restriction field.
  269. */
  270. function _honeypot_time_restriction_validate(&$element, &$form_state) {
  271. if (!empty($form_state['programmed'])) {
  272. // Don't do anything if the form was submitted programmatically.
  273. return;
  274. }
  275. // Don't do anything if the triggering element is a preview button.
  276. if ($form_state['triggering_element']['#value'] == t('Preview')) {
  277. return;
  278. }
  279. if ($form_state['values']['honeypot_time'] == 'no_js_available') {
  280. // Set an error, but do not penalize the user as it might be a legitimate
  281. // attempt.
  282. form_set_error('', t('You seem to have javascript disabled. Please confirm your form submission.'));
  283. if (variable_get('honeypot_log', 0)) {
  284. $variables = array(
  285. '%form' => $form_state['values']['form_id'],
  286. );
  287. watchdog('honeypot', 'User tried to submit form %form without javascript enabled.', $variables);
  288. }
  289. // Update the value in $form_state and $element.
  290. $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
  291. $element['#value'] = $form_state['values']['honeypot_time'];
  292. return;
  293. }
  294. $honeypot_time = FALSE;
  295. // Update the honeypot_time for JS requests and get the $honeypot_time value.
  296. if (strpos($form_state['values']['honeypot_time'], 'js_token:') === 0) {
  297. $interval = _honeypot_get_interval_from_signed_js_value($form_state['values']['honeypot_time']);
  298. if ($interval) {
  299. // Set correct value for timestamp validation.
  300. $honeypot_time = REQUEST_TIME - $interval;
  301. // Update form_state and element values so they're correct.
  302. $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp($honeypot_time);
  303. $element['#value'] = $form_state['values']['honeypot_time'];
  304. }
  305. }
  306. // Otherwise just get the $honeypot_time value.
  307. else {
  308. // Get the time value.
  309. $honeypot_time = honeypot_get_time_from_signed_timestamp($form_state['values']['honeypot_time']);
  310. }
  311. // Get the honeypot_time_limit.
  312. $time_limit = honeypot_get_time_limit($form_state['values']);
  313. // Make sure current time - (time_limit + form time value) is greater than 0.
  314. // If not, throw an error.
  315. if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) {
  316. _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
  317. // Get the time limit again, since it increases after first failure.
  318. $time_limit = honeypot_get_time_limit($form_state['values']);
  319. // Update the honeypot_time value in the form state and element.
  320. $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
  321. $element['#value'] = $form_state['values']['honeypot_time'];
  322. form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
  323. }
  324. }
  325. /**
  326. * Returns an interval if the given javascript submitted value is valid.
  327. *
  328. * @param string $honeypot_time
  329. * The signed interval as submitted via javascript.
  330. *
  331. * @return int|FALSE
  332. * The interval in seconds if the token is valid, FALSE otherwise.
  333. */
  334. function _honeypot_get_interval_from_signed_js_value($honeypot_time) {
  335. $t = explode('|', $honeypot_time);
  336. if (count($t) != 3) {
  337. return FALSE;
  338. }
  339. $js_token = $t[0] . '|' . $t[1];
  340. $token_check = honeypot_get_time_from_signed_timestamp($js_token);
  341. if (!$token_check) {
  342. return FALSE;
  343. }
  344. $interval = (int) $t[2];
  345. if ($interval == 0) {
  346. return FALSE;
  347. }
  348. return $interval;
  349. }
  350. /**
  351. * Log blocked form submissions.
  352. *
  353. * @param string $form_id
  354. * Form ID for the form on which submission was blocked.
  355. * @param string $type
  356. * String indicating the reason the submission was blocked. Allowed values:
  357. * - honeypot: If honeypot field was filled in.
  358. * - honeypot_time: If form was completed before the configured time limit.
  359. */
  360. function _honeypot_log($form_id, $type) {
  361. honeypot_log_failure($form_id, $type);
  362. if (variable_get('honeypot_log', 0)) {
  363. $variables = array(
  364. '%form' => $form_id,
  365. '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
  366. );
  367. watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
  368. }
  369. }
  370. /**
  371. * Look up the time limit for the current user.
  372. *
  373. * @param array $form_values
  374. * Array of form values (optional).
  375. */
  376. function honeypot_get_time_limit($form_values = array()) {
  377. global $user;
  378. $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
  379. // Only calculate time limit if honeypot_time_limit has a value > 0.
  380. if ($honeypot_time_limit) {
  381. $expire_time = variable_get('honeypot_expire', 300);
  382. // Query the {honeypot_user} table to determine the number of failed
  383. // submissions for the current user.
  384. $query = db_select('honeypot_user', 'hs')
  385. ->condition('uid', $user->uid)
  386. ->condition('timestamp', REQUEST_TIME - $expire_time, '>');
  387. // For anonymous users, take the hostname into account.
  388. if ($user->uid === 0) {
  389. $query->condition('hostname', ip_address());
  390. }
  391. $number = $query->countQuery()->execute()->fetchField();
  392. // Don't add more than 30 days' worth of extra time.
  393. $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
  394. $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
  395. if (count($additions)) {
  396. $honeypot_time_limit += array_sum($additions);
  397. }
  398. }
  399. return $honeypot_time_limit;
  400. }
  401. /**
  402. * Log the failed submision with timestamp and hostname.
  403. *
  404. * @param string $form_id
  405. * Form ID for the rejected form submission.
  406. * @param string $type
  407. * String indicating the reason the submission was blocked. Allowed values:
  408. * - honeypot: If honeypot field was filled in.
  409. * - honeypot_time: If form was completed before the configured time limit.
  410. */
  411. function honeypot_log_failure($form_id, $type) {
  412. global $user;
  413. db_insert('honeypot_user')
  414. ->fields(array(
  415. 'uid' => $user->uid,
  416. 'hostname' => ip_address(),
  417. 'timestamp' => REQUEST_TIME,
  418. ))
  419. ->execute();
  420. // Allow other modules to react to honeypot rejections.
  421. module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
  422. // Trigger honeypot_reject action.
  423. if (module_exists('trigger')) {
  424. $aids = trigger_get_assigned_actions('honeypot_reject');
  425. $context = array(
  426. 'group' => 'honeypot',
  427. 'hook' => 'honeypot_reject',
  428. 'form_id' => $form_id,
  429. // Do not provide $user in context because it is available as a global.
  430. 'type' => $type,
  431. );
  432. // Honeypot does not act on any specific object.
  433. $object = NULL;
  434. actions_do(array_keys($aids), $object, $context);
  435. }
  436. // Trigger rules honeypot_reject event.
  437. if (module_exists('rules')) {
  438. rules_invoke_event('honeypot_reject', $form_id, $type);
  439. }
  440. }
  441. /**
  442. * Retrieve the location of the Honeypot CSS file.
  443. *
  444. * @return string
  445. * The path to the honeypot.css file.
  446. */
  447. function honeypot_get_css_file_path() {
  448. return honeypot_file_default_scheme() . '://honeypot/honeypot.css';
  449. }
  450. /**
  451. * Create CSS file to hide the Honeypot field.
  452. *
  453. * @param string $element_name
  454. * The honeypot element class name (e.g. 'url').
  455. */
  456. function honeypot_create_css($element_name) {
  457. $path = honeypot_file_default_scheme() . '://honeypot';
  458. if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  459. 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');
  460. }
  461. else {
  462. $filename = $path . '/honeypot.css';
  463. $data = '.' . $element_name . '-textfield { display: none !important; }';
  464. file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
  465. }
  466. }
  467. /**
  468. * Check Honeypot's CSS file for a given Honeypot element name.
  469. *
  470. * This function assumes the Honeypot CSS file already exists.
  471. *
  472. * @param string $element_name
  473. * The honeypot element class name (e.g. 'url').
  474. *
  475. * @return bool
  476. * TRUE if CSS is has element class name, FALSE if not.
  477. */
  478. function honeypot_check_css($element_name) {
  479. $path = honeypot_get_css_file_path();
  480. $handle = fopen($path, 'r');
  481. $contents = fread($handle, filesize($path));
  482. fclose($handle);
  483. if (strpos($contents, $element_name) === 1) {
  484. return TRUE;
  485. }
  486. return FALSE;
  487. }
  488. /**
  489. * Sign the timestamp $time.
  490. *
  491. * @param mixed $time
  492. * The timestamp to sign.
  493. *
  494. * @return string
  495. * A signed timestamp in the form timestamp|HMAC.
  496. */
  497. function honeypot_get_signed_timestamp($time) {
  498. return $time . '|' . drupal_hmac_base64($time, drupal_get_private_key());
  499. }
  500. /**
  501. * Validate a signed timestamp.
  502. *
  503. * @param string $signed_timestamp
  504. * A timestamp concateneted with the signature
  505. *
  506. * @return int
  507. * The timestamp if the signature is correct, 0 otherwise.
  508. */
  509. function honeypot_get_time_from_signed_timestamp($signed_timestamp) {
  510. $honeypot_time = 0;
  511. // Fail fast if timestamp was forged or saved with an older Honeypot version.
  512. if (strpos($signed_timestamp, '|') === FALSE) {
  513. return $honeypot_time;
  514. }
  515. list($timestamp, $received_hmac) = explode('|', $signed_timestamp);
  516. if ($timestamp && $received_hmac) {
  517. $calculated_hmac = drupal_hmac_base64($timestamp, drupal_get_private_key());
  518. // Prevent leaking timing information, compare second order hmacs.
  519. $random_key = drupal_random_bytes(32);
  520. if (drupal_hmac_base64($calculated_hmac, $random_key) === drupal_hmac_base64($received_hmac, $random_key)) {
  521. $honeypot_time = $timestamp;
  522. }
  523. }
  524. return $honeypot_time;
  525. }
  526. /**
  527. * Gets the default file stream for honeypot.
  528. *
  529. * @return
  530. * 'public', 'private' or any other file scheme defined as the default.
  531. *
  532. * @see file_default_scheme()
  533. */
  534. function honeypot_file_default_scheme() {
  535. return variable_get('honeypot_file_default_scheme', file_default_scheme());
  536. }