I am building a small app for Nextcloud (16). I have to execute some code in an external PHP file, not in the Nextcloud app. This page has to be secured against unauthorized access. I want to achieve this with the existing Nextcloud session cookie.
Currently, I read the nc_session_id
cookie from the user's browser and check if this session exists in PHP's session path. This should be secure because an attacker can usually not guess the id.
This is what the Nextcloud session in the browser looks like:
I have tried to check the cookie with
session_status('nc_session_id') != PHP_SESSION_NONE
but this always returns int(1) --> the session does not exist, because I would have to run session_start() before that. BUT in this special case, the external page shall never start a new session itself - it should only check if a valid Nextcloud session already exists.
My current code seems to do the job:
session_name('nc_session_id');
$sessid_cook = filter_input(INPUT_COOKIE, "nc_session_id", FILTER_SANITIZE_STRING);
$sess_path = session_save_path().'/sess_'.$sessid_cook;
if(isset($_COOKIE['nc_session_id']) &&
isset($_COOKIE['nc_username']) &&
file_exists($sess_path)) {
echo "Session okay";
session_start();
} else {
echo "Access denied";
exit;
}
// my protected logic here
If I manipulate the session cookie in my browser, the PHP code on the server can not find the session file for that manipulated cookie. So the access is denied.
This works in my current setup, but what happens if the sessions are handled by Redis or Memcache? The cookies could not be checked locally.
Is there some better way to "validate" session cookies before starting a PHP session?
Is my solution secure or does it have some flaws?