Our social:

Latest Post

Saturday, August 30, 2014

Preventing SQL Injection attack ASP.NET PART I



Title: Preventing SQL Injection attack ASP.NET PART I
Author: Mayur V Lohite
Email: mayur.lohite@nullplex.com
Language: C# 4.0
Platform: Windows
Technology: ASP.NET
Level: Beginner
Description: The SQL Injection is very common attack in web
applications the article is explaining how the SQL Injection
is occur and how to prevent it.






Introduction



Security is the most important attribute for any system. Providing secure experience is one of the key principles in the process of gaining customer confidence for a system. Now days, almost all the websites are asking to store user’s personal information in servers to understand the customer and serve better. It’s the responsibility of an organization to confirm that customer’s data is safe and accessed in a secured manner.



Security in web application is always big headache to developer but providing secure environments is one of the key principles in the process of gaining customer confidence for a system. In this era of web application almost all websites are dynamic i.e. database driven and large data will accepts from user.


SQL Injection flaws are introduced when software developers create dynamic database queries that include user supplied input. This article explains how SQL Injection is prevented in ASP.NET.



Background



What is Actually SQL Injection attack?
SQL Injection is a attack used to inject unintended SQL commands (statements) in a database by accepting malicious, unsecured, un-validated user input. Injected SQL commands can alter SQL statement and compromise the security of a web application. If you want to know SQL Injection attack in detail please visit following link:
https://www.owasp.org/index.php/SQL_Injection



Methods of exploit SQL Injection



Methods of exploits:
1. Input boxes
2. Query Strings [GET]



How to exploit?



In today's dynamic web applications world its necessary to get user input and process it so we have to write the various types of SQL queries to process the data according to user input. Consider the following query.
Table - user_info, Columns - userID,name,email,password.
SELECT name,email FROM user_info WHERE userID = 1
We can devide this query into 2 parts.
PART-1: Query Part - SELECT userID,email FROM user_info
PART-2: Input Part - userID=1



A hacker usually not interested in PART-1 , he just interested , how he can insert malicious query in your PART-2. Let's take an example how SQL injection will be exploits.



Using the code



1. Suppose we have table user_info with some data. Following is the Script.



CREATE TABLE [dbo].[user_info](
[userID] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](200) NULL,
[email] [nvarchar](200) NULL,
[password] [nvarchar](50) NULL,
CONSTRAINT [PK_user_info] PRIMARY KEY CLUSTERED
(
[userID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[user_info] ON
INSERT [dbo].[user_info] ([userID], [name], [email], [password]) VALUES (1, N'Mayur Lohite', N'mayur@mayur.com', N'123456')
INSERT [dbo].[user_info] ([userID], [name], [email], [password]) VALUES (2, N'John Doe', N'john@john.com', N'654321')
INSERT [dbo].[user_info] ([userID], [name], [email], [password]) VALUES (3, N'Hacker', N'hack@hack.com', N'789123')
SET IDENTITY_INSERT [dbo].[user_info] OFF


2. create a new empty ASP.NET website project. Add following two pages into it. I. Default.aspx II. viewuser.aspx



3. Code for Default.aspx



<%@ page language=""C#"" autoeventwireup=""true"" codefile=""Default.aspx.cs""
inherits=""_Default"" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL Injection Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 50%; margin: 0 auto; text-align: center;">
<table>
<tr>
<td colspan="2">
<h2>
SQL Injection Demo</h2>
</td>
</tr>
<tr>
<td>
Search by userid
<asp:textbox id="txtUserID" runat="server">
</asp:textbox>
</td>
<td>
<asp:button id="btnSubmit" onclick="BtnSubmit_Click" runat="server" text="Search" />
</td>
</tr>
<tr>
<asp:gridview id="gvUserInfo" width="100%" runat="server" datakeynames="userID" autogeneratecolumns="false">
<Columns>
<asp:BoundField DataField="userID" HeaderText="userID" />
<asp:BoundField DataField="name" HeaderText="name" />
<asp:BoundField DataField="email" HeaderText="email" />
<asp:HyperLinkField DataNavigateUrlFields="userID" DataNavigateUrlFormatString="viewuser.aspx?userid={0}"
Text="View User" HeaderText="action" />
</Columns>
</asp:gridview>
</tr>
</table>
</div>
</form>
</body>
</html>



4. Code for Default.aspx.cs



public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet dset = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyExpConnectionString"].ToString());
using (conn)
{
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SELECT userID, name, email FROM user_info", conn);
cmd.CommandType = CommandType.Text;
adapter.SelectCommand = cmd;
adapter.Fill(dset);
gvUserInfo.DataSource = dset;
gvUserInfo.DataBind();

}

}
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
DataSet dset = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyExpConnectionString"].ToString());
using (conn)
{
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
string sqlQuery = string.Format("SELECT userID, name, email FROM user_info WHERE userID={0}", txtUserID.Text);
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.CommandType = CommandType.Text;
adapter.SelectCommand = cmd;
adapter.Fill(dset);
gvUserInfo.DataSource = dset;
gvUserInfo.DataBind();

}

}
}


Default page screen shot


Default aspx page


5. Code for viewuser.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewuser.aspx.cs" Inherits="viewuser" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL Injection Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 50%; margin: 0 auto; text-align: center;">
<table>
<tr>
<td colspan="2">
<h2>
SQL Injection Demo</h2>
</td>
</tr>
<tr>
<td>
<h3>
Welcome
<asp:Label ID="lblDetails" runat="server"></asp:Label>
</h3>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



6. Code for viewuser.aspx.cs



public partial class viewuser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["userid"] != null)
{
DataSet dset = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyExpConnectionString"].ToString());
using (conn)
{
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
string sqlQuery = string.Format("SELECT name FROM user_info WHERE userID={0}", Request.QueryString["userid"]);
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.CommandType = CommandType.Text;
adapter.SelectCommand = cmd;
adapter.Fill(dset);
if (dset.Tables[0].Rows.Count > 0)
{
lblDetails.Text = dset.Tables[0].Rows[0]["name"].ToString(); ;
}

}
}
}
}


viewuser page screen shot


Viewuser page source code


Exploitation



Approach 1: By Input Boxes.



A-1. First Consider the Default Page, we have One TextBox, One Button and One GridView. On form load all data will be displayed on grid view. We have functionality to search user by their ID. Suppose I enter 1 to textbox and press button it will display the record associated with userID = 1.



A-2. Now if we take look at above code in Default.aspx.cs there is button click event i.e.



protected void BtnSubmit_Click(object sender, EventArgs e)


The query is written as a string and user input is concatenated with it.



string sqlQuery = string.Format("SELECT userID, name, email FROM user_info WHERE userID={0}", txtUserID.Text);


A-3.suppose , the user input is not validate properly then hacker or attacker can concatenate any malicious query with it. In this scenario I am concatenating another SELECT statement with help of UNION to txtUserID.Text



A-4. I have entered the following text on textbox (txtUserID) without quotes "1 UNION SELECT userID,email,password FROM user_info"



A-5. Now complete query becomes:



string sqlQuery = SELECT userID, name, email FROM user_info WHERE userID=1 UNION SELECT userID,email,password FROM user_info


A-6. If I hit click on button the gridview display combination of both SELECT QUERY and the user password is revealed. If the query used with user input concatenation without any input validations then code is always vulnerable for SQL Injection Attack.



Note: I have increased the size of textbox to understand the query better.


Default page affected to sql injection


Approach 2: Query Strings [GET]



B-1. Now please go to default.aspx and click on viewuser link on GridView. The page will redirect to viewuser.aspx with userid query string parameter.



B-2. The page welcomes the user by their name. The name will founded by userid from query string value.



B-3. Now if we take look at above code in viewuser.aspx.cs Form_Load event



protected void Page_Load(object sender, EventArgs e)


The query is written as a string and the query string is concatenated with it.



string sqlQuery = string.Format("SELECT name FROM user_info WHERE userID={0}", Request.QueryString["userid"]);


B-4. Now Suppose I append the malicious Select query to Request.QueryString["userid"] as same as the above approach the URL becomes


http://mayurlohite.com/viewsuer.aspx?userid=1 UNION SELECT password FROM user_info WHERE userID = 1



B-5. If I hit enter then the label will display the password associated with userID = 1


view user page query string affected to sql injection


Why this happens?



In above both approaches the query is concatenated with user input and the user input is not validating properly. So the attacker take advantage of it and concatenate the malicious query with it and Attacker can get the passwords , install the backdoor. Attacker can manipulate the whole database from sysobject.



How to prevent



1. Validate the user input properly
2. Use parameterized SQL queries (sqlParameter) with stored procedures.



1. Validate user input:
If your input take only ids or integers add some validations for accept only numbers.
If inputs are complicated then use the regex patterns to identify the correct inputs.



2. Parameterized SQL query & Stored Procedure:
Parameterized queries do proper substitution of arguments prior to running the SQL query. It completely removes the possibility of "dirty" input changing the meaning of your query, with parameterized queries, in addition to general injection, you get all the data types handled, numbers (int and float), strings (with embedded quotes), dates and times (no formatting problems or localization issues when .ToString() is not called with the invariant culture and your client moves to a machine with and unexpected date format).



I have rewritten the above code safe from SQL Inection. Please take a look at
it.



1. Code for ConnectionManager.cs Class



public class ConnectionManager
{
public static SqlConnection GetDatabaseConnection()
{
SqlConnection connection = new SqlConnection(Convert.ToString(ConfigurationManager.ConnectionStrings["MyExpConnectionString"]));
connection.Open();

return connection;
}
}


2. Code for DataAccessLayer.cs Class



public class DataAccessLayer
{
public static DataSet DisplayAllUsers()
{
DataSet dSet = new DataSet();
using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
{
try
{
SqlCommand command = new SqlCommand("spDisplayUserAll", connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(dSet);
}
catch (Exception ex)
{
throw;
}
return dSet;
}
}

public static DataSet DisplayUserByID(int userID)
{
DataSet dSet = new DataSet();
using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
{
try
{
SqlCommand command = new SqlCommand("spDisplayUserByID", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@userID", SqlDbType.Int).Value = userID;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(dSet);
}
catch (Exception ex)
{
throw;
}
return dSet;
}
}
}


3. Code for Default.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL Injection Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 50%; margin: 0 auto; text-align: center;">
<table>
<tr>
<td colspan="2">
<h2>
SQL Injection Demo</h2>
</td>
</tr>
<tr>
<td>
Search by userid
<asp:TextBox ID="txtUserID" runat="server">
</asp:TextBox>
<<asp:RequiredFieldValidator ID="rfvUserID" ControlToValidate="txtUserID" Display="Dynamic"
runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revUserID" runat="server" ErrorMessage="Numbers Only"
ValidationExpression="[0-9]+" ControlToValidate="txtUserID" Display="Dynamic"></asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="btnSubmit" OnClick="BtnSubmit_Click" runat="server" Text="Search" />
</td>
</tr>
<tr>
<asp:GridView ID="gvUserInfo" Width="100%" runat="server" DataKeyNames="userID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="userID" HeaderText="userID" />
<asp:BoundField DataField="name" HeaderText="name" />
<asp:BoundField DataField="email" HeaderText="email" />
<asp:HyperLinkField DataNavigateUrlFields="userID" DataNavigateUrlFormatString="viewuser.aspx?userid={0}"
Text="View User" HeaderText="action" />
</Columns>
</asp:GridView>
</tr>
</table>
</div>
</form>
</body>
</html>



4. Code for Default.aspx.cs



public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet dset = DataAccessLayer.DisplayAllUsers();
if (dset.Tables[0].Rows.Count > 0)
{
gvUserInfo.DataSource = dset;
gvUserInfo.DataBind();
}

}
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
int userID = Convert.ToInt32(txtUserID.Text);
DataSet dSet = DataAccessLayer.DisplayUserByID(userID);
if (dSet.Tables[0].Rows.Count > 0)
{
gvUserInfo.DataSource = dSet;
gvUserInfo.DataBind();
}
}
}


5. Code for viewuser.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="viewuser.aspx.cs" Inherits="viewuser" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL Injection Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 50%; margin: 0 auto; text-align: center;">
<table>
<tr>
<td colspan="2">
<h2>
SQL Injection Demo</h2>
</td>
</tr>
<tr>
<td>
<h3>
Welcome
<asp:Label ID="lblDetails" runat="server"></asp:Label>
</h3>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



6. Code for viewuser.aspx.cs



