Skip to content

Session Management Attacks – Part One

First, before I get to the main topic of this article – session management – I will start by introducing some facts about sessions and why they are needed.

Hypertext Transfer Protocol (HTTP) is a stateless protocol!

This means multiple requests can be sent through one HTTP connection; requests are executed independently. 

The server is not attaching any additional information to the requests, so each request cannot know of the requests which are executed before. Once the transaction is terminated, the connection between the browser and the server is lost.

Historically, web used stateless protocol because the goal was to allow web pages to be served to many people using basic hardware as a server. If the connection was maintained for a long time, that would be very resource expensive.

Flow of an HTTP GET file:

– Request it made to get the file via URL

– File is returned in the response

– Connection disconnects

 

What is a session?

The session is a sequence of HTTP requests and transactions initiated by the user. 

 

What is session management?

Session management is the management of sessions between the web application and the users. Usually, web applications assign each user a specific session ID. Session IDs are used to uniquely identify the user, to maintain the state of the user and the state of the required web server so it can “remember” which user it is communicating with. Sessions are maintained by the server, and the session ID is sent with each request user makes.

This picture, which is taken from https://thecyphere.com/, gives a simple explanation of session management:

Solution for storing user data between HTTP requests:

In web applications, you need to find a way to store data between HTTP requests to associate one request with the other. Most often, developers use cookies and URLs to transfer the data. If you have sensitive data or you don’t want it to be visible in the UI, the best way to store it is in the session. As I mentioned before, in session management, the solution would be to provide each user session ID to maintain the data. 

 

Session cookies

Session ID needs to be stored somewhere, and cookies are often used for storage.

So, we have session ID, for example, SESSID=asdsadsa123456789, and we will store it in a cookie. Developers often set a short life for the session, which is automatically deleted if unused for some time (like 20 minutes).

Session management can use two types of cookies, non-persistent cookies, and persistent cookies. Non-persistent are also called session cookies. Persistent cookie will be the one which presents Max-Age or Expires attributes, and it is going to be stored on disk by the web browser until the expiration time.

 

Session Management Attacks

For the attackers to successfully perform the attack, they first need to explore how the application manages session IDs. After the user authenticates themselves with a known session ID, the target is to hijack the user-validated session with the session ID.

 

What is a cookie?

Wikipedia’s definition of a cookie is” A cookie is a baked or cooked snack or dessert that is typically small, flat, and sweet.”

But unfortunately, the definition of the cookie in the computer world is not so sweet.

A cookie is just a text file saved on the user’s computer. Maximum size of a cookie is 4KB. Other names of this type of cookie would be HTTP cookie, web cookie, etc.

How is it created?

When a user first visits a website, the site sends data packets to the user’s computer in the form of a text file, a so-called cookie.

*Very important to mention cookies are less safe than sessions because third-party can manipulate content in them. Whereas sessions are considered safer because they are stored in an encrypted form that only the user can read.

 

Implementation of cookie service in Angular

First, do nmp install of ngx package: npm i ngx-cookie-service 

Documentation of this package can be found here; also, if you need to check out older

versions: https://www.npmjs.com/package/ngx-cookie-service                  

Second, import the service in the app module:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  ...
    providers:
[CookieService],
...
})
export class AppModule {
}

You will also see in the documentation that it is easily used; just import in the class, inject in the constructor, and then you can use all methods from the cookie service.

constructor(private cookieService: CookieService)
{
  this.cookieService.set(Cookie1, 'Cookie value');
  this.cookieValue = this.cookieService.get('Cookie1');
}

Methods you can use from the cookie service:

  • check (checks cookie name)

  • get

  • getAll (returns cookie name, value, expires, path, domain, secure)

  • set (sets value: name, path, domain)

  • delete

  • deleteAll

 

How to implement Session Storage in Angular?

There is some confusion regarding the difference between session and local storage. The quick explanation is that data in session storage is lost when the browser closes and data in local storage remains until the browser cache is cleared. For a more detailed explanation, you can check out this site.

So, session storage is part of the web API, which stores ‘key’ – ‘value’ pairs. It can be accessed by the client side only, not by the server, to eliminate the security threat cookies present. 

As for implementation concerns, the best approach is to create the class with some helper methods, such as store and retrieveObject. I named that class SessionStorageManager.

import { Injectable } from "@angular/core";
 
@Injectable()
export class SessionStorageManager {
  readonly roles: string = "roles";
  readonly tenantsSettings: string = "tenantsSettings";
 
  store(key: string, content: Object) {
    sessionStorage.setItem(key, JSON.stringify(content));
  }
 
  private retrieve(key: string) {
    let storedItem: string = sessionStorage.getItem(key);
    if (!storedItem)
      throw No object with key ${key} found in the session storage!;
    return storedItem;
  }
 
  public retrieveObject(key: string) {
    let object = null;
    try {
      object = JSON.parse(this.retrieve(key));
    } catch (err) {
      console.error(err);
    }
    return object;
  }
}

As you can see, we can import this class into other classes that will store or retrieve items.

SessionStorage already has two methods: get and set item.

After we created the class SessionStorageManager, we need to add it also in app.module.ts, in providers.

As I mentioned, we can use it in any class we need to set or get data. For example, if we use Role Guard (if you want to check out its implementation, check out my article about IDOR), we can retrieve roles previously stored when the user logs in. When a user logs in from the API, we get their roles, and then we use SessionStorageManager and method store. So, in Role Guard, we can use SessionStorageManager and the method retrieveObject.

Store method in role service: 

  public loadUserRoles(): void {
    this._roleService.getEntity("/roles").pipe(
      delay(1),
    ).subscribe((data) => {
      this.userRoles = data;
      this._sessionStorage.store(
        this._sessionStorage.roles,
        data
      );
    });
  }

Retrieve method:

 let assignedRoles = this._sessionStorage.retrieveObject(
      this._sessionStorage.roles
 );

The data will be available until the browser closes!

Conclusion

In this article, I explained the best practice for implementing session management, whether it would be the implementation of session storage or cookie service in Angular.

There are many ways to write more secure code to prevent this attack from happening and hackers from succeeding, but first, it is important to choose the right way to set up session management!

In the next part of Session Management attacks article, I will write more about what you should pay attention to while implementing secured session management.

In the end, secure code is the cheapest code!

 

#session_management #session_cookies #cookie_service 

Cover photo by Mae Mu

About Version 2 Limited
Version 2 Limited is one of the most dynamic IT companies in Asia. The company develops and distributes IT products for Internet and IP-based networks, including communication systems, Internet software, security, network, and media products. Through an extensive network of channels, point of sales, resellers, and partnership companies, Version 2 Limited offers quality products and services which are highly acclaimed in the market. Its customers cover a wide spectrum which include Global 1000 enterprises, regional listed companies, public utilities, Government, a vast number of successful SMEs, and consumers in various Asian cities.

About Topia
TOPIA is a consolidated vulnerability management platform that protects assets in real time. Its rich, integrated features efficiently pinpoint and remediate the largest risks to your cyber infrastructure. Resolve the most pressing threats with efficient automation features and precise contextual analysis.