SlideShare a Scribd company logo
1 of 33
Defending Application against
Injections
Defending – Input & SQLi
Input Validation
• Design Strategy
• Assume all input is malicious.
• Centralize validation approach.
• Client-side validation doesn’t help.
• Be careful with canonicalization
issues.
• Constrain, reject, and sanitize your
input.
Input Validation
• Design Strategy
• Validate for type, length, format and
range.
• Prepare Whitelist of characters
instead of Blacklist.
Input Validation
• Options for constraining data,
Requirement Options
Type checks
• .NET Framework type system. Parse string data, convert to a strong type,
and then handle FormatExceptions. Regular expressions.
•Use ASP.NET RegularExpressionValidator control or Regex class.
Length checks Regular expressions String.Length property
Format checks Regular expressions for pattern matching .NET Framework type system
Range checks
ASP.NET RangeValidator control (supports currency, date, integer, double,
and string data) Typed data comparisons
Input Validation
• Validation Controls,
Validation Server Control Description
CompareValidator Compares the value of one input control to the value of another input
control or to a fixed value
CustomValidator Allows you to write a method to handle the validation of the value entered
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified pattern
RequiredFieldValidator Makes an input control a required field
ValidationSummary Displays a report of all validation errors occurred in a Web page
Input Validation
• RegulareExpressionValidator
<script  runat="server">
sub submit(sender As Object, e As EventArgs) 
if Page.IsValid then 
   lbl.Text="The page is valid!"
else 
   lbl.Text="The page is not valid!"
end if
end sub
</script> <html> <body>
<form runat="server">
Enter a US zip code:
<asp:TextBox id="txtbox1" runat="server" />
<br /><br />
<asp:Button text="Submit" OnClick="submit" runat="server" />
<br /><br />
<asp:Label id="lbl" runat="server" />
<br />
<asp:RegularExpressionValidator 
ControlToValidate="txtbox1"
ValidationExpression="d{5}"
EnableClientScript="false"
ErrorMessage="The zip code must be 5 numeric digits!"
runat="server" />
</form> </body> </html>
Input Validation
• Regex (System.Text.RegularExpressions)
Regular expressions are much easier to understand if you use the 
following syntax and comment each component of the expression 
using #. To enable comments, you must also specify 
RegexOptions.IgnorePatternWhitespace, which means that non-escaped 
white space is ignored.
Regex regex = new Regex(@"
                        ^          # anchor at the start
                       (?=.*d)    # must contain at least one 
digit
                       (?=.*[a-z])  # must contain one lowercase
                       (?=.*[A-Z])  # must contain one uppercase
                       .{8,10}      # From 8 to 10 characters in 
length
                       $            # anchor at the end", 
                       RegexOptions.IgnorePatternWhitespace);
Input Validation
• String Fields (Name, Address..)
• For Social Security Number the
expression would be "d{3}-d{2}-d{4}"
<form id="WebForm" method="post" runat="server">
  <asp:TextBox id="txtName" runat="server"></asp:TextBox>
  <asp:RegularExpressionValidator id="nameRegex "runat="server" 
        ControlToValidate="txtName" 
        ValidationExpression="[a-zA-Z'.'-'s]{1,40}" 
        ErrorMessage="Invalid name">
  </asp:regularexpressionvalidator>
</form>
Input Validation
• Date/Time Field Validation
try
{
DateTime dt = DateTime.Parse(txtDate.Text).Date;
}
// If the type conversion fails, a FormatException is thrown
catch(FormatException ex)
{
// Return invalid date message to caller
}
//range check on a date field
// Exception handling is omitted for brevity
DateTime dt = DateTime.Parse(txtDate.Text).Date;
// The date must be today or earlier
if(dt > DateTime.Now.Date)
throw new ArgumentException("Date must be in the past");
Input Validation
• Numeric Field Validation
• Convert input to integer type and
return the error if exception raised.
try
{
int i = Int32.Parse(txtAge.Text);
. . .
}
catch( FormatException)
{
. . .
}
Input Validation
• Range Validation
• Use RangeValidator control with
RequiredFieldValidator control so it
can't accept blank input.
• Convert into Integer with
FormatException handling and check
the integer range.
Input Validation
• Range Validation
<form id="WebForm3" method="post" runat="server">
<asp:TextBox id="txtNumber" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
id="rangeRegex"
runat="server"
ErrorMessage="Please enter a number between 0 and 255"
ControlToValidate="txtNumber"
style="LEFT: 10px; POSITION: absolute; TOP: 47px" >
</asp:RequiredFieldValidator>
<asp:RangeValidator
id="RangeValidator1"
runat="server"
ErrorMessage="Please enter a number between 0 and 255"
ControlToValidate="TextBox1"
Type="Integer"
MinimumValue="0"
MaximumValue="255"
style="LEFT: 10px; POSITION: absolute; TOP: 47px" >
</asp:RangeValidator>
<asp:Button id="Button1" style="LEFT: 10px; POSITION: absolute; TOP: 100px"
runat="server" Text="Button"></asp:Button>
</form>
Input Validation
• Sanitizing Inputs
• Strips out a range of potentially unsafe
characters, including < >  " ' % ; ( ) &.
private string SanitizeInput(string input)
{
Regex badCharReplace = new Regex(@"([<>""'%;()&])");
string goodChars = badCharReplace.Replace(input, "");
return goodChars;
}
Input Validation
• Validating HTML controls
private void Page_Load(object sender, System.EventArgs e)
{
// Note that IsPostBack applies only for
// server forms (with runat="server")
if ( Request.RequestType == "POST" ) // non-server forms
{
// Validate the supplied email address
if( !Regex.Match(Request.Form["email"],
@"w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*",
RegexOptions.None).Success)
{
// Invalid email address
}
// Validate the supplied name
if ( !RegEx.Match(Request.Form["name"],
@"[A-Za-z'- ]",
RegexOptions.None).Success)
{
// Invalid name
}
}
}
Input Validation
• File/Path Input
• Avoid code which accepts file input or path
input from the caller.
• Use fixed file names and locations
• Canonicalize path names before validating
by System.IO.Path.GetFullPath or
Request.MapPath to check that the file path
is valid in the context of your application.
• Use .NET code access security to grant the
precise FileIOPermission to your code
Input Validation
• MapPath API
try
{
string mappedPath = Request.MapPath( inputPath.Text,
Request.ApplicationPath, false);
//Is path is what supposed to be
if(!validateFilepath(mappedPath))
{
return null;
}
if(mappedPath.exist())
{
return abspath;
}
}
catch (HttpException)
{
// Cross-application mapping attempted
}
For XML Input
• Create and use xml schema definition
(XSD) or DTD file for xml validation
• Don’t just check XML for certain tags.
• Pay special attention to XPATH query
inputs.
Input Validation
• ESAPI (The OWASP Enterprise Security
API)
• Open source free library
• Set of security control interfaces.
• Reference implementation for each
security control. The logic is not
organization or application-specific.
An example: string-based input
validation.
OWASP ESAPI
Namespace ESAPI
{ AccessController
Encoder
Encryptor
HttpUtilities
IntrusionDetector
Logger
Randomizer
SecurityConfiguration
Validator
}
Input Validation
• ESAPI Sample
public void Test_IsValidDouble()
{
IValidator validator = Esapi.Validator;
//testing negative range
Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Double, "-4"));
//testing empty string
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Double, ""));
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Double, "alsdkf"));
}
public void Test_GetValidDate()
{
IValidator validator = Esapi.Validator;
Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Date, "June 23, 1967"));
Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Date, "Jun 23, 1967"));
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, "June 32,
1967"));
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, string.Empty));
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, null));
}
Input Validation
• ESAPI Sample
public void Test_StringRule()
{
IValidator validator = Esapi.Validator;
string id = Guid.NewGuid().ToString();
StringValidationRule rule = new StringValidationRule();
validator.AddRule(id, rule);
// Test valid
Assert.IsTrue(validator.IsValid(id, Guid.NewGuid().ToString()));
// Test allow null or empty
Assert.IsFalse(validator.IsValid(id, string.Empty));
Assert.IsFalse(validator.IsValid(id, null));
rule.AllowNullOrEmpty = true;
// Test whitelist
Assert.IsTrue(validator.IsValid(id, "abc"));
rule.AddWhitelistPattern("d+");
Assert.IsFalse(validator.IsValid(id, "abc"));
Assert.IsTrue(validator.IsValid(id, "123"));
// Test blacklist
rule.AddBlacklistPattern("1");
Assert.IsFalse(validator.IsValid(id, "123"));
Assert.IsTrue(validator.IsValid(id, "23"));
}
Input Validation
• ESAPI Sample
public void Test_StringRuleRange()
{
IValidator validator = Esapi.Validator;
// Test range
string id = Guid.NewGuid().ToString();
StringValidationRule rule = new StringValidationRule() { MinLength = 1,
MaxLength = 10 };
validator.AddRule(id, rule);
Assert.IsTrue(validator.IsValid(id, "a"));
Assert.IsFalse(validator.IsValid(id, ""));
Assert.IsFalse(validator.IsValid(id, "12345678901"));
}
public void Test_IsValidPrintable()
{
IValidator validator = Esapi.Validator;
Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Printable, "abcDEF"));
Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Printable, "!
@#R()*$;><()"));
char[] bytes = new char[] { (char)(0x60), (char)(0xFF), (char)(0x10), (char)
(0x25) };
Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Printable, new
String(bytes)));
}
Prevent SQL Injection
• Design Strategy
• Constrain Input
• Use Type Safe SQL parameters for data
access.
• SQL parameters can be used with stored
procedures or dynamically constructed SQL
command strings. Parameters perform type
and length checks and also ensure that
injected code is treated as literal data, not
executable statements in the database.
Prevent SQL Injection
• Design Strategy
• Use least privilege account that has
restricted permissions in the database.
• Only grant execute permissions to selected
stored procedures in the database and
provide no direct table access.
• Protect sensitive data in storage.
• Use separate data access assemblies.
• Use Windows authentication
Prevent SQL Injection
• Use Separate Data Access Assemblies
Prevent SQL Injection
• Type Safe SQL Parameters
• Input is treated as a literal value and SQL
does not treat it as executable code.
• Enforce type and length checks.
• Stored Procedure without SQL parameters
do not protect against SQL Injection.
Prevent SQL Injection
• Stored Procedure Example
//the good example
SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parm = myCommand.SelectCommand.Parameters.Add(
"@au_id", SqlDbType.VarChar, 11);
parm.Value = Login.Text;
//the bad example
SqlDataAdapter myCommand = new SqlDataAdapter("LoginStoredProcedure '"
+
Login.Text + "'", conn);
Prevent SQL Injection
• Dynamic SQL With Parameters
• Escape routine (can’t rely completely)
SqlDataAdapter myCommand = new SqlDataAdapter( "SELECT au_lname,
au_fname FROM Authors WHERE au_id = @au_id", conn);
SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id",
SqlDbType.VarChar, 11);
parm.Value = Login.Text;
private string SafeSqlLiteral(string inputSQL)
{
return inputSQL.Replace("'", "''");
}
Prevent SQL Injection
Prevent SQL Injection
• Default error page revels
• Database information
• Tables and Stored Procedure
information
• Internal file structure
• Configure Generic Error Page (5xx page)
<customErrors mode="On" defaultRedirect="YourErrorPage.htm" />
Prevent SQL Injection
• Use Microsoft Enterprise Library
Conclusion

More Related Content

What's hot

Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...adonatwork
 
Episode 4 - Introduction to SOQL in Salesforce
Episode 4  - Introduction to SOQL in SalesforceEpisode 4  - Introduction to SOQL in Salesforce
Episode 4 - Introduction to SOQL in SalesforceJitendra Zaa
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsIvan Novikov
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template EnginesEfficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Enginesadonatwork
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
 
Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Susam Pal
 
Solr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachSolr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachAlexandre Rafalovitch
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)SqliChema Alonso
 
Black Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data RetrievalBlack Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data Retrievalqqlan
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
ERRest: the Basics
ERRest: the BasicsERRest: the Basics
ERRest: the BasicsWO Community
 
Advance java session 3
Advance java session 3Advance java session 3
Advance java session 3Smita B Kumar
 
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult CasesPositive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult CasesPositive Hack Days
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersKrzysztof Kotowicz
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoPichaya Morimoto
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
Solr Query Parsing
Solr Query ParsingSolr Query Parsing
Solr Query ParsingErik Hatcher
 

What's hot (20)

Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
Frontend Security: Applying Contextual Escaping Automatically, or How to Stop...
 
Episode 4 - Introduction to SOQL in Salesforce
Episode 4  - Introduction to SOQL in SalesforceEpisode 4  - Introduction to SOQL in Salesforce
Episode 4 - Introduction to SOQL in Salesforce
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
Efficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template EnginesEfficient Context-sensitive Output Escaping for Javascript Template Engines
Efficient Context-sensitive Output Escaping for Javascript Template Engines
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)
 
Solr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approachSolr Troubleshooting - TreeMap approach
Solr Troubleshooting - TreeMap approach
 
Playing With (B)Sqli
Playing With (B)SqliPlaying With (B)Sqli
Playing With (B)Sqli
 
Black Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data RetrievalBlack Hat: XML Out-Of-Band Data Retrieval
Black Hat: XML Out-Of-Band Data Retrieval
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
ERRest: the Basics
ERRest: the BasicsERRest: the Basics
ERRest: the Basics
 
Advance java session 3
Advance java session 3Advance java session 3
Advance java session 3
 
Solr Presentation
Solr PresentationSolr Presentation
Solr Presentation
 
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult CasesPositive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya MorimotoSQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Solr Query Parsing
Solr Query ParsingSolr Query Parsing
Solr Query Parsing
 

Viewers also liked

La tarjeta principal o mother board
La tarjeta principal o mother boardLa tarjeta principal o mother board
La tarjeta principal o mother boardKelin Arango
 
Successful startup = strong team
Successful startup = strong teamSuccessful startup = strong team
Successful startup = strong teamCaroline Rute
 
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15Teresa Clotilde Ojeda Sánchez
 

Viewers also liked (8)

NormShieldBrochure
NormShieldBrochureNormShieldBrochure
NormShieldBrochure
 
Traning
TraningTraning
Traning
 
Proyecto para laboratori1
Proyecto para laboratori1Proyecto para laboratori1
Proyecto para laboratori1
 
La tarjeta principal o mother board
La tarjeta principal o mother boardLa tarjeta principal o mother board
La tarjeta principal o mother board
 
Energia
EnergiaEnergia
Energia
 
Successful startup = strong team
Successful startup = strong teamSuccessful startup = strong team
Successful startup = strong team
 
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15
Documentos primaria-sesiones-unidad05-quinto grado-integrados-5g-u5-sesion15
 
Message app
Message appMessage app
Message app
 

Similar to Defending Apps from Injections - Input Validation & SQLi Prevention

Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra Zaa
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava SchmidtJavaDayUA
 
Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Jyotasana Bharti
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applicationssilviad74
 
WhiteList Checker: An Eclipse Plugin to Improve Application Security
WhiteList Checker: An Eclipse Plugin to Improve Application SecurityWhiteList Checker: An Eclipse Plugin to Improve Application Security
WhiteList Checker: An Eclipse Plugin to Improve Application Securityguest032fe5
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...GeeksLab Odessa
 
Web Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolWeb Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolSperasoft
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017Eoin Keary
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net ProgrammingAdam Getchell
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAnthony Ferrari
 
Apache mod security 3.1
Apache mod security   3.1Apache mod security   3.1
Apache mod security 3.1Hai Dinh Tuan
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingOrtus Solutions, Corp
 
Developer power tools
Developer power toolsDeveloper power tools
Developer power toolsNick Harrison
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guideAdy Liu
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaJevgeni Kabanov
 
Search-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsSearch-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsLionel Briand
 
Istio's mixer policy enforcement with custom adapters (cloud nativecon 17)
Istio's mixer  policy enforcement with custom adapters (cloud nativecon 17)Istio's mixer  policy enforcement with custom adapters (cloud nativecon 17)
Istio's mixer policy enforcement with custom adapters (cloud nativecon 17)Torin Sandall
 
Post Sharp Talk
Post Sharp TalkPost Sharp Talk
Post Sharp Talkwillmation
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 

Similar to Defending Apps from Injections - Input Validation & SQLi Prevention (20)

Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava Schmidt
 
Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Data annotation validation (ASP.net)
Data annotation validation (ASP.net)
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applications
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
WhiteList Checker: An Eclipse Plugin to Improve Application Security
WhiteList Checker: An Eclipse Plugin to Improve Application SecurityWhiteList Checker: An Eclipse Plugin to Improve Application Security
WhiteList Checker: An Eclipse Plugin to Improve Application Security
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 
Web Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolWeb Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI Tool
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net Programming
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor Monitoring
 
Apache mod security 3.1
Apache mod security   3.1Apache mod security   3.1
Apache mod security 3.1
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Developer power tools
Developer power toolsDeveloper power tools
Developer power tools
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Search-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsSearch-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing Systems
 
Istio's mixer policy enforcement with custom adapters (cloud nativecon 17)
Istio's mixer  policy enforcement with custom adapters (cloud nativecon 17)Istio's mixer  policy enforcement with custom adapters (cloud nativecon 17)
Istio's mixer policy enforcement with custom adapters (cloud nativecon 17)
 
Post Sharp Talk
Post Sharp TalkPost Sharp Talk
Post Sharp Talk
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 

More from Blueinfy Solutions

Mobile Application Scan and Testing
Mobile Application Scan and TestingMobile Application Scan and Testing
Mobile Application Scan and TestingBlueinfy Solutions
 
Mobile security chess board - attacks & defense
Mobile security chess board - attacks & defenseMobile security chess board - attacks & defense
Mobile security chess board - attacks & defenseBlueinfy Solutions
 
Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013Blueinfy Solutions
 
iOS Application Security Testing
iOS Application Security TestingiOS Application Security Testing
iOS Application Security TestingBlueinfy Solutions
 
Automation In Android & iOS Application Review
Automation In Android & iOS 	Application Review�Automation In Android & iOS 	Application Review�
Automation In Android & iOS Application ReviewBlueinfy Solutions
 
Web Services Hacking and Security
Web Services Hacking and SecurityWeb Services Hacking and Security
Web Services Hacking and SecurityBlueinfy Solutions
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SASTBlueinfy Solutions
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectBlueinfy Solutions
 
Applciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumerationApplciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumerationBlueinfy Solutions
 
Assessment methodology and approach
Assessment methodology and approachAssessment methodology and approach
Assessment methodology and approachBlueinfy Solutions
 
Advanced applications-architecture-threats
Advanced applications-architecture-threatsAdvanced applications-architecture-threats
Advanced applications-architecture-threatsBlueinfy Solutions
 

More from Blueinfy Solutions (18)

Mobile Application Scan and Testing
Mobile Application Scan and TestingMobile Application Scan and Testing
Mobile Application Scan and Testing
 
Mobile security chess board - attacks & defense
Mobile security chess board - attacks & defenseMobile security chess board - attacks & defense
Mobile security chess board - attacks & defense
 
Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013
 
iOS Application Security Testing
iOS Application Security TestingiOS Application Security Testing
iOS Application Security Testing
 
Html5 on mobile
Html5 on mobileHtml5 on mobile
Html5 on mobile
 
Android secure coding
Android secure codingAndroid secure coding
Android secure coding
 
Android attacks
Android attacksAndroid attacks
Android attacks
 
Automation In Android & iOS Application Review
Automation In Android & iOS 	Application Review�Automation In Android & iOS 	Application Review�
Automation In Android & iOS Application Review
 
Web Services Hacking and Security
Web Services Hacking and SecurityWeb Services Hacking and Security
Web Services Hacking and Security
 
Source Code Analysis with SAST
Source Code Analysis with SASTSource Code Analysis with SAST
Source Code Analysis with SAST
 
HTML5 hacking
HTML5 hackingHTML5 hacking
HTML5 hacking
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
 
Blind SQL Injection
Blind SQL InjectionBlind SQL Injection
Blind SQL Injection
 
Application fuzzing
Application fuzzingApplication fuzzing
Application fuzzing
 
SQL injection basics
SQL injection basicsSQL injection basics
SQL injection basics
 
Applciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumerationApplciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumeration
 
Assessment methodology and approach
Assessment methodology and approachAssessment methodology and approach
Assessment methodology and approach
 
Advanced applications-architecture-threats
Advanced applications-architecture-threatsAdvanced applications-architecture-threats
Advanced applications-architecture-threats
 

Recently uploaded

Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...itnewsafrica
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 

Recently uploaded (20)

Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 

Defending Apps from Injections - Input Validation & SQLi Prevention

  • 3. Input Validation • Design Strategy • Assume all input is malicious. • Centralize validation approach. • Client-side validation doesn’t help. • Be careful with canonicalization issues. • Constrain, reject, and sanitize your input.
  • 4. Input Validation • Design Strategy • Validate for type, length, format and range. • Prepare Whitelist of characters instead of Blacklist.
  • 5. Input Validation • Options for constraining data, Requirement Options Type checks • .NET Framework type system. Parse string data, convert to a strong type, and then handle FormatExceptions. Regular expressions. •Use ASP.NET RegularExpressionValidator control or Regex class. Length checks Regular expressions String.Length property Format checks Regular expressions for pattern matching .NET Framework type system Range checks ASP.NET RangeValidator control (supports currency, date, integer, double, and string data) Typed data comparisons
  • 6. Input Validation • Validation Controls, Validation Server Control Description CompareValidator Compares the value of one input control to the value of another input control or to a fixed value CustomValidator Allows you to write a method to handle the validation of the value entered RangeValidator Checks that the user enters a value that falls between two values RegularExpressionValidator Ensures that the value of an input control matches a specified pattern RequiredFieldValidator Makes an input control a required field ValidationSummary Displays a report of all validation errors occurred in a Web page
  • 8. Input Validation • Regex (System.Text.RegularExpressions) Regular expressions are much easier to understand if you use the  following syntax and comment each component of the expression  using #. To enable comments, you must also specify  RegexOptions.IgnorePatternWhitespace, which means that non-escaped  white space is ignored. Regex regex = new Regex(@"                         ^          # anchor at the start                        (?=.*d)    # must contain at least one  digit                        (?=.*[a-z])  # must contain one lowercase                        (?=.*[A-Z])  # must contain one uppercase                        .{8,10}      # From 8 to 10 characters in  length                        $            # anchor at the end",                         RegexOptions.IgnorePatternWhitespace);
  • 9. Input Validation • String Fields (Name, Address..) • For Social Security Number the expression would be "d{3}-d{2}-d{4}" <form id="WebForm" method="post" runat="server">   <asp:TextBox id="txtName" runat="server"></asp:TextBox>   <asp:RegularExpressionValidator id="nameRegex "runat="server"          ControlToValidate="txtName"          ValidationExpression="[a-zA-Z'.'-'s]{1,40}"          ErrorMessage="Invalid name">   </asp:regularexpressionvalidator> </form>
  • 10. Input Validation • Date/Time Field Validation try { DateTime dt = DateTime.Parse(txtDate.Text).Date; } // If the type conversion fails, a FormatException is thrown catch(FormatException ex) { // Return invalid date message to caller } //range check on a date field // Exception handling is omitted for brevity DateTime dt = DateTime.Parse(txtDate.Text).Date; // The date must be today or earlier if(dt > DateTime.Now.Date) throw new ArgumentException("Date must be in the past");
  • 11. Input Validation • Numeric Field Validation • Convert input to integer type and return the error if exception raised. try { int i = Int32.Parse(txtAge.Text); . . . } catch( FormatException) { . . . }
  • 12. Input Validation • Range Validation • Use RangeValidator control with RequiredFieldValidator control so it can't accept blank input. • Convert into Integer with FormatException handling and check the integer range.
  • 13. Input Validation • Range Validation <form id="WebForm3" method="post" runat="server"> <asp:TextBox id="txtNumber" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="rangeRegex" runat="server" ErrorMessage="Please enter a number between 0 and 255" ControlToValidate="txtNumber" style="LEFT: 10px; POSITION: absolute; TOP: 47px" > </asp:RequiredFieldValidator> <asp:RangeValidator id="RangeValidator1" runat="server" ErrorMessage="Please enter a number between 0 and 255" ControlToValidate="TextBox1" Type="Integer" MinimumValue="0" MaximumValue="255" style="LEFT: 10px; POSITION: absolute; TOP: 47px" > </asp:RangeValidator> <asp:Button id="Button1" style="LEFT: 10px; POSITION: absolute; TOP: 100px" runat="server" Text="Button"></asp:Button> </form>
  • 14. Input Validation • Sanitizing Inputs • Strips out a range of potentially unsafe characters, including < > " ' % ; ( ) &. private string SanitizeInput(string input) { Regex badCharReplace = new Regex(@"([<>""'%;()&])"); string goodChars = badCharReplace.Replace(input, ""); return goodChars; }
  • 15. Input Validation • Validating HTML controls private void Page_Load(object sender, System.EventArgs e) { // Note that IsPostBack applies only for // server forms (with runat="server") if ( Request.RequestType == "POST" ) // non-server forms { // Validate the supplied email address if( !Regex.Match(Request.Form["email"], @"w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*", RegexOptions.None).Success) { // Invalid email address } // Validate the supplied name if ( !RegEx.Match(Request.Form["name"], @"[A-Za-z'- ]", RegexOptions.None).Success) { // Invalid name } } }
  • 16. Input Validation • File/Path Input • Avoid code which accepts file input or path input from the caller. • Use fixed file names and locations • Canonicalize path names before validating by System.IO.Path.GetFullPath or Request.MapPath to check that the file path is valid in the context of your application. • Use .NET code access security to grant the precise FileIOPermission to your code
  • 17. Input Validation • MapPath API try { string mappedPath = Request.MapPath( inputPath.Text, Request.ApplicationPath, false); //Is path is what supposed to be if(!validateFilepath(mappedPath)) { return null; } if(mappedPath.exist()) { return abspath; } } catch (HttpException) { // Cross-application mapping attempted }
  • 18. For XML Input • Create and use xml schema definition (XSD) or DTD file for xml validation • Don’t just check XML for certain tags. • Pay special attention to XPATH query inputs.
  • 19. Input Validation • ESAPI (The OWASP Enterprise Security API) • Open source free library • Set of security control interfaces. • Reference implementation for each security control. The logic is not organization or application-specific. An example: string-based input validation.
  • 20. OWASP ESAPI Namespace ESAPI { AccessController Encoder Encryptor HttpUtilities IntrusionDetector Logger Randomizer SecurityConfiguration Validator }
  • 21. Input Validation • ESAPI Sample public void Test_IsValidDouble() { IValidator validator = Esapi.Validator; //testing negative range Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Double, "-4")); //testing empty string Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Double, "")); Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Double, "alsdkf")); } public void Test_GetValidDate() { IValidator validator = Esapi.Validator; Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Date, "June 23, 1967")); Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Date, "Jun 23, 1967")); Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, "June 32, 1967")); Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, string.Empty)); Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Date, null)); }
  • 22. Input Validation • ESAPI Sample public void Test_StringRule() { IValidator validator = Esapi.Validator; string id = Guid.NewGuid().ToString(); StringValidationRule rule = new StringValidationRule(); validator.AddRule(id, rule); // Test valid Assert.IsTrue(validator.IsValid(id, Guid.NewGuid().ToString())); // Test allow null or empty Assert.IsFalse(validator.IsValid(id, string.Empty)); Assert.IsFalse(validator.IsValid(id, null)); rule.AllowNullOrEmpty = true; // Test whitelist Assert.IsTrue(validator.IsValid(id, "abc")); rule.AddWhitelistPattern("d+"); Assert.IsFalse(validator.IsValid(id, "abc")); Assert.IsTrue(validator.IsValid(id, "123")); // Test blacklist rule.AddBlacklistPattern("1"); Assert.IsFalse(validator.IsValid(id, "123")); Assert.IsTrue(validator.IsValid(id, "23")); }
  • 23. Input Validation • ESAPI Sample public void Test_StringRuleRange() { IValidator validator = Esapi.Validator; // Test range string id = Guid.NewGuid().ToString(); StringValidationRule rule = new StringValidationRule() { MinLength = 1, MaxLength = 10 }; validator.AddRule(id, rule); Assert.IsTrue(validator.IsValid(id, "a")); Assert.IsFalse(validator.IsValid(id, "")); Assert.IsFalse(validator.IsValid(id, "12345678901")); } public void Test_IsValidPrintable() { IValidator validator = Esapi.Validator; Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Printable, "abcDEF")); Assert.IsTrue(validator.IsValid(BuiltinValidationRules.Printable, "! @#R()*$;><()")); char[] bytes = new char[] { (char)(0x60), (char)(0xFF), (char)(0x10), (char) (0x25) }; Assert.IsFalse(validator.IsValid(BuiltinValidationRules.Printable, new String(bytes))); }
  • 24. Prevent SQL Injection • Design Strategy • Constrain Input • Use Type Safe SQL parameters for data access. • SQL parameters can be used with stored procedures or dynamically constructed SQL command strings. Parameters perform type and length checks and also ensure that injected code is treated as literal data, not executable statements in the database.
  • 25. Prevent SQL Injection • Design Strategy • Use least privilege account that has restricted permissions in the database. • Only grant execute permissions to selected stored procedures in the database and provide no direct table access. • Protect sensitive data in storage. • Use separate data access assemblies. • Use Windows authentication
  • 26. Prevent SQL Injection • Use Separate Data Access Assemblies
  • 27. Prevent SQL Injection • Type Safe SQL Parameters • Input is treated as a literal value and SQL does not treat it as executable code. • Enforce type and length checks. • Stored Procedure without SQL parameters do not protect against SQL Injection.
  • 28. Prevent SQL Injection • Stored Procedure Example //the good example SqlDataAdapter myCommand = new SqlDataAdapter("AuthorLogin", conn); myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; SqlParameter parm = myCommand.SelectCommand.Parameters.Add( "@au_id", SqlDbType.VarChar, 11); parm.Value = Login.Text; //the bad example SqlDataAdapter myCommand = new SqlDataAdapter("LoginStoredProcedure '" + Login.Text + "'", conn);
  • 29. Prevent SQL Injection • Dynamic SQL With Parameters • Escape routine (can’t rely completely) SqlDataAdapter myCommand = new SqlDataAdapter( "SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", conn); SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11); parm.Value = Login.Text; private string SafeSqlLiteral(string inputSQL) { return inputSQL.Replace("'", "''"); }
  • 31. Prevent SQL Injection • Default error page revels • Database information • Tables and Stored Procedure information • Internal file structure • Configure Generic Error Page (5xx page) <customErrors mode="On" defaultRedirect="YourErrorPage.htm" />
  • 32. Prevent SQL Injection • Use Microsoft Enterprise Library