public partial class viewuser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["userid"] != null)
{
int userID = Convert.ToInt32(Request.QueryString["userID"]);
DataSet dSet = DataAccessLayer.DisplayUserByID(userID);
if (dSet.Tables[0].Rows.Count > 0)
{
lblDetails.Text = Convert.ToString(dSet.Tables[0].Rows[0]["name"]);
}
}
}
}


7. Stored Procedure: spDisplayUserAll



CREATE PROCEDURE spDisplayUserAll
AS
BEGIN
SET NOCOUNT ON;
SELECT userID, name, email
FROM user_info
END


8. Stored Procedure: spDisplayUserByID



CREATE PROCEDURE spDisplayUserByID
@userID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT userID, name, email
FROM user_info
WHERE userID = @userID
END


Points of Interest



The SQL Injection is most common security vulnerability known in web applications. The dynamic webpages without handling validations and improper handling of code may lead to SQLI but by knowing proper code standred and tricks we will successfully prevent it.

Friday, February 7, 2014

Search engine friendly url in asp.net

Hello,

Here I presenting an important aspect Search Engine optimization technique. URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site. Download code sample for this.

What is URL Rewriting?
1. On today's modern internet, most of the websites are database driven. So, exchange of data between different pages is essential need of database driven websites. The query strings or GET parameters are very good approach to achieve this goal.
e.g. http://mayurlohite.com/page.aspx?productID=1
The above URL is dynamic and its sending the product id to page.aspx

2. So, what’s the problem with it?
Well, Maximum search engines (some exceptions – like Google) will not index any pages that have a question mark or other character (like an ampersand or equals sign) in the URL. So that means the page with question marks in URL is ignored by most of the search engines.

3. So, How search engine finds or index my page ?
There will be a solution of this problem, which is rewrite the URL to search engine friendly URL.

4. What is exactly the search engine friendly URL?
Lets take a look at above URL - http://mayurlohite.com/page.aspx?productID=1 &Productnane=visual-studio
we have to convert this URL to - http://mayurlohite.com/displayproduct/1/visual-studio
Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers.

5. How to convert Non search friendly URL to search friendly URL?
Its an easy task to converting URLs. Actually, I am working with ASP.NET C#. So, I will explaining how to achive this with ASP.NET. I am using Global.axas Application_BeginRequest event handler.

Application_BeginRequest:
is an event handler. It is part of the ASP.NET website system. The Application_BeginRequest method is executed on all requests handled by the ASP.NET runtime.
First, this event handler is declared in a class that derives from HttpApplication. In such classes, the Application_BeginRequest method is automatically used when a request is received.

So. Lets get started.

1. First we are creating new website in visual studio 2010 for that open visual studio 2010. Click on File -> New -> Website

2. Select Visual C# from left and click on ASP.NET Empty Website template. In Bottom Web location Select File System and Type path to create new website.Give name "URLRewriteDemo" to website.

[caption id="" align="aligncenter" width="1366"]New Website in ASP.NET New Website in ASP.NET[/caption]

3. Now empty asp.net website is created there is nothing to display on solution so first we create Default.aspx page. To create new page right click on solution explorer click Add New Item. Select Webform from template and name it Default.aspx and click on add.

4. Add one new page to solution(same as Default.aspx) and name it page.aspx.

5. Now we want to send the Product ID and Product Name from Default.aspx to page.aspx So, We are using Query String to pass the values  e.g. http://mayurlohite.com/page.aspx?productid=1&productname=visual-studio

6. we can access these values on page.aspx by Request.QueryString["productid"] and Request.QueryString["productname"] but this is not a SEO friendly pattern.

7. To solve this Add one Hyperlink field to Default.aspx and set NavigateUrl="~/displayproduct/1/visual-studio".

ASPX CODE FOR Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> URL Rewrite Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center;">
<h1>
URL Rewrite Demo</h1>
</div>
<br />
<div style="text-align: center;">
<h2>
<asp:HyperLink ID="URLHyperLink" runat="server" NavigateUrl="~/displayproduct/1/new-product">URL Rewrite</asp:HyperLink>
</h2>
</div>
</form>
</body>
</html>
ASPX CODE FOR page.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>URL Rewrite Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center;">
<h1>
URL Rewrite Demo</h1>
</div>
<br />
<div style="width:500px; margin:0 auto;">
<table style="width: 100%;">
<tr>
<td>
&nbsp;
<asp:Label ID="Label1" runat="server" Text="Product ID:"></asp:Label>
</td>
<td>
&nbsp;
<asp:Label ID="ProductLabel" runat="server"></asp:Label>
</td>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
&nbsp;
<asp:Label ID="Label2" runat="server" Text="Product Name:"></asp:Label>
</td>
<td>
&nbsp;
<asp:Label ID="ProductNameLabel" runat="server"></asp:Label>
</td>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
<td>
&nbsp;
</td>
<td>
&nbsp;
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

