honeypot.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
  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. * Build an array of all the protected forms on the site, by form_id.
  127. *
  128. * @todo - Add in API call/hook to allow modules to add to this array.
  129. */
  130. function honeypot_get_protected_forms() {
  131. $forms = &drupal_static(__FUNCTION__);
  132. // If the data isn't already in memory, get from cache or look it up fresh.
  133. if (!isset($forms)) {
  134. if ($cache = cache_get('honeypot_protected_forms')) {
  135. $forms = $cache->data;
  136. }
  137. else {
  138. $forms = array();
  139. // Look up all the honeypot forms in the variables table.
  140. $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
  141. // Add each form that's enabled to the $forms array.
  142. foreach ($result as $variable) {
  143. if (variable_get($variable, 0)) {
  144. $forms[] = substr($variable, 14);
  145. }
  146. }
  147. // Save the cached data.
  148. cache_set('honeypot_protected_forms', $forms, 'cache');
  149. }
  150. }
  151. return $forms;
  152. }
  153. /**
  154. * Form builder function to add different types of protection to forms.
  155. *
  156. * @param array $options
  157. * Array of options to be added to form. Currently accepts 'honeypot' and
  158. * 'time_restriction'.
  159. *
  160. * @return array
  161. * Returns elements to be placed in a form's elements array to prevent spam.
  162. */
  163. function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
  164. global $user;
  165. // Allow other modules to alter the protections applied to this form.
  166. drupal_alter('honeypot_form_protections', $options, $form);
  167. // Don't add any protections if the user can bypass the Honeypot.
  168. if (user_access('bypass honeypot protection')) {
  169. return;
  170. }
  171. // Build the honeypot element.
  172. if (in_array('honeypot', $options)) {
  173. // Get the element name (default is generic 'url').
  174. $honeypot_element = variable_get('honeypot_element_name', 'url');
  175. // Add 'autocomplete="off"' if configured.
  176. $attributes = array();
  177. if (variable_get('honeypot_autocomplete_attribute', 1)) {
  178. $attributes = array('autocomplete' => 'off');
  179. }
  180. // Get the path to the honeypot css file.
  181. $honeypot_css = honeypot_get_css_file_path();
  182. // Build the honeypot element.
  183. $honeypot_class = $honeypot_element . '-textfield';
  184. $form[$honeypot_element] = array(
  185. '#type' => 'textfield',
  186. '#title' => t('Leave this field blank'),
  187. '#size' => 20,
  188. '#weight' => 100,
  189. '#attributes' => $attributes,
  190. '#element_validate' => array('_honeypot_honeypot_validate'),
  191. '#prefix' => '<div class="' . $honeypot_class . '">',
  192. '#suffix' => '</div>',
  193. // Hide honeypot using CSS.
  194. '#attached' => array(
  195. 'css' => array(
  196. 'data' => $honeypot_css,
  197. ),
  198. ),
  199. );
  200. }
  201. // Build the time restriction element (if it's not disabled).
  202. if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
  203. // Set the current time in a hidden value to be checked later.
  204. $form['honeypot_time'] = array(
  205. '#type' => 'hidden',
  206. '#title' => t('Timestamp'),
  207. '#default_value' => honeypot_get_signed_timestamp(REQUEST_TIME),
  208. '#element_validate' => array('_honeypot_time_restriction_validate'),
  209. );
  210. // Disable page caching to make sure timestamp isn't cached.
  211. if (user_is_anonymous()) {
  212. drupal_page_is_cacheable(FALSE);
  213. }
  214. }
  215. // Allow other modules to react to addition of form protection.
  216. if (!empty($options)) {
  217. module_invoke_all('honeypot_add_form_protection', $options, $form);
  218. }
  219. }
  220. /**
  221. * Validate honeypot field.
  222. */
  223. function _honeypot_honeypot_validate($element, &$form_state) {
  224. // Get the honeypot field value.
  225. $honeypot_value = $element['#value'];
  226. // Make sure it's empty.
  227. if (!empty($honeypot_value)) {
  228. _honeypot_log($form_state['values']['form_id'], 'honeypot');
  229. form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
  230. }
  231. }
  232. /**
  233. * Validate honeypot's time restriction field.
  234. */
  235. function _honeypot_time_restriction_validate($element, &$form_state) {
  236. if (!empty($form_state['programmed'])) {
  237. // Don't do anything if the form was submitted programmatically.
  238. return;
  239. }
  240. // Don't do anything if the triggering element is a preview button.
  241. if ($form_state['triggering_element']['#value'] == t('Preview')) {
  242. return;
  243. }
  244. // Get the time value.
  245. $honeypot_time = honeypot_get_time_from_signed_timestamp($form_state['values']['honeypot_time']);
  246. // Get the honeypot_time_limit.
  247. $time_limit = honeypot_get_time_limit($form_state['values']);
  248. // Make sure current time - (time_limit + form time value) is greater than 0.
  249. // If not, throw an error.
  250. if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) {
  251. _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
  252. // Get the time limit again, since it increases after first failure.
  253. $time_limit = honeypot_get_time_limit($form_state['values']);
  254. $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(REQUEST_TIME);
  255. form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
  256. }
  257. }
  258. /**
  259. * Log blocked form submissions.
  260. *
  261. * @param string $form_id
  262. * Form ID for the form on which submission was blocked.
  263. * @param string $type
  264. * String indicating the reason the submission was blocked. Allowed values:
  265. * - honeypot: If honeypot field was filled in.
  266. * - honeypot_time: If form was completed before the configured time limit.
  267. */
  268. function _honeypot_log($form_id, $type) {
  269. honeypot_log_failure($form_id, $type);
  270. if (variable_get('honeypot_log', 0)) {
  271. $variables = array(
  272. '%form' => $form_id,
  273. '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
  274. );
  275. watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
  276. }
  277. }
  278. /**
  279. * Look up the time limit for the current user.
  280. *
  281. * @param array $form_values
  282. * Array of form values (optional).
  283. */
  284. function honeypot_get_time_limit($form_values = array()) {
  285. global $user;
  286. $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
  287. // Only calculate time limit if honeypot_time_limit has a value > 0.
  288. if ($honeypot_time_limit) {
  289. $expire_time = variable_get('honeypot_expire', 300);
  290. // Query the {honeypot_user} table to determine the number of failed
  291. // submissions for the current user.
  292. $query = db_select('honeypot_user', 'hs')
  293. ->condition('uid', $user->uid)
  294. ->condition('timestamp', REQUEST_TIME - $expire_time, '>');
  295. // For anonymous users, take the hostname into account.
  296. if ($user->uid === 0) {
  297. $query->condition('hostname', ip_address());
  298. }
  299. $number = $query->countQuery()->execute()->fetchField();
  300. // Don't add more than 30 days' worth of extra time.
  301. $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000);
  302. $additions = module_invoke_all('honeypot_time_limit', $honeypot_time_limit, $form_values, $number);
  303. if (count($additions)) {
  304. $honeypot_time_limit += array_sum($additions);
  305. }
  306. }
  307. return $honeypot_time_limit;
  308. }
  309. /**
  310. * Log the failed submision with timestamp and hostname.
  311. *
  312. * @param string $form_id
  313. * Form ID for the rejected form submission.
  314. * @param string $type
  315. * String indicating the reason the submission was blocked. Allowed values:
  316. * - honeypot: If honeypot field was filled in.
  317. * - honeypot_time: If form was completed before the configured time limit.
  318. */
  319. function honeypot_log_failure($form_id, $type) {
  320. global $user;
  321. db_insert('honeypot_user')
  322. ->fields(array(
  323. 'uid' => $user->uid,
  324. 'hostname' => ip_address(),
  325. 'timestamp' => REQUEST_TIME,
  326. ))
  327. ->execute();
  328. // Allow other modules to react to honeypot rejections.
  329. module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
  330. // Trigger honeypot_reject action.
  331. if (module_exists('trigger')) {
  332. $aids = trigger_get_assigned_actions('honeypot_reject');
  333. $context = array(
  334. 'group' => 'honeypot',
  335. 'hook' => 'honeypot_reject',
  336. 'form_id' => $form_id,
  337. // Do not provide $user in context because it is available as a global.
  338. 'type' => $type,
  339. );
  340. // Honeypot does not act on any specific object.
  341. $object = NULL;
  342. actions_do(array_keys($aids), $object, $context);
  343. }
  344. // Trigger rules honeypot_reject event.
  345. if (module_exists('rules')) {
  346. rules_invoke_event('honeypot_reject', $form_id, $type);
  347. }
  348. }
  349. /**
  350. * Retrieve the location of the Honeypot CSS file.
  351. *
  352. * @return string
  353. * The path to the honeypot.css file.
  354. */
  355. function honeypot_get_css_file_path() {
  356. return variable_get('file_public_path', conf_path() . '/files') . '/honeypot/honeypot.css';
  357. }
  358. /**
  359. * Create CSS file to hide the Honeypot field.
  360. *
  361. * @param string $element_name
  362. * The honeypot element class name (e.g. 'url').
  363. */
  364. function honeypot_create_css($element_name) {
  365. $path = 'public://honeypot';
  366. if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  367. 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');
  368. }
  369. else {
  370. $filename = $path . '/honeypot.css';
  371. $data = '.' . $element_name . '-textfield { display: none !important; }';
  372. file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
  373. }
  374. }
  375. /**
  376. * Check Honeypot's CSS file for a given Honeypot element name.
  377. *
  378. * This function assumes the Honeypot CSS file already exists.
  379. *
  380. * @param string $element_name
  381. * The honeypot element class name (e.g. 'url').
  382. *
  383. * @return bool
  384. * TRUE if CSS is has element class name, FALSE if not.
  385. */
  386. function honeypot_check_css($element_name) {
  387. $path = honeypot_get_css_file_path();
  388. $handle = fopen($path, 'r');
  389. $contents = fread($handle, filesize($path));
  390. fclose($handle);
  391. if (strpos($contents, $element_name) === 1) {
  392. return TRUE;
  393. }
  394. return FALSE;
  395. }
  396. /**
  397. * Sign the timestamp $time.
  398. *
  399. * @param mixed $time
  400. * The timestamp to sign.
  401. *
  402. * @return string
  403. * A signed timestamp in the form timestamp|HMAC.
  404. */
  405. function honeypot_get_signed_timestamp($time) {
  406. return $time . '|' . drupal_hmac_base64($time, drupal_get_private_key());
  407. }
  408. /**
  409. * Validate a signed timestamp.
  410. *
  411. * @param string $signed_timestamp
  412. * A timestamp concateneted with the signature
  413. *
  414. * @return int
  415. * The timestamp if the signature is correct, 0 otherwise.
  416. */
  417. function honeypot_get_time_from_signed_timestamp($signed_timestamp) {
  418. $honeypot_time = 0;
  419. // Fail fast if timestamp was forged or saved with an older Honeypot version.
  420. if (strpos($signed_timestamp, '|') === FALSE) {
  421. return $honeypot_time;
  422. }
  423. list($timestamp, $received_hmac) = explode('|', $signed_timestamp);
  424. if ($timestamp && $received_hmac) {
  425. $calculated_hmac = drupal_hmac_base64($timestamp, drupal_get_private_key());
  426. // Prevent leaking timing information, compare second order hmacs.
  427. $random_key = drupal_random_bytes(32);
  428. if (drupal_hmac_base64($calculated_hmac, $random_key) === drupal_hmac_base64($received_hmac, $random_key)) {
  429. $honeypot_time = $timestamp;
  430. }
  431. }
  432. return $honeypot_time;
  433. }