How to store session id as foreign key in phpmyadmin - php

I have stores a unique session id in session when user logged in using session_regenerate_id() funciton . Every time user gets loged in in my website he will get a fresh session id.
now i want to save some of his data in a db table. I want to know how should i store data so that the new table gets foreign key from the user id of main table.
Because i want to relate that information with the user id that is stored in main table. I dont want to store main table ID column in session as user_id because of security.
Please all you big developers suggest me a good way in core PHP instead of frameworks.
Developers Will easily understand what i want to ask . I am a bit new :)
THANKS so much
Faysal

When using session, a random string is generated to identify a user - this string is called session ID. Session ID is stored in cookies. Cookies are sent to the web server with every request. On the server, session ID is then connected with session data.
Attacker can't change the session data, therefore, storing a user ID in session is not a security threat.
For cases when an attacker steals someone's session ID, for protection you can check if the user agent and IP address are the same as when session was created. If not, just destroy the session.
To identify a user, you need to connect session with a user. Doing so through a chain of tables in database doesn't provide any security.

Related

PHP - Storing session username or ID preferred?

I'm just wondering, for a PHP session, would it be preferred to store a session variable containing a logged in user's ID or username?
At the moment it stores the username, whereas would ID be safer because to potential "hackers", they may not know which user the ID correlates to?
PHP sessions work by giving an "opaque" cookie to users - that is, the cookie is just a number, and the actual data is stored on your server. When a user sends you the session cookie, PHP looks up the number in a table to retrieve the data you've stored for that user.
This means that it is impossible, without access to your server, for anyone listening over the network to figure out what the session cookie actually means. They would need the table stored on your server. So it really doesn't matter if you store an ID number or a username in the session: if they have enough access to see what's in the session, then they could probably just look up the username based on the ID number anyway.

How to secure User ID inside cookie value

After logined user, I keep user ID inside cookie ($_COOKIE['user_id']) and after this mysql check if isset user_id inside cookie and if user_id is exists in DB:
SELECT * FROM users WEHERE user_id = '$_COOKIE[user_id]'
It works, but cookie value can be changed by every cliend, so client can set cookie user_id to 1 or 2,3,4 and it will be loggined, So they can hack page.
I want to hash or secure somehow my cookie user_id value. I hope you understand me.
Can you give me any suggestions?
Do not do that in a cookie. Save a hash in the cookie and store the corresponding user id in your database. You can't make the cookie secure.
To be more clear:
When the user logs in, store a unique hash for him in the database. This could be something like that: sha512('9a7fd98asf'.time().$username). This is the value you save in the cookie, too. You know the user is logged in, if he has such a token in the database and if it matches the value from the cookie. This actually is how sessions are handled.
Cookies are prone to numerous types of attacks including someone stealing a cookie from one user and presenting it later to impersonate that user. If you were to instead use sessions, you would either have to use session cookies or URL, both of which are problematic from a security point of view.
The best you could possibly do is encrypt the cookie so you can later decrypt it when you read the user_id. This will ensure that a user cannot randomly change their user_id. However, this does not protect against one user using the data from the cookie of another user.
To guard both against reply attacks (either by the same user, or by a different user), in addition to storing the user_id, you would also want to store the expiry time in the cookie. When you get back the cookie, you can decrypt and also get the time that you need. This does mean though that this type of replay attack is possible within that time during which cookie is valid.
For encryption/decryption, you can search and find how to correctly do it using the language you are employing. You will still have to test against corrupted cookies (in which case you can assume user is not authenticated).
You want to use a meaningless token. That's the most secure way, because the token is inherently meaningless and cannot be attacked in itself. Because the token also needs to be stored on the server with associated data, this also gives the server the ultimate control over logins; because the server can revoke active tokens at any time (you cannot revoke a cookie which stores just a self-contained user id).
A standard PHP session is such a meaningless token and works just fine for most cases. Sessions can even be configured to last extremely long, and you can even change the session storage backend to a database or any custom backend you want.
If, for whatever reason, you need something else, you still want the same idea:
generate a completely random, meaningless value
store it in a database, together with what user it belongs to
send the token in a cookie to the client
You could store an additional cookie, named 'user_hash':
$_COOKIE['user_hash']=sha1($user_id . md5($user_pass . $salt1) . $salt2);
Using some constant $salt values.
When using the user_id cookie, first check if user_hash matches the user login information stored in the database.
Since the sha1 is irreversible, the password cannot be derived from it.

Best way to keep track of logged in user information