8. In this example we are passing "displayproduct/1/visual-studio" to hyperlink[navigateurl] which is SEO friendly URL.

9. To write our rewrite rule we have to add Global.asax file in project. To add Global.asax right click on solution and click Add New Item and select "Global Application Class" from templates.

[caption id="" align="aligncenter" width="1366"]Adding Global.asax in asp.net Adding Global.asax in asp.net[/caption]

10. We are creating new Event Handler in Global.asax name it protected void Application_BeginRequest(Object sender, EventArgs e){}

CODE FOR GLOBAL.ASAX

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup

}

void Application_End(object sender, EventArgs e)
{
//  Code that runs on application shutdown

}

void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started

}

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}

protected void Application_BeginRequest(Object sender, EventArgs e)
{
//Grab the URL for matching the pattern. Returns the current URL path.
//e.g. http://example.com/displayproduct/1/visual-studio
HttpContext incoming = HttpContext.Current;
string oldpath = incoming.Request.Path.ToLower();

//Declare variables for Query Strings.
string productid = string.Empty;
string productname = string.Empty;

// Regular expressions to grab the productid and productname from the page.aspx
//Here I am using regular expression to match tghe pattern.
Regex regex = new Regex(@"displayproduct/(\d+)/(.+)", RegexOptions.IgnoreCase
| RegexOptions.IgnorePatternWhitespace);
MatchCollection matches = regex.Matches(oldpath);

//If Matches found then Grab the product id and name and rewrite it as our typical query string format.
//e.g: http://example.com/page.aspx?productid=1&productname=visual-studio
if (matches.Count > 0)
{
productid = matches[0].Groups[1].ToString();
productname = matches[0].Groups[2].ToString();
incoming.RewritePath(String.Concat("~/page.aspx?productid=", productid, "&productname=", productname ), false);
}
}

</script>

11. Now we are analyzing Application_BeginRequest(Object sender, EventArgs e) event handler.

A. The first two lines returns the current URL path.
HttpContext incoming = HttpContext.Current;
string oldpath = incoming.Request.Path.ToLower();

B. By using regular expression we can match the pattern of our requested URL with our rewrite URL. Means, when http://example.com/displayproduct/1/visual-studio is pattern matched with our regular expression and it rewrite the path to http://example.com/productid=1&productname=visual-studio

12. We can access the both query string parameter as same previous. e.g. Request.QueryString["productid"] and Request.QueryString["productname"] there is no change in traditional ASP.NET Query String system.

Hence, we achieve the SEO friendly URL by Global.asax Rewrite rule.

I have attached the Code sample for this project.Please download and run to get more clarification.
Download Code
Or
Download Link : http://mayurlohite.com/wp-content/uploads/2014/02/URLRewriteDemo.rar

 

Friday, December 20, 2013

SQL Injection Vulnerability On Yahoo

Hi guys,
Few days ago I have found SQL Injection Vulnerability on Yahoo adverting domain. I have reported to yahoo but unfortunately someone is very faster than me and reported to Yahoo. So, its a duplicate vulnerability.
Now its fixed so I am sharing POC.

Vulnerability Name : SQL Injection
Target URL: http://in.advertising.yahoo.net/show_details.php?id=14
Number of MySQL Column: 6
Version of MySQL: 5.5.32
Database Name: inadvt1

VIDEO POC :
 

If you have difficulty to seen embed video then you can check the following link.

VIDEO LINK:
http://mayurlohite.com/yahoo/yahoosqli.swf.html

Another XSS and redirect on rediff.com

Hi
While analyzing the rediff.com I have found there is XSS as well as Open redirection vulnerability But as per rediff security team open redirection is not a serious vulnerability.

