effective security in asp.net applications
DESCRIPTION
Effective Security in ASP.Net Applications. Jatin Sharma. Types of Threats. Network. Host. Application. Threats against the network. Threats against the host. Threats against the application. Application Security. Error handling Form authentication Input validation - PowerPoint PPT PresentationTRANSCRIPT
Effective Security inEffective Security in ASP.Net Applications ASP.Net Applications
Jatin SharmaJatin Sharma
Types of ThreatsTypes of Threats
Threats againstthe network
Threats against the host
Threats against the application
Network Host Application
Application SecurityApplication Security Error handlingError handling
Form authenticationForm authentication
Input validationInput validation
Data access & data protectionData access & data protection
Error Handling Error Handling Use web.config to handle errorsUse web.config to handle errors
Three different modes for customErrorsThree different modes for customErrors
<customErrors mode=“RemoteOnly” /><customErrors mode=“RemoteOnly” /> or =“Off” or =“Off” or =“On” or =“On”
Off – display detailed asp.net error informationOff – display detailed asp.net error information On – display custom (friendly) messages.On – display custom (friendly) messages. RemoteOnly – no detailed error for remote clients.RemoteOnly – no detailed error for remote clients.
Securing the site with Securing the site with error handlingerror handling
Example 1Example 1
<customErrors mode="On" defaultRedirect="error.aspx"/><customErrors mode="On" defaultRedirect="error.aspx"/>
Site SecuritySite Security By default, site users are anonymous.By default, site users are anonymous. They may need to be They may need to be authenticatedauthenticated and and authorizedauthorized..
AuthenticationAuthentication: the process of verifying a user’s : the process of verifying a user’s identity.identity.
AuthorizationAuthorization: to measure or establish the power or : to measure or establish the power or permission that has been given or granted by an permission that has been given or granted by an authority.authority.
ASP.Net AuthenticationASP.Net Authentication 4 different modes of authentication.4 different modes of authentication.
- - WindowsWindows: uses windows authentication system on the: uses windows authentication system on the web server (for intranet). web server (for intranet).
- - FormsForms: uses ASP.Net form-based authentication (for: uses ASP.Net form-based authentication (for internet). internet).
- - PassportPassport: uses Microsoft’s Passport Authentication: uses Microsoft’s Passport Authentication
- - NoneNone: no authentication. : no authentication.
Specifying Authentication TypeSpecifying Authentication Type
Web.configWeb.config
<configuration> <system.web> <!-- mode="Windows|Passport|Forms|None" --> <authentication mode="Windows" /> </system.web></configuration>
Forms Authentication OptionsForms Authentication Options
<configuration> <system.web> <authentication mode="Forms"> <!-- forms Attributes: name="[cookie name]" - Authentication cookie name loginUrl="[url]" - URL of login page protection="[All|None|Encryption|Validation]" timeout="[minutes]" - Length of time cookie valid path="/" - Cookie path requireSSL="[true|false]" - Restrict cookie to SSL? slidingExpiration="[true|false]" - Renew cookie? --></authentication> </system.web></configuration>
See Page 862.
Web.config
Authenticating Against the Authenticating Against the Web.Config fileWeb.Config file
<configuration><configuration><system.web><system.web> <authentication mode="Forms"><authentication mode="Forms"> <forms name=“.MyCookie" <forms name=“.MyCookie" loginUrl=“Login.aspx” loginUrl=“Login.aspx” protection=“All"protection=“All" timeout="15”timeout="15” path="/" >path="/" >
<credentials passwordFormat=“Clear”><credentials passwordFormat=“Clear”> <user name=“Sam” password=“Secret” /><user name=“Sam” password=“Secret” /> <user name=“Fred” password=“Fred” /> <user name=“Fred” password=“Fred” />
</credentials></credentials></forms></forms>
</authentication></authentication></system.web></system.web>
</configuration></configuration>
User AuthorizationUser Authorization
<!-- Deny access to anonymous (unauthenticated) users --><deny users="?" />
<!-- Grant access to Robin and Tim but no one else --><allow users="Bob, Alice" /><deny users="*" />
<!-- Grant access to everyone EXCEPT Bob and Alice --><deny users=“Robin, Tim" /><allow users="*" />
<!-- Grant access to any manager --><allow roles="Manager" /><deny users="*" />
Web.config
The Login PageThe Login Page First provide a namespace to the classes in the First provide a namespace to the classes in the
top of your class module as follows:top of your class module as follows:
Imports System.Web.SecurityImports System.Web.Security
The Login Page (cont.)The Login Page (cont.)
Using the Using the Authenticate()Authenticate() Method Method
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then FormsAuthentication.RedirectFromLoginPage(txtName.Text, False)Else lblMessage.Text = "Bad Login"End If
End Sub
Global.AsaxGlobal.Asaxprotected void Application_AuthenticateRequest(Object sender, EventArgs e)protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{{ if (HttpContext.Current.User != null)if (HttpContext.Current.User != null) {{ if (HttpContext.Current.User.Identity.IsAuthenticated)if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity){ if (HttpContext.Current.User.Identity is FormsIdentity) {{ // Get Forms Identity From Current User // Get Forms Identity From Current User
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
// Get Forms Ticket From Identity object// Get Forms Ticket From Identity object
FormsAuthenticationTicket ticket = id.Ticket;FormsAuthenticationTicket ticket = id.Ticket;
// Retrieve stored user-data (our roles from db)// Retrieve stored user-data (our roles from db)
string userData = ticket.UserData;string userData = ticket.UserData;string[] roles = userData.Split(',');string[] roles = userData.Split(',');
// Create a new Generic Principal Instance and assign to Current User// Create a new Generic Principal Instance and assign to Current User
HttpContext.Current.User = new GenericPrincipal(id, roles);HttpContext.Current.User = new GenericPrincipal(id, roles);}}
}} }} }}
The Authenticate() Method (cont.)The Authenticate() Method (cont.)
The FormsAuthentication Object handles The FormsAuthentication Object handles form security as specified in the Web.Config.form security as specified in the Web.Config.
RedirectFromLogin Page redirects to the RedirectFromLogin Page redirects to the requested page if the user has the permission.requested page if the user has the permission.
Authenticating Against a DatabaseAuthenticating Against a Databasecnn.Open() Dim i As Integer Dim myCommand As New SqlClient.SqlCommand myCommand.Connection = cnn myCommand.CommandText = "select * from userList where uname='" & _ txtName.Text & "' and upassword='" & txtPassword.Text & "'" i = myCommand.ExecuteScalar If i > 0 Then FormsAuthentication.RedirectFromLoginPage(txtName.Text, False) Else lblMessage.Text = "Bad Login" End IfCnn.Close() End Sub
SQL InjectionSQL Injection Exploits applications that use external input in Exploits applications that use external input in
database commandsdatabase commands The technique:The technique: Find a <form> field or query string parameter used Find a <form> field or query string parameter used
to generate SQL commandsto generate SQL commands Submit input that modifies the commandsSubmit input that modifies the commands
Compromise, corrupt, and destroy dataCompromise, corrupt, and destroy data
How SQL Injection WorksHow SQL Injection Works
SELECT COUNT (*) FROM UsersWHERE UserName=‘Jeff’AND Password=‘imbatman’
SELECT COUNT (*) FROM UsersWHERE UserName=‘’ or 1=1--AND Password=‘’
Model Query
Malicious Query
"or 1=1" matches everyrecord in the table
"--" comments out theremainder of the query
Avoid SQL InjectionAvoid SQL Injection
Validation Control.Validation Control.
SQL Stored Procedure.SQL Stored Procedure.
Accessing Data SecurelyAccessing Data SecurelyUse stored procedures
Never use sa to access Web databases
Store connection strings securely
Optionally use SSL/TLS or IPSec to secure theconnection to the database server 2
Apply administrative protections to SQL Server
The sa AccountThe sa Account For administration only; For administration only; nevernever use it to access a use it to access a
database programmaticallydatabase programmatically Instead, use one or more accounts that have limited Instead, use one or more accounts that have limited
database permissionsdatabase permissions For queries, use SELECT-only accountFor queries, use SELECT-only account Better yet, use stored procs and grant account EXECUTE Better yet, use stored procs and grant account EXECUTE
permission for the stored procspermission for the stored procs Reduces an attacker's ability to execute harmful Reduces an attacker's ability to execute harmful
commands (e.g., DROP TABLE)commands (e.g., DROP TABLE)
Creating a Limited AccountCreating a Limited Account
USE LoginGO
-- Add account named webuser to Login databaseEXEC sp_addlogin 'webuser', 'mxyzptlk', 'Login'
-- Grant webuser access to the databaseEXEC sp_grantdbaccess 'webuser'
-- Limit webuser to calling proc_IsUserValidGRANT EXECUTE ON proc_IsUserValid TO webuser
Connection StringsConnection Strings Storing plaintext database connection strings in Storing plaintext database connection strings in
Web.config is riskyWeb.config is risky Vulnerable to file disclosure attacksVulnerable to file disclosure attacks
Storing encrypted database connection strings Storing encrypted database connection strings increases securityincreases security
Encrypting connection strings is easyEncrypting connection strings is easy System.Security.Cryptography classesSystem.Security.Cryptography classes
Database PasswordsDatabase Passwords EncryptingEncrypting
string name =string name =FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text,"MD5");FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text,"MD5");
DecryptingDecryptingstring pwd = string pwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text,"MD5");FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text,"MD5");
string command = "SELECT roles FROM users WHERE username = string command = "SELECT roles FROM users WHERE username = '" + TextBox1.Text + "' AND pass = '" + pwd + "'";'" + TextBox1.Text + "' AND pass = '" + pwd + "'";