CSRF Token not correct - php

I am facing "CSRF Token not correct". This was working perfectly on the Linux server. Today I migrated my website to the windows system and cannot log in to the admin interface due to this issue.
Kindly assist How to get rid of this issue.?
<?php
$samesite = 'strict';
if(PHP_VERSION_ID < 70300) {
session_set_cookie_params('samesite='.$samesite);
} else {
session_set_cookie_params(['samesite' => $samesite]);
}
if (isset($_COOKIE['PHPSESSID']))
session_start();
function login()
{
if (session_status() == PHP_SESSION_NONE) return false;
if (isset($_SESSION[config("site.url")]['user']) && !empty($_SESSION[config("site.url")]['user']))
{
return true;
} else {
return false;
}
}
?>
I am unsure if this issue is related to the session or something else.

Related

PHP Auto Login after Registration

I'm having some issues with a request from my boss.
I'm using the http://www.html-form-guide.com/ Registration forms he has created for use (I've attached the link just in case anyone want to use or look at it)
So I'm pretty new to PHP, but I've been gaining a crazy amount of knowledge.
Here is my problem - I need to make this form Register the user than Login Automatically. (This form has a Email confirmation system)
So I've managed to bypass the Email Confirmation and get the user to register, but I can't seem to figure out how to get auto login.
Here is what I've traced in the code:
function RegisterUser()
{
if(!isset($_POST['submitted']))
{
return false;
}
$formvars = array();
if(!$this->ValidateRegistrationSubmission())
{
return false;
}
$this->CollectRegistrationSubmission($formvars);
if(!$this->SaveToDatabase($formvars))
{
return false;
}
/*if(!$this->SendUserConfirmationEmail($formvars))
{
return false;
}*/
$this->SendAdminIntimationEmail($formvars);
$this->AutoLogin($formvars);// My call
return true;
}
This will pull in the name, email and password - put them in an array then send it off for validation and sanitation. I've placed a call function here.
After which I'll need to manually login with:
function Login()
{
if(empty($_POST['email']))
{
$this->HandleError("Email is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$email = trim($_POST['email']);
$password = trim($_POST['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
So I took the last portion of the login function and made:
function AutoLogin(&$formvars)
{
$email = trim($formvars['email']);
$password = trim($formvars['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
I did an echo $email; echo $password; exit; test and I can see that the email and password are appearing. But the "Session" (I think) is not starting or the Check Login is not getting the data.
function CheckLogin()
{
if(!isset($_SESSION)){ session_start(); }
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
Now I see the is a CheckLoginInDB which is:
function CheckLoginInDB($email,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$email = $this->SanitizeForSQL($email);
$pwdmd5 = md5($password);
$qry = "Select name, email, pagecode, welcome from $this->tablename where email='$email' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The email or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
$_SESSION['pagecode_of_user'] = $row['pagecode'];
$_SESSION['welcome_user'] = $row['welcome'];
return true;
}
What I can gather from this, its just a standard checking the database to see if this user exists and returning the results.
I've searching through stackoverflow and can't seem to see an answer to my problem.
I looked into Cookies, but I don't think that is something I really need here.
My questions are:
How can I make this bad boy start the session on registration?
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
Just in case here is the GetLoginSessionVar():
function GetLoginSessionVar()
{
$retvar = md5($this->rand_key);
$retvar = 'usr_'.substr($retvar,0,10);
return $retvar;
}
It's a pity I can't attached the file I'm working on, but if you need any further code snippets let me know and I'll be sure to Edit this straight away!
But the "Session" (I think) is not starting or the Check Login is not
getting the data.
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
It's not something wrong with the syntax, otherwise the code wouldn't even be compiled. Nevertheless I believe it's not the right idea.
You need to understand what's the problem before trying to fix it.
Debug the code. Use xdebug. If it's installed and active, you can use IDEs (e.g.: Visual Studio Code) to easily debug the code. Add breakpoints where you suspect there's something wrong.
If you don't want to use xdebug, you can add temporarily echoes or var_dumps to check if some areas of the code are processed and check some relevant values.
Also enable all errors reports and use a logger.
If the session is started after any output, there should be some warning.
Handle the errors and throw exceptions.
http://php.net/manual/en/function.error-log.php
http://php.net/manual/en/function.syslog.php
https://jtreminio.com/2012/07/xdebug-and-you-why-you-should-be-using-a-real-debugger/
session_start() works after output being sent
http://php.net/manual/en/function.error-reporting.php
You don't need to use the & in AutoLogin(&$formvars) if you're not changing the argument $formvars (you're just reading it).
You don't need to set session variables with all the user data. Create some structure (a class, an array, ...) with the user data outside those function and change those. AutoLogin should update that structure, something like this:
<?php
if (!$_SESSION) {
session_start();
}
$currentUser = array();
function getUserFromID($userID)
{
//TODO implement function
return $user;
}
function AutoLogin()
{
global $currentUser;
if(!empty($_SESSION['userID'])) {
return false;
}
$user = getUserFromID($_SESSION['userID']);
if (empty($user)) {
return false;
}
$currentUser = $user;
return true;
}
Maybe the session is not initialised before CheckLoginInDB is invoked (make var_dump($_SESSION); to check it). Use the $_SESSION only to save the user ID (or email) and read it to retrieve the user data.

PHP Session security key steps

I am struggling with PHP login and user validation after they log on to the system. I know the basics but I'm not sure if I'm doing it right. I will try to explain it step by step.
I have a form for user name and password.
After users enter they login and password i'm using LDAP authentication to authorize them. And if authentication pass then i need to start new session.
New session (and this is where i'm struggling).
if ($validation->ldap_authentication())
{
$session = new session();
$session -> login($validation->getUsername(), $validation->logedAs(), $validation->getSID());
if($session->validate_login())
{
exit(header('Location:index2.php'));
}
else
{
echo 'error';
}
}
And my session class:
class session
{
public function __construct()
{
if(!isset($_SESSION))
{
session_name(SESSIONNAME);
ob_start();
session_start();
} else {
session_regenerate_id(true) ;
}
}
public function login($sessionUserName, $logedAs, $sid)
{
$_SESSION['logedUserName'] = isset($sessionUserName) ? $sessionUserName : null;
$_SESSION['logedAs'] = isset($logedAs) ? $logedAs : null;
$_SESSION['sid'] = isset($sid) ? $sid : null;
}
public function validate_login()
{
if (!isset($_SESSION['logedUserName']) || (trim($_SESSION['logedUserName']) == '') ||
!isset($_SESSION['logedAs']) || (trim($_SESSION['logedAs']) == '') ||
!isset($_SESSION['sid']) || (trim($_SESSION['sid']) == '')
)
{
return false;
} else {
return true;
}
}
}
So in the another pages i need to start a class session (again) and validate validate_login()?
For me it looks really poor authentication.
What do I need to add and improve?
I already searched online but couldn't find an answer and don't know what exactly I need to improve.
I'm a beginer in PHP, so my answer might be worthless.
I think you can trust the variable stored in $_SESSION as only the server can access them. So you could have a boolean $_SESSION['loggedIn'] that let you know that the user have gone through the login process successfully, and this variable would be accessible from any page.

Session_start causes 500 ERROR

I have been working on website (Yii + angularJs) and everything was okey.
Then I decided to work at home and cloned repository to my laptop.
And then a problem appeared.
Website doesn't give any resources or files to display, just white screen and error 500 (Internal Server Error) appears with no reasons or explanations.
And only when I comment some lines in Main Controller everything goes okey.
I comment session_start() function and checks of users rigths from $_Session array.
Example below.
(Note, if I leave session_start() line, site loads index page with login form, then I fill fields and then white screen again)
public function actionIndex() {
$page = safe($_GET,'page','index');
$pages = $this->get_pages();
$pageInfo = safe($pages,$page);
//session_start();
if(safe($pageInfo,'layout')) {
$this->layout = $pageInfo['layout'];
}
if($page == 'reset-password') {
$params = array_change_key_case($_GET, CASE_UPPER);
if(!isset($params['RECOVERY_TOKEN']))
$this->redirect('/');
} else if($page == 'request') {
$id = safe($_GET, 'id');
if(!$id || !$this->validID($page, $id)) {
$this->redirect('/requests');
}
}
$this->render(safe($pageInfo,'render',$page)); //moved from comments below
/*if($_SESSION['rights'][$page] && !$_SESSION['rights'][$page]['show']){
$this->redirect('/dashboard');
}else {
try {
if (!safe($pageInfo,'layout') && empty($_SESSION) && $pages[$page]) {
$this->redirect('/');
}else{
$this->render(safe($pageInfo,'render',$page));
}
} catch (Exception $e) {
throw new CHttpException(404);
}
}*/
}
Strange is that after login to website I also have session_start() function, but this one doesn't cause such error.
And also, i have no problems with my code on my work computer and on dev-server.
We have tried to clone this site to another laptop, the same error appeared.
I have no ideas what is wrong. Please, help. Thanks!

session_status() is showing error because my server is not using PHP 5.4

it is saying this session_status is undefined function . can you tell me whats the replacement of it.
in the given code
<?php
in this line it gives error.. plz give me the replacement of this code
if (session_status() != PHP_SESSION_NONE) {
session_destroy();
}
session_start();
if(!isset($_POST['secure'])){
$_SESSION['secure']= rand(1000, 2000);
}
else
{
if($_SESSION['secure']==$_POST['secure'])
{
}
else
{
echo 'incorrect , try again';
$_SESSION['secure']= rand(1000, 2000);
}
}
?>
plz help me i am stucked here
Well as you can see on http://php.net/manual/en/function.session-status.php the function was introduces in 5.4 so there is no hope in getting it in 5.3.
You can see in the comments that you can use return session_id() === '' ? FALSE : TRUE; as a sort off replacement, but it is not 100% correct.
Tell your host to update to php 5.4 the 5.3 is EOL since 14 Aug 2014.
if (isset($_SESSION)) {
//do something
} else {
//do other stuff
}

Web Service doesn't keep state between requests

I am developing an ASP.NET Web Service:
# MyWS.cs
[WebMethod(EnableSession = true)]
public bool TryLogin(string user, string pass)
{
if (/* user validation is successful*/)
{
Context.Session["user"] = user;
return true;
}
else
{
Context.Session.Abandon();
return false;
}
}
[WebMethod(EnableSession = true)]
public string RetrieveSomething()
{
if (Context.Session["user"] == null)
throw Exception("User hasn't logged in.");
/* retrieve something */;
}
This ASP.NET must be consumed by a PHP Web site I am developing as well:
# ws_client.php
function get_soap_client()
{
if (!isset($_SESSION['client']))
$_SESSION['client'] = new SoapClient('MyWS.asmx?WSDL');
return $_SESSION['client'];
}
function try_login($user, $pass)
{
return get_soap_client()->TryLogin(
array('user' => $user, 'pass' => $pass))
->TryLoginResult;
}
function retrieve_something()
{
return get_soap_client()->RetrieveSomething(
array())->RetrieveSomethingResult;
}
# index.html
<?php
if (isset($_POST['submit']))
{
session_start();
require_once('ws_client.php');
if (try_login($_POST['user'],
$_POST['pass']))
{
session_write_close();
header('Location: /main.php');
exit();
}
?>
<html> <!-- login form here >
# main.php
<?php
session_start();
require_once('ws_client.php');
// Here I get the Exception "User hasn't logged in.", even though
// the user has logged in and the web service has already been notified.
echo htmlspecialchars(retrieve_something());
?>
What could be wrong with either my Web Service or my PHP site?
I don't know the PHP SOAP tools, but Session state is maintained through a cookie. Will this code accept a cookie the first time, then send it back on subsequent calls?

Categories