ℙℕℤℝ 2016-02-13 17:01
浏览 32

如何在Ajax上输入CSRF?

I have this code

    ---------- index.php ----------
    <script>
    function validLogin() {
    var email=$('#memail').val();
    var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var password=$('#mpass').val();
    var dataString = email='+ email + '&password='+ password;
          $.ajax({
          type: "POST",
          url: "processed.php",
          data: dataString,
          cache: false,
          success: function(result){
                   var result=trim(result);
                   if(result=='correct'){
                         window.location='/';
                   } else {
                   }
          }
          });
        return true;
    }

    function trim(str){
         var str=str.replace(/^\s+|\s+$/,'');
         return str;
    }
    </script>

    <div class="login">
        <div class="input-group">
            <input type="text" id="memail" value="" placeholder="Email" class="memail">
        </div>
        <div class="input-group">
            <input type="password" id="mpass" value="" placeholder="Password" class="mpassword">
        </div>
        <div class="checkout-submit-section">
            <div class="payment-submit">
                <div class="order-submit">
                    <button id="msubmit" type="submit" name="submit_button" class="greenx" style="margin-top:-20px;" onclick="validLogin()">
                        Login
                    </button>
                </div>
            </div>
        </div>
    </div>

and

    ------ processed.php ---------
    <?php
    session_start();
    include_once('../db/ds.php');
    $message=array();
    if(isset($_POST['email']) && !empty($_POST['email'])){
        $email = $mysqli->real_escape_string($_POST['email']);
    $email= htmlentities($email);
    }else{
        $message[]='email';
    }
    if(isset($_POST['password']) && !empty($_POST['password'])){
        $password = $mysqli->real_escape_string($_POST['password']); 
    $password= htmlentities($password);
    }else{
        $message[]='password';
    }
    $countError=count($message);
    if($countError > 0){
     for($i=0;$i<$countError;$i++){
     }
}else{
$password=md5($password);
$query = "select * from user where email='$email' and password='$password'";
$res = $mysqli->query($query);
$checkUser = $res->num_rows;
    if($checkUser > 0){
    $lol = $res->fetch_array(MYSQLI_BOTH);
    $iduser = $lol['id'];
    $_SESSION['status']=true;
    $_SESSION['id']=$iduser;
    echo 'correct';
    }else{
    }
}
}
?>

maybe this code for CSRF, but I do not know how to use them

function createToken()
{
    $token= base64_encode( openssl_random_pseudo_bytes(32));
    $_SESSION['csrfvalue']=$token;
    return $token;  
}
function unsetToken()
{
    unset($_SESSION['csrfvalue']);
}
function validation()
{   
    $csrfvalue = isset($_SESSION['csrfvalue']) ? mysql_real_escape_string($_SESSION['csrfvalue']) : ''; 
    if(isset($_POST['csrf_name']))
    {       
        $value_input=$_POST['csrf_name'];

        if($value_input==$csrfvalue)
        {
            unsetToken();
            return true;            
        }else{
            unsetToken();
            return false;
        }
    }else{
        unsetToken();
        return false;
    }
}

<input type="hidden" name="csrf_name" value="<?php echo createToken();?>"/>

How to use CSRF without input <form action="" method="post">? Because when I test the security of this code, this code dangerous if not using CSRF. I've been looking for to several sites , but they all use input form.

1.How to use CSRF in the above code ?

  1. Whether my code is too simple? and could be tricked ? How do I secure it ?

  2. If i use ajax , Whether I have to use CSRF ?

EDIT

--------------- processed.php ----------------

<?php
require '../../db/sessions.php';
require '../../db/ds.php';
require '../../db/error.php';
$user=$row['id'];
$message=array();

if(isset($_POST['emailx']) && !empty($_POST['emailx'])){
    $emailx = $mysqli->real_escape_string($_POST['emailx']);
$emailx= htmlentities($emailx);
}else{
    $message[]='email';
}
if(isset($_POST['hpx']) && !empty($_POST['hpx'])){
    $hpx = $mysqli->real_escape_string($_POST['hpx']); 
$hpx= htmlentities($hpx);
}else{
    $message[]='hp';
}
if(isset($_POST['namax']) && !empty($_POST['namax'])){
    $namax = $mysqli->real_escape_string($_POST['namax']); 
    $namax= htmlentities($namax);
}else{
    $message[]='nama';
}
if(isset($_POST['token']) && !empty($_POST['token'])){
    $tokens = $mysqli->real_escape_string($_POST['token']);
}else{
    $message[]='email';
}
$countError=count($message);

if($countError > 0){
     for($i=0;$i<$countError;$i++){
     }
}else{

    if(validation($tokens, $crsfa)==true) {
        $query = "UPDATE user SET email='$emailx', nama='$namax', hp='$hpx' WHERE id='$user'";
        $res = $mysqli->query($query);
        echo 'OKS';
    }else{
        echo "Null";
        return false;
    }
}

?>

--------------- index.php ----------------

<meta name="csrf_token" content="<?php echo createToken();?>">
.
.
.
.
.
<script>
function validUbah() {
      var hpx=$('#hp').val();
      var emailx=$('#email').val();
      var namax=$('#nama').val();
      var token=$('[name="csrf_token"]').attr('content');
      var dataString = 'hpx='+ hpx + '&emailx='+ emailx + '&namax='+ namax + '&token='+ token;
      $.ajax({
      type: "POST",
      url: "processed.php",
      data: dataString,
      success: function(result){
               var result=trim(result);
               if(result=='OKS'){
            $(".spinner").hide();
            $(".spanlogin").show();
            $(".spanlogin").html('Berhasil');
            $(".nm7").html(namax);
               } else {
            $(".spinner").hide();
            $(".spanlogin").show();
            $(".spanlogin").html(result);
        return false;
               }

      }
      });
    return true;
}
function trim(str){
     var str=str.replace(/^\s+|\s+$/,'');
     return str;
}
</script>

--------------- sessions.php ---------------------

function unsetToken()
{
    unset($crsfa);
    createToken();
}

function validation($varians, $crsfa)
{   
    $csrfvalue = isset($crsfa); 
    if(isset($varians))
    {       
        $value_input=$varians;

        if($value_input==$csrfvalue)
        {
            unsetToken();
            return true;            
        }else{
            unsetToken();
            return false;
        }
    }else{
        unsetToken();
        return false;
    }
}

    $crsfa=$_SESSION['csrfvalue'];
  • 写回答

1条回答 默认 最新

  • weixin_33701564 2016-02-13 21:30
    关注

    if you are implementing anti-CSRF techniques, you should use the token on every post/ajax request.

    Maybe you can implement your token as meta-Tag: <meta name="csrf-token" content="MERvRHE0MmVHcSU9OEUfPHs3JSALZQpcAC1ccBVcZA14KVlxN35xHQ==">

    Whatever you do, do NOT use MD5 for hashing passwords. Use PHP's crypt() or other means for password storage.

    Cheers

    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3