Beginner Guide to Understand Cookies and Session Management

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);

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.

A 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.


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.

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

Beginner Guide to Insecure Direct Object References

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.

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 is alive. Through given screenshot it is clear what will be output when host IP will submit.

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

Understanding DOM Based XSS in DVWA (Bypass All Security)

This article is written to bring awareness among all security researchers and developers so that they may be able to learn the level of damage cause by XSS attack if the web server is suffering from cross site scripting vulnerability.

DOM Based XSS (TYPE 0)

The DOM-Based Cross-Site Scripting is vulnerability which appears in document object model instead of html page. An attacker is not allowed to execute malicious script on the user’s website although on his local machine in URL, it is quite different from reflected and XSS because in this attack developer cannot able to find malicious script in HTML source code as well as in HTML response, it can be observed at execution time.

This can make it stealthier than other attacks and WAFs or other protections which are reading the page body does not see any malicious content.

Let’s start!!!
Target: DVWA

Low security

 For this tutorial I had targeted DVWA and explore localhost IP in browser; now login with admin: password into web application and Set security level low.


Select the DOM cross site scripting vulnerability from given list of vulnerability. The web application allows the user to select any language form drop down list.


Now let’s understand current scenario when security is low; in this part the developer has not add any filter while framing the code for web site that could check for any malicious activity. Hence if an attacker opens the website in low security and tries for XSS attack possible he gets successful in his deed.  


The JavaScript code obtains value from the URL parameter “default” and writes the value in the webpage and as the result the web page show English as output. Now attacker will inject following code into URL and send this link to the client through social engineering.


Great!! Now you can check the output in the given screenshot.


Medium Security
Let change the security level from low to medium level


In medium security the developer has tried to add a simple pattern matching to remove any references to "

Beginners Guide to Cross Site Scripting (XSS)

Java Script

JavaScript is the programming language of the web. It's one of the most popular and in demand skills in today's job market for good reason. JavaScript enables you to add powerful interactions to websites

A Scripting Language understood by the browser.
JS is embedded in HTML Pages
The Browser RUNS the js instead of displaying it

The tags.


Event Handler

When JavaScript is used in HTML pages, JavaScript can "react" on these events.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

Onload 

Basically java script uses onload function to load an object on any web page. For example I want to generate an alert for user those who visit my website; I will give the following JavaScript code.


So whenever the body tag loads, an alert will pop up with following text Welcome to Hacking Articles for the visitors. Here the loading of the body tag is an event or a happening and onload is an event handler which decides what will action will happen on that event.

Similarly, there are many JavaScript event handlers which define what event occurs for such type of action like scroll down of page, or when an image fails to load etc.


Onmouseover
Onmouseover, when the user moves his cursor over the text, the additional code will be executed. For example let understand following code:


Now when user moves his cursor over the surprise the displayed text on the page, an alert box will pop up with 50% discount.


onclick:
Use this to invoke JavaScript upon clicking (a link, or form boxes)
onload:
Use this to invoke JavaScript after the page or an image has finished loading
onmouseover
Use this to invoke JavaScript if the mouse passes by some link
onmouseout
Use this to invoke JavaScript if the mouse goes pass some link
onunload
Use this to invoke JavaScript right after someone leaves this page.


Cross Site Scripting (XSS)

XSS is listed as top third web application security risk in the OWASP to top 10 risk model 2017.
Cross-site scripting (XSS) is a flaw in a web application that allows an attacker to execute malicious JavaScript through code injection attack in another victim's browser.

In this attack user is not directly targeted through a payload, although attacker shoot the XSS vulnerability by inserting malicious script into a web page that appears to be a genuine part of the website to the users, whenever any user visit that website it will automatically send the malicious JavaScript code in his browser without his knowledge.

Let’s take an example that following code is XSS vulnerable, an attacker may possibly present a history that holds a malicious payload such as 

Print ""
Print "

Recent History

"
Print request.Recent History print "
"

Users visiting the web page will get the following HTML page without his knowledge.

Recent History




              Types of XSS:

There are actually three types of Cross-Site Scripting, commonly named as:
·         Persistent XSS
·         Non-persistent XSS
·         DOM-Based XSS

Persistent

A persistent XSS also known as stored XSS because through this vulnerability the injected malicious script get permanently stored inside the webserver and the application server give out it back to the user when he visits the respective website. Hence when the client will click on payload which appears as an official part of the website, the injected JavaScript will get execute by the browser. The most common example is comment option on blogs, which allow the users to POST their comment for administer or other user.

Persistent XSS is considered more dangerous because the malicious payload is stored inside web server as the more visitors will interact with the website will result into more XSS infected user. Attack does not require phishing technique to target its users.

Example:
An example of a web application vulnerable to stored XSS as shown in the screenshot.


This JavaScript gets stored in the database of the web application and gets executed on the victim's browser, which capture the cookie and send it to the attacker.



Read complete article from here

Non-Persistent

The non-persistent XSS is also known as reflected XSS is occurs when the web application respond immediately on user’s input without validating the inputs this lead an attacker to injects browser executable code inside the single HTML response. It’s named as “non-persistent” since the malicious script does not get stored inside the web server, therefore attacker will send the malicious link through phishing to trap the user.

The most common applying of this kind of vulnerability is in Search engines in website: the attacker writes some arbitrary HTML code in the search textbox and, if the website is vulnerable, the result page will return the result of these HTML entities.

Example:
An example of a web application vulnerable to reflected XSS as shown in the screenshot.


It is also known as type 1 because this attack is carried out through single request/response then gets executed on the victim's browser, and will prompt an alert “hellllooo” to his browser.


Read complete article from here

DOM-Based:

The Document Object Model (DOM) is an API that increases the skill of programmers or developers to produce and change HTML and XML documents as programming objects.
The JavaScript language is used in DOM, which is also used for other websites. Through JavaScript it allows programmer to make the dynamic changes in HTML document can be accessed, modify, deleted, or added using the DOM.

When an HTML document is loaded into a web browser, it becomes a document object.
The document object is the root node of the HTML document and the "owner" of all other nodes
The HTML DOM model is constructed as a tree of Objects


With the object model, JavaScript gets all the power it needs to create dynamic HTML:

·         JavaScript can change all the HTML elements in the page
·         JavaScript can change all the HTML attributes in the page
·         JavaScript can change all the CSS styles in the page
·         JavaScript can remove existing HTML elements and attributes
·         JavaScript can add new HTML elements and attributes
·         JavaScript can react to all existing HTML events in the page
·         JavaScript can create new HTML events in the page


The DOM-Based Cross-Site Scripting is vulnerability which appears in document object model instead of html page. An attacker is not allowed to execute malicious script on the user’s website although on his local machine in URL, it is quite different from reflected and XSS because in this attack developer cannot able to find malicious script in HTML source code as well as in HTML response, it can be observed at execution time.

The DOM-Based XSS exploits these problems on user’s local machines in this way:
– The attacker creates a well built malicious website
– The ingenious user opens that sites
– The user has a vulnerable page on his machine
– The attacker’s website sends commands to the vulnerable HTML page
– The vulnerable local page execute that commands with the user’s privileges on that machine.
– The attacker easily gain control on the victim computer.


Example:
The following screenshot is an example of a web application server that is affect with DOM based XSS attack. The web application let you to choose the following language and will execute through URL.


Attacker will add malicious script inside URL

http://localhost:81/dvwa/vulnerabilities/xss_d/?default=English#

The major difference between DOM XSS and Reflected or Stored XSS flaw is that it cannot be stopped by server-side filters because anything written after the "#" (hash) will never forward to the server.