dev312 building secure web applications: defenses and countermeasures

41
DEV312 Building Secure Web Applications: Defenses And Countermeasures Jeff Prosise Jeff Prosise Co-founder Co-founder Wintellect Wintellect (www.wintellect.com) (www.wintellect.com)

Upload: aretha

Post on 23-Mar-2016

37 views

Category:

Documents


2 download

DESCRIPTION

DEV312 Building Secure Web Applications: Defenses And Countermeasures. Jeff Prosise Co-founder Wintellect (www.wintellect.com). Holistic Approach To Security. Network. Host. Application. Port blocking Filtering Encryption. Updates Internet Information Server hardening ACLs CAS - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: DEV312 Building Secure Web Applications: Defenses And Countermeasures

DEV312 Building Secure Web Applications: Defenses And Countermeasures

Jeff ProsiseJeff ProsiseCo-founderCo-founderWintellect (www.wintellect.com)Wintellect (www.wintellect.com)

Page 2: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Holistic Approach To SecurityHolistic Approach To SecurityPort blockingPort blockingFilteringFilteringEncryptionEncryption

UpdatesUpdatesInternet Information Server hardeningInternet Information Server hardeningACLsACLsCASCASLoggingLoggingLeast privilegeLeast privilegeAccount Account managementmanagement

ValidationValidationHashingHashingEncryptionEncryptionSecrets managementSecrets managementCookie management Cookie management Session managementSession managementError handlingError handling

Spoofed packets, etc.Spoofed packets, etc.

Buffer overflows, illicit paths, etc. Buffer overflows, illicit paths, etc.

SQL injection, XSS, input tampering, etc.SQL injection, XSS, input tampering, etc.

NetworkNetwork HostHost ApplicationApplication

Defend the networkDefend the network

Defend the hostDefend the host

Defend the applicationDefend the application

Page 3: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The NetworkHarden firewallsHarden firewalls

i

Harden routers and switchesHarden routers and switches

Encrypt sensitive communicationsEncrypt sensitive communications

http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh15.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh15.asp

Stay current with patches and updatesStay current with patches and updatesBlock unused ports and protocolsBlock unused ports and protocolsUse filtering to reject illicit requestsUse filtering to reject illicit requests

Stay current with patches and updatesStay current with patches and updatesUse ingress/egress filtering to reject spoofed packetsUse ingress/egress filtering to reject spoofed packetsScreen ICMP traffic from the internal networkScreen ICMP traffic from the internal networkScreen directed broadcast requests from the internal networkScreen directed broadcast requests from the internal networkReject trace routing requestsReject trace routing requests

http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asp http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT18.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT18.asp

Page 4: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The Host

i

Stay current with service packs and updatesStay current with service packs and updates

Harden Internet Information Server 5 by running Harden Internet Information Server 5 by running IISLockdownIISLockdown

Harden Internet Information Server 5 and 6 Harden Internet Information Server 5 and 6 by installing URLScanby installing URLScan

Disables FTP, SMTP, and NNTPDisables FTP, SMTP, and NNTPRemoves key script mappings such as .idq, .htr, and .printerRemoves key script mappings such as .idq, .htr, and .printerRemoves IISSamples, IISHelp, Scripts, and other virtual directoriesRemoves IISSamples, IISHelp, Scripts, and other virtual directoriesACLs system tools and Web content directories to limit accessACLs system tools and Web content directories to limit accessDisables WebDAVDisables WebDAVInstalls URLScanInstalls URLScan

Logs failed requestsLogs failed requestsLimits request sizes to mitigate DoS attacksLimits request sizes to mitigate DoS attacksMasks content headers revealing IIS type and version numberMasks content headers revealing IIS type and version numberBlocks requests with potentially injurious characters (e.g., dots in path names)Blocks requests with potentially injurious characters (e.g., dots in path names)Canonicalizes and verifies path names to thwart directory traversal attacksCanonicalizes and verifies path names to thwart directory traversal attacksDisables specified verbs (e.g., "DEBUG")Disables specified verbs (e.g., "DEBUG")

http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh16.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh16.asp

Page 5: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The HostHarden the Web server’s TCP/IP stackHarden the Web server’s TCP/IP stack

http://msdn.microsoft.com/library/en-us/dnnetsec/html/HTHardTCP.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/HTHardTCP.asp

Run ASP.NET using the principle of least privilegeRun ASP.NET using the principle of least privilegeAvoid running as SYSTEMAvoid running as SYSTEMConsider running with partial trustConsider running with partial trust

Limit the size of file uploadsLimit the size of file uploads

<configuration> <system.web> <!-- Limit request length to 128K (default = 4 MB) --> <httpRuntime maxRequestLength="128" /> </system.web></configuration>

Page 6: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The HostDisable unused shares and servicesDisable unused shares and services

Harden user accountsHarden user accounts

Delete nonessential shares and restrict access to othersDelete nonessential shares and restrict access to othersDisable nonessential services and protocols (e.g., SMB and NetBIOS)Disable nonessential services and protocols (e.g., SMB and NetBIOS)Remove or secure Remote Data Services (RDS)Remove or secure Remote Data Services (RDS)

Disable the Guest accountDisable the Guest accountUse strong passwords on all accountsUse strong passwords on all accountsRename the administrator accountRename the administrator accountDisallow null sessions (anonymous logons)Disallow null sessions (anonymous logons)Restrict remote logons to only those who need itRestrict remote logons to only those who need it

Be aggressive about logging and auditingBe aggressive about logging and auditingLog failed logon attemptsLog failed logon attemptsLog failed actions anywhere in the systemLog failed actions anywhere in the systemSecure IIS log files with NTFS permissionsSecure IIS log files with NTFS permissionsAudit access to Metabase.binAudit access to Metabase.bin

Page 7: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The HostUse ACLs to limit access to critical resourcesUse ACLs to limit access to critical resources

Restrict access to the %systemroot%\System32 directoryRestrict access to the %systemroot%\System32 directoryRestrict access to %systemroot%\Microsoft.NET\FrameworkRestrict access to %systemroot%\Microsoft.NET\FrameworkRestrict write access to %systemroot%\System32\LogfilesRestrict write access to %systemroot%\System32\LogfilesRestrict write access to Web content directoriesRestrict write access to Web content directoriesRestrict access to registry keys where secrets are storedRestrict access to registry keys where secrets are stored

See http://msdn.microsoft.com/library/en-us/dnnetsec/html/See http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh19.asp?frame=true#c19618429_025 for information THCMCh19.asp?frame=true#c19618429_025 for information on NTFS permissions required by ASP.NETon NTFS permissions required by ASP.NET

Page 8: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Defending The ApplicationDefending The Application

NeverNever trust user input (validate!) trust user input (validate!)

Access databases securelyAccess databases securely

Store secrets securelyStore secrets securely

Avoid vulnerabilities in forms authenticationAvoid vulnerabilities in forms authentication

Secure ASP.NET session stateSecure ASP.NET session state

Anticipate errors and handle them appropriatelyAnticipate errors and handle them appropriately

i http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh10.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh10.asp

Page 9: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Validating InputValidating InputFilter potentially injurious characters and stringsFilter potentially injurious characters and strings

HTML-encode all input echoed to a Web pageHTML-encode all input echoed to a Web page

Avoid using file names as input if possibleAvoid using file names as input if possible

Use "safe" character encodingsUse "safe" character encodings

<globalization requestEncoding="ISO-8859-1" responseEncoding="ISO-8859-1" />

Page 10: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Tools For Validating InputTools For Validating InputToolTool DescriptionDescription

RegexRegex Class in System.Text.RegularExpressions Class in System.Text.RegularExpressions namespace that wraps .NET Framework's namespace that wraps .NET Framework's regular expression engineregular expression engine

Validation controlsValidation controls Set of six controls that validate input on both Set of six controls that validate input on both client and server: RequiredFieldValidator, client and server: RequiredFieldValidator, RegularExpression-Validator, RegularExpression-Validator, RangeValidator, etc.RangeValidator, etc.

HttpUtility.HtmlEncodeHttpUtility.HtmlEncode HTML-encodes input, converting potentially HTML-encodes input, converting potentially dangerous characters such as "<" into harmless dangerous characters such as "<" into harmless escape sequencesescape sequences

Request.MapPathRequest.MapPath Resolves path names and optionally checks for Resolves path names and optionally checks for path names that violate application boundariespath names that violate application boundaries

ASP.NET 1.1 request ASP.NET 1.1 request validationvalidation

Feature of ASP.NET 1.1 that automatically Feature of ASP.NET 1.1 that automatically rejects requests containing certain characters rejects requests containing certain characters and character sequences (e.g., "<script")and character sequences (e.g., "<script")

Page 11: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Input ValidationInput Validation

Page 12: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Accessing Data SecurelyAccessing Data SecurelyUse stored procedures or parameterized commandsUse stored procedures or parameterized commands

NeverNever use sa to access Web databases use sa to access Web databases

Store connection strings securelyStore connection strings securely

Optionally use SSL/TLS or IPSec to secure theOptionally use SSL/TLS or IPSec to secure theconnection to the database serverconnection to the database server

Apply administrative protections to SQL ServerApply administrative protections to SQL Server

http://msdn.microsoft.com/library/enus/dnnetsec/html/SecNetHT18.asphttp://msdn.microsoft.com/library/enus/dnnetsec/html/SecNetHT18.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT19.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT19.asp

http://www.microsoft.com/sql/techinfo/administration/2000/security/http://www.microsoft.com/sql/techinfo/administration/2000/security/securingsqlserver.aspsecuringsqlserver.asp

Page 13: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Dynamic SQL CommandsDynamic SQL Commands

// DANGER! User input used to generate database query

string sql = String.Format ("select count (*) " + "from users where username=\'{0}\' and cast " + "(password as varbinary)=cast (\'{1}\' as " + varbinary)", username, password);

SqlCommand command = new SqlCommand (sql, connection);int count = (int) command.ExecuteScalar ();

Vulnerable to SQL injection attacksVulnerable to SQL injection attacks

Page 14: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Parameterized CommandsParameterized Commands

// BETTER: Input passed to parameterized command

SqlCommand command = new SqlCommand ("select count (*) from users where " + "username=@username and cast (password as " + "varbinary)=cast (@password as varbinary)", connection);

command.Parameters.Add ("@username", SqlDbType.VarChar).Value = username;command.Parameters.Add ("@password", SqlDbType.VarChar).Value = password;int count = (int) command.ExecuteScalar ();

Less vulnerable to SQL Less vulnerable to SQL injection attacksinjection attacks

Page 15: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Stored Procedures

// BEST: Input passed to stored procedure

SqlCommand command = new SqlCommand ("proc_IsUserValid", connection);command.CommandType = CommandType.StoredProcedure;command.Parameters.Add ("@username", SqlDbType.VarChar).Value = username;command.Parameters.Add ("@password", SqlDbType.VarChar).Value = password;command.Parameters.Add ("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;int count = (int) command.ExecuteScalar ();

Less vulnerable to SQL Less vulnerable to SQL injection attacksinjection attacksAdded security via Added security via EXECUTE permissionEXECUTE permission

Page 16: DEV312 Building Secure Web Applications: Defenses And Countermeasures

The sa AccountFor administration only; For administration only; nevernever use it to use it to access a database programmaticallyaccess a database programmaticallyInstead, use one or more accounts that Instead, use one or more accounts that have limited database permissionshave limited database permissions

For queries, use SELECT-only accountFor queries, use SELECT-only accountBetter yet, use stored procs and grant Better yet, use stored procs and grant account EXECUTE permission for the account EXECUTE permission for the stored procsstored procs

Reduces an attacker's ability to execute Reduces an attacker's ability to execute harmful commandsharmful commands

Page 17: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Creating A Limited AccountCreating A Limited Account

USE LoginGO

-- Add account named webuser to Login databaseEXEC sp_addlogin 'webuser', 'm1x2y3z4p5t6l7k8', 'Login'

-- Grant webuser access to the databaseEXEC sp_grantdbaccess 'webuser'

-- Limit webuser to calling proc_IsUserValidGRANT EXECUTE ON proc_IsUserValid TO webuser

Page 18: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Secure Data AccessSecure Data Access

Page 19: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Storing Data SecurelyStoring Data SecurelySensitive data stored persistently Sensitive data stored persistently should be encrypted or hashedshould be encrypted or hashed

Credit card numbersCredit card numbersLogin passwords, etc.Login passwords, etc.

For maximum security, connection For maximum security, connection strings should also be encryptedstrings should also be encryptedEncryption is easyEncryption is easy

System.Security.Cryptography classesSystem.Security.Cryptography classesWindows Data Protection API (DPAPI)Windows Data Protection API (DPAPI)

Securing decryption keys is notSecuring decryption keys is not

Page 20: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Data Protection API (DPAPI)Data Protection API (DPAPI)Present in Windows 2000 and higherPresent in Windows 2000 and higherProvides strong encryption, automatic Provides strong encryption, automatic key generation, and secure key storagekey generation, and secure key storage

Triple-DES encryptionTriple-DES encryptionPKCS #5 key generationPKCS #5 key generation

Two “stores”Two “stores”User storeUser storeMachine store Machine store GreatGreat tool for ASP.NET tool for ASP.NET programmers!programmers!

Operating system manages keysOperating system manages keys

Page 21: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Building A DPAPI LibraryThe .NET Framework Class Library 1.x The .NET Framework Class Library 1.x doesn’t wrap DPAPIdoesn’t wrap DPAPISee “How to Create a DPAPI Library” See “How to Create a DPAPI Library” for instructions on creating your ownfor instructions on creating your own

http://msdn.microsoft.com/library/default.asp?url=/http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/-SecNetHT07.asplibrary/en-us/dnnetsec/html/-SecNetHT07.asp

Managed wrapper around DPAPIManaged wrapper around DPAPIHandles interop and marshaling for youHandles interop and marshaling for youFeatures DataProtector class with simple Features DataProtector class with simple methods named Encrypt and Decryptmethods named Encrypt and DecryptSupports machine store and user storesSupports machine store and user stores

Page 22: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Encrypting Connection Strings

<configuration> <appSettings> <add key="ConnectionString" value="AQNCMnd8BFdERjHoAwE/Cl+sBAAAA..." /> </appSettings></configuration>

DataProtector dp = new DataProtector (DataProtector.Store.USE_MACHINE_STORE);string val = ConfigurationSettings.AppSettings ["ConnectionString"];byte[] data = Convert.FromBase64String (val);string connect = Encoding.ASCII.GetString (dp.Decrypt (data, null));

PagePage

Web.configWeb.config

Page 23: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Encrypting And ACLingConnection Strings

DataProtector dp = new DataProtector (DataProtector.Store.USE_MACHINE_STORE);RegistryKey key = Registry.LocalMachine.OpenSubKey ("SOFTWARE\\MyWebApp");string val = (string) key.GetValue ("ConnectionString");byte[] data = Convert.FromBase64String (val);string connect = Encoding.ASCII.GetString (dp.Decrypt (data, null));

PagePage

RegistryRegistry

Admins: FullAdmins: FullSYSTEM: FullSYSTEM: FullASP.NET: ReadASP.NET: Read

Page 24: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Encrypting Connection Encrypting Connection StringsStrings

Page 25: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Windows AuthenticationWindows AuthenticationMicrosoft SQL Server supports two Microsoft SQL Server supports two types of authenticationtypes of authentication

Authentication using SQL Server loginsAuthentication using SQL Server loginsAuthentication using Windows identitiesAuthentication using Windows identities

Windows authentication reduces threat Windows authentication reduces threat surface area by eliminating user names surface area by eliminating user names and passwords from connection and passwords from connection stringsstrings

server=localhost;database=pubs;Trusted_Connection=yes

Page 26: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Forms AuthenticationForms AuthenticationProtect login credentials with SSL/TLSProtect login credentials with SSL/TLS

Don't store passwords; store password hashesDon't store passwords; store password hashes

Don't rely on forms authentication to protectDon't rely on forms authentication to protectresources not owned by ASP.NETresources not owned by ASP.NET

Limit authentication cookie lifetimes to minimizeLimit authentication cookie lifetimes to minimizewindows for replay attackswindows for replay attacks

Assume authentication cookies are spoofed orAssume authentication cookies are spoofed orstolen when performing sensitive operationsstolen when performing sensitive operations

http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asp

Page 27: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Protecting LoginsProtecting LoginsPlace login forms in directories protected by Place login forms in directories protected by SSL/TLS to guard against eavesdroppingSSL/TLS to guard against eavesdropping

<authentication mode="Forms"> <forms loginUrl="https://.../LoginPage.aspx" /></authentication>

Encrypted connectionEncrypted connection

Page 28: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Storing Login Passwords

FormatFormat CommentsCommentsPlaintext passwordsPlaintext passwords Exposes entire application if database is Exposes entire application if database is

compromisedcompromisedEncrypted passwordsEncrypted passwords Better than plaintext, but still vulnerable if Better than plaintext, but still vulnerable if

decryption key is compromiseddecryption key is compromised1-way password 1-way password hasheshashes

Better than encrypted passwords, but still Better than encrypted passwords, but still vulnerable to dictionary attacksvulnerable to dictionary attacks

Salted password Salted password hasheshashes Less vulnerable to dictionary attacksLess vulnerable to dictionary attacks

Don’t store plaintext passwordsDon’t store plaintext passwordsStore encrypted passwords or Store encrypted passwords or password hashes for added securitypassword hashes for added security

Page 29: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Password HashesPassword Hashes

string hash = FormsAuthentication.HashPasswordForStoringInConfigFile (password, "SHA1"));

FormsAuthentication.HashPassword-FormsAuthentication.HashPassword-ForStoringInConfigFile makes ForStoringInConfigFile makes hashing easyhashing easy

SHA-1 hashesSHA-1 hashesMD5 hashesMD5 hashes

Page 30: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Generating Salted HashesGenerating Salted Hashes

string CreateSaltedPasswordHash (string password){ // Generate random salt string RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider (); byte[] saltBytes = new byte[16]; csp.GetNonZeroBytes (saltBytes); string saltString = Convert.ToBase64String (saltBytes);

// Append the salt string to the password string saltedPassword = password + saltString;

// Hash the salted password string hash = FormsAuthentication.HashPasswordForStoringInConfigFile (saltedPassword, "SHA1");

// Append the salt to the hash string saltedHash = hash + saltString; return saltedHash;}

Page 31: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Validating Salted HashesValidating Salted Hashes

bool ValidatePassword (string password, string saltedHash){ // Extract hash and salt string string saltString = saltedHash.Substring (saltedHash.Length - 24); string hash1 = saltedHash.Substring (0, saltedHash.Length - 24);

// Append the salt string to the password string saltedPassword = password + saltString;

// Hash the salted password string hash2 = FormsAuthentication.HashPasswordForStoringInConfigFile (saltedPassword, "SHA1");

// Compare the hashes return (hash1.CompareTo (hash2) == 0);}

Page 32: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Authentication CookiesAuthentication Cookies

DefenseDefense CommentsComments

Restrict cookies Restrict cookies to SSLto SSL

Prevents cookie theft (strongest defense)Prevents cookie theft (strongest defense)

Limit cookie lifetimeLimit cookie lifetime Mitigates replay attacks by limiting Mitigates replay attacks by limiting attack windowattack window

Disable sliding renewalDisable sliding renewal Mitigates replay attacks by limiting attack windowMitigates replay attacks by limiting attack window

Forms authentication cookies are Forms authentication cookies are encrypted and validated by defaultencrypted and validated by default

Prevents reading and alterationPrevents reading and alterationDoesn’t prevent theft and replayDoesn’t prevent theft and replay

Preventative measures are required to Preventative measures are required to defend against unauthorized accessdefend against unauthorized access

Page 33: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Auth Cookie LifetimeAuth Cookie LifetimeTemporary authentication cookiesTemporary authentication cookies

Lifetime limited (by default) to 30 minutesLifetime limited (by default) to 30 minutesControlled by <forms> timeout attributeControlled by <forms> timeout attribute

Subject to sliding renewal in ASP.NET 1.0Subject to sliding renewal in ASP.NET 1.0Sliding renewal disabled by default in 1.1Sliding renewal disabled by default in 1.1

Controlled by <forms> slidingExpiration attributeControlled by <forms> slidingExpiration attribute

Persistent authentication cookiesPersistent authentication cookiesDefault lifetime = 50 years!Default lifetime = 50 years!

Longer lifetime = Greater vulnerability to Longer lifetime = Greater vulnerability to replay attacksreplay attacks

Page 34: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Limiting The Lifetimes Of Limiting The Lifetimes Of Persistent Authentication Persistent Authentication CookiesCookiesif (Authenticate (name, password)) { string url = FormsAuthentication.GetRedirectUrl (name, true); FormsAuthentication.SetAuthCookie (name, true); HttpCookie cookie = Response.Cookies [FormsAuthentication.FormsCookieName]; // Set the cookie to expire 7 days from now cookie.Expires = DateTime.Now.AddDays (7); Response.Redirect (url);}

Page 35: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Securing Session StateSecuring Session StateLimit session time-outs as much as possibleLimit session time-outs as much as possible

Avoid using cookieless session state if possibleAvoid using cookieless session state if possible

Disable ASP.NET state service if you're not using itDisable ASP.NET state service if you're not using it

Close port 42424 in firewall if using state serviceClose port 42424 in firewall if using state service

Encrypt connection string if using SQL ServerEncrypt connection string if using SQL Server

Close ports 1433 and 1434 if using SQL ServerClose ports 1433 and 1434 if using SQL Server

http://support.microsoft.com/default.aspx?scid=kb;en-us;329290http://support.microsoft.com/default.aspx?scid=kb;en-us;329290

Page 36: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Session StateSession State

Optionally use SSL/TLS to protect session Optionally use SSL/TLS to protect session ID cookiesID cookies

Optionally use SSL/TLS or IPSec to secure theOptionally use SSL/TLS or IPSec to secure theconnection to the database serverconnection to the database server

Don’t store potentially injurious data (such asDon’t store potentially injurious data (such ascredit card numbers) in session statecredit card numbers) in session state

http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT16.asp

http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT18.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT18.asp http://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT19.asphttp://msdn.microsoft.com/library/en-us/dnnetsec/html/SecNetHT19.asp

Page 37: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Error HandlingError HandlingAnticipate errors and handle them sensiblyAnticipate errors and handle them sensibly

Use <customErrors> to display custom error pagesUse <customErrors> to display custom error pages

Beware mode="off" and debug="true"Beware mode="off" and debug="true"

Don't reveal too much information in error pagesDon't reveal too much information in error pages

Log unhandled exceptionsLog unhandled exceptions

Be aggressive about logging failuresBe aggressive about logging failures

Page 38: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Logging Unhandled Logging Unhandled ExceptionsExceptions

void Application_Error (Object sender, EventArgs e){ // Formulate message to write to event log string msg = "Error accessing " + Request.Path + "\n" + Server.GetLastError ().ToString ();

// Write the message to Windows event log EventLog log = new EventLog (); log.Source = "My ASP.NET Application"; log.WriteEntry (msg, EventLogEntryType.Error);}

Global.asaxGlobal.asax

Page 39: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Why Is This Code Insecure?

<html> <body> <form runat="server"> <asp:TextBox ID="Input" runat="server" /> <asp:Button Text="Click Me" OnClick="OnSubmit" runat="server" /> <asp:Label ID="Output" runat="server" /> </form> </body></html>

<script language="C#" runat="server">void OnSubmit (Object sender, EventArgs e){ Output.Text = "Hello, " + Input.Text;}</script>

Input is echoed to pageInput is echoed to pagewithout HTML encodingwithout HTML encoding

Input is neither validated norInput is neither validated norconstrained; user can type anything!constrained; user can type anything!

Page 40: DEV312 Building Secure Web Applications: Defenses And Countermeasures

Microsoft Products And Services For Lifelong Learningwww.microsoft.com/learning

AssessmentsAssessments www.microsoft.com/assessmentwww.microsoft.com/assessment

CoursesCourses2310: Developing Microsoft ASP .NET Web Applications Using Visual 2310: Developing Microsoft ASP .NET Web Applications Using Visual Studio .NETStudio .NET2640: Upgrading Web Development Skills from ASP to Microsoft ASP .NET2640: Upgrading Web Development Skills from ASP to Microsoft ASP .NET1905: Building XML-Based Web Applications 1905: Building XML-Based Web Applications 2311: Advanced ASP.NET (scheduled release July 04)2311: Advanced ASP.NET (scheduled release July 04)

BooksBooks

Designing ASP .NET Applications, ISBN: 0-7356-1348-6Designing ASP .NET Applications, ISBN: 0-7356-1348-6Programming Microsoft ASP .NET, ISBN: 0-7356-1903-4Programming Microsoft ASP .NET, ISBN: 0-7356-1903-4Microsoft ASP .NET Coding Strategies with the Microsoft ASP .NET Team, Microsoft ASP .NET Coding Strategies with the Microsoft ASP .NET Team, ISBN: 0-7356-1900-XISBN: 0-7356-1900-XDeveloping Microsoft® ASP.NET Server Controls and Components, ISBN: Developing Microsoft® ASP.NET Server Controls and Components, ISBN: 0-7356-1582-9 0-7356-1582-9 Building Secure Microsoft ASP .NET Applications, ISBN: 0-7356-1890-9Building Secure Microsoft ASP .NET Applications, ISBN: 0-7356-1890-9Building Microsoft ASP .NET Applications for Mobile Devices (Second Building Microsoft ASP .NET Applications for Mobile Devices (Second Edition), Edition), ISBN: 0-7356-1914-XISBN: 0-7356-1914-XMCAD/MCSD Self-Paced Training Kit: Developing Web Applications with MCAD/MCSD Self-Paced Training Kit: Developing Web Applications with Microsoft Visual Basic .NET and Microsoft Visual C# .NET (Second Microsoft Visual Basic .NET and Microsoft Visual C# .NET (Second Edition), ISBN 0-7356-1927-1Edition), ISBN 0-7356-1927-1

Microsoft Products and Services for Lifelong LearningMicrosoft Products and Services for Lifelong Learning

Page 41: DEV312 Building Secure Web Applications: Defenses And Countermeasures

DEV312 Building Secure Web Applications: Defenses And Countermeasures

Jeff ProsiseJeff ProsiseCo-founderCo-founderWintellect (www.wintellect.com)Wintellect (www.wintellect.com)