Beginner Guide to Understand Cookies and Session Management

From Wikipedia and w3schools

Cookie

Cookie is a small piece of data sent by a server to a browser and stored on the user’s computer while the user is browsing. Cookies are produced and shared between the browser and the server using the HTTP Header.

It Allows server store and retrieve data from the client, It Stored in a file on the client side and maximum size of cookie that can stored is limited upto 4K in any web browser. Cookies have short time period because they have expiry date and time as soon as browser closed.

Example- when you visit YouTube and search for Bollywood songs, this gets noted in your browsing history, the next time you open YouTube on your browser, the cookies reads your browsing history and you will be shown Bollywood songs on your YouTube homepage

Creating cookie

The setcookie() function is used for the cookie to be sent along with the rest of the HTTP headers.

When developer creates a cookie, with the function setcookie, he must specify atleast three arguments. These arguments are setcookie(name, value, expiration);

Image Source Goolge

Cookie Attributes

  1. Name: Specifies the name of the cookie
  2. Value: Specifies the value of the cookie
  3. Secure: Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE
  4. Domain: Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to “example.com”. Setting it to www.example.com will make the cookie only available in the www subdomain
  5. Path: Specifies the server path of the cookie. If set to “/”, the cookie will be available within the entire domain. If set to “/php/”, the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in
  6. HTTPOnly: If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE
  7. Expires: Specifies when the cookie expires. The value: time ()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0

Necessity of Cookies

Cookies can be used for various purposes –

  • Identifying Unique Visitors.
  • Http is a stateless protocol; cookies permit us to track the state of the application using small files stored on the user’s computer.
  • Recording the time each user spends on a website.

Type of cookies

Session Cookie

This type of cookies dies when the browser is closed because they are stored in browser’s memory. They’re used for e-commerce websites so user can continue browsing without losing what he put in his cart. If the user visits the website again after closing the browser these cookies will not be available. It is safer, because no developer other than the browser can access them.

Persistent Cookie

These cookies do not depend on the browser session because they are stored in a file of browser computer. If the user closes the browser and then access the website again then these cookies will still be available. The lifetime of these cookies are specified in cookies itself (as expiration time). They are less secure.

Third Party Cookie

A cookie set by a domain name that is not the domain name that appears in the browser address bar these cookies are mainly used for tracking user browsing patterns and/or finding the Advertisement recommendations for the user.

Secure Cookie

A secure cookie can only be transmitted over an encrypted connection.  A cookie is made secure by adding the secure flag to the cookie. Browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page.

HTTP Only Cookie

It informs the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly prohibited. This is an important security protection for session cookies.

Zombies Cookie

A zombie cookie is an HTTP cookie that is recreated after deletion. Cookies are recreated from backups stored outside the web browser’s dedicated cookie storage.

Sessions

PHP session: when any user made any changes in web application like sign in or out, the server does not know who that person on the system is. To shoot this problem PHP session introduce which store user information to be used across several web pages.

Session variables hold information about one single user, and are exist to all pages in one application.

Example: login ID user name and password.

Session ID

PHP code generates a unique identification in the form of hash for that specific session which is a random string of 32 hexadecimal numbers such as 5f7dok65iif989fwrmn88er47gk834 is known as PHPsessionID.

session ID or token is a unique number which is used to identify a user that has logged into a website. Session ID is stored inside server, it is assigns to a specific user for the duration of that user’s visit (session). The session ID can be stored as a cookie, form field, or URL.

Explanation:

Now let’s have a look over this picture and see what this picture says:

In given picture we can clearly see there are three components inside it: HTTP Client, HTTP server and Database (holding session ID).

Step1: client send request to server via POST or GET.

Step2: session Id created on web server. Server save session ID into database and using set-cookie function send session ID to the client browser as response.

Step3: cookie with session ID stored on client browser is send back to server where server matches it from database and sends response as HTTP 200 OK.

Image Source: Google Images

Session hijacking

As we know different users have unique session ID when an attacker sniff the session via man-in-middle attack or via XSS and steal session ID or session token this is called session hijacking. When attacker sends the stealing session ID to web server, server match that ID from database stored session ID. If they both matched to each other then the server reply with HTTP 200 OK and attacker get successfully access without submitting proper Identification.

Example 1: Using the session cookies issued to the user by the server.