1. Cross Site Scripting XSS
Target URL: http://www.rediff.com/login/inredirect.php?url=
Type of Vulnerability: Cross Site Scripting - [XSS]
Risk : High
String used: ">< s c r i p t >alert(document.cookie);< / s c r i p t>

Clean URL:
http://www.rediff.com/login/inredirect.php?url=">< s c r i p t >alert(document.cookie);< / s c r i p t>



 
2. Open Redirect
Target URL: http://www.rediff.com/login/inredirect.php?url=
Type of Vulnerability: Redirection
Risk : High
String used: http://mayurlohite.com


Proof of concept:
1. First visit the Target URL and wait for some moment
http://www.rediff.com/login/inredirect.php?url=http://mayurlohite.com



2. The URL automatically redirect to http://mayurlohite.com3. This will generate Phishing Attack and victim looses their sensitive information

Screenshot:




[caption id="" align="aligncenter" width="829"]XSS on rediff.com XSS on rediff.com[/caption]


Reply from rediff:


[caption id="" align="aligncenter" width="692"]Reply from rediff Reply from rediff[/caption]

 

Cross site scripting on rediff.com

Hi
This is my old XSS.

Here is complete details.

Target URL: http://sitesearch.rediff.com/dirsrch/default.asp?MT=
Type of Vulnerability: Cross Site Scripting - [XSS]
Risk : High
String used: "><script>alert(1)</script>

Screenshot:

[caption id="" align="aligncenter" width="1366"]XSS on rediff.com XSS on rediff.com[/caption]

Reply from rediff:

[caption id="" align="aligncenter" width="690"]Reply from rediff.com Reply from rediff.com[/caption]

Thursday, December 19, 2013

Two step open redirection on facebook.com

Vulnerability Details:

Target URL: https://www.facebook.com/dialog/oauth?client_id=1609715306561351&redirect_uri=
Type: Open Redirection
Risk: High
String Used: http://nullplex.com/login.html
Impact: This vulnerability may lead to phishing attack and normal victims looses their sensitive login information.

Proof of Concept

1. Attacker gives the URL to victims.
Example: Hey friend I have found new game on facebook it is really very nice please take look at it.
https://www.facebook.com/dialog/oauth?client_id=1609715306561351&redirect_uri=http://nullplex.com/login.html

2. After visiting URL the following Warning Appear
Sorry, this feature isn't available right now: An error occurred while processing this request. Please try again later.

3. After clicking Okay the Page directly redirect to target URL (http://nullplex.com/login.html) without any redirect warning.

4. Now at this point the victim see the login page and he feels that I have logged out from facebook that's why I cant find the game.

5. Then he login on that fake page and looses the sensitive information.

Details of Attack:
1. The Original URL (Photo Contest app)
https://www.facebook.com/dialog/oauth?client_id=160971530656135&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fthephotocontest%2F%3Ffb_source%3Dreminders%26request_ids%3D198303430334474%26ref%3Dreminders&state=4695db802e67475707d31a24ffceb2d2&scope=email%2Cfriends_photos%2Cuser_photos%2Cpublish_actions%2Cfriends_actions.music%2Cfriends_actions.news%2Cfriends_actions.video

2. I have removed all parameters after redirect_uri and change the client_id to 609715306561351 just append 1 into it.

Original client_id=60971530656135
Changed client_id =609715306561351

3. Now the target URL leads to Phishing attack.

Update:
This Vulnerability is fixed now If I change the client_id it gives Error: "Invalid App ID"

Thanking You.

Reply from facebook:

[caption id="" align="aligncenter" width="670"]Reply from facebook Reply from facebook[/caption]

Saturday, October 26, 2013

Several Information Disclosure Vulnerabilities on Adobe Inc

1. Vulnerability One

Name: Database Configuration file Readable

Description:
A backup/temporary configuration file was found on this directory. It has been confirmed that this file contains PHP source code.
Several popular text editors like Vim and Emacs automatically create backup copies of the files you edit, giving them names like "wp-config.php~" and "#wp-config.php#". If the text editor crashes or the SSH connection drops during editing, then the temporary backup files may not be cleaned up correctly. Also, sometimes developers create this type of files to backup their work or by administrators when making backups of the web server. Most servers, including Apache, will serve the plaintext of .php~ and .php# files without passing them through the PHP preprocessor first, since they don#t have the .php file extension.


The impact of this vulnerability

Configuration files will disclose sensitive information that will help a malicious user to prepare more advanced attacks


Attack Details 

PHP DB Test
// we connect to example.com and port 3307
$link = mysql_connect('marleydb.corp.adobe.com:3313', '[removed]', '[removed]');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

Here Host, Database username, Password easily disclosed.


Database Username: [removed]

Password: [removed]



2. Vulnerability Two

Name: PHPinfo page found



Vulnerability description

PHPinfo page has been found in this directory. The PHPinfo page outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.



The impact of this vulnerability

This file may expose sensitive information that may help an malicious user to prepare more advanced attacks.

Attack details

phpinfo() page found at : /info.php



3. Vulnerability Three

Name: File upload

Target URL: http://yoseif.host.adobe.com/webcal/day.php
Vulnerability description

This page allows visitors to upload files to the server. Various web applications allow users to upload files (such as pictures, images, sounds, ...). Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code.


The impact of this vulnerability

If the uploaded files are not safely checked an attacker may upload malicious files.


4. Vulnerability Four

Name: Open Directory Listing

Target URL: http://yoseif.host.adobe.com/test.php

Description
The web server is configured to display the list of files contained in this directory. This is not recommended because the directory may contain files that are not normally exposed through links on the web site.Impact
A user can view a list of all files from this directory possibly exposing sensitive information.

For finding this vulnerabilities adobe acknowledge me. By placing my name in hall of fame :

Link:
http://www.adobe.com/support/security/bulletins/securityacknowledgments.html

Wednesday, October 9, 2013

.htaccess File Readable Vulnerability on Yahoo Inc

Hello All

Yahoo:  Yahoo! Inc. is an American multinational internet corporation headquartered in Sunnyvale, California. It is widely known for its web portal, search engine Yahoo! Search, and related services, including Yahoo! Directory, Yahoo! Mail, Yahoo! News, Yahoo! Finance, Yahoo! Groups, Yahoo! Answers, advertising, online mapping, video sharing, fantasy sports and its social media website.

White I experimenting I have found Critical Vulnerability on some of  Yahoo sub domains which Wordpress is installed on it.

Vulnerable URL : [Cant disclose it because vulnerability is not fixed yet.]
Vulnerability Name: .htaccess File Readable
Description: This directory contains an .htaccess file that is readable. This may indicate a server misconfiguration. htaccess files are designed to be parsed by web server and should not be dirrectly accessible. These files could contain sensitive information that could help an attacker to conduct further attacks. The .htacess file contains
1. Redirection rules
2. Sensitive directories
3. Some sensitive configuration
Impact: Possible sensitive information disclosure.

After reporting I have got response from Yahoo Security Team

Reply 1:


[caption id="" align="aligncenter" width="766"]Reply from Yahoo Reply from Yahoo[/caption]

 

Reply 2:


[caption id="" align="aligncenter" width="762"]Reply from Yahoo Reply from Yahoo[/caption]

 

My Gift:


[caption id="" align="aligncenter" width="1200"]Gift from yahoo Gift from yahoo[/caption]

 

Open Redirection Vulnerability on Adobe Inc

Welcome back guys,

I have reported the Open Redirect Vulnerability to Adobe.

Target URL: http://feeds.adobe.com
Type of Vulnerability: Open Redirection
Risk : Medium
String used: http://mayurlohite.blogspot.in/
Impact: This vulnerability leads to phishing attack.

Adobe gives me acknowledgement for my findings. Here is the link for acknowledgement page.
http://www.adobe.com/support/security/bulletins/securityacknowledgments.html

Cross Site Scripting Vulnerability on Yahoo Inc

Hello Guys,
Reported the Cross Site Scripting vulnerability to Yahoo Inc.

Vulnerability Details:
Target URL: http://l.yimg.com
Type of Vulnerability: Cross Site Scripting - [XSS]
Risk : High
String used: " > < s c r i p t > a l e r t ('XSS') < / s c r i p t >

Yahoo sent me the T Shirt for reported the Cross Site Scripting vulnerability to Yahoo. The vulnerability is fixed now.

[caption id="" align="aligncenter" width="640"]Yahoo T Shirt Yahoo T Shirt[/caption]