Author
yasar-selcuk-okmen
View
227
Download
0
Embed Size (px)
8/6/2019 Dotnet Sec
1/58
Adam Getchell ([email protected])
Scott Kirkland ([email protected])
Alan Lai ([email protected])
College of Agricultural & Environmental SciencesDeans OfficeIT Security Symposium
June 20-22, 2007
8/6/2019 Dotnet Sec
2/58
Introductions Not experts, just offering experience gained from .NET
programs weve done
Goal is practical advice, based on principles and codesmells1, rather than exact code one is supposed toapply to every programs (though reusable code isgood)
This (mostly) works for us it may not work for you.Use what works for your team, but remember:
Good Software = Secure Software
8/6/2019 Dotnet Sec
3/58
OWASP Top 10 20072
1. Cross Site Scripting (XSS)
2. SQL Injection
3. Malicious File Execution (via Remote File Inclusion)
4. Insecure Direct Object Reference
5. Cross Site Request Forgery (CSRF)
6. Information Leakage and Improper Error Handling
7. Broken Authentication and Session Management
8. Insecure Cryptographic Storage
9. Insecure Communications
10. Failure to Restrict URL Access
8/6/2019 Dotnet Sec
4/58
XSS Cross site scripting is the most prevalent/pernicious web
application security issue. XSS flaws occur whenever anapplication takes data that originated from a user andsends it to a web browser without first validating orencoding that content.
XSS types:1. Reflected displaying user supplied (hostile) data directly2. Stored storing user supplied (hostile) data and displaying
(e.g. CMS, blogs, forums)3. DOM Injection Manipulating JavaScript directly on the
page, including using XmlHttpRequest (basis of AJAX) toget around same source origination policies to forwardusers to hostile sites, etc.
8/6/2019 Dotnet Sec
5/58
SQL Injection Attacks SQL Injection Attacks: Easy, Common, Dangerous.
Definition: Injection occurs when user-supplied datais sent to an interpreter as part of a command or query.Attackers trick the interpreter into executingunintended commands via supplying specially crafted
data.
8/6/2019 Dotnet Sec
6/58
SQL Injection AttacksVulnerability:
String query = "SELECT user_id FROM user_dataWHERE user_name = '" + txtUserName.Text + "'";
8/6/2019 Dotnet Sec
7/58
SQL Injection AttacksProtection:
Use Input Validation Check for length, type, sytax,etc.
Use Stored Procedures or at least strongly typedparameterized queries.
Dont show detailed error messages.
8/6/2019 Dotnet Sec
8/58
SQL Injection AttacksParameterized Queries:
SqlCommand command = new SqlCommand();command.CommandText = "SELECT user_id FROM
user_data WHERE user_name = @user_name";
command.Parameters.AddWithValue("@user_name",
txtUserName.Text);
8/6/2019 Dotnet Sec
9/58
Input Validation .NET makes it easy to validate input controls using the
controls.
ASP.NET Validators (except for the customValidator)validate controls once using client side JavaScript andagain on the server side (protecting you from clients
who turn off JavaScript).
8/6/2019 Dotnet Sec
10/58
.NET Validation Tips An Empty Control will pass every validation test except for
the RequiredFieldValidator Ex: If you want to make sure a string is not empty and
matches a regular expression (like an Email address),you must use both a RequiredFieldValidator and aRegularExpressionValidator.
The CompareValidator can do much more than comparingtwo controls. Leave the ControlToValidate propery blank, use the
Type, Operator and ValueToCompare properties. Operators: dataTypeCheck, Equal, NotEqual,
GreaterThan, GreaterThanEqual, LessThan,LessThanEqual
Types: Currency, Date, Double, Integer, String
8/6/2019 Dotnet Sec
11/58
.NET CompareValidator Examples The value entered should convert to an integer greater
than one
8/6/2019 Dotnet Sec
12/58
.NET CompareValidator Examples The value entered should convert to a DateTime
8/6/2019 Dotnet Sec
13/58
Parsing Objectsint age = 0;
if (int.TryParse(textBoxAge.Text, out age))
{
// Success in parsing string to int
}
else // Was not able to parse string{
// Handle error
}
8/6/2019 Dotnet Sec
14/58
Microsoft Enterprise Library [9] What is it?
Reusable source-code components implementing best practices andproviding proven solutions to common problems. Can be integratedinto applications and extended/customized
Caching Application Block
Cryptography Application Block
Data Access Application Block
Exception Handling Application Block
Logging Application Block
Policy Injection Application Block
Security Application Block
Validation Application Block
8/6/2019 Dotnet Sec
15/58
Validation Application BlockEx: Nullable Phone Number
[IgnoreNulls()]
[RegexValidator(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",MessageTemplate="Phone number must be properlyformatted")]public virtual string HRPhone
{ get { return _HRPhone; }set { _HRPhone = value; }
}
8/6/2019 Dotnet Sec
16/58
Validation Application Block Ex: Non-Null Email Address between 7 and 150 chars.
[NotNullValidator()][StringLengthValidator(7, RangeBoundaryType.Inclusive,
150, RangeBoundaryType.Inclusive,MessageTemplate = "Email address must be from 7 to 150characters")][RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",MessageTemplate = "Email must be properly formatted")]
public virtual string HREmail{get { return _HREmail; }set { _HREmail = value; }
}
8/6/2019 Dotnet Sec
17/58
Validation Application Block Ex: Non-Null String between 1 and 100 chars.
[NotNullValidator()][StringLengthValidator(1, 100)]public virtual string PositionTitle{
get { return _PositionTitle; }set { _PositionTitle = value;}
}
8/6/2019 Dotnet Sec
18/58
Validation Application BlockEx: Nullable DateTime between now and next month.
[IgnoreNulls()]
[DateTimeRangeValidator(DateTime.Now,DateTime.Now.AddMonths(1))]
public virtual DateTime? DatePosted
{
get { return _DatePosted; }set { _DatePosted = value; }
}
8/6/2019 Dotnet Sec
19/58
Validation Application Blockpublic static class ValidateBO
{
public static bool isValid(T obj)
{
return Validation.Validate(obj).IsValid;
}
public static ValidationResults GetValidationResults(T obj){
return Validation.Validate(obj);
}
public static string GetValidationResultsAsString(T obj)
{
StringBuilder ErrorString = new StringBuilder();
foreach (ValidationResult r in GetValidationResults(obj))
{
ErrorString.AppendLine(string.Format("{0}, {1}", r.Key, r.Message));
}
return ErrorString.ToString();
}}
8/6/2019 Dotnet Sec
20/58
Validation Application Blockif (ValidateBO.isValid(jobDescription))
{
newPosition.DescriptionFile = jobDescription;
}else
{
Trace.Warn(ValidateBO.GetValidationResultsAsSt
ring(jobDescription));
//Throw error
}
8/6/2019 Dotnet Sec
21/58
File Upload/Download -- No direct
file access
Dont allow direct URL access to stored (user supplied)files.
Potential Issues:
Remote Code Execution
Unauthorized File Access
8/6/2019 Dotnet Sec
22/58
File Upload/Download -- No direct
file access
Protection Obscure Filenames: Store files as a hash or partial
reference
Use a proxy class to retrieve files on behalf of a user
Check user permissions on retrieval Return the file as a binary stream (application/octet-stream)
8/6/2019 Dotnet Sec
23/58
8/6/2019 Dotnet Sec
24/58
Insecure Direct Object Reference A direct object reference occurs when a developer exposes a reference to an
internal implementation object, such as a file, directory, database record, orkey as a URL or form parameter
Without access control checks such as authorization and parameter checking,very easy to abuse/manipulate systems.
Ex: (can you spot the flaws)
Franais require_once($_REQUEST['language]."lang.php");
And, assuming no SQL injection is possible, what is wrong with the following?
int cartID = Integer.parseInt( request.getParameter("cartID" ) ); String query = "SELECT * FROM table WHEREcartID=" + cartID;
8/6/2019 Dotnet Sec
25/58
Direct Object Reference
countermeasuresAvoid use of object references whenever possible, such
as primary keys or filenames
Validate any private object references extensively (e.g.RegExs)
Verify authorization to all referenced objects
Its the web Assume a user will access any published
URL, dont assume theyll follow links to get there But see more on CSRF!
8/6/2019 Dotnet Sec
26/58
Code Access Security Identify Permissions your application requires using
Permission Calculator (Permcalc.exe)
Choose an appropriate trust level with requiredpermissions, or better yet, create a custom trust levelwith only the permissions needed by the application
Configure the ASP.NET application to use
8/6/2019 Dotnet Sec
27/58
Code Access Security Declarative Code Security Checks
Check by Role, User or Authenticated
In the System.Security.Permissions namespace.
Throws a System.Security.SecurityException.
[PrincipalPermission(
SecurityAction.Demand,
Role="Admin")]
private void secureOperation() { }
8/6/2019 Dotnet Sec
28/58
Custom Permissions Copy the Medium trust policy file, web_MediumTrust.conf,located in%windir%\Microsoft.NET\Framework\{version}\CONFIG\ to afile located in your application directory
Add RegistryPermission to inWeb_CustomTrust.config:
8/6/2019 Dotnet Sec
29/58
Custom Permissions Add new element to the section of the Web.config file to define newlevel called Custom associated with custom policy file
8/6/2019 Dotnet Sec
30/58
Custom Permissions Add RegistryPermission to in
Web_CustomTrust.config:
8/6/2019 Dotnet Sec
31/58
Custom Permissions Refer to web_CustomTrust.config in your applicationsweb.config:...
...
8/6/2019 Dotnet Sec
32/58
Code Signing Sign common necessary files with private key to
emplace in the Global Assembly Cache
8/6/2019 Dotnet Sec
33/58
Example of Signing Enterprise
Library Signing Enterprise Library 3.0 is easier than ever!
Strong-Naming Guidance Package (included indownload)
Generates Key Pair files
Places keys into each project (each application block hasits own project )
All you have to do is build
8/6/2019 Dotnet Sec
34/58
CSRF Cross site request forger forces a logged-on browser to send a request to avulnerable web app, which performs chosen actions on behalf of the victim.
Example:
Changed to:
Note the use of Direct Object access, but done in the context ofthe user!
(Hence my own preference to not use URL-based objectreferences)
8/6/2019 Dotnet Sec
35/58
Information Leakage and Improper
Error Handling
In a production environment, always set customErrorsto On or RemoteOnly in theweb.config file.
You can set a generic error page to be displayed when anuncaught error is raised, and specific error pages whencertain status codes appear (403/404/etc).
8/6/2019 Dotnet Sec
36/58
Information Leakage and Improper
Error Handling Using Global.asax to handle and log uncaught exceptions
globally
voidApplication_Error(object sender, EventArgs e){
Exception baseException =Server.GetLastError().GetBaseException();
//Handle Error: Log and Redirect to Error Page
}
8/6/2019 Dotnet Sec
37/58
Information Leakage and Improper
Error HandlingOverriding System.UI.Web.Page to handle
and log uncaught exceptions globally
public classApplicationPage : System.Web.UI.Page{
publicApplicationPage() { }
protected override void OnError(EventArgs e){
Exception baseException = Server.GetLastError().GetBaseException();
//Handle Error: Log and Redirect to Error Pagebase.OnError(e);
}}
8/6/2019 Dotnet Sec
38/58
Error Handling / Logging Logging of errors
Writing errors to database
Emailing errors
Writing to the event log
When reporting errors be sure to get any innerexceptions, not just the outer most exception
8/6/2019 Dotnet Sec
39/58
Error Handling / LoggingErrorReporting eReport = newErrorReporting("ApplicationName", "EventLogName");
try{
// Execute Database call}catch (SqlException sqlEx){
eReport.ReportError(sqlEx,System.Reflection.MethodBase.GetCurrentMethod());}
8/6/2019 Dotnet Sec
40/58
GridView DataKeys Use DataKeys to store primary key fields without
displaying them to the user.
Note: The DataKeyNames property must be set for theautomatic updating and deleting features of theGridView control to work.
8/6/2019 Dotnet Sec
41/58
GridView DataKeys
//Access the datakey in your codefile
gViewData.DataKeys[rowIndex].Value;
8/6/2019 Dotnet Sec
42/58
Broken Authentication/Session
ManagementAccount credentials and session tokens are not often
properly protected. Attackers compromise passwords,keys, or authentication tokens to assume other users
identities.
8/6/2019 Dotnet Sec
43/58
Role Provider The fundamental job of a role provider is to interface
with data sources containing role data mapping usersto roles, and to provide methods for creating roles,
deleting roles, adding users to roles, and so on. Given a user name, the role manager relies on the role
provider to determine whether what role or roles theuser belongs to.
8/6/2019 Dotnet Sec
44/58
Role Providerpublic abstract class RoleProvider : ProviderBase{
// Abstract propertiespublic abstract string ApplicationName { get; set; }
// Abstract methods
public abstract bool IsUserInRole(string username,string roleName);
public abstract string[] GetRolesForUser(string username);public abstract void CreateRole(string roleName);public abstract bool DeleteRole(string roleName,
bool throwOnPopulatedRole);public abstract bool RoleExists(string roleName);public abstract void AddUsersToRoles(string[] usernames,
string[] roleNames);
public abstract void RemoveUsersFromRoles(string[] usernames,string[] roleNames);public abstract string[] GetUsersInRole(string roleName);public abstract string[] GetAllRoles();public abstract string[] FindUsersInRole(string roleName,
string usernameToMatch);}
8/6/2019 Dotnet Sec
45/58
Role Provider
8/6/2019 Dotnet Sec
46/58
Role Provider
8/6/2019 Dotnet Sec
47/58
Role Provider: Code Demo Login.aspx.cs
8/6/2019 Dotnet Sec
48/58
Encrypting the Web.configWhy use the Web.Config?
Centrally store sensitive information (passwords,connection strings, etc.)
Why encrypt?
Sensitive information in plain text is no good
Password
8/6/2019 Dotnet Sec
49/58
Encrypting the Web.Config Methods
Programmatic Encryption
Requires manual encryption and decryption in code
Changes to legacy programs required
Encrypting using Machine Keys (RSA Keys)
Performs on the fly decryption
No changes to code necessary
8/6/2019 Dotnet Sec
50/58
Encrypting the Web.ConfigChanges to make to the web.config :
8/6/2019 Dotnet Sec
51/58
Encrypting the Web.Config How? (Using machine key method)
Use tool called aspnet_regiis.exe
1. Add necessary lines to the web.config
2. Import / create machine key
3. Encrypt desired section (appSettings or
connectionStrings)
8/6/2019 Dotnet Sec
52/58
Insecure Communications Use SSL
Purchase Certs at IT Secuity site:
http://security.ucdavis.edu/
Or you can use selfcert.exe or OpenSSH to create your
own certificates
No excuse!
http://security.ucdavis.edu/http://security.ucdavis.edu/8/6/2019 Dotnet Sec
53/58
Secure SQL server access Use Windows Authentication
Mixed mode uses trivially crackable encryption
Unicode passwordXORdwith byte value 0xA5! [4]
Recommend local Windows password rather thanDomain account
Associate with Application Pool
Keep separate accounts for separate App Pools
Development vs. Production
Sensitive vs. Non-sensitive
8/6/2019 Dotnet Sec
54/58
Other SQL Server practices Strong password to sa account, even when not in mixed mode Prevent brute force attacks Yes, SQL Server 2005 has an sa account
Use Firewall to only allow certain servers to talk to particular ports
Dont give generic access to 1433 and 1434 Lots of attacks that do not require authentication
Check for backdoors Audit startup procedures (sp_MSRepl_startup) Audit commonly run procedures (sp_help, sp_password) Administrator Xstatus (2218 allows Admin login with no password)
Use SQL Server 2005 if possible Reduced attack surface Table and column encryption [6]
8/6/2019 Dotnet Sec
55/58
But All that can change next year. So what principles stay in common?
Software Engineering - A systematic approach to the analysis, design,implementation and maintenance ofsoftware3
Software Development Life Cycle Security is a process Maintainable, auditable, provably correct code
Architecture Separation of concerns into functional, independent, minimally coupled layers Service Oriented Architecture
Infrastructure Separation of concerns into functional, independent, minimally coupled tiers Deployment, maintenance, upgrade, and retirement handled separately from
programming/development
http://dictionary.reference.com/browse/softwarehttp://dictionary.reference.com/browse/softwarehttp://dictionary.reference.com/browse/software8/6/2019 Dotnet Sec
56/58
Software Engineering Team Foundation Server with Visual Studio Team System Source control and code check-in policies
Require compilation(!) Require passing FxCop Require evaluation
Bug and project tracking Automated (nightly) builds with MSBuild Test-driven development
Unit testing Database testing
Setup & deployment projects Use Design Patterns
Singletons
Factories Inversion of Control/Dependency Injection
Consider using frameworks Microsoft Enterprise Library NHibernate (Object-relational mapping) [7] Castle (Object interceptors) [8]
8/6/2019 Dotnet Sec
57/58
References1. A Taxonomy for Bad Code Smells.http://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htm
2. The Open Web Application SecurityProject..
3. "software engineering." The Free On-line Dictionary of Computing. Denis Howe. 13Jun. 2007. .
4. Threat Profiling Microsoft SQL Server (A Guide to Security Auditing), DavidLitchfield, 20 July 2002. http://www.nextgenss.com/papers/tp-SQL2000.pdf
5. Security in SQL Server 2005 as seen by a programmer, Software Developers Journal,21 March 2006. http://www.codeproject.com/database/sqlserver_secure.asp
6. How To: Use Code Access Security in ASP.NET 2.0, Microsoft Patterns & PracticesDeveloper Center, August 2005. http://msdn2.microsoft.com/en-us/library/ms998326.aspx
7. NHibernate for .NET, SergeyKoshcheyev, Ayende Rahien, and others.http://www.hibernate.org/343.html
8. Castle Project, Castle Project. http://www.castleproject.org/
9. Enterprise Library, Microsoft Patterns & Practices Developer Center, May 2007.http://msdn2.microsoft.com/en-us/library/aa480453.aspx
http://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htmhttp://dictionary.reference.com/browse/software%20engineeringhttp://dictionary.reference.com/browse/software%20engineeringhttp://www.nextgenss.com/papers/tp-SQL2000.pdfhttp://www.codeproject.com/database/sqlserver_secure.asphttp://msdn2.microsoft.com/en-us/library/ms998326.aspxhttp://msdn2.microsoft.com/en-us/library/ms998326.aspxhttp://www.hibernate.org/343.htmlhttp://www.castleproject.org/http://www.castleproject.org/http://www.hibernate.org/343.htmlhttp://msdn2.microsoft.com/en-us/library/ms998326.aspxhttp://msdn2.microsoft.com/en-us/library/ms998326.aspxhttp://msdn2.microsoft.com/en-us/library/ms998326.aspxhttp://www.codeproject.com/database/sqlserver_secure.asphttp://www.nextgenss.com/papers/tp-SQL2000.pdfhttp://www.nextgenss.com/papers/tp-SQL2000.pdfhttp://www.nextgenss.com/papers/tp-SQL2000.pdfhttp://dictionary.reference.com/browse/software%20engineeringhttp://dictionary.reference.com/browse/software%20engineeringhttp://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htm8/6/2019 Dotnet Sec
58/58
Adam Getchell ([email protected])Scott Kirkland ([email protected])
Alan Lai ([email protected])
College of Agricultural & Environmental SciencesDeans OfficeIT Security Symposium
June 20-22, 2007