For example, on any website an official user logged-in, and the server has generate a session cookie SESSION-TOKEN for that user. If the SESSION-TOKEN is the cookie which recognized the session of that user, the attacker can steal the SESSION-TOKEN cookie value to login as the legitimate user. The attacker can perform a cross-site scripting or other technique to steal the cookie from the victim’s browser.

Let’s suppose the attacker steals the cookie PHPSESSID=user-raj-logged-in-2341785645. Now, he can use the cookie with the following request to post a status (HACKED!!!!!!) in the victim’s home page:

 POST /home/post_status.php HTTP/1.1

Host: www.Facebook.com

Cookie: PHPSESSID=user-raj-logged-in-2341785645

Content-Length:38

Content-Type:application/x-www-form-urlencoded

 Status= HACKED!!!!!&Submit=submit

The attacker uses the cookie subjected to the authorized user, and gains control on the user’s session.

Example 2: Guessing the cookie values of users if a complicated algorithm is not used for the cookie generation.

For example, consider a website uses an algorithm to generate cookies for the users. If the user name is “raj”, then the cookie generated for the user could be “LOGINID=-772017- qszbik”. In this case, the algorithm used to generate the cookie can be as follows:

First part of the cookie is the date i.e. 7/7/2017 and second part is the arrangement of the previous and next alphabet letter for each letter of the username “John” (i.e., the previous letter for r is “q” and the following letter is “s”). If the attacker is able to break the algorithm, he might estimate the cookie of users and hack their session.

  r=qs

  a=zb

  j=ik

If the attacker decide to hack the session of admin, he can make a cookie as LOGINID =772017- zbcelnhjmo, login to raj’s session and post a status on his account.

Host: www.facebook.com

Cookie:LOGINID =772017- zbcelnhjmo

Content-Length:45

Content-Type:application/x-www-form-urlencoded

 Todays_status=I am hacked!!!!!!&Submit=submit

Session hijacking tutorial

For this tutorial I have targeted DVWA, here cookie name is dvwa Session.

Note: session ID for this page will change every time when we will close the browser.

Now capture the browser request using burp suite.

From given image we can see the cookie holds PHPSESSID P38kq30vi6arr0b321p2uv86k0; now send this intercepted data into repeater to observe its response.

In response you can see the highlighted data show set –cookie: dvwaSession =1 more over HTTP 200 OK response from server side.

According to developer each time a new sessionID will generate by server each time, but attacker sniff this session ID P38kq30vi6arr0b321p2uv86k0 for unauthorized login.

Next time we receive another session id when data is intercepted through burp suite i.e. PHPSESSID= gutnu601knp4qsrgfdb4ad0te3, again send this intercepted data into repeater to observe its response.

But before we perceive its response, replace new PHPSESSID from old PHPSESSID.

From given image you can observe we have replaced the SESSION ID and then generate its response in which set –cookie: dvwaSession =6 and HTTP 200 OK response from server side.  

Now change the value inside intercepted data and then forward this request to the server.

Session Vs cookies

Session Cookies
Data are stored on Server Data are stored in Client’s Browser
Sessions Data are more secure because they never travel on every HTTPRequest Travel with each and Every HTTP request
You can store Objects (Store Large Amount of Data) You can store strings type (Max File Size 4 kb)
Session Cannot be used for Future Reference Cookies are mostly used for future reference

Author: AArti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

Beginner Guide to Insecure Direct Object References (IDOR)

Insecure Direct Object References (IDOR) has been placed fourth on the list of OWASP Top 10 Web application security risks since 2013. It allows an authorized user to obtain the information of other users, and could be establish in any type of web applications. Basically it allows requests to be made to specific objects through pages or services without the proper verification of requester’s right to the content.

OWASP definition: Insecure Direct Object References allow attackers to bypass authorization and access resources directly by modifying the value of a parameter used to directly point to an object. Such resources can be database entries belonging to other users, files in the system, and more. This is caused by the fact that the application takes user supplied input and uses it to retrieve an object without performing sufficient authorization checks.

The Application uses untested data in a SQL call that is accessing account information.

Let consider a scenario where a web application allow the login user to change his secret value.

Here you can see the secret value must be referring to some user account of the database.

Currently user bee is login into web server for changing his secret value but he is willing to perform some mischievous action that will change the secret value for other user.

Using burp suite we had captured the request of browser where you can see in the given image login user is bee and secret value is hello; now manipulate the user from another user.

SQLquery = “SELECT * FROM useraccounts WHERE account = ‘bee’;

Now let’s change user name into raj as shown in given image. To perform this attack in an application it requires atleast two user accounts.

