Presentation is loading. Please wait.

Presentation is loading. Please wait.

DEV353.NET Framework: Defensive Development Deborah Kurata Consultant InStep Technologies, Inc.

Similar presentations


Presentation on theme: "DEV353.NET Framework: Defensive Development Deborah Kurata Consultant InStep Technologies, Inc."— Presentation transcript:

1 DEV353.NET Framework: Defensive Development Deborah Kurata Consultant InStep Technologies, Inc

2 Defensive Development? A set of coding techniques for minimizing application failure? OR Security techniques for protecting your application against hackers?

3 Deborah Kurata Is... Author of: “Doing Objects in VB 6.0” “Doing Web Development” “Best Kept Secrets in.NET” “Doing Objects in.NET” (coming soon!) Software designer and developer INETA Speakers Bureau Microsoft MVP DeborahK@insteptech.com

4 InStep Technologies Is... Consulting Strategic technology consulting, mentoring and training services Software architecture and design Custom software development for the desktop and the Internet Kick-start services to get you started and keep you going Trainingwww.insteptech.com

5 You Are... Using a defined set of programming standards? Implementing exception handling in your applications? Logging exceptions? Using a Unit Testing tool? Implementing advanced security features in your applications?

6 Defensive Development Is… Anticipating where failures can occur Creating an infrastructure that mitigates failures Using damage-control techniques to manage failures Using notification techniques to collect information useful for diagnosing failures when they do occur

7 This Session Is... 7 defensive development practices for.NET OR 7 “walls” for defending your application against failure

8 Anticipating Failures

9 Common Failure Points Design errors Unauthorized application access User entry Bad data (from database or other feed) Coding errors Third-party controls Database errors (concurrency, timeout) Unanticipated system crashes Unanticipated system attacks

10 Threat Modeling 1. Identify your assets Find out what hackers could want Find out what hackers could want 2. Create an architecture overview Identify common technology-specific threats Identify common technology-specific threats 3. Decompose the application Trust boundaries, data flow, and entry points Trust boundaries, data flow, and entry points 4. Identify the threats Network, host, and application threats Network, host, and application threats 5. Document the threats Description, target, techniques, countermeasures Description, target, techniques, countermeasures 6. Rank the threats DREAD model DREAD model

11 DREAD Model Damage potential ReproducibilityExploitation Affected users Discoverability More information in MSDN Patterns and Practices http://msdn.microsoft.com/library/en- us/dnnetsec/html/ThreatCounter.asp http://msdn.microsoft.com/library/en- us/dnnetsec/html/ThreatCounter.asp

12 Creating An Infrastructure: Building The Seven Walls

13 1 st Wall Of Defense: Application Design Define a methodology for the design Document the design List the scenarios and business rules Consider installation and security issues Ensure the users review and approve the design Best done with the user interface design Provide a conduit for getting design questions answered

14 2 nd Wall Of Defense: Application Security Ensure your application has the proper security mechanisms Username, password Requirements depend on the deployment Internet versus Intranet versus Smart Client Requirements depend on the application Catalog application versus bank application Requirements may be different for different features of the application Catalog feature versus purchase feature

15 Password Tips Use a one-way hash Use a salt value Salt is pre-pended to the encrypted key Increases the work required to mount a brute-force (dictionary) attack public static String ComputeHash(string textToHash) { SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider(); SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider(); byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(textToHash); byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(textToHash); byte[] byteHash = SHA1.ComputeHash(byteValue); byte[] byteHash = SHA1.ComputeHash(byteValue); SHA1.Clear(); SHA1.Clear(); return Convert.ToBase64String(byteHash); return Convert.ToBase64String(byteHash);}

16 3 rd Wall Of Defense: User Entry Validation Validate the data entered by the users Restriction Using controls to prevent invalid entry Date controls, masked edit controls, etc. Validation Using code to verify user’s entry is valid Validating event (WinForms) Client-side validation (WebForms)

17 User Entry Validation Web Application Use Validator controls Windows Application Use Validating event Use ErrorProvider control Can do the above with a base form class Define validation rules in the middle tier

18 4 th Wall Of Defense: Data Validation Cannot assume that incoming data is valid Not all incoming data is from the user Data from the database may also be invalid Translated data Updates to data from other applications Errors due to changes in the database Example: Nulls in newly added fields Errors in data due to programming errors

19 Parameter Checking Give some thought to your method signature Minimizes the amount of refactoring that needs to be done later Verify each parameter passed into a routine Confirms parameter assumptions made by the routine These assumptions should be documented in the parameter comments Add as the first code lines of the routine ExceptionsAssertions

20 Exceptions Throw an exception when the parameter is not as expected Public Function Retrieve(ByVal iID As Int32) As DataSet If iID <= 0 Then If iID <= 0 Then Throw New ArgumentException(String.Format("ID must be greater than 0. ID was {0}", iID.ToString)) Throw New ArgumentException(String.Format("ID must be greater than 0. ID was {0}", iID.ToString)) End If End If Public Function ValLogin(ByVal oUserEntity As UserEntity) _ As Boolean If oUserEntity Is Nothing Then If oUserEntity Is Nothing Then Throw New ArgumentException("UserEntity object must be set before calling this function") Throw New ArgumentException("UserEntity object must be set before calling this function") End If End If

21 Assertions Assert when the parameter is not as expected Public Function Retrieve(ByVal iID As Int32) As DataSet Debug.Assert(iID > 0, _ Debug.Assert(iID > 0, _ String.Format("ID must be greater than 0. ID was {0}", iID.ToString)) String.Format("ID must be greater than 0. ID was {0}", iID.ToString)) Public Function ValLogin(ByVal oUserEntity As UserEntity) _ As Boolean Debug.Assert(Not oUserEntity Is Nothing, _ Debug.Assert(Not oUserEntity Is Nothing, _ "UserEntity object must be set before calling this function") "UserEntity object must be set before calling this function")

22 Exceptions Versus Assertions Uses more code Less performant Included in the release build Can be logged in a production environment Cannot easily be turned on/off Uses less code More performant Only included in the debug build Can be included in trace information Can easily be turned on/off using configuration file

23 Configuring Assertions Use a configuration file Turn on/off assertions Log assertions <configuration> </configuration>

24 5 th Wall Of Defense: Code Correctness Prevent coding errors by Using good coding practices Anticipating potential problem areas Including third-party coding errors Including system (database and framework) errors Use damage control techniques when a failure does occur Log any failures for evaluation and correction

25 Defining Good Coding Practices Develop a set of programming standards Defines "best practices" Makes maintenance easier Perform code reviews to ensure adherence to standards.NET Framework Design Guidelines: http://msdn.microsoft.com/library/ default.asp?url=/library/en-us/cpgenref/html/ cpconnetframeworkdesignguidelines.asp http://msdn.microsoft.com/library/ default.asp?url=/library/en-us/cpgenref/html/ cpconnetframeworkdesignguidelines.asp http://msdn.microsoft.com/library/ default.asp?url=/library/en-us/cpgenref/html/ cpconnetframeworkdesignguidelines.asp

26 Type Your Data Declare your types Catches inconsistencies before they become bugs Use Option Explicit Use Option Strict Dim dsProduct As DataSet Dim sConn As String

27 Use Constants When Appropriate Declare constants for values that should not change Reused strings Action codes Field names Etc. Public Const PRODUCT_DESCRIPTION As String = "Description" Public Const PRODUCT_PRICE As String = "Price" Public Const VALIDATE_REQUIRED As String = "ValidateRequired" Public Const VALIDATE_NUMERIC As String = "ValidateNumeric" Public Const VALIDATE_REG_EX_PHONE As String = "^\d{10}$"

28 Make A Statement For Success When using a Case statement, always include a Case Else to prevent falling through Select Case e.Button.Text Case tbBtnCancel.Text Case tbBtnCancel.Text Me.Close() Me.Close() Case tbBtnNew.Text Case tbBtnNew.Text MessageBox.Show("This would perform a new operation") MessageBox.Show("This would perform a new operation") Case Else Case Else Debug.Assert(False, "Missing handler for button with text: " _ Debug.Assert(False, "Missing handler for button with text: " _ & e.Button.Text) End Select End Select

29 Keep Your Code Clean Organize your code Refactor when needed Encapsulate your classes Remove duplicate code Duplicated code can lead to MANY bugs – code is updated in one place but not the other Keep it simple Obfuscation can be bad Document your code Prevents other developers (or yourself) from making coding errors when making changes/enhancements later

30 Clean Up Your Objects Implement IDisposable This is important to do now in preparation for the Using statement in Whidbey Public Class Product Implements IDisposable Implements IDisposable Public Sub Dispose() Implements System.IDisposable.Dispose Public Sub Dispose() Implements System.IDisposable.Dispose ' Code here to dispose of your object ' Code here to dispose of your object End Sub End Sub End Class

31 Marking Old Routines Obsolete Attribute This notifies other developers of a routine that should no longer be used _ _ Public Function Retrieve(ByVal sProduct As String) As DataSet ' Code here to get using the product string ' Code here to get using the product string End Function

32 Damage Control Techniques

33 Damage Control The application should never terminate abnormally Rather, throw an exception when a failure occurs Catch the exception in the calling code

34 Throw Exceptions Throw simple exceptions with the Throw statement Public Function ValidateLogin(ByVal sUserName As String, _ Public Function ValidateLogin(ByVal sUserName As String, _ ByVal sPassword As String) As Boolean ByVal sPassword As String) As Boolean If sUserName <> "DeborahK" Then If sUserName <> "DeborahK" Then Throw New ApplicationException("Invalid username") Throw New ApplicationException("Invalid username") End If End If If sPassword <> "password" Then If sPassword <> "password" Then Throw New ApplicationException("Invalid password") Throw New ApplicationException("Invalid password") End If End If Return True Return True End Function End Function End Function

35 Catch Exceptions Catch exceptions using a Try Catch block Try Dim oUser As New User() Dim oUser As New User() bValid = oUser.ValidateLogin(txtUserName.Text, _ bValid = oUser.ValidateLogin(txtUserName.Text, _ txtPassword.Text) txtPassword.Text) DialogResult = DialogResult.OK DialogResult = DialogResult.OK Catch ex As Exception MessageBox.Show(ex.Message) MessageBox.Show(ex.Message) End Try

36 Add Finally Add a Finally to the Try Catch block for clean-up code that must be executed on success or failure Try Dim oUser As New User() Dim oUser As New User() bValid = oUser.ValidateLogin(txtUserName.Text, _ bValid = oUser.ValidateLogin(txtUserName.Text, _ txtPassword.Text) txtPassword.Text) DialogResult = DialogResult.OK DialogResult = DialogResult.OK Catch ex As Exception MessageBox.Show(ex.Message) MessageBox.Show(ex.Message)Finally ‘Clean up code here ‘Clean up code here End Try

37 Build Your Own Exception Classes Add exception classes to same code file Inherits properties and methods – not constructors Public Class UsernameNotFoundException : Inherits Exception Public Sub New() Public Sub New() MyBase.New() MyBase.New() End Sub End Sub Public Sub New(ByVal message As String) Public Sub New(ByVal message As String) MyBase.New(message) MyBase.New(message) End Sub End Sub Public Sub New(ByVal message As String, ByVal innerEx As Exception) Public Sub New(ByVal message As String, ByVal innerEx As Exception) MyBase.New(message, innerEx) MyBase.New(message, innerEx) End Sub End Sub End Class

38 Multiple Exceptions Try Dim oUser As New User() Dim oUser As New User() bValid = oUser.ValidateLogin(txtUserName.Text, _ bValid = oUser.ValidateLogin(txtUserName.Text, _txtPassword.Text) DialogResult = DialogResult.OK DialogResult = DialogResult.OK Catch ex As UsernameNotFoundException MessageBox.Show(ex.Message) MessageBox.Show(ex.Message) txtUserName.Focus() txtUserName.Focus() Catch ex As PasswordInvalidException MessageBox.Show(ex.Message) MessageBox.Show(ex.Message) txtPassword.Focus() txtPassword.Focus() End Try

39 Another Example Catch ex As System.Data.SqlClient.SqlException Me.TransactionRollback() Me.TransactionRollback() Select Case ex.Number Select Case ex.Number Case UNIQUE_CONSTRAINT_ERROR Case UNIQUE_CONSTRAINT_ERROR Throw New UniqueConstraintException(ex.Message, _ Throw New UniqueConstraintException(ex.Message, _ oDS.Tables(sTableName(iTableIndex)), iRowIndex, ex) Case DEADLOCK_ERROR_NUMBER Case DEADLOCK_ERROR_NUMBER Throw New DacDeadlockException(ex.Message) Throw New DacDeadlockException(ex.Message) Case Is >= SQLSERVERS_RULES_BEGIN Case Is >= SQLSERVERS_RULES_BEGIN Throw New SQLServerRulesException(ex.Message, _ Throw New SQLServerRulesException(ex.Message, _ iRowIndex, ex) iRowIndex, ex) Case Else Case Else Throw Throw End Select End Select

40 Catch Any Other Failure Use the ThreadException event to trap any other failures AddHandler Application.ThreadException, _ New System.Threading.ThreadExceptionEventHandler(AddressOf gEx.OnThreadException) New System.Threading.ThreadExceptionEventHandler(AddressOf gEx.OnThreadException)

41 Notification Mechanisms

42 Logging Exceptions Use notification techniques to collect information useful for diagnosing the problem Include information on the context Operation performed Value of key variables Etc. The easier you make the defect analysis, the easier it will be to fix the defects Don’t count on the users!

43 Log Exception Routine Public Sub LogException(ByVal sError As String, _ ByVal sUserName As String, _ ByVal sUserName As String, _ ByVal eLogEntryType As EventLogEntryType) ByVal eLogEntryType As EventLogEntryType) ' Write the error to the Output window ' Write the error to the Output window Debug.WriteLine(sError) Debug.WriteLine(sError) ' If there are any errors, put up a message box if debugging ' If there are any errors, put up a message box if debugging #If DEBUG Then MsgBox(sError, MsgBoxStyle.Critical, "Debug Message") MsgBox(sError, MsgBoxStyle.Critical, "Debug Message") #End If AddEventLogEntry(sError, eLogEntryType) AddEventLogEntry(sError, eLogEntryType) SendEmail(sError) SendEmail(sError) End Sub

44 Writing To The Event Log Private Sub AddEventLogEntry(ByVal sText As String, _ ByVal eEntryType As EventLogEntryType) ByVal eEntryType As EventLogEntryType) Dim EvtLog As New System.Diagnostics.EventLog() Dim EvtLog As New System.Diagnostics.EventLog() ' Ensure application is registered in event log ' Ensure application is registered in event log If Not EventLog.SourceExists(me.ApplicationName) Then If Not EventLog.SourceExists(me.ApplicationName) Then EventLog.CreateEventSource(me.ApplicationName, "Application") EventLog.CreateEventSource(me.ApplicationName, "Application") End If End If ' Add entry ' Add entry EvtLog.WriteEntry(me.ApplicationName, sText, eEntryType) EvtLog.WriteEntry(me.ApplicationName, sText, eEntryType) End Sub

45 Unit Testing Validates functionality Validates functional changes Regression testing

46 Unit Testing Versus Defensive Coding Unit testing does NOT prevent the need for other defensive development techniques The golden rule of testing: “Testing can only prove the presence of errors, not the absence of errors” Reliability = correctness + robustness Unit Testing Defensive Coding

47 Testing Class Libraries Change the project type to “Console Application” Add a Class with Sub Main as a test harness Add testing code to the Sub Main Alternatively, use a unit testing tool Class eOrderOnlineBOMain Public Shared Sub Main() Public Shared Sub Main() End Sub End Sub End Sub

48 NUnit Unit Testing Tool http://sourceforge.net/projects/nunit Framework for unit testing

49 TIP Use the Console to write testing data Console.WriteLine Console.ReadLine will keep the console window open Or use the Debug window Debug.WriteLine Dump the contents of a dataset Debug.WriteLine(ds.GetXml())

50 6 th Wall Of Defense: Database Security Secure the database server Secure the database Define one ID and password for the application and only allow access through this ID Do NOT use sa Do NOT use no password Secure the connection string

51

52 7 th Wall Of Defense: Monitor System Security Review the following on a regular basis THREAT model Security log Error log

53 Summary: 7 Walls Of Defense 1. Ensure the design is clear 2. Implement an application security scheme 3. Validate user entry 4. Validate data coming into/out of the system 5. Use good development practices to prevent coding errors Perform damage control when exceptions occur Perform damage control when exceptions occur Log exceptions to assist in diagnosing problems Log exceptions to assist in diagnosing problems 6. Implement a database security scheme 7. Monitor system security regularly

54 Assessmentshttp://www.microsoft.com/assessment/ Courses 2415: Programming with the Microsoft.NET Framework (Microsoft Visual Basic.NET) 2349: Programming with the Microsoft.NET Framework (Microsoft Visual C#.NET) Books The Microsoft Platform Ahead, ISBN: 0-7356-2064-4 Network Programming for the Microsoft.NET Framework, ISBN: 0-7356-1959-X Programming Microsoft.NET, ISBN: 0-7356-1376-1 Applied Microsoft Windows.NET Framework Programming, ISBN: 0-7356-1422-9 Applied Microsoft Windows.NET Framework Programming in Microsoft Visual Basic.NET, ISBN: 0-7356-1787-2 Microsoft Windows.NET Framework 1.1 Class Library References Performance Testing Microsoft.NET Web Applications, ISBN: 0-7356-1538-1 Microsoft Products and Services for Lifelong Learning Microsoft Products And Services For Lifelong Learning www.microsoft.com/learning

55 © 2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.


Download ppt "DEV353.NET Framework: Defensive Development Deborah Kurata Consultant InStep Technologies, Inc."

Similar presentations


Ads by Google