I have built multiple sites already using PHP that allow users to log in and keeps their user id and username in session variables. I keep learning more about security and I want to check up on what the safest way is to store user information.
I am currently working on a user account page which allows users to view and edit their profile information. Currently the site does a simple MySQL query that pulls the users information from the database based on what the id stored in the session is.
Example:
$getUserInfoSQL = $connection->prepare("SELECT * FROM Accounts WHERE id = ?");
$getUserInfoSQL->bind_param("s",$userid);
$getUserInfoSQL->execute();
I just want to make sure its not reckless to provide user information just based on the session variable userid.
You can easily use a session to store userdata, as the session contents are stored on YOUR server. However, storing userdata in a session can cause some problems:
If you e.g. ban a user, the session would still be active, and the user could browse your site, even though it is not in the database
If a user is logged in on two machines (e.g. a computer and smartphone), and changes userdata on one device, you'd have to update the session on the device they're changing the userdata from, but then the other session contains outdated info.
Server restarts can wipe session data
Using session variables should be safe enough. The session data in kept on the server and the only thing stored locally on the user's end is the session ID.
PHP stores the session data in a file on the server, but you can store it in the database as well. It's a bit faster and should be safer as well. — Check out the answer by RobertPitt at https://stackoverflow.com/a/2950504/859999 to find out how to store session data in the database.

PHP Storing Current Session IDs in Database using Cookies

I've created a login system that uses cookies and stores a session ID in a database, so your login will only work with that particular session ID. I realise this has a few problems:
If you login on another device the session ID changes (no multi logins)
The session ID is really the only thing identifying the user as logged in (I'm not really sure if this is a security risk since the cookie is domain specific)
However I want to retain the persistant login that comes with cookies while still keeping stuff secure.
Effectively I want to know if there is a better way to securely log a user into a website using cookies.
First of all, keeping stuff secure and persistent logins don't go together; you will always compromise security by introducing persistent logins in some way.
Having said that, an article from Charles Miller outlines such a system:
create a (big enough) random key, preferably by using /dev/urandom or openssl_random_pseudo_bytes() and associate it with an account (in database terms: a separate table with the random key as the primary (or unique) index and the account as a foreign key); the key will be the cookie value.
when a non-logged in user presents a cookie, the key and account are looked up and the user is logged in; afterwards, the used key is replaced with a new random key (cookie is updated too).
users who are logged in via cookie alone should be asked for their password again when they access sensitive (account) information.
the user should have an option to log out from all his devices.
It's also a good practice to use a renew the session id using session_regenerate_id() whenever a user is logged in (either via a form or cookie). This prevents someone from launching a session fixation attack against someone else and possibly steal their identity.
An improvement on this design by Barry Jaspen that can also handle identify theft detection can be found here.

PHP & MySQL username storage and cookie

How to securely store usernames in database, without adding them directly to cookie value?
Example:
I want to display username of logged user.
If he have closed his browser early the only way to do this is $_COOKIE['cookie name']
where cookie value links with username in database.
So I don' t need to hash username.
Is it right? And if it's right, is it secure?
It is secure. Just do not store the password on the client (browser). Also never send the password to the browser.
You can store the username in the cookie, this is safe as long as you do not save the password there.
You can also save there user id, then it does not give away any of the authentication details while letting you find the correct user.
Use sessions. data stored in $_SESSION is stored on server, not on client.
The below is assuming you are talking about a persistent login feature using cookies. For the purpose of just remembering the user name (but not signing them in automatically), having a username in the cookie (optionally encoded) should be okay though. Regardless, passwords should never be in the cookie.
Cookies should NOT be directly identifying, i.e. user ids / names should not appear in the cookie. Instead, you should assign a sufficiently long enough string with random data to the users in your table and store that in the cookie value. Once used you should update the string and issue another cookie.
For example:
john | ewojroj1234ojqewor
jack | ljqwelkn1k31n23k33
The second column will be placed in the cookie. Later you will query that value against the user table and:
fetch the user data and store inside a session
regenerate the random string
issue another cookie
Password changes and signing out should also cause a change in the user token string.
For further reading, Barry Jaspan wrote a good article on this approach.
The best way to do it is to store only the user_id (the uniquely identifying primary key) of the user table in the $_COOKIE or $_SESSION variable - perhaps in $_COOKIE['user_id'].
Then on each page load, you can use that id to retrieve any user information you wish from the database. For example (Note this is conceptual/psuedo-code only. You would of course sanitize/clean/validate/bind the $_COOKIE or $_SESSION data parameter first):
SELECT * FROM user_table WHERE user_id = $_COOKIE['user_id']

Categories