SQLquery = “SELECT * FROM useraccounts WHERE account = ‘raj’;

Great!!!  We have successfully changed the secret value for raj.

Note: in any official website the attacker will replace user account from admin account.

Let take another scenario that look quite familiar for most of IDOR attack.

Many times we book different order online through their web application for example bookmyshow.com for movie ticket booking.

Let consider same scenario in bwapp for movie ticket booking, where I had book 10 tickets of 15 EUR for each.

Now let’s confirm it and capture the browser request through burp suite.

Now you can see we have intercepted request where highlighted text contains number of tickets and price of one ticket i.e 15 EUR it means it will reduce 150 EUR from my (user) account; now manipulate this price from your desire price.

I had changed it into 1 EUR which means now it will reduce only 10 EUR from account, you can observe it from given image then forward the request.

Awesome!!! We had booked the 10 tickets in 10 EUR only.

Author: AArti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

Beginner Guide to OS Command Injection

The dynamic Web applications may make the most of scripts to call up some functionality in the command line on the web server to process the input that received from the client and unsafe user input may led to OS command injection.  OS Command injection is refer as shell injection attack arise when an attacker try to perform system level commands through a vulnerable application in order to retrieve information of  web server or try to make unauthorized access into server .

Impact Analysis

Impact: Critical

Ease of Exploitability: Medium

Risk Rating: High

In this attack the attacker will inject his unwanted system level command so that he can fetch the information of web server; for example: ls , whoami , uname -a and etc.

Let’s consider a scenario where web application allows user to PING an IP other user so that it get confirms that the host connection 

Verify parameters to inject data

 The following parameters should be tested for command injection flaws, as the application may be using one of these parameters to build a command back at the web server:

  • GET: In this method input parameters are sent in URLs.
  • POST: In this method, input parameters are sent in HTTP body.
  • HTTP header: Applications frequently use header fields to discover end users and display requested information to the user based on the value in the headers.

Some of the important header fields to check for command injection are:

  • Cookies
  • X-Forwarded-For
  • User-agent
  • Referrer

METACHARACTER

Using vulnerability scanner attacker come to know that current web application is vulnerable to command injection and try injecting system level unwanted command using Meta character.

Metacharacter are symbolic operators which are use to separate actual command from unwanted command. The ampercent (&) was used as a separator that would divide the authentic input and the command that you are trying to inject.

It will more clear in following image where attacker will inject his payload dir using metacharacter that retrieve present directory of web server.  

As result it will dump following output as shown in given image where it has validated wrong user input.

OS Command Injection Operators

 The developer possibly will set filters to obstruct the some metacharacter. This would block our injected data, and thus we need to try out with other metacharacters too, as shown in the following table:

Operators Description
; The semicolon is most common metacharacter used to test an injection flaw. The shell would run all the commands in sequence separated by the semicolon.
& It separates multiple commands on one command line. It runs the first command then the second command.
&& It runs the command following  && only if the preceding command is successful
||(windows) It run the command following || only if the preceding command fails. Runs the first command then runs the second command only if the first command did not complete successfully.
|| ( Linux) Redirects standard outputs of the first command to standard input of the second command
The unquoting metacharacter is used to force the shell to interpret and run the command between the backticks. Following is an example of this command: Variable= “OS version `uname -a`” && echo $variable
() It is used to nest commands
# It is used as command line comment

Steps to exploit – OS Command Injection

Step 1: Identify the input field

Step 2: Understand the functionality

Step 3: Try the Ping method time delay

Step 4: Use various operators to exploit OS command Injection

Type of Command Injection

 Error based injection: When attacker injects a command through an input parameter and the output of that command is displayed on the certain web page, it proof that the application is vulnerable to the command injection. The displayed result might be in the form of an error or the actual outcomes of the command that you tried to run. An attacker then modifies and adds additional commands depending on the shell the web server and assembles information from the application.

Blind based Injection: The results of the commands that you inject will not displayed to the attacker and no error messages are returned it similar as blind SQL injection. The attacker will use another technique to identify whether the command was really executed on the server.

Mitigation-OS Command Injection

  • Strong server side validation
  • Implement a white list
  • OS Hardening
  • Use build in API’s for interacting with the OS if needed. More secure!!
  • Avoid applications from calling out directly the OS system commands

Author: AArti Singh is a Researcher and Technical Writer at Hacking Articles an Information Security Consultant Social Media Lover and Gadgets. Contact here

