Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

ကီးကီး

SQL Injection User Input characters data


access SQL query database
privileged account

♦ SQL injection attacks


♦ SQL injection user input
♦ SQL injection SQL Command parameters
♦ Database account
♦ is

database
commands Login page SQL
injection application database over-privileged account
application’s Login page
database Attacker

SQL injection attacks ႕ Data Code

- User
- parameters SQL statements
- Over-privileged database login

SQL Injection
User SSN text box String

' ; DROP DATABASE pubs --


string text box application Dynamic
SQL Statement ( ) Store Procedure (SQL statement )

// Use dynamic SQL


SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM authors WHERE au_id = '" +
SSN.Text + "'", myConnection);

// Use stored procedures


SqlDataAdapter myCommand = new SqlDataAdapter(
"LoginStoredProcedure '" + SSN.Text + "'", myConnection);

Code run code user ၏ SQL Statement


Developer ၏
SELECT au_lname, au_fname FROM authors WHERE au_id = '172-32-9999'

Code user ၏ malicious query

SELECT au_lname, au_fname FROM authors WHERE au_id = ''; DROP DATABASE pubs --'

‘ (single quotation mark) Malware input SQL statement


current string current statement
new statement current statement
input ႕ single quotation mark ႕
SELECT au_lname, au_fname FROM authors WHERE au_id = ' '

; (semicolon) SQL statement statement


malicious SQL code ; (semicolon) ၏
; DROP DATABASE pubs

; SQL statements vendor ( i e entation


Microsoft SQL Server SQL Server

SELECT * FROM MyTable DELETE FROM MyTable

-- (double dash) te t SQL comment


SQL SQL parser error ‘ (single quotation mark )
--'

SQL injection attacks -


- Input data type , length, format range
ata
- Data access SQL parameters SQL paramenters stored
procedures ( ) SQL command strings na ica

- SQLParameterCollection Parameter collections type Length validation


parameters collection input
SQL Server excutable code parameter collection type
length Values outside of the range trigger an
exception.
- Database permissions account database
stored procedures permissions table

- Database Error Information database error ၏


error user
SSL (Secure Socket Layer) IP Security

SQL injection
- ၁ input
- ၂ stored procedures parameters
- ၃ dynamic SQL parameters

၁ input ASP.NET application type length format range


input data access queries input SQL injection

input characters
characters characters
regular expressions validation character

ASP.NET web page input


ASP.NET web page in t server side code client-side
validation server to client client
to server round trip user experience client-side validation

Server controls input RegularExpressionValidator RangeValidator


ASP.NET validator controls HTML input controls input
server-side code Regex class
code ASP.NET TextBox control SSN Textbox Value
Value RegularExpressionValidator
Value
<%@ language="C#" %>
<form id="form1" runat="server">
<asp:TextBox ID="SSN" runat="server"/>
<asp:RegularExpressionValidator ID="regexpSSN" runat="server"
ErrorMessage="Incorrect SSN Number"
ControlToValidate="SSN"
ValidationExpression="^\d{3}-\d{2}-\d{4}$" />
</form>

SSN input HTML control query string parameter ( ) cookie


System.Text.RegularExpressions namespace Regex class
Input cookie
using System.Text.RegularExpressions;
if (Regex.IsMatch(Request.Cookies["SSN"], "^\d{3}-\d{2}-\d{4}$"))
{
// access the database
}
else
{
// handle the bad input
}

ASP.Net Injection Attacks

Data o e user input


ASP.NET page-level validation data access code validation Data
access code validation (၂)
Untrusted Clients
Data ( ) ata validate
data input
validation logic

Library code
data access code library ac a e data access code
validation client applications

Regular expressions data access validate

using System;
using System.Text.RegularExpressions;

public void CreateNewUserAccount(string name, string password)


{
// Check name contains only lower case or upper case letters,
// the apostrophe, a dot, or white space. Also check it is
// between 1 and 40 characters long
if ( !Regex.IsMatch(userIDTxt.Text, @"^[a-zA-Z'./s]{1,40}$"))
throw new FormatException("Invalid name format");

// Check password contains at least one digit, one lower case


// letter, one uppercase letter, and is between 8 and 10
// characters long
if ( !Regex.IsMatch(passwordTxt.Text,
@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$" ))
throw new FormatException("Invalid password format");

// Perform data access logic (using type safe parameters)


...
}

(၂) Stored Procedure Parameter


Stored procedures SQL injection
stored procedure parameter parameter
Overview unfiltered input SQL injection
code stored procedure SqlParameterCollection

using System.Data;
using System.Data.SqlClient;

using (SqlConnection connection = new SqlConnection(connectionString))


{
DataSet userDataset = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(
"LoginStoredProcedure", connection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;

myCommand.Fill(userDataset);
}

ဤ code @au_id parameter executable code


parameter type length code ႕
input character (၁၁) data parameter
type ( ) length SqlParameter class exception
throw

Application Parameterized Stored Procedure


Parameter stored procedure SQL injection
ဤ stored procedure type ၏
parameterized stored procedure
CREATE PROCEDURE dbo.RunQuery
@var ntext
AS
exec sp_executesql @var
GO

႕ code example stored procedure

• statement asse stored procedure execute @var variable


DROP TABLE ORDERS; ဤ code ORDERS table
• Stored procedure Dbo privileges run
• Store procedure RunQuery attacker
database attacker stored procedure RunQuery
attacker query run stored procedure

(၃) Dynamic SQL Parameter


Stored Procedure D na ic SQL state ent
parameters code dynamic SQL
SqlParametersCollection
using System.Data;
using System.Data.SqlClient;

using (SqlConnection connection = new SqlConnection(connectionString))


{
DataSet userDataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id",
connection);
myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
myDataAdapter.Fill(userDataset);
}

Parameter Batching
single round trip server a batch of statement
SQL statement parameter
parameter name SQL text concatenation
unique parameter
using System.Data;
using System.Data.SqlClient;
...
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(
"SELECT CustomerID INTO #Temp1 FROM Customers " +
"WHERE CustomerID > @custIDParm; SELECT CompanyName FROM Customers " +
"WHERE Country = @countryParm and CustomerID IN " +
"(SELECT CustomerID FROM #Temp1);",
connection);
SqlParameter custIDParm = dataAdapter.SelectCommand.Parameters.Add(
"@custIDParm", SqlDbType.NChar, 5);
custIDParm.Value = customerID.Text;

SqlParameter countryParm = dataAdapter.SelectCommand.Parameters.Add(


"@countryParm", SqlDbType.NVarChar, 15);
countryParm.Value = country.Text;

connection.Open();
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
}
...
SQL injection
- Special input characters escape routines
- Privileged database account
- o in o ation

Special input characters escape routines


Dynamic SQL Special input characters threat
parameterized SQL code ႕ SQL Server
Escape routines S ecia eanin characters escape character

private string SafeSqlLiteral(string inputSQL)


{
return inputSQL.Replace("'", "''");
}

A Least-Privileged database account


Privileged account application atabase Windows
authentication Operation System privileged account
limited privileges Windo s eso ces windows
authentication ( ) SQL authentication SQL Server
login database e issions
ic oso t in o s Se e run ASP.NET application
default ASP.NET application et o Se ice acco nt run application pool
run account a east i i e e acco nt
Network Service account SQL Server
၁ Web server ၏ Network Service account SQL Server Login Network
Service account DOMAIN\WEBSERVERNAME$ database server network
credentials domain XYZ Web Server 123
XYZ/123$ database login
၂ database user database role user
database Login
၃ database role database tab e sto e
oce e permission application
stored procedures application ႕
table
ASP.NET application database ata update
table read access attacker SQL
injection attack attacker

o in o ation
Error exception handling client error
error information Local Log client
error
User database e o user error nature
ata database error
database security compromise
malicious user Attacker SQL query
deconstruct error message
a icio s co e
error message connection string, SQL server name
table database naming conventions

XSS Cross Site Scripting Attack eb Site ႕ ne abi ities


Web Site Structure a a Sc i t ttac e ac e
Attack (vulnerabilities) XSS
( ) Cross-Site Scripting Web Developer
႕၏ Web Site SS User

-
♦ Web page oss-Site sc i tin
(vulnerabilities)
♦ oss-Site ttac s

♦ e a e ession input
ASP.NET ႕ validator controls
♦ B o se Script code HTML tag execute
♦ HTML tags attributes review

XSS Cross Site Scripting Attack eb Site ႕


ne abi ities ient-si e sc i t co e sc i t co e
User User script code ႕ browser
run trusted site script code browser download
code Cross Site sc i tin attac s
HTTP HTTPS (SSL) connection Cross-site scripting attack ႕
attacker (၁ trusted site (၁) authentication
cookies script (၁) cookies web address attacker
attacker user
Web Application ၁ oss-site sc i tin attac vulnerabilities
♦ In t
♦O t t encode
♦ Shared database trusting data

-
Cross-site scripting (XSS) attack countermeasures (၂)
♦ In t
♦O t t encode

input
Input malicious code type, length, format, range
Validate
♦ ASP.NET input Server site validator controls
RegularExpressionValidator RangeValidor
♦ Regular expression server side code check
System.Text.RegularExpressions.Regex client-side ႕ HTML input controls
( ) source query strings or cookies ႕ input supply
input ႕
♦ Va i ate intergers, doubles, dates currency amounts
NET Framework data type e i a ent input data convert
resulting conversion errors handle
Output encode User input ( ) database ( )
source input HttpUtility.HtmlEncode method HtmlEncode
special meaning characters replace - < is
replaced with < and " is replaced with " Data encode browser
႕ Execute code Data L a ess rendered
in t const cte output URLs encode
HttpsUtility.UrlEncode Cross-site scripting

♦ Ste 1 - ASP.NET ႕ Request enabled /


♦ Ste - HTML Output ASP.NET code Review
♦ Ste - HTML Output input parameters
♦ Ste 4 - HTML tags attributes Review

♦ Ste - (countermeasures) evaluate

Step(1)- ASP.NET ႕ Request enabled Check


Machine.config request validation Enable server ႕
Machine.config file request validation enab e ValidateRequest t e
example code Check
<system.web>
<pages buffer="true" validateRequest="true" />
</system.web>
Page by page basic request validation disable Pages isab e
feature - feature disable page
free-format, rich-text entry field design HTML characters in t
a e handle step 5 ႕
Evaluate Countermeasures ႕ ASP.NET request validation ႕ Enable

1. Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in
the following code example.
2. <%@ Page Language="C#" ValidateRequest="false" %>
3. <html>
4. <script runat="server">
5. void btnSubmit_Click(Object sender, EventArgs e)
6. {
7. // If ValidateRequest is false, then 'hello' is displayed
8. // If ValidateRequest is true, then ASP.NET returns an exception
9. Response.Write(txtString.Text);
10. }
11. </script>
12. <body>
13. <form id="form1" runat="server">
14. <asp:TextBox id="txtString" runat="server" Text="<script>alert('hello');</script>" />
15. <asp:Button id="btnSubmit" runat="server"
16. OnClick="btnSubmit_Click"
17. Text="Submit" />
18. </form>
19. </body>
20. </html>

page run txtString sc i t Hello message box


ValidateRequest="true" ( ) ValidateRequest page attribute page b o se
e o essa e

A potentially dangerous Request.Form value was detected


from the client (txtString="<script>alert('hello...").

error ASP.NET request validation acti e HTML characters


input reject ASP.NET request validation
input validation

Step(2)- HTML Output ASP.NET code Review


ASP.NET HTML . Output two ways example code

Response.Write
<% =
HTML . URL output . Client et n page . Locate

Step(3)- HTML Output input parameters Determine


Web design page code in t a a ete analyze a a ete
source in t so ce . list
• Form fields, such as the following.
• Response.Write(name.Text);
• Response.Write(Request.Form["name"]);
• Query Strings
• Response.Write(Request.QueryString["name"]);

• Query strings, such as the following:


• Response.Write(Request.QueryString["username"]);

• Databases and data access methods, such as the following:


• SqlDataReader reader = cmd.ExecuteReader();
• Response.Write(reader.GetString(1));
Be particularly careful with data read from a database if it is shared by other applications.
• Cookie collection, such as the following:
• Response.Write(
• Request.Cookies["name"].Values["name"]);
• Session and application variables, such as the following:
• Response.Write(Session["name"]);
• Response.Write(Application["name"]
Source code analysis simple test ၁ .form field "XYZ" . output
testing Browser "XYZ" HTML . Source . .
More dynamic . . inject <script>alert('hello');</script> input field .
technique cases o t t ene ate
in t e en s

Step(4)- HTML tags attributes Review


HTML tags construct tag attributes create
HTML-encode tags Attributes .asp page <asp:Literal> control
HTML direct return page inserted text sa e
the page HTMLEncode
<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
<form id="form1" runat="server">
<div>
Color: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Show color"
OnClick="Button1_Click" /><br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</html>

<script runat="server">
private void Page_Load(Object Src, EventArgs e)
{
protected void Button1_Click(object sender, EventArgs e)
{
Literal1.Text = @"<span style=""color:"
+ Server.HtmlEncode(TextBox1.Text)
+ @""">Color example</span>";
}
}
</Script>
HTML Tags -
List HTML tags malicious user a o
inject script -
• <applet>
• <body>
• <embed>
• <frame>
• <script>
• <frameset>
• <html>
• <iframe>
• <img>
• <style>
• <layer>
• <link>
• <ilayer>
• <meta>
• <object>
Attacker ၁ src, lowsrc, style href L att ib tes cross-site scripting
<img> ႕ Src attributes source of injection
<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A; script:alert('hello');">
st e ta
<style TYPE="text/javascript">
alert('hello');
</style>

Ste - (countermeasures) evaluate


L ene ates ႕ Input ASP.NET code ႕ specific
application appropriate countermeasures evaluate Countermeasures
-
♦ Lo t t Encode
♦U Lo t t Encode
♦ User input Filter

HTML output Encode


Web page ၁ text output text special characters ( -<,
>,&) code example ႕ HttpUtillity.HtmlEncode method
text pre-process
Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));
Input well-formed, correct encoding output substitute
additional security precaution

URL output Encode


Input URL String Client et n HttpUtility.UrlEncode method
URL String encode example code
Response.Write(HttpUtility.UrlEncode(urlString));

User input Filter


HTML elements range accept pa es -ASP.NET
request validation disable Common practice HTML element safe
o attin est ict bold(<b>), italic(<i>) Allow restricted HTML input
sa et
1. ValidateRequest="false" attribute @ Page directive Adding
ASP.NET request validation disable
t nco e et o string input Encode
3. StringBuilder ႕ Replace method encoding HTML elements ႕
selectively remove permit
.aspx page code this approach ValidateRequest="false"
ASP.NETpage disable HTML encode the input simple text format support
selectively allows <b>, <i> ႕ HTML elements
<%@ Page Language="C#" ValidateRequest="false"%>

<script runat="server">

void submitBtn_Click(object sender, EventArgs e)


{
// Encode the string input
StringBuilder sb = new StringBuilder(
HttpUtility.HtmlEncode(htmlInputTxt.Text));
// Selectively allow <b> and <i>
sb.Replace("<b>", "<b>");
sb.Replace("</b>", "");
sb.Replace("<i>", "<i>");
sb.Replace("</i>", "");
Response.Write(sb.ToString());
}
</script>

<html>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="htmlInputTxt" Runat="server"
TextMode="MultiLine" Width="318px"
Height="168px"></asp:TextBox>
<asp:Button ID="submitBtn" Runat="server"
Text="Submit" OnClick="submitBtn_Click" />
</div>
</form>
</body>
</html>
techniques future cross-site scripting prevent
countermeasures
♦ o ect c a acte enco in set
♦ In t sanitization do not rely
♦ tt On coo ies o tion Use
♦ a e sec it att ib te Use
♦ InnerHTML innerText property Use

Correct character encoding set


Web pages restrict valid data s ccess represented in t ata ႕
Ways limit Malicious user in t a i ation o tines t ic
canonicalization multi-byte escape Multi-byte
escape sequence attack -character encodings uniform translation format-8
(UTF-8) non-ASCII character muliti-bytes sequence
႕ byte sequence not legitimate UTF-8
႕ UTF-8 decoder accept exploitable security hole providing

ASP.NET a e e e ( a ication e e Web.config file element


character set specify code
example ISO-8859-1 both approaches Page level character
encoding set element ( ႕) ResponseEncoding page level attribute

<meta http-equiv="Content Type"


content="text/html; charset=ISO-8859-1" />

OR
<% @ Page ResponseEncoding="iso-8859-1" %>

Web.config file character encoding set configuration


use
<configuration>
<system.web>
<globalization
requestEncoding="iso-8859-1"
responseEncoding="iso-8859-1"/>
</system.web>
</configuration>
code page Unicode character a i ate

using System.Text.RegularExpressions;
...

public class WebForm1 : System.Web.UI.Page


{
private void Page_Load(object sender, System.EventArgs e)
{
// Name must contain between 1 and 40 alphanumeric characters
// and (optionally) special characters such as apostrophes
// for names such as O'Dell

if (!Regex.IsMatch(Request.Form["name"],
@"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
throw new ArgumentException("Invalid name parameter");

// Use individual regular expressions to validate other parameters


...
}
}
code regular expression
-
♦^၏ - this position looking
♦ \p{ ..} ၏ - s eci ie name character class
any character matches
♦ L ၏ Left-to-right match
♦ L ၏ upper case ၏ match
♦ L ၏ lower case ၏ match
♦ Zs ၏ separator space matches
♦' matches ၏
♦ 1,4 - character ၏ number 1
40
♦$၏ - this position looking sto

In t Sanitization ႕
Unsafe character filtering out code in t sanitize ႕
Rely malicious
user a i ation a te nati e
secure, safe input check Table 1
႕common character ၏ sa e various way

HttpOnly Cookies Option


Internet Explorer 6 Service Pack 1 HttpOnly cookies attributes supports later
Virsion -document.cookie property cookie accessing client-side script
prevent script empty string et n cookies server
user ႕ Browse current domain Web Site
- Web browser HttpOnly cookies attribute support coo ies
att ib te (၂) ignore -cross-site scripting attacks

System.Net.Cookie class Microsoft.Net Framework version 2.0 HttpOnly property


support .NET Framework ႕ a ie e sion version 1.0 1.1 code
Application EndRequest event
application Global.asax file ၏ a e HttpOnly attribute explicity set
protected void Application_EndRequest(Object sender, EventArgs e)
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
// Just set the HttpOnly attribute on the Forms
// authentication cookie. Skip this check to set the attribute
// on all cookies in the collection
if (sCookie.Equals(authCookie))
{
// Force HttpOnly to be added to the cookie header
Response.Cookies[sCookie].Path += ";HttpOnly";
}
}
}

<frame> Security Attribute


Internet Explorer 6 later version <frame> <iframe> ႕ new secrrity attribute
s ot frame iframe user ၏ Restricted Sites Internet Explorer security zone
setting security attribute Restricted Sites zone script execution
support
Security attribute "restricted " set
<frame security="restricted" src="http://www.somesite.com/somepage.htm"> </frame>

innerHTML innerText Property


Page (၁) innerHTML property built HTML otentia nt ste in t
sa e HtmlEncode innerText
innerText property en e s
content sa e script executed
example this approach two HTML control
innerText property Welcome1element Page Load
method Text encoding innerText
property Welcome2element sa e HtmlEncode

<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
<body>
<span id="Welcome1" runat="server"> </span>
<span id="Welcome2" runat="server"> </span>
</body>
</html>

<script runat="server">
private void Page_Load(Object Src, EventArgs e)
{
// Using InnerText renders the content safe–no need to HtmlEncode
Welcome1.InnerText = "Hello, " + User.Identity.Name;

// Using InnerHtml requires the use of HtmlEncode to make it safe


Welcome2.InnerHtml = "Hello, " +
Server.HtmlEncode(User.Identity.Name);
}
</Script>

oss-Site Sc i tin eb e e o e ebsite ၏ co in


၏ ata i te nction
eb e e o e ebsite ၏ co in i te
i en o ie Q e St in ain a e sec it
co in injection ata
e te na ocess atabase in t a i ation
Sec it nction
t s ecia c a s nction c a acte t st in
eb e e o e eb e e o e
t c a acte t ans ate t s ecia c a s co an
t c a acte t ans ate
• '&' (ampersand) becomes '&amp;'
• '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
• "'" (single quote) becomes '&#039;' only when ENT_QUOTES is set.
• '<' (less than) becomes '&lt;'
• '>' (greater than) becomes '&gt;'
ht s ecia c a s

Example #1 htmlspecialchars() example


<?php
$new = htmlspecialchars("<a href='test'>Test </a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>
a s as es

nction atabase e ies c a acte single quote (‘), double quote (“ ,


bac s as ULL c a acte st in
a s as es

Example #1 An addslashes() example


<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?


echo addslashes($str);
?>

co an s ea esca e st in
s ea esca e st in MySQL’s ib a nction nction bac s as e
\x00, \n, \r, \, ‘, “ a c a acte nction
SQL e ata
s ea esca e st in

Example #1 Simple mysql_real_escape_string() example


<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>

SQL Injection ttac Sec it

Example #2 An example SQL Injection Attack


<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Query database to check if there are any matching users


$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// This means the query sent to MySQL would be:


echo $query;
?>

ac e ass o o in
Sec it
eb e e o e Sec it
ebsite function
……

http://www.mmcert.org.mm/ ..

You might also like