J’utilise encore beaucoup QuickForm de PEAR pour gérer mes formulaires, une classe pour disposer automatiquement d’une « protection » contre les CSRF trouvée à l’adresse : http://shiflett.org/articles/cross-site-request-forgeries#comment-66
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <?php /** * @uses HTML_QuickForm * @desc Add automatic CSRF mitigation to all forms by incorporating a token that must be matched in the session and forcing the use of POST method */ require_once "QuickForm.php"; class HTML_QuickFormS extends HTML_QuickForm { /** * @property string $_sessionTokenKey The name of the session variable containing the token */ private $_sessionTokenKey; /** * @method HTML_QuickFormS * @desc Override the method to always use post and pass it on to the parent constructor. Create a session key for the token based on the form name. * @param string $formName * @param string $method * @param string $action * @param string $target * @param mixed $attributes * @param boolean $trackSubmit */ public function HTML_QuickFormS($formName='', $method='post', $action='', $target='', $attributes=null, $trackSubmit=false){ $this->_sessionTokenKey = "QuickFormS_".md5($formName); parent::HTML_QuickForm($formName, 'post', $action, $target, $attributes, $trackSubmit); } /** * @method display * @desc Create a token if necessary and place a hidden field in the form before displaying * @return void */ public function display(){ //A token hasn't been created so do so if(!isset($_SESSION[$this->_sessionTokenKey])){ $_SESSION[$this->_sessionTokenKey] = md5(uniqid(rand(), true).session_id()); //requires the session id to be known in order to add extra difficulty to compromising } //Hide the token at the end of the form $this->addElement("hidden", "qfS_csrf", $_SESSION[$this->_sessionTokenKey]); parent::display(); } /** * @method validate * @desc Check if the passed token matches the session before allowing validation * @return boolean */ public function validate(){ //The token was not passed or does not match if(!isset($this->_submitValues['qfS_csrf']) || $this->_submitValues['qfS_csrf']!=$_SESSION[$this->_sessionTokenKey]){ $this->setElementError("qfS_csrf", "Anti-CSRF token does not match"); } return parent::validate(); } } ?> |
Post a Comment