Understanding the HTTP Protocol

HTTP (Hyper Text Transfer Protocol) is basically a client-server protocol, wherein the client (web browser) makes a request to the server and in return the server responds to the request. The response by the server is mostly in the form of HTML formatted pages. HTTP protocol by default uses port 80, but the web server and the client can be configured to use a different port.

HTTP is a stateless protocol which means that server does not retain the information by each user. HTTP is the backbone of the World Wide Web (www) and for it being stateless simply means that it does not remember each and every client that connects to the internet and it does not matter if a single user sends multiple requests one after another, they all will still be treated as independent requests by the server.

We are currently using HTTP 2, its predecessors were HTTP 1.0 and 1.1, and the major differences between 1.X and 2, at a higher level, are:

  • Http 2 is binary and not textual
  • Http 2 is multiplexed, it can use a single connection for parallelism, Http one on the other hand is based on ordering and blocking.
  • Http 2 uses compression in its headers to reduce the overhead.
  • Http2 gives servers the capability to “push” responses to client servers proactively.

HTTP works through different methods and these methods are:

HTTP Request Methods

Method Description
GET Used to retrieve information from the given URL
POST Used to send data to the server, for example, customer information, file upload, etc. using HTML forms
DELETE Delete a File of the specified URL
PUT Uploads a File of the specified URL
TRACE Trace on the jsp resource returns the content of the resource.
HEAD GET only HTTP headers and no document body
OPTIONS HTTP methods that the server supports

There is major difference between GET and POST method which people fail to understand. Once you understand these properly, you can manipulate and increase the security of your web application. The differences are as follows:

GET POST
Get request can be cached Post request are never cached
Remain in browser history Do not remain in browser history
It can be bookmarked It cannot be bookmarked
Get request should never be used when dealing with sensitive data Post should always be used for sensitive data
Get request has length restriction post request have no length restriction
Get request should be used to retrieve data
It is less secure It is more secure

An HTTP client sends an HTTP request to a server in the form of a request message which includes following format

http://yahoo.com/

GET / HTTP/1.1

Host: yahoo.com

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Connection: keep-alive

Upgrade-Insecure-Requests: 1

There are several fields in the header, but we will discuss the more important ones:

Host: This field is in the header and it is used to identify individual website by a hostname if they are sharing the same IP address. The client web browser also sets a user-agent string to identify the type and version of the browser.

User-Agent: This field is set correctly to its default values by the web browser, but it can be spoofed by the end user. This is usually done by malicious user to retrieve contents designed for other types of web browsers.

Cookie: This field stores a temporary value shared between the client and server for session management.

Referer: This is another important field that you would often see when you are redirected from one URL to another. This field contains the address of the previous web page from which a link to the current page was followed. Attackers manipulate the Referer field using an XSS attack and redirect the user to a malicious website.

Accept-Encoding: This field defines the compression scheme supported by the client; gzip and Deflate are the most common ones. There are other parameters too, but they are of little use to penetration testers.

Response

Response: When a request is sent to the server; the server replies in the form of response. Following is an example of response:

HTTP/1.1 200 OK

Date: Sat, 10 Jun 2017 05:17:18 GMT

Set-Cookie: autorf=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/;

domain=in.yahoo.com

Content-Type: text/html; charset=UTF-8

Server: ATS

Expires: -1

Content-Length: 477864

HTTP Response Code: The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit

Code Meaning Example
1xx Information 100: server agrees to handle client request.
2xx Success 200: request succeeded.

204: no client present.

3xx Redirection 301: page moved.

304: cached page still available.

4xx Client error 403: forbidden page.

404: page not found.

5xx Server error 500: internal server error.

503: try again later.

HTTP Version: A server supporting HTTP version 1.1 will return the following version information

 Date: The date and time that the message was originated

 Set-Cookie: This field, if defined, will contain a random value that can be used by the server to identify the client and store temporary data

Server: This field is of interest to a penetration tester and will help in the recon phase of a test. It displays useful information about the web server hosting the website.
Content-Length: This field will contain a value indicating the number of bytes in the body of the response. It is used so that the other party can know when the current request/response has finished.

Source:
https://www.tutorialspoint.com/http/index.htm

https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
https://www.httpwatch.com/httpgallery/

AuthorYashika Dhir is a passionate Researcher and Technical Writer at Hacking Articles. She is a hacking enthusiast. contact here.

Related Posts Plugin for WordPress, Blogger...