25
Effective Security Effective Security in in ASP.Net ASP.Net Applications Applications Jatin Sharma Jatin Sharma

Effective Security in ASP.Net Applications

  • Upload
    jeff

  • View
    35

  • Download
    0

Embed Size (px)

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 Presentation

Citation preview

Page 1: Effective Security in  ASP.Net Applications

Effective Security inEffective Security in ASP.Net Applications ASP.Net Applications

Jatin SharmaJatin Sharma

Page 2: Effective Security in  ASP.Net Applications

Types of ThreatsTypes of Threats

Threats againstthe network

Threats against the host

Threats against the application

Network Host Application

Page 3: Effective Security in  ASP.Net Applications

Application SecurityApplication Security Error handlingError handling

Form authenticationForm authentication

Input validationInput validation

Data access & data protectionData access & data protection

Page 4: Effective Security in  ASP.Net Applications

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.

Page 5: Effective Security in  ASP.Net Applications

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"/>

Page 6: Effective Security in  ASP.Net Applications

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.

Page 7: Effective Security in  ASP.Net Applications

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.

Page 8: Effective Security in  ASP.Net Applications

Specifying Authentication TypeSpecifying Authentication Type

Web.configWeb.config

<configuration> <system.web> <!-- mode="Windows|Passport|Forms|None" --> <authentication mode="Windows" /> </system.web></configuration>

Page 9: Effective Security in  ASP.Net Applications

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

Page 10: Effective Security in  ASP.Net Applications

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>

Page 11: Effective Security in  ASP.Net Applications

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

Page 12: Effective Security in  ASP.Net Applications

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

Page 13: Effective Security in  ASP.Net Applications

The Login Page (cont.)The Login Page (cont.)

Page 14: Effective Security in  ASP.Net Applications

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

Page 15: Effective Security in  ASP.Net Applications

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);}}

}} }} }}

Page 16: Effective Security in  ASP.Net Applications

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.

Page 17: Effective Security in  ASP.Net Applications

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

Page 18: Effective Security in  ASP.Net Applications

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

Page 19: Effective Security in  ASP.Net Applications

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

Page 20: Effective Security in  ASP.Net Applications

Avoid SQL InjectionAvoid SQL Injection

Validation Control.Validation Control.

SQL Stored Procedure.SQL Stored Procedure.

Page 21: Effective Security in  ASP.Net Applications

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

Page 22: Effective Security in  ASP.Net Applications

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)

Page 23: Effective Security in  ASP.Net Applications

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

Page 24: Effective Security in  ASP.Net Applications

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

Page 25: Effective Security in  ASP.Net Applications

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 + "'";