Skip to content

Instantly share code, notes, and snippets.

@mishudark
Created June 25, 2012 23:02
Show Gist options
  • Save mishudark/2992007 to your computer and use it in GitHub Desktop.
Save mishudark/2992007 to your computer and use it in GitHub Desktop.
DRUPAL - csrf - one time usage
diff --git a/drupal/includes/common.inc b/drupal/includes/common.inc
index 8d15d1f..2d73f58 100644
--- a/drupal/includes/common.inc
+++ b/drupal/includes/common.inc
@@ -2605,8 +2605,21 @@ function drupal_get_private_key() {
* An additional value to base the token on.
*/
function drupal_get_token($value = '') {
+ global $user;
$private_key = drupal_get_private_key();
- return md5(session_id() . $value . $private_key);
+ $key = md5(session_id() . $value . $private_key . date('YmdHis'));
+ if(!isset($_SESSION['form-keys'])){
+ $_SESSION['form-keys'] = array();
+ }
+ if(!isset($_SESSION['form-keys'][$user->uid])){
+ $_SESSION['form-keys'][$user->uid] = array();
+ }
+ if(!isset($_SESSION['form-keys'][$user->uid][$value])){
+ $_SESSION['form-keys'][$user->uid][$value] = array();
+ }
+ $_SESSION['form-keys'][$user->uid][$value][$key] = $key;
+
+ return $key;
}
/**
@@ -2624,7 +2637,17 @@ function drupal_get_token($value = '') {
*/
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
global $user;
- return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
+ if($skip_anonymous && $user->uid == 0){
+ return true;
+ }
+ $token == md5(session_id() . $value . variable_get('drupal_private_key', '') . date('YmdHis'));
+
+ if(!isset($_SESSION['form-keys'][$user->uid][$value][$token])){
+ return false;
+ }
+ //eliminamos el roken
+ unset($_SESSION['form-keys'][$user->uid][$value][$token]);
+ return true;
}
/**
diff --git a/drupal/includes/form.inc b/drupal/includes/form.inc
index 0736493..1f21f25 100644
--- a/drupal/includes/form.inc
+++ b/drupal/includes/form.inc
@@ -572,7 +572,7 @@ function drupal_prepare_form($form_id, &$form, &$form_state) {
* web service requests, or other expensive requests that should
* not be repeated in the submission step.
*/
-function drupal_validate_form($form_id, $form, &$form_state) {
+function drupal_validate_form($form_id, &$form, &$form_state) {
static $validated_forms = array();
if (isset($validated_forms[$form_id])) {
@@ -586,6 +586,7 @@ function drupal_validate_form($form_id, $form, &$form_state) {
// Setting this error will cause the form to fail validation.
form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
}
+ $form['form_token']['#value'] = drupal_get_token($form['#token']);
}
_form_validate($form, $form_state, $form_id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment