CaptchaBehavior.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. define('CAPTCHA_MIN_TIME', 3); // Seconds the form will need to be filled in by a human
  3. define('CAPTCHA_MAX_TIME', HOUR); // Seconds the form will need to be submitted in
  4. App::uses('ModelBehavior', 'Model');
  5. App::uses('CaptchaLib', 'Tools.Lib');
  6. App::uses('Utility', 'Tools.Utility');
  7. /**
  8. * CaptchaBehavior
  9. * NOTES: needs captcha helper
  10. *
  11. * validate passive or active captchas
  12. * active: session-based, db-based or hash-based
  13. */
  14. class CaptchaBehavior extends ModelBehavior {
  15. protected $_defaultConfig = [
  16. 'minTime' => CAPTCHA_MIN_TIME,
  17. 'maxTime' => CAPTCHA_MAX_TIME,
  18. 'log' => false, // Log errors
  19. 'hashType' => null,
  20. ];
  21. protected $error = '';
  22. protected $internalError = '';
  23. /**
  24. * CaptchaBehavior::setup()
  25. *
  26. * @param Model $Model
  27. * @param array $config
  28. * @return void
  29. */
  30. public function setup(Model $Model, $config = []) {
  31. $defaults = $this->_defaultConfig + CaptchaLib::$defaults;
  32. $this->Model = $Model;
  33. // Bootstrap configs
  34. $this->settings[$Model->alias] = $defaults;
  35. $this->settings[$Model->alias] = (array)Configure::read('Captcha') + $this->settings[$Model->alias];
  36. if (!empty($config)) {
  37. $this->settings[$Model->alias] = $config + $this->settings[$Model->alias];
  38. }
  39. // Local configs in specific action
  40. if (!empty($config['minTime'])) {
  41. $this->settings[$Model->alias]['minTime'] = (int)$config['minTime'];
  42. }
  43. if (!empty($config['maxTime'])) {
  44. $this->settings[$Model->alias]['maxTime'] = (int)$config['maxTime'];
  45. }
  46. if (isset($config['log'])) {
  47. $this->settings[$Model->alias]['log'] = (bool)$config['log'];
  48. }
  49. }
  50. /**
  51. * CaptchaBehavior::beforeValidate()
  52. *
  53. * @param Model $Model
  54. * @param array $options
  55. * @return bool Success
  56. */
  57. public function beforeValidate(Model $Model, $options = []) {
  58. parent::beforeValidate($Model, $options);
  59. if (!empty($this->Model->whitelist)) {
  60. $this->Model->whitelist = array_merge($Model->whitelist, $this->fields());
  61. }
  62. if (empty($Model->data[$Model->alias])) {
  63. $this->Model->invalidate('captcha', __d('tools', 'captchaContentMissing'));
  64. } elseif (!$this->_validateDummyField($Model->data[$Model->alias])) {
  65. $this->Model->invalidate('captcha', __d('tools', 'captchaIllegalContent'));
  66. } elseif (!$this->_validateCaptchaMinTime($Model->data[$Model->alias])) {
  67. $this->Model->invalidate('captcha', __d('tools', 'captchaResultTooFast'));
  68. } elseif (!$this->_validateCaptchaMaxTime($Model->data[$Model->alias])) {
  69. $this->Model->invalidate('captcha', __d('tools', 'captchaResultTooLate'));
  70. } elseif (in_array($this->settings[$Model->alias]['type'], ['active', 'both']) && !$this->_validateCaptcha($Model->data[$Model->alias])) {
  71. $this->Model->invalidate('captcha', __d('tools', 'captchaResultIncorrect'));
  72. }
  73. unset($Model->data[$Model->alias]['captcha']);
  74. unset($Model->data[$Model->alias]['captcha_hash']);
  75. unset($Model->data[$Model->alias]['captcha_time']);
  76. return true;
  77. }
  78. /**
  79. * Returns the current used field names to be passed in whitelist etc
  80. *
  81. * @return array
  82. */
  83. public function fields() {
  84. $list = ['captcha', 'captcha_hash', 'captcha_time'];
  85. if ($this->settings[$this->Model->alias]['dummyField']) {
  86. $list[] = $this->settings[$this->Model->alias]['dummyField'];
  87. }
  88. return $list;
  89. }
  90. /**
  91. * CaptchaBehavior::_validateDummyField()
  92. *
  93. * @param mixed $data
  94. * @return bool Success
  95. */
  96. protected function _validateDummyField($data) {
  97. $dummyField = $this->settings[$this->Model->alias]['dummyField'];
  98. if (!isset($data[$dummyField])) {
  99. return $this->_setError(__d('tools', 'Illegal call'));
  100. }
  101. if (!empty($data[$dummyField])) {
  102. // Dummy field not empty - SPAM!
  103. return $this->_setError(__d('tools', 'Illegal content'), 'DummyField = \'' . $data[$dummyField] . '\'');
  104. }
  105. return true;
  106. }
  107. /**
  108. * Flood protection by time
  109. * TODO: SESSION based one as alternative
  110. *
  111. * @return bool Success
  112. */
  113. protected function _validateCaptchaMinTime($data) {
  114. if ($this->settings[$this->Model->alias]['minTime'] <= 0) {
  115. return true;
  116. }
  117. if (isset($data['captcha_hash']) && isset($data['captcha_time'])) {
  118. if ($data['captcha_time'] < time() - $this->settings[$this->Model->alias]['minTime']) {
  119. return true;
  120. }
  121. }
  122. return false;
  123. }
  124. /**
  125. * Validates maximum time
  126. *
  127. * @param array $data
  128. * @return bool Success
  129. */
  130. protected function _validateCaptchaMaxTime($data) {
  131. if ($this->settings[$this->Model->alias]['maxTime'] <= 0) {
  132. return true;
  133. }
  134. if (isset($data['captcha_hash']) && isset($data['captcha_time'])) {
  135. if ($data['captcha_time'] + $this->settings[$this->Model->alias]['maxTime'] > time()) {
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. /**
  142. * Flood protection by false fields and math code
  143. * TODO: build in floodProtection (max Trials etc)
  144. * TODO: SESSION based one as alternative
  145. *
  146. * @return bool Success
  147. */
  148. protected function _validateCaptcha($data) {
  149. if (!isset($data['captcha'])) {
  150. // form inputs missing? SPAM!
  151. return $this->_setError(__d('tools', 'captchaContentMissing'));
  152. }
  153. $hash = $this->_buildHash($data);
  154. if ($data['captcha_hash'] === $hash) {
  155. return true;
  156. }
  157. // wrong captcha content or session expired
  158. return $this->_setError(__d('tools', 'Captcha incorrect'), 'SubmittedResult = \'' . $data['captcha'] . '\'');
  159. }
  160. /**
  161. * Return error message (or empty string if none)
  162. *
  163. * @return string
  164. */
  165. public function errors() {
  166. return $this->error;
  167. }
  168. /**
  169. * Only necessary if there is more than one request per model
  170. *
  171. * @return void
  172. */
  173. public function reset() {
  174. $this->error = '';
  175. }
  176. /**
  177. * Build and log error message
  178. * TODO: dont return boolean false
  179. *
  180. * @return bool false
  181. */
  182. protected function _setError($msg = null, $internalMsg = null) {
  183. if (!empty($msg)) {
  184. $this->error = $msg;
  185. }
  186. if (!empty($internalMsg)) {
  187. $this->internalError = $internalMsg;
  188. }
  189. $this->_logAttempt();
  190. }
  191. /**
  192. * CaptchaBehavior::_buildHash()
  193. *
  194. * @param array $data
  195. * @return string Hash
  196. */
  197. protected function _buildHash($data) {
  198. return CaptchaLib::buildHash($data, $this->settings[$this->Model->alias]);
  199. }
  200. /**
  201. * Logs attempts
  202. *
  203. * @param bool ErrorsOnly (only if error occured, otherwise always)
  204. * @returns null if not logged, true otherwise
  205. */
  206. protected function _logAttempt($errorsOnly = true) {
  207. if ($errorsOnly === true && empty($this->error) && empty($this->internalError)) {
  208. return null;
  209. }
  210. if (!$this->settings[$this->Model->alias]['log']) {
  211. return null;
  212. }
  213. $msg = 'IP \'' . Utility::getClientIp() . '\', Agent \'' . env('HTTP_USER_AGENT') . '\', Referer \'' . env('HTTP_REFERER') . '\', Host-Referer \'' . Utility::getReferer() . '\'';
  214. if (!empty($this->error)) {
  215. $msg .= ', ' . $this->error;
  216. }
  217. if (!empty($this->internalError)) {
  218. $msg .= ' (' . $this->internalError . ')';
  219. }
  220. $this->log($msg, 'captcha');
  221. return true;
  222. }
  223. }