I have a class that has a function, lets say class.php:
class fun {
public function get_cookie() {
$old_cookie = $_COOKIE['mycookie'];
}
public function ssl() {
//redirect from http to https
}
In another php file, lets say index.php:
//include fun class
$fun = new fun;
$fun->ssl();
$fun->get_cookie();
My question is since the function get_cookie is after $fun->ssl() does the user send the cookie encrypted? or since the cookie code is coded before the $fun->ssl() is executed, the cookie gets sent unencrypted?
Never send anything via cookies which requires encryption.
Regardless of the answer to the actual question posed here, the contents of your cookies should be considered to be publically accessible and insecure.
Firstly, the entire set of cookies for the site is sent (in both directions) with every single web request. So even if you successfully encrypted them with SSL in this particular request, the user would only need to make a plain HTTP request for an image on your site, and he'd transmit them and get them sent back unencrypted.
Secondly, it is not unheard of for cookies to leak between sites. Many cross-site scripting hacks exist which can allow third-parties to get hold of your user's cookies. These would not be stored encrypted on the user's machine, even if they were sent via SSL.
So I'll repeat my initial statement again: never send anything via cookies which you need to keep secure.
The Wikipedia article has a very nice explanation of how cookies work. Basically, cookies are sent along with the request header. So unless the connection is being made via HTTPS then the cookie is being sent in the clear.
The cookie is sent before your code is running. PHP reads the header, fills the global variable $_COOKIE[] and then executes your code. So if somebody makes a request with HTTP, he will get the cookie unencrypted.
When you create the cookie, you can define, that the cookie is only sent to pages requested with HTTPS. You do this with the functions session_set_cookie_params() or setcookie() with the $secure parameter. Such cookies won't be sent, if a page is requested with HTTP.
Related
I have built up a login on my website where I set a $_SESSION['user'] variable if the login was successful.
Now I protect all the content for logged in users by
if(!isset($_SESSION['user'])) {
header('Location: login.php');
}
This means that if there hasn't been a successful login, you directly come back to the login page.
Now my question: Is this secure? Couldn't a $_SESSION['user'] variable have been set by another website?
This is correct. This is the way generally used by most websites using PHP.
The $_SESSION is a super global variable that is only managed by your server.
What happens:
You call session_start()
A cookie named PHPSESSID (or anything that you name it in php.ini) with a cryptographically secure value will be generated.
PHP declares a variable called $_SESSION, which is internally stored with association to the generated cookie value.
Why it cannot be changed by other websites:
The value of $_SESSION is only stored internally. Not even the client knows its value. It only holds a cookie for session ID, but it doesn't even know what that session ID means, nor what other people's session ID should be.
This session ID cookie cannot be stolen or modified by other websites. By default, the cookie path is set to your own domain, and the client should only send it to you. (If the client wants to send to other websites, it's leaking its own credentials and it is none of your responsibility but the bug of the client browser)
Unless you are running other websites on the same server, this won't be a problem (under normal circumstances).
As a side note, please be reminded that you should add a return; statement after using header("Location: index.php");. This is a common source of bugs, and in this context, it may expose your server to danger, because even though your browser won't display the content after it received the Location header, your server is actually still sending the data that should be generated for the user as if he has logged in.
TL;DR: if you have a script that should not send any data if client is not logged in, not adding the return; statement after header("Location: ..."); will make the server still send the data, but normal browsers will not display it (because it redirects), but if there is someone who tries to view the data sent (using methods as simple as curl without adding the -L option) will easily see them.
What you have done so far is fine and seems not vulnerable, and no attacker setting session variable from other site doesnt effect yours, but take care how you handle session once a session is created. Also generate random session tokens on each login and also change session tokens when passwords are changed.
In general a session itself can be considered safe. The problem is that is possible to steal a session allowing a hacker to have total access to whatever is in that session.
Since PHP stores the session ID as a cookie, a hacker can steal the session simply by using XSS.
Maybe have a look here for further information: Is this a safe use of Session Variables?
You're not likely to face this problem unless there's another login page on the same server. Say, login of admin and front end users.
If you want to strengthen your session and other security components, you could refer to this:
PHP Session Security
No.
Your website creates an unique hash and file on the server machine for the session and the hash is stored in the users browser as a cookie so when it hits your webserver, it could know which file exactly to read.
If any other website sets the same key to the $_SESSION variable it will be only for its hash, which your server wont read.
I am working with CORS on a website.
Code sample:
header("Access-Control-Allow-Origin: *");
session_start();
$session_id = session_id();
This code is working fine, but it's returning a new session id every time.
How can I maintain the session data in this situation?
Although you allow access from external domains with the Access-Control-Allow-Origin header, the session itself is cookie based.
If the script which makes the request is delivered from the external domain, it will not be able to read the cookie and pass it to your server.
Solution: Deliver the JS which makes the call from the same context (i.e. same protocol/domain/port) as the AJAX service. Also make sure that the cookie itself is not restricted to a different subdomain or path.
DO NOT try passing the session identifier by POST or GET requests, this will make your application vulnerable to CSRF.
By the way, setting the allowed origin to * is also discouraged, because it can also be used for XSS/CSRF, in combination with other techniques. Please do limit requests to the third-party domain.
Last, but not least, you might also want to look into the subject of preflight requests via HTTP OPTIONS.
A server (in this case the PHP application) can have a session with many different clients at the same time. There is no way for the session to tell which session belongs to which client without having the PHPSESSID cookie. This cooke has to set in the request header for PHP to identify the client.
I have a weird problem. I have a web page, that on the main page sets a session variable for each user that visits, and then on the next pages if the session variable is set, some stuff is shown, and some other isn't. The variable i'm setting is just an "1".
$_SESSION['user_id'] = $user_id;
Everything is simple, everything is working great, but I have this one user, that the server doesn't save the session variable for. Just one guy as far as I know. What can be causing this behaviour? He is using a mac if that matters, but on other macs the website works great.
Thanks.
When you call session_start() PHP sets a cookie with just the PHPSESSID variable set. This variable is used to identify the client browser with the session data on the server. If your user has disabled cookies, then it is not possible to use sessions without passing PHPSESSID back and forth in every request via GET or POST.
HTTP is a stateless protocol. IF session would be only in server side, how could it be able to distinguish between users?
[HTTP is a stateless protocol means: HTTP requests are responded from the server, and it forgets who sent the request, where did that come from.]
This is why cookies are storing the session ids.
In other words, if a user is disabling the cookies, he is not allowing PHP to set the session for himself. This is the reason behind.
What is the distinction between Sessions and Cookies in PHP?
A cookie is a bit of data stored by the browser and sent to the server with every request.
A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.
You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.
If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.
A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.
The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.
Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.
Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.
Cookie
is a small amount of data saved in the browser (client-side)
can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)
can be set directly client-side in Javascript: document.cookie = 'foo=bar';
if no expiration date is set, by default, it will expire when the browser is closed.
Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.
you can also set a precise expiration date other than "deleted when browser is closed".
the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:
can be read client-side with document.cookie
can be read server-side with $_COOKIE['foo']
Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):
from bottle import get, run, request, response
#get('/')
def index():
if request.get_cookie("visited"):
return "Welcome back! Nice to see you again"
else:
response.set_cookie("visited", "yes")
return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)
Session
is some data relative to a browser session saved server-side
each server-side language may implement it in a different way
in PHP, when session_start(); is called:
a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:
(it can also be be sent via the URL instead of cookie but not the default behaviour)
you can see the session ID on client-side with document.cookie:
the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.
can be set/read in PHP with $_SESSION
the client-side does not see the session data but only the ID: do this in index.php:
<?php
session_start();
$_SESSION["abc"]="def";
?>
The only thing that is seen on client-side is (as mentioned above) the session ID:
because of this, session is useful to store data that you don't want to be seen or modified by the client
you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie
A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.
A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.
Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.
Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.
One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie.
You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.
Did I get this right?
Session
Session is used for maintaining a dialogue between server and user.
It is more secure because it is stored on the server, we cannot easily access it.
It embeds cookies on the user computer. It stores unlimited data.
Cookies
Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session.
It stores limited amount of data, and is maintained for a limited time.
I'm new to the cookie. But I think I might have done some wrong with my PHP code. During login process I have a verify login script that verifies the user. And if the user passes it the script will automatically set a cookie, setcookie("userid", $row["profileId"], time() + 24*3600*14); and the script also redirects the user to the main page with header("Location: ../../index.php"); As I'm looking on the network tab in Google Chrome's developer tools, I can see the cookie just for the verify script, both request cookie and response cookie. But why can't see this on all other AJAX request? I can't retrieve the cookies at all, what have I done wrong? I know I have made some common pitfall
The only Cookie I can retrieve is the session cookie. I need the retrieve the cookie using $_COOKIE in php. I'm using localhost as the domain
Cookies are fully automatic. You don't need to grab them in js to send them. The ajax call with automatically send them in the request, you can even set more with the response. But you must be on the same domain for any of this to work. Cross domain cookies are disabled for security.
cookies are client side, http://plugins.jquery.com/project/Cookie