Asked  2 Years ago    Answers:  5   Viewed   75 times

Currently when user logged in, i created 2 sessions.

$_SESSION['logged_in'] = 1;
$_SESSION['username']  = $username; // user's name

So that, those page which requires logged in, i just do this:

// Do whatever I want

Is there any security loopholes? I mean, is it easy to hack my session? How does people hack session? and how do I prevent it??


Just found this:

Just found the links, are those methods good enough?? Please give your opinions. I still have not get the best answer yet.




  • User: A visitor.
  • Client: A particular web-capable software installed on a particular machine.

Understanding Sessions

In order to understand how to make your session secure, you must first understand how sessions work.

Let's see this piece of code:


As soon as you call that, PHP will look for a cookie called PHPSESSID (by default). If it is not found, it will create one:


If it is found, it takes the value of PHPSESSID and then loads the corresponding session. That value is called a session_id.

That is the only thing the client will know. Whatever you add into the session variable stays on the server, and is never transfered to the client. That variable doesn't change if you change the content of $_SESSION. It always stays the same until you destroy it or it times out. Therefore, it is useless to try to obfuscate the contents of $_SESSION by hashing it or by other means as the client never receives or sends that information.

Then, in the case of a new session, you will set the variables:

$_SESSION['user'] = 'someuser';

The client will never see that information.

The Problem

A security issue may arise when a malicious user steals the session_id of an other user. Without some kind of check, he will then be free to impersonate that user. We need to find a way to uniquely identify the client (not the user).

One strategy (the most effective) involves checking if the IP of the client who started the session is the same as the IP of the person using the session.

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];

// The Check on subsequent load
if($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) {
    die('Session MAY have been hijacked');

The problem with that strategy is that if a client uses a load-balancer, or (on long duration session) the user has a dynamic IP, it will trigger a false alert.

Another strategy involves checking the user-agent of the client:

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['agent'] = $_SERVER['HTTP_USER_AGENT'];

// The Check on subsequent load
if($_SESSION['agent'] != $_SERVER['HTTP_USER_AGENT']) {
    die('Session MAY have been hijacked');

The downside of that strategy is that if the client upgrades it's browser or installs an addon (some adds to the user-agent), the user-agent string will change and it will trigger a false alert.

Another strategy is to rotate the session_id on each 5 requests. That way, the session_id theoretically doesn't stay long enough to be hijacked.

if(logging_in()) {
    $_SESSION['user'] = 'someuser';
    $_SESSION['count'] = 5;

// The Check on subsequent load
if(($_SESSION['count'] -= 1) == 0) {
    $_SESSION['count'] = 5;

You may combine each of these strategies as you wish, but you will also combine the downsides.

Unfortunately, no solution is fool-proof. If your session_id is compromised, you are pretty much done for. The above strategies are just stop-gap measures.

Friday, August 5, 2022

Read OWASP A3-Broken Authentication and Session Management. Also read about OWASP A5-CSRF, which is sometimes called "session riding".

You should use this code in a php header file:


This code prevents session fixation. It also helps protect against xss from access document.cookie which is one way that Session Hijacking can occur. Enforcing HTTPS only cookies is a good way of addressing OWASP A9-Insufficient Transport Layer Protection. This way of using HTTPS is sometimes called "secure cookies", which is a terrible name for it. Also STS is a very cool security feature, but not all browsers support it (yet).

Tuesday, December 6, 2022

You can extend the official ngnix to build the dynamic modules then load them in nginx:

# syntax=docker/dockerfile:experimental
FROM nginx:${NGINX_VERSION} as build

RUN apt-get update && 
    apt-get install -y 
        make && 
    rm -rf /var/cache/apt

RUN wget "${NGINX_VERSION}.tar.gz" && 
    tar -C /usr/src -xzvf nginx-${NGINX_VERSION}.tar.gz

RUN mkdir -p -m 0600 ~/.ssh && 
    ssh-keyscan >> ~/.ssh/known_hosts

WORKDIR /src/ngx_devel_kit
RUN --mount=type=ssh git clone [email protected]:simpl/ngx_devel_kit .

WORKDIR /src/set-misc-nginx-module
RUN --mount=type=ssh git clone [email protected]:openresty/set-misc-nginx-module.git .

WORKDIR /usr/src/nginx-${NGINX_VERSION}
RUN NGINX_ARGS=$(nginx -V 2>&1 | sed -n -e 's/^.*arguments: //p') 
    ./configure --with-compat --with-http_ssl_module --add-dynamic-module=/src/ngx_devel_kit --add-dynamic-module=/src/set-misc-nginx-module ${NGINX_ARGS} && 
    make modules


COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/nginx-${NGINX_VERSION}/objs/ /usr/src/nginx-${NGINX_VERSION}/objs/ /usr/lib/nginx/modules/

Note: this example is a multi-staged build that uses the docker build enhancements to clone the repositories (depending on your version of docker you may have to enable experimental features).

You can load the modules in the nginx.conf that's copied in the final image:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/;

load_module /usr/lib/nginx/modules/;
load_module /usr/lib/nginx/modules/;

events {
    worker_connections  1024;

http {

Build the image: DOCKER_BUILDKIT=1 docker build --rm --ssh=default --build-arg NGINX_VERSION=1.17.3 --network host -t so:57739560 .

Run the container: docker run --rm -it -p 80:80 so:57739560

For another example of building dynamic modules using the official nginx image you can check out my nginx-modsecurity repo (nginx image extended with Modsecurity and Modsecurity-nginx).

Thursday, September 22, 2022

Session security risks come from three different possibilities:

  • Prediction
  • Capture
  • Fixation

Prediction would mean that someone that's not the user for whom the session was created guessed their session ID. The chances of that happening are almost 0, although they do grow as more users use the site simultaneously.

With your code, you would make that risk even lower because it would only work if the attacker shared the user agent and the ip of the predicted session. But the difference is trivial in this case.

Fixation would mean that an attacker can create a session and then force another user into using their session. In this case it would depend: If the attacker knows that you are doing it and they fake the user agent and ip of the client, they could fixate the session. Or if they share ip and user agent.

And finally we have session hijacking, probably the most common method of the three. In this case an attacker would somehow gain access to the session id of a valid logged in user, and then use it to log in to their account. As with the previous method, this would only work for them if they know that you are checking the ip and user agent, and faked the same ones as the user. The technique you are using is not unique, and some attackers might fake them just in case.

That being said, is it secure? Yes and no

If you are obsessed with security, the answer is always the same: Use SSL

Unless your code is open source, almost anything you do that changes the behavior of the php sessions will be secure enough.

The only exception to that would be really popular sites that will attract the attention of hackers.

There is some very good documentation on this topic available:

  • PHP Session Security
Wednesday, September 21, 2022

What happens if you use the <pre> tag to display HTML markup on your blog:

<pre>Use a <span style="background: yellow;">span tag with style attribute</span> to hightlight words</pre>

This will pass HTML validation, but does it produce the expected result? No. The correct way is:

<pre>Use a &lt;span style=&quot;background: yellow;&quot;&gt;span tag with style attribute&lt;/span&gt; to hightlight words</pre>

Another example: if you use the pre tag to display some other language code, the HTML encoding is still required:

<pre>if (i && j) return;</pre>

This might produce the expected result but does it pass HTML validation? No. The correct way is:

<pre>if (i &amp;&amp; j) return;</pre>

Long story short, HTML-encode the content of a pre tag just the way you do with other tags.

Tuesday, December 27, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages