Pregunta

can someone explain me how to protect the profile page from the wrong user editing the URL to see some other users profile page. i am using a token class to generate a random number to protect against Cross Site Request Forgery. for some reason it doesn't work any suggestion or other way to do that

Also i get the following error : Undefined index: token in PhpProject22_CSRF\profile.php on line 12

<?php 
session_start();
require_once 'Classes/Token.php';
$tk = new Token();

if(isset($_POST['username'],$_POST['product'],$_POST['token'])){
$username = $_POST['username'];
$product = $_POST['product'];
if(!empty($product) && !empty($username)){
    if(Token::check($_POST['token'])){
        echo $_POST['token'].'<br>';
        $tk->get('username');
        $_SESSION['user'] = $tk->name();
        echo 'Process Order';
    }
}
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>CSRF Protection</title>
</head>
<body>
    <form action="" method="POST">
        <div class="product">
            <strong>Profile</strong>
            <div class='field'>
                Username: <input type='text' name='username'>
            </div>
            <input type='submit' value='Order'>
            <input type='hidden' name='product' value='1'>
            <input type='hidden' name='token' value='<?php echo Token::generate();?>'>
        </div>
    </form>
    <?php
    if(isset($_POST['username'])){
    ?>
    <p>Hello <a href = 'profile.php?user=<?php echo $tk->name();?>'><?php echo $tk-  >name();?></a>!</p>
    <?php
    }
    ?>
</body>
</html>

<?php
class Token{
private $_data;

public static function generate(){
    return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}

public static function check($token){
    if(isset($_SESSION['token']) && $token === $_SESSION['token']){      
        unset($_SESSION['token']);
        return true;
    }
    return false;
}

public function get($item){
    if(isset($_POST[$item])){
        $this->_data = $_POST[$item];
    }
}

public function name(){
return $this->_data;
}
}
?>

<?php
require_once 'Classes/Token.php';
session_start();
?>
<form action="" method="POST">
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</form>

<?php
echo 'Hello '.$_SESSION['user'].'!<br>';
if(isset($_GET['user'])){
if(Token::check($_POST['token'])){
    echo $_GET['user'];
}
}
?> 
¿Fue útil?

Solución

When checking post you need to do the following:

if($_POST){
    if(isset($_POST['token']) && Token::check($_POST['token']){
        code
    }else{
        error
    }
}

If someone spoof the post, and doesn't include the token, you're going to get an undefined index error, because $_POST['token'] doesn't exist and you are referencing it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top