ajax login csrf input de input após o envio

meu login .php

          <meta name="csrf-token" content=""/> finest - מערכת ניהול        $(document).ready(function() { $('.inplaceError').each( function(i) { $(this).focus(function(e){ $("#errorMessage").html(""); }); } ); $('#container').fadeIn(); function sale() { $('#footer').fadeIn(200); } setTimeout(sale, 500); });   $(document).ready(function(){ $('form input:submit').bind('click', validLogin); }); function validLogin(){ if($.trim($("#password").val()) == '') { var p = ''; } else { $("#p").val( hex_sha512( $("#password").val() ) ); var p = $("#p").val(); } var key = $('#key').val(); var nonce = $('#nonce').val(); var email = $.trim($('#email').val()); var dataString = 'email='+ email + '&key='+ encodeURIComponent(key) + '&nonce='+ nonce + '&p='+ p; $.ajax({ url: "processed.php", type: "POST", data: dataString, dataType:'json', cache: false, success: function(data) { if(data.login == true) { window.location = "index.php"; } else { $("#siimage").trigger("click"); $("form input:submit").effect("shake", {times:2}, 100); $("#errorMessage").html(data.message); get_nonce(); } if(data.cblocked == true) { $("#email").prop('disabled', true); $("#password").prop('disabled', true); $('input[type="submit"]').attr('disabled','disabled'); document.getElementById("Submit").value = 'נעול'; } if(data.csrf == true) { $("#email").prop('disabled', true); $("#password").prop('disabled', true); $('input[type="submit"]').attr('disabled','disabled'); document.getElementById("Submit").value = 'נעול'; } } }); return false; } function get_nonce(){ $.ajax({ url: "../includes/nonce.php", type: "POST", dataType:'json', async: false, data: {ajax:"true"}, success: function(response) { $("#nonce").val(response.nonce); $("#key").val(response.key); } }); }     checkbruteGuest(ulUtils::GetRemoteIP(false), $func->mysqli) == true) { $disabled = 'disabled'; } else { $disabled = ''; } ?> 
admin_logged_in){ header('location: index.php'); } else { ?>
generateFormFields(); ?>
שם משתמש:
סיסמא:
<input type="text" name="email" id="email" onclick="this.value='';" value="לדוגמא: a@test.com" class="inplaceError" />
<input type="password" name="password" id="password" class="inplaceError" onclick="this.value='';"/>
checkbruteGuest(ulUtils::GetRemoteIP(false), $func->mysqli) == true) { echo ucwords(htmlentities('ההתחברות נחסמה ל- 10 דקות עקב יותר מידי ניסיונות התחברות כושלים.')); } ?>
שכחת שם משתמש או סיסמא?
checkbruteGuest(ulUtils::GetRemoteIP(false), $func->mysqli) == true) { echo ''; } else { echo ''; } ?>

E o nonce.php:

 secret) throw new Exception("You cannot leave \$secret blank. Please set it to a random string."); if(strlen($this->secret) secret = hash('sha224', $this->secret); if($this->store){ try{ $this->dbh = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_user, $this->db_pass); $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch (PDOException $e){ throw new Exception($e); } } } /** * Checks the validity of a nonce. If valid (and $store is true) the nonce * will become 'used' and invalid (meaning it cannot be used again). * * @param int $timestamp the time in the form of the unix epoch * @param float $uid a unique id created by php's uniqid() function (although this can technically be anything). * @param string $content optional additional content supplied by the user. * @param float $uid a unique id created by php's uniqid() function (although this can technically be anything). * @return Boolean true on success or will throw exception on error. **/ public function validateAndUseNonce($timestamp, $uid, $content = '', $nonce) { $hash = $this->getNonce($timestamp, $uid, $content, strlen($nonce)); // Check to see if nonce has been used. Only checks if nonce's are being stored. if($this->store && $this->nonceExists($nonce)){ throw new Exception("This form has already been submitted once."); } // Check to see if time has expired if($this->expire > -1){ if(time() > $timestamp + $this->expire){ throw new Exception("This form has expired. Please reload the page and try submitting again."); } } if($nonce == $hash){ if($this->store) $this->storeNonce($nonce); return true; } else { throw new Exception("Invalid form request. Please try again."); } } /** * Creates a unique nonce string with an optional length. Max length is dependent upon hashing algorithm. * @param int $timestamp the time in the form of the unix epoch * @param float $uid a unique id. * @param string $content optional additional content supplied by the user. * @param int length optional the length of the returned nonce. Max Dependent upon hashing algorithm. * @return string the nonce. **/ public function getNonce($timestamp, $uid, $content = '', $length = NULL) { global $site; $hash = hash($this->hash, $timestamp . $this->secret . $uid . $content); $i = 0; do{ $hash = hash($this->hash, $hash); $i++; } while ($i iter); if($length){ $hash = substr($hash, 0, $length); } return $hash; } /** * Store the nonce in the database. * @param string $nonce * @return boolean true on success false on failure **/ private function storeNonce($nonce) { $sql = "INSERT INTO " . $this->db_table . " (nonce) VALUES (:nonce)"; $q = $this->dbh->prepare($sql); return $q->execute(array(":nonce" => $nonce)); } /** * Checks the existence of a nonce in a database * @param string $nonce * @return mixed boolean false if does not exist, or int 1 if it does **/ private function nonceExists($nonce) { if(!$this->store) throw new Exception("Cannot determine if this nonce has been used since \$store is set to false. Set \$store to true in order to track nonce usage."); $sql = "SELECT COUNT(*) FROM " . $this->db_table . " WHERE nonce = :nonce LIMIT 1"; $q = $this->dbh->prepare($sql); $q->execute(array(":nonce" => $nonce)); return $q->fetchColumn(); } /** * This may be called to validate a form that was generated using generateFormFields() * * @param string $content optional the additional content that was provided when * generateFormFields() was called * * @return boolean true if valid **/ public function validateForm($content = '') { $plain = $this->fnDecrypt($_POST['key']); $plain = explode(' ', $plain, 2); $time = $plain[0]; $uid = $plain[1]; if($content && $content !== $plain[2]){ } return $this->validateAndUseNonce($time, $uid, $content, $_REQUEST['nonce']); } /** * Generates 2 hidden fields to add nonce capability to a form. Forms using this method * can be validated using validateForm(). * * @param integer $length optional The length of the nonce * @param string $content optional content that will be hashed into the nonce. * This might be useful if you want to include a user id. Remeber anything added here * must also be included as an argument when validateForm() is called. * * @return string **/ public function generateFormFields($content = '', $length = NULL) { $time = time(); $uid = $this->generateUid(); $key = $time . " " . $uid; // We'll need this info later so we don't want to simply hash it. We could just send it in plain // text but this is a little more secure and makes things very difficult to break. $key = $this->fnEncrypt($key); $nonce = $this->getNonce($time, $uid, $content, $length); //The ajax variable decides if ajax wants the keys or page being loaded first time. $ajax = isset($_POST['ajax']) ? $_POST['ajax'] : "false"; if($ajax=="false"){ echo "\r\n\r\n"; echo "\r\n"; } else { echo json_encode(array("key" => $key, "nonce" => $nonce)); //This would work when ajax called. } } /** * Checks to see if a form was posted that contains fields generated by generateFormFields(). * * @return boolean true if form was posted **/ public function isFormPosted() { if(isset($_REQUEST['key']) && isset($_REQUEST['nonce'])) return true; } /** * Creates a cryptographically secure random string. Tries first using urandom (for *nix systems), * then tries openssl_random_pseudo_bytes and as a last resort mt_rand. * * @return string a random string **/ public function generateUid($length = 32) { // Best option, but only on *nix systems. Also some web servers don't have access to this. if(is_readable('/dev/urandom')){ $f = fopen('/dev/urandom', 'r'); $seed = fgets($f, $length); // note that this will always return full bytes fclose($f); return base64_encode($seed); } // Next best thing but requires openssl if(extension_loaded('openssl')){ $seed = bin2hex(openssl_random_pseudo_bytes($length)); return base64_encode($seed); } // Last resort, mt_rand for ($i = 0; $i hash, $this->secret, true), $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv( mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND ) ) ) ); } private function fnDecrypt($sValue) { return trim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, hash($this->hash, $this->secret, true), base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv( mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB ), MCRYPT_RAND ) ) ); } /** * Deletes any nonce's from the DB that are older than $expire. Nonce's older than $expire * can be safely deleted since they cannot be used anymore. * * @return boolean true on success **/ public function cleanUpDb() { $sql = "DELETE FROM " . $this->db_table . " WHERE timestamp dbh->prepare($sql); return $q->execute(array(":expire" => $this->expire)); } }; $n = new Nonce; 

meu proccsed.php

 isFormPosted()){ try{ // Wil return true if valid. $msg = $n->validateForm(); }catch (Exception $e){ $msg = $e->getMessage(); } } if($msg === true) : foreach($_POST as $key => $value) { if (!is_array($key)) { // sanitize the input data if ($key != 'ct_message') $value = strip_tags($value); $_POST[$key] = $purifier->purify($value); } } function cleanPost($val) { if(!isset($_POST[$val])) { $_POST[$val] = NULL; return; } $_POST[$val] = trim(htmlentities($_POST[$val], ENT_QUOTES, 'UTF-8')); } if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { cleanPost('email'); cleanPost('p'); $message[]='לא ניתן להתחבר עם פרוקסי.'; } if ($_SERVER["REQUEST_METHOD"]  "POST") die("You can only reach this page by posting from the html form"); $message=array(); if(isset($_POST['email']) && !empty($_POST['email'])) { if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $email = $purifier->purify(@$_POST['email']); } else { $message[]='האימייל שהזנת שגוי או לא תקין נסה שוב'; } } else { $message[]='אנא הכנס אימיל'; } if(isset($_POST['p']) && !empty($_POST['p'])) { $password = $purifier->purify(@$_POST['p']); } else if($_POST['p'] == '') { $message[]='אנא הכנס סיסמא'; } if(get_magic_quotes_gpc()){ $password = stripslashes($password); $email = stripslashes($email); } $countError=count($message); if($countError > 0) { $errmsg = ''; foreach($message as $key => $error) { if($key > 0) $errmsg .= " ,"; $errmsg .= "{$error}"; } $return = array('error' => 1, 'message' => $errmsg); echo json_encode($return); } else { if($session->admin_login($email, $password, $func->mysqli) == true) { $return = array('login' => true); echo json_encode($return); } else { //return the errors from the function } } elseif($msg): $return = array('message' => $msg); echo json_encode($return); endif; ?> 

nonce.php, proccsed.php, login.php

que todos os arquivos.

iv adicionou todos os códigos que estou presos tão dificilmente não consigo corrigi-lo, obrigado e muito, muito obrigado pela ajuda!

Este cria as chaves:

  public function generateFormFields($content = '', $length = NULL) { $time = time(); $uid = $this->generateUid(); $key = $time . " " . $uid; // We'll need this info later so we don't want to simply hash it. We could just send it in plain // text but this is a little more secure and makes things very difficult to break. $key = $this->fnEncrypt($key); echo "\r\n\r\n"; echo "\r\n"; } 

Você não está passando as chaves na matriz? Passe-os como matriz. Adicione isso em vez de echo........ no seu código,

 $nonce = $this->getNonce($time, $uid, $content, $length); echo json_encode(array("key" => $key, "nonce" => $nonce)); 

Agora no ajax onde você recebe novas chaves,

 $.ajax({ url: "file_to_get_new_keys.php", type: "POST", data: dataString, success: function(data) { $("#nonce").val(data.nonce); $("#key").val(data.key); } }); 

Última edição ,

Passe dadosString agora.

  $.ajax({ url: "file_to_get_new_keys.php", type: "POST", data: {ajax:"true"}, success: function(data) { $("#nonce").val(data.nonce); $("#key").val(data.key); } }); 

Agora, no seu php, tenha uma nova variável $ajax , na function que retorna as variables.

 $ajax = isset($_POST['ajax']) ? $_POST['ajax'] : "false"; //The ajax variable decides if ajax wants the keys or page being loaded first time. if($ajax=="false"){ echo "\r\n\r\n"; echo "\r\n"; // OR return json_encode(array("key" => $key, "nonce" => $nonce)); //whatever you need above, when ajax not called. } else { echo json_encode(array("key" => $key, "nonce" => $nonce)); //This would work when ajax called. } 

Sim, o problema pode ser que outro site possa chamar seu arquivo php usando o ajax e obter as chaves e depois usá-las. Aqui está uma pergunta, que pode ajudá-lo.

Claves da API de serviços da Web e Ajax – Protegendo a chave

Você não incluiu sua function de sucesso jQuery. Deveria parecer algo assim.

 success: function(data) { // Get the key from the response var generatedkey = data['key']; // Set the appropiate field to the new key $("input[name=key]").val(generatedkey); } 

E a resposta de uma resposta “válida” deveria ser semelhante.

 echo json_encode(array("key" => $newkey));