honeypot.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 of 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', time() - variable_get('honeypot_expire', 300), '<')
  42. ->execute();
  43. // Regenerate the honeypot css file if it does not exist.
  44. $honeypot_css = honeypot_get_css_file_path();
  45. if (!file_exists($honeypot_css)) {
  46. honeypot_create_css(variable_get('honeypot_element_name', 'url'));
  47. }
  48. }
  49. /**
  50. * Implements hook_form_alter().
  51. *
  52. * Add Honeypot features to forms enabled in the Honeypot admin interface.
  53. */
  54. function honeypot_form_alter(&$form, &$form_state, $form_id) {
  55. // Don't use for maintenance mode forms (install, update, etc.).
  56. if (defined('MAINTENANCE_MODE')) {
  57. return;
  58. }
  59. $unprotected_forms = array(
  60. 'user_login',
  61. 'user_login_block',
  62. 'search_form',
  63. 'search_block_form',
  64. 'views_exposed_form',
  65. 'honeypot_admin_form',
  66. );
  67. // If configured to protect all forms, add protection to every form.
  68. if (variable_get('honeypot_protect_all_forms', 0) && !in_array($form_id, $unprotected_forms)) {
  69. // Don't protect system forms - only admins should have access, and system
  70. // forms may be programmatically submitted by drush and other modules.
  71. if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) {
  72. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  73. }
  74. }
  75. // Otherwise add form protection to admin-configured forms.
  76. elseif ($forms_to_protect = honeypot_get_protected_forms()) {
  77. foreach ($forms_to_protect as $protect_form_id) {
  78. // For most forms, do a straight check on the form ID.
  79. if ($form_id == $protect_form_id) {
  80. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  81. }
  82. // For webforms use a special check for variable form ID.
  83. elseif ($protect_form_id == 'webforms' && (strpos($form_id, 'webform_client_form') !== FALSE)) {
  84. honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
  85. }
  86. }
  87. }
  88. }
  89. /**
  90. * Implements hook_trigger_info().
  91. */
  92. function honeypot_trigger_info() {
  93. return array(
  94. 'honeypot' => array(
  95. 'honeypot_reject' => array(
  96. 'label' => t('Honeypot rejection'),
  97. ),
  98. ),
  99. );
  100. }
  101. /**
  102. * Implements hook_rules_event_info()
  103. */
  104. function honeypot_rules_event_info() {
  105. return array(
  106. 'honeypot_reject' => array(
  107. 'label' => t('Honeypot rejection'),
  108. 'group' => t('Honeypot'),
  109. 'variables' => array(
  110. 'form_id' => array(
  111. 'type' => 'text',
  112. 'label' => t('Form ID of the form the user was disallowed from submitting.'),
  113. ),
  114. // Don't provide 'uid' in context because it is available as
  115. // site:current-user:uid.
  116. 'type' => array(
  117. 'type' => 'text',
  118. 'label' => t('String indicating the reason the submission was blocked.'),
  119. ),
  120. ),
  121. ),
  122. );
  123. }
  124. /**
  125. * Build an array of all the protected forms on the site, by form_id.
  126. *
  127. * @todo - Add in API call/hook to allow modules to add to this array.
  128. */
  129. function honeypot_get_protected_forms() {
  130. $forms = &drupal_static(__FUNCTION__);
  131. // If the data isn't already in memory, get from cache or look it up fresh.
  132. if (!isset($forms)) {
  133. if ($cache = cache_get('honeypot_protected_forms')) {
  134. $forms = $cache->data;
  135. }
  136. else {
  137. $forms = array();
  138. // Look up all the honeypot forms in the variables table.
  139. $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'honeypot_form_%'")->fetchCol();
  140. // Add each form that's enabled to the $forms array.
  141. foreach ($result as $variable) {
  142. if (variable_get($variable, 0)) {
  143. $forms[] = substr($variable, 14);
  144. }
  145. }
  146. // Save the cached data.
  147. cache_set('honeypot_protected_forms', $forms, 'cache');
  148. }
  149. }
  150. return $forms;
  151. }
  152. /**
  153. * Form builder function to add different types of protection to forms.
  154. *
  155. * @param array $options
  156. * Array of options to be added to form. Currently accepts 'honeypot' and
  157. * 'time_restriction'.
  158. *
  159. * @return array
  160. * Returns elements to be placed in a form's elements array to prevent spam.
  161. */
  162. function honeypot_add_form_protection(&$form, &$form_state, $options = array()) {
  163. global $user;
  164. // Allow other modules to alter the protections applied to this form.
  165. drupal_alter('honeypot_form_protections', $options, $form);
  166. // Don't add any protections if the user can bypass the Honeypot.
  167. if (user_access('bypass honeypot protection')) {
  168. return;
  169. }
  170. // Build the honeypot element.
  171. if (in_array('honeypot', $options)) {
  172. // Get the element name (default is generic 'url').
  173. $honeypot_element = variable_get('honeypot_element_name', 'url');
  174. // Add 'autocomplete="off"' if configured.
  175. $attributes = array();
  176. if (variable_get('honeypot_autocomplete_attribute', 1)) {
  177. $attributes = array('autocomplete' => 'off');
  178. }
  179. // Get the path to the honeypot css file.
  180. $honeypot_css = honeypot_get_css_file_path();
  181. // Build the honeypot element.
  182. $honeypot_class = $honeypot_element . '-textfield';
  183. $form[$honeypot_element] = array(
  184. '#type' => 'textfield',
  185. '#title' => t('Leave this field blank'),
  186. '#size' => 20,
  187. '#weight' => 100,
  188. '#attributes' => $attributes,
  189. '#element_validate' => array('_honeypot_honeypot_validate'),
  190. '#prefix' => '<div class="' . $honeypot_class . '">',
  191. '#suffix' => '</div>',
  192. // Hide honeypot using CSS.
  193. '#attached' => array(
  194. 'css' => array(
  195. 'data' => $honeypot_css,
  196. ),
  197. ),
  198. );
  199. }
  200. // Build the time restriction element (if it's not disabled).
  201. if (in_array('time_restriction', $options) && variable_get('honeypot_time_limit', 5) != 0) {
  202. // Set the current time in a hidden value to be checked later.
  203. $form['honeypot_time'] = array(
  204. '#type' => 'hidden',
  205. '#title' => t('Timestamp'),
  206. '#default_value' => honeypot_get_signed_timestamp(time()),
  207. '#element_validate' => array('_honeypot_time_restriction_validate'),
  208. );
  209. // Disable page caching to make sure timestamp isn't cached.
  210. if (user_is_anonymous()) {
  211. drupal_page_is_cacheable(FALSE);
  212. }
  213. }
  214. // Allow other modules to react to addition of form protection.
  215. if (!empty($options)) {
  216. module_invoke_all('honeypot_add_form_protection', $options, $form);
  217. }
  218. }
  219. /**
  220. * Validate honeypot field.
  221. */
  222. function _honeypot_honeypot_validate($element, &$form_state) {
  223. // Get the honeypot field value.
  224. $honeypot_value = $element['#value'];
  225. // Make sure it's empty.
  226. if (!empty($honeypot_value)) {
  227. _honeypot_log($form_state['values']['form_id'], 'honeypot');
  228. form_set_error('', t('There was a problem with your form submission. Please refresh the page and try again.'));
  229. }
  230. }
  231. /**
  232. * Validate honeypot's time restriction field.
  233. */
  234. function _honeypot_time_restriction_validate($element, &$form_state) {
  235. // Don't do anything if the triggering element is a preview button.
  236. if ($form_state['triggering_element']['#value'] == t('Preview')) {
  237. return;
  238. }
  239. // Get the time value.
  240. $honeypot_time = honeypot_get_time_from_signed_timestamp($form_state['values']['honeypot_time']);
  241. // Get the honeypot_time_limit.
  242. $time_limit = honeypot_get_time_limit($form_state['values']);
  243. // Make sure current time - (time_limit + form time value) is greater than 0.
  244. // If not, throw an error.
  245. if (!$honeypot_time || time() < ($honeypot_time + $time_limit)) {
  246. _honeypot_log($form_state['values']['form_id'], 'honeypot_time');
  247. // Get the time limit again, since it increases after first failure.
  248. $time_limit = honeypot_get_time_limit($form_state['values']);
  249. $form_state['values']['honeypot_time'] = honeypot_get_signed_timestamp(time());
  250. form_set_error('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', array('@limit' => $time_limit)));
  251. }
  252. }
  253. /**
  254. * Log blocked form submissions.
  255. *
  256. * @param string $form_id
  257. * Form ID for the form on which submission was blocked.
  258. * @param string $type
  259. * String indicating the reason the submission was blocked. Allowed values:
  260. * - honeypot: If honeypot field was filled in.
  261. * - honeypot_time: If form was completed before the configured time limit.
  262. */
  263. function _honeypot_log($form_id, $type) {
  264. honeypot_log_failure($form_id, $type);
  265. if (variable_get('honeypot_log', 0)) {
  266. $variables = array(
  267. '%form' => $form_id,
  268. '@cause' => ($type == 'honeypot') ? t('submission of a value in the honeypot field') : t('submission of the form in less than minimum required time'),
  269. );
  270. watchdog('honeypot', 'Blocked submission of %form due to @cause.', $variables);
  271. }
  272. }
  273. /**
  274. * Look up the time limit for the current user.
  275. *
  276. * @param array $form_values
  277. * Array of form values (optional).
  278. */
  279. function honeypot_get_time_limit($form_values = array()) {
  280. global $user;
  281. $honeypot_time_limit = variable_get('honeypot_time_limit', 5);
  282. // Only calculate time limit if honeypot_time_limit has a value > 0.
  283. if ($honeypot_time_limit) {
  284. $expire_time = variable_get('honeypot_expire', 300);
  285. // Get value from {honeypot_user} table for authenticated users.
  286. if ($user->uid) {
  287. $number = db_query("SELECT COUNT(*) FROM {honeypot_user} WHERE uid = :uid AND timestamp > :time", array(
  288. ':uid' => $user->uid,
  289. ':time' => time() - $expire_time,
  290. ))->fetchField();
  291. }
  292. // Get value from {flood} table for anonymous users.
  293. else {
  294. $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :hostname AND timestamp > :time", array(
  295. ':event' => 'honeypot',
  296. ':hostname' => ip_address(),
  297. ':time' => time() - $expire_time,
  298. ))->fetchField();
  299. }
  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.
  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. // Log failed submissions for authenticated users.
  322. if ($user->uid) {
  323. db_insert('honeypot_user')
  324. ->fields(array(
  325. 'uid' => $user->uid,
  326. 'timestamp' => time(),
  327. ))
  328. ->execute();
  329. }
  330. // Register flood event for anonymous users.
  331. else {
  332. flood_register_event('honeypot');
  333. }
  334. // Allow other modules to react to honeypot rejections.
  335. module_invoke_all('honeypot_reject', $form_id, $user->uid, $type);
  336. // Trigger honeypot_reject action.
  337. if (module_exists('trigger')) {
  338. $aids = trigger_get_assigned_actions('honeypot_reject');
  339. $context = array(
  340. 'group' => 'honeypot',
  341. 'hook' => 'honeypot_reject',
  342. 'form_id' => $form_id,
  343. // Do not provide $user in context because it is available as a global.
  344. 'type' => $type,
  345. );
  346. // Honeypot does not act on any specific object.
  347. $object = NULL;
  348. actions_do(array_keys($aids), $object, $context);
  349. }
  350. // Trigger rules honeypot_reject event.
  351. if (module_exists('rules')) {
  352. rules_invoke_event('honeypot_reject', $form_id, $type);
  353. }
  354. }
  355. /**
  356. * Retrieve the location of the Honeypot CSS file.
  357. *
  358. * @return string
  359. * The path to the honeypot.css file.
  360. */
  361. function honeypot_get_css_file_path() {
  362. return variable_get('file_public_path', conf_path() . '/files') . '/honeypot/honeypot.css';
  363. }
  364. /**
  365. * Create CSS file to hide the Honeypot field.
  366. *
  367. * @param string $element_name
  368. * The honeypot element class name (e.g. 'url').
  369. */
  370. function honeypot_create_css($element_name) {
  371. $path = 'public://honeypot';
  372. if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  373. 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');
  374. }
  375. else {
  376. $filename = $path . '/honeypot.css';
  377. $data = '.' . $element_name . '-textfield { display: none !important; }';
  378. file_unmanaged_save_data($data, $filename, FILE_EXISTS_REPLACE);
  379. }
  380. }
  381. /**
  382. * Sign the timestamp $time.
  383. *
  384. * @param mixed $time
  385. * The timestamp to sign.
  386. *
  387. * @return string
  388. * A signed timestamp in the form timestamp|HMAC.
  389. */
  390. function honeypot_get_signed_timestamp($time) {
  391. return $time . '|' . drupal_hmac_base64($time, drupal_get_private_key());
  392. }
  393. /**
  394. * Validate a signed timestamp.
  395. *
  396. * @param string $signed_timestamp
  397. * A timestamp concateneted with the signature
  398. *
  399. * @return int
  400. * The timestamp if the signature is correct, 0 otherwise.
  401. */
  402. function honeypot_get_time_from_signed_timestamp($signed_timestamp) {
  403. $honeypot_time = 0;
  404. // Fail fast if timestamp was forged or saved with an older Honeypot version.
  405. if (strpos($signed_timestamp, '|') === FALSE) {
  406. return $honeypot_time;
  407. }
  408. list($timestamp, $received_hmac) = explode('|', $signed_timestamp);
  409. if ($timestamp && $received_hmac) {
  410. $calculated_hmac = drupal_hmac_base64($timestamp, drupal_get_private_key());
  411. // Prevent leaking timing information, compare second order hmacs.
  412. $random_key = drupal_random_bytes(32);
  413. if (drupal_hmac_base64($calculated_hmac, $random_key) === drupal_hmac_base64($received_hmac, $random_key)) {
  414. $honeypot_time = $timestamp;
  415. }
  416. }
  417. return $honeypot_time;
  418. }