Threat Modelingan introduction toSecurity Principals and Patterns in Application Architectural DesignCaleb JenkinsSoftware Ninja | Architecthttp://DevelopingUX.com
Threat
+ThreatAttack
or is your world more like this?
AgendaThreat AnalysisBasic Security ConceptsSecurity Code ReviewSummary / Q&A
T.J. Maxx theft believed largest hack everTJX cos. put number to loss Wednesday, acknowledges it could still go upBy Mark JewellAssociated PressMarch 30, 2007BOSTON - A hacker or hackers stole data from at least 45.7 million credit and debit cards of shoppers at off-price retailers including T.J. Maxx and Marshalls in a case believed to be the largest such breach of consumer information.Experts say TJX’s disclosures in a regulatory filing late Wednesday revealed security holes that persist at many firms entrusted with consumer data: failure to promptly delete data on customer transactions, and to guard secrets about how such data is protected through encryption.
T.J. Maxx theft believed largest hack everTJX cos. put number to loss Wednesday, acknowledges it could still go upBy Mark JewellAssociated PressMarch 30, 2007Police charged six people in Florida last week with using credit card numbers that investigators believe were stolen from a TJX database to buy about $1 million in merchandise with gift cards.
Assets are the things an attacker wants to take from youThreats are the ways in which the attacker will try to get at your assetsMitigations are the ways you block the attacker from getting the assetsVulnerabilities are unmitigated threatsThreat Models are an assessment of the Assets, Threats, Mitigations and Vulnerabilities of the system you are building or have built
Assets are more than money…Reputation & Customer ConfidenceConfidential DataProcessor, Storage, BandwidthAvailabilityPerformance
Threat AnalysisSecure software starts with understanding the threatsThreats are not vulnerabilitiesThreats live foreverHow will attackers attempt to compromise the system?AssetMitigationThreatVulnerability
Security User StoriesDescribes something the bad guy wants to do (a threat)Short and to the point
Written by the user in non-technical languageAs an attackerI want to <attack>So that <crime>By <method>
Security User StoriesAs an attackerI want to obtain credentialsSo that I can plunder bank accountsBy tricking users into logging into my bogus site with a Phishing mail
Security ObjectivesWhat do you not want to happen?Confidentiality“I do not want unauthorized users to gain access to confidential information”Integrity“I do not want unauthorized users to tamper with data”Availability“I do not want the system to be unavailable because of an attack”Agree on security objectives up frontHelps to scope and focus your security effortsAgendaThreat AnalysisBasic Security ConceptsSecurity Code ReviewSummary / Q&A
Basic Security ConceptsReduce Attack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
Attack SurfaceThe “Attack Surface” is the sum of the ways in which an attacker can get at you	Smaller Attack Surface is betterAttack SurfaceThe “Attack Surface” is the sum of the ways in which an attacker can get at you	Smaller Attack Surface is betterWhich one has the Smaller attack surface?
Attack SurfaceThe “Attack Surface” is the sum of the ways in which an attacker can get at you	Smaller Attack Surface is betterHint: No way to know… what’s on the other side?
Understand Your Attack SurfaceNetworking protocols that are enabled by defaultNetwork EndpointsCode that auto-starts or will execute when accessedExamples: Services, daemons, ISAPI filters and applications, SOAP services, and Web rootsReusable components ActiveX controls, COM objects, and .NET Framework assemblies, especially those marked with the AllowParticallyTrustedCallersAttribute)Process identities for all the code you runUser accounts installed
Reducing Attack SurfaceTCP/UDPTCP/UDPTCP/UDPService: Autostart SYSTEM
Reducing Attack SurfaceTCP/UDPTCP/UDPTCP/UDPService: Autostart SYSTEM Turn off less-used ports
Reducing Attack SurfaceTCP/UDPTCP onlyService: Autostart SYSTEM Turn off UDP connections
Reducing Attack SurfaceTCP onlyService: Autostart SYSTEM Restrict requeststo subnet/IP range
Reducing Attack SurfaceTCP onlyService: Autostart SYSTEM Authenticate connections
Reducing Attack SurfaceTCP onlyService: Manual NetServiceLower privilegeTurn feature off
Reducing Attack SurfaceTCP onlyService: Manual NetServiceEveryone (Full Control)Admin (Full Control)Everyone (Read)Service (RW)Harden ACLs on data store
Basic Security ConceptsReduce Attack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
Defense In DepthDon’t count on one line of defense for everythingWhat if the attacker penetrates that defense?Contain the damageExample – Nuclear Plants
“Multiple redundant safety systems. Nuclear plants are designed according to a "defense in depth" philosophy that requires redundant, diverse, reliable safety systems. Two or more safety systems perform key functions independently, such that, if one fails, there is always another to back it up, providing continuous protection.- Nuclear Energy Institute“
System Failures can be Bad
Defense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableCode made more conservative during Security PushDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableEven if the buffer was large enoughCode made more conservative during Security PushProcess halts rather than executes malicious code, due to buffer-overrun detection code (-GS)IIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
The underlying DLL (NTDLL.DLL) not vulnerableEven if the buffer was large enoughCode made more conservative during Security PushProcess halts rather than executes malicious code, due to buffer-overrun detection code (-GS)IIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledEven if it there was an exploitable buffer overrunWould have occurred in w3wp.exe which is now running as ‘network service’Defense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
Basic Security ConceptsReduce Attack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
Least PrivilegeA defense in depth measureCode should run with only the permissions it requiresAttackers can only do whatever the code was already allowed to doRecommendationsUse least privilege accounts
Use code access security
Write Apps that non-admins can actually useFail To Secure ModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True   Try  Dim conn As New SqlConnection(connString)      conn.Open()      Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”)      Dim count As Integer      count = cmd.ExecuteScalar()      Authenticated = (count = 1)  Catch ex As Exception      MessageBox.Show("Error logging in " + ex.Message)  End Try  Return AuthenticatedEnd Function
Fail To Secure ModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True   Try  Dim conn As New SqlConnection(connString)      conn.Open()      Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”)      Dim count As Integer      count = cmd.ExecuteScalar()      Authenticated = (count = 1)  Catch ex As Exception      MessageBox.Show("Error logging in " + ex.Message)  End Try  Return AuthenticatedEnd FunctionAuthenticated As Boolean = TrueDanger!!Assumes Success
Fail To Secure ModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True   Try  Dim conn As New SqlConnection(connString)      conn.Open()      Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”)      Dim count As Integer      count = cmd.ExecuteScalar()      Authenticated = (count = 1)  Catch ex As Exception      MessageBox.Show("Error logging in " + ex.Message)  End Try  Return AuthenticatedEnd FunctionAuthenticated As Boolean = TrueDanger!!Assumes SuccessAuthenticated flag may still be true hereCatch ex As Exception
AgendaThreat AnalysisBasic Security ConceptsSecurity Code ReviewSummary / Q&A
TryDim conn As SqlConnection = NothingDim results As New DataSet()   conn = New SqlConnection("data source=localhost;" _         + "user id=sa;password=password;" + _         "Initial Catalog=SqlInjectionDemo")conn.Open()   sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException   Dim status As String   status = sqlString + " failed"For Each err As SqlError In se.Errors   status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code Review
TryDim conn As SqlConnection = NothingDim results As New DataSet()   conn = New SqlConnection("data source=localhost;" _         + "user id=sa;password=password;" + _         "Initial Catalog=SqlInjectionDemo")conn.Open()   sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException   Dim status As String   status = sqlString + " failed"For Each err As SqlError In se.Errors   status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak Password
TryDim conn As SqlConnection = NothingDim results As New DataSet()   conn = New SqlConnection("data source=localhost;" _         + "user id=sa;password=password;" + _         "Initial Catalog=SqlInjectionDemo")conn.Open()   sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException   Dim status As String   status = sqlString + " failed"For Each err As SqlError In se.Errors   status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak PasswordWHERE ID='" + ID + "'"Don’t Concatenate arguments
TryDim conn As SqlConnection = NothingDim results As New DataSet()   conn = New SqlConnection("data source=localhost;" _         + "user id=sa;password=password;" + _         "Initial Catalog=SqlInjectionDemo")conn.Open()   sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException   Dim status As String   status = sqlString + " failed"For Each err As SqlError In se.Errors   status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak PasswordWHERE ID='" + ID + "'"Don’t Concatenate argumentsDon’t reveal everything to an attackerFor Each err As SqlError
Why not connect as SA?Violates the principle of least privilegeThreat: Code is subject to attacker elevating privilegeMitigation RecommendationDefense in depth Action: Run SQL as Network Service rather than Local SystemReduce surface area: eliminate privileges on everything except for the required stored proceduresAction: Create stored proceduresLeast privilege: run as a lesser privileged user when connecting to databaseAction: Fix the connection string
Why not embed secrets?Violates the principle of avoiding security by obscurityThreat: Secrets are easily discoveredMitigation RecommendationDon’t Store SecretsTip: Use Windows AuthenticationEncrypt secretsFor .NET 1.1 consider Enterprise LibraryFor .NET 2.0 use Enterprise Library or System.Security.Cryptography.ProtectedDataFor SQL Server 2005 use EncryptByKey / DecryptByKey
Storing SecretsHackers use search engines to locate secretsSearch engines will find anything you have hidden
Storing SecretsMySQL Data DumpsConfig Files on *nix systems
Fix Connection StringNot goodMuch Better
Never create your own encryption
Never create your own encryption
Never create your own encryption
Why not use easy passwords?Because they are easily broken by brute force attacksThreat: Attacker guesses or brute forces password to access secretsMitigation:Enforce a strong password policy
Enable password policy enforcement on SQL Server
Uses Windows Server 2003 policyBrute Force Dictionary Attacks
Password PolicySQL Server 2005 Management Studio Tool Shown
Why not concatenate arguments?Violates the principle of All Input Is Evil (Until Proven Otherwise)Threat: Code is subject to luring attacks via SQL InjectionMitigation RecommendationReduce Attack Surface
Use parameters with SQL
Create stored procedures and grant access only to the stored procedure
Consider Table-Valued Functions in SQL 2005
Disable unneeded SQL Server FeaturesUsing Parameters and Sprocs
Reduce SQL Surface Area
Reduce SQL Surface AreaIf you don’t connect in a sysadmin role the account used by xp_cmdshell will be the one defined by xp_cmdshell_proxy_account which may have reduced privilege
Evil Input Attack - HotmailOctober 2001 an XSS vulnerability which allowed an attacker to steal a user's Microsoft .NET Passport session cookies. Exploit for this vulnerability consisted of sending a malicious email to a Hotmail user, which contained malformed HTML. The script filtering code in Hotmail's site failed to remove the broken HTML and Internet Explorer's parsing algorithm happily interpreted the malicious code.
Security Fix: Validate InputConstrainLook for valid data and reject everything else
Set Max Length to 5
Use Regular Expressions to permit only what you want
Integer expression: “^[0-9]{0,5}$”RejectReject things you know are badSanitizeUse SQL Parameters
HTMLEncode outputdiscussion: White Listing vs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)
discussion: White Listing vs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”
discussion: White Listing vs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”“deldeleteete”
discussion: White Listing vs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”“deldeleteete”“delete”
demo: SQL InjectionSanitizing User InputSelect Count(*) From UsersWhere User Name = ‘’ OR1+1=2; -- ‘ and password = ‘’
demo: SQL InjectionSanitizing User Input
Discussion: XSSSanitizing User Input
Why not reveal all exceptions?Most users won’t understand the details anywayThreat: Code is subject to information disclosure threatsMitigation RecommendationMap low level error messages to meaningful messages for your users
Never disclose secrets in error messagesMeaningful Error MessagesWhat this error really means…No SmartCard inserted in card reader

Threat Modeling - Writing Secure Code

  • 1.
    Threat Modelingan introductiontoSecurity Principals and Patterns in Application Architectural DesignCaleb JenkinsSoftware Ninja | Architecthttp://DevelopingUX.com
  • 2.
  • 3.
  • 4.
    or is yourworld more like this?
  • 9.
    AgendaThreat AnalysisBasic SecurityConceptsSecurity Code ReviewSummary / Q&A
  • 10.
    T.J. Maxx theftbelieved largest hack everTJX cos. put number to loss Wednesday, acknowledges it could still go upBy Mark JewellAssociated PressMarch 30, 2007BOSTON - A hacker or hackers stole data from at least 45.7 million credit and debit cards of shoppers at off-price retailers including T.J. Maxx and Marshalls in a case believed to be the largest such breach of consumer information.Experts say TJX’s disclosures in a regulatory filing late Wednesday revealed security holes that persist at many firms entrusted with consumer data: failure to promptly delete data on customer transactions, and to guard secrets about how such data is protected through encryption.
  • 11.
    T.J. Maxx theftbelieved largest hack everTJX cos. put number to loss Wednesday, acknowledges it could still go upBy Mark JewellAssociated PressMarch 30, 2007Police charged six people in Florida last week with using credit card numbers that investigators believe were stolen from a TJX database to buy about $1 million in merchandise with gift cards.
  • 12.
    Assets are thethings an attacker wants to take from youThreats are the ways in which the attacker will try to get at your assetsMitigations are the ways you block the attacker from getting the assetsVulnerabilities are unmitigated threatsThreat Models are an assessment of the Assets, Threats, Mitigations and Vulnerabilities of the system you are building or have built
  • 13.
    Assets are morethan money…Reputation & Customer ConfidenceConfidential DataProcessor, Storage, BandwidthAvailabilityPerformance
  • 14.
    Threat AnalysisSecure softwarestarts with understanding the threatsThreats are not vulnerabilitiesThreats live foreverHow will attackers attempt to compromise the system?AssetMitigationThreatVulnerability
  • 15.
    Security User StoriesDescribessomething the bad guy wants to do (a threat)Short and to the point
  • 16.
    Written by theuser in non-technical languageAs an attackerI want to <attack>So that <crime>By <method>
  • 17.
    Security User StoriesAsan attackerI want to obtain credentialsSo that I can plunder bank accountsBy tricking users into logging into my bogus site with a Phishing mail
  • 18.
    Security ObjectivesWhat doyou not want to happen?Confidentiality“I do not want unauthorized users to gain access to confidential information”Integrity“I do not want unauthorized users to tamper with data”Availability“I do not want the system to be unavailable because of an attack”Agree on security objectives up frontHelps to scope and focus your security effortsAgendaThreat AnalysisBasic Security ConceptsSecurity Code ReviewSummary / Q&A
  • 19.
    Basic Security ConceptsReduceAttack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
  • 20.
    Attack SurfaceThe “AttackSurface” is the sum of the ways in which an attacker can get at you Smaller Attack Surface is betterAttack SurfaceThe “Attack Surface” is the sum of the ways in which an attacker can get at you Smaller Attack Surface is betterWhich one has the Smaller attack surface?
  • 21.
    Attack SurfaceThe “AttackSurface” is the sum of the ways in which an attacker can get at you Smaller Attack Surface is betterHint: No way to know… what’s on the other side?
  • 22.
    Understand Your AttackSurfaceNetworking protocols that are enabled by defaultNetwork EndpointsCode that auto-starts or will execute when accessedExamples: Services, daemons, ISAPI filters and applications, SOAP services, and Web rootsReusable components ActiveX controls, COM objects, and .NET Framework assemblies, especially those marked with the AllowParticallyTrustedCallersAttribute)Process identities for all the code you runUser accounts installed
  • 23.
  • 24.
    Reducing Attack SurfaceTCP/UDPTCP/UDPTCP/UDPService:Autostart SYSTEM Turn off less-used ports
  • 25.
    Reducing Attack SurfaceTCP/UDPTCPonlyService: Autostart SYSTEM Turn off UDP connections
  • 26.
    Reducing Attack SurfaceTCPonlyService: Autostart SYSTEM Restrict requeststo subnet/IP range
  • 27.
    Reducing Attack SurfaceTCPonlyService: Autostart SYSTEM Authenticate connections
  • 28.
    Reducing Attack SurfaceTCPonlyService: Manual NetServiceLower privilegeTurn feature off
  • 29.
    Reducing Attack SurfaceTCPonlyService: Manual NetServiceEveryone (Full Control)Admin (Full Control)Everyone (Read)Service (RW)Harden ACLs on data store
  • 30.
    Basic Security ConceptsReduceAttack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
  • 31.
    Defense In DepthDon’tcount on one line of defense for everythingWhat if the attacker penetrates that defense?Contain the damageExample – Nuclear Plants
  • 33.
    “Multiple redundant safetysystems. Nuclear plants are designed according to a "defense in depth" philosophy that requires redundant, diverse, reliable safety systems. Two or more safety systems perform key functions independently, such that, if one fails, there is always another to back it up, providing continuous protection.- Nuclear Energy Institute“
  • 34.
  • 35.
    Defense in Depth(MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 36.
    The underlying DLL(NTDLL.DLL) not vulnerableCode made more conservative during Security PushDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 37.
    The underlying DLL(NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 38.
    The underlying DLL(NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 39.
    The underlying DLL(NTDLL.DLL) not vulnerableCode made more conservative during Security PushIIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 40.
    The underlying DLL(NTDLL.DLL) not vulnerableEven if the buffer was large enoughCode made more conservative during Security PushProcess halts rather than executes malicious code, due to buffer-overrun detection code (-GS)IIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledDefense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 41.
    The underlying DLL(NTDLL.DLL) not vulnerableEven if the buffer was large enoughCode made more conservative during Security PushProcess halts rather than executes malicious code, due to buffer-overrun detection code (-GS)IIS 6.0 not running by default on Windows Server 2003Even if it was vulnerableIIS 6.0 doesn’t have WebDAV enabled by defaultEven if it was runningMaximum URL length in IIS 6.0 is 16kb by default (>64kb needed) Even if it did have WebDAV enabledEven if it there was an exploitable buffer overrunWould have occurred in w3wp.exe which is now running as ‘network service’Defense in Depth (MS03-007)Windows Server 2003 UnaffectedMicrosoft Security Bulletin MS03-007Unchecked Buffer In Windows Component Could Cause Server Compromise (815021)Originally posted: March 17, 2003 Impact of vulnerability: Run code of attacker's choiceMaximum Severity Rating: CriticalAffected Software: Microsoft Windows NT 4.0 Microsoft Windows 2000 Microsoft Windows XP Not Affected Software:Microsoft Windows Server 2003
  • 42.
    Basic Security ConceptsReduceAttack SurfaceDefense In DepthLeast PrivilegeFail to Secure Mode
  • 43.
    Least PrivilegeA defensein depth measureCode should run with only the permissions it requiresAttackers can only do whatever the code was already allowed to doRecommendationsUse least privilege accounts
  • 44.
  • 45.
    Write Apps thatnon-admins can actually useFail To Secure ModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True Try Dim conn As New SqlConnection(connString) conn.Open() Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”) Dim count As Integer count = cmd.ExecuteScalar() Authenticated = (count = 1) Catch ex As Exception MessageBox.Show("Error logging in " + ex.Message) End Try Return AuthenticatedEnd Function
  • 46.
    Fail To SecureModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True Try Dim conn As New SqlConnection(connString) conn.Open() Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”) Dim count As Integer count = cmd.ExecuteScalar() Authenticated = (count = 1) Catch ex As Exception MessageBox.Show("Error logging in " + ex.Message) End Try Return AuthenticatedEnd FunctionAuthenticated As Boolean = TrueDanger!!Assumes Success
  • 47.
    Fail To SecureModeFunction Authenticate(UserID As String, Password As String)Dim Authenticated As Boolean = True Try Dim conn As New SqlConnection(connString) conn.Open() Dim cmd As New SqlCommand("SELECT Count(*) FROM Users …”) Dim count As Integer count = cmd.ExecuteScalar() Authenticated = (count = 1) Catch ex As Exception MessageBox.Show("Error logging in " + ex.Message) End Try Return AuthenticatedEnd FunctionAuthenticated As Boolean = TrueDanger!!Assumes SuccessAuthenticated flag may still be true hereCatch ex As Exception
  • 48.
    AgendaThreat AnalysisBasic SecurityConceptsSecurity Code ReviewSummary / Q&A
  • 49.
    TryDim conn AsSqlConnection = NothingDim results As New DataSet() conn = New SqlConnection("data source=localhost;" _ + "user id=sa;password=password;" + _ "Initial Catalog=SqlInjectionDemo")conn.Open() sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException Dim status As String status = sqlString + " failed"For Each err As SqlError In se.Errors status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code Review
  • 50.
    TryDim conn AsSqlConnection = NothingDim results As New DataSet() conn = New SqlConnection("data source=localhost;" _ + "user id=sa;password=password;" + _ "Initial Catalog=SqlInjectionDemo")conn.Open() sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException Dim status As String status = sqlString + " failed"For Each err As SqlError In se.Errors status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak Password
  • 51.
    TryDim conn AsSqlConnection = NothingDim results As New DataSet() conn = New SqlConnection("data source=localhost;" _ + "user id=sa;password=password;" + _ "Initial Catalog=SqlInjectionDemo")conn.Open() sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException Dim status As String status = sqlString + " failed"For Each err As SqlError In se.Errors status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak PasswordWHERE ID='" + ID + "'"Don’t Concatenate arguments
  • 52.
    TryDim conn AsSqlConnection = NothingDim results As New DataSet() conn = New SqlConnection("data source=localhost;" _ + "user id=sa;password=password;" + _ "Initial Catalog=SqlInjectionDemo")conn.Open() sqlString = "SELECT HasShipped" + _" FROM Shipment WHERE ID='" + ID + "'"cmd = New SqlCommand(sqlString, conn)Dim adapter As New SqlDataAdapter(cmd)adapter.Fill(results)Catch se As SqlException Dim status As String status = sqlString + " failed"For Each err As SqlError In se.Errors status = status + err.MessageNextMesssageBox.Show(status)End TrySecurity Code ReviewNever connect as SADon’t Embed Secretsuser id=sapassword=passwordUnencrypted & Weak PasswordWHERE ID='" + ID + "'"Don’t Concatenate argumentsDon’t reveal everything to an attackerFor Each err As SqlError
  • 53.
    Why not connectas SA?Violates the principle of least privilegeThreat: Code is subject to attacker elevating privilegeMitigation RecommendationDefense in depth Action: Run SQL as Network Service rather than Local SystemReduce surface area: eliminate privileges on everything except for the required stored proceduresAction: Create stored proceduresLeast privilege: run as a lesser privileged user when connecting to databaseAction: Fix the connection string
  • 54.
    Why not embedsecrets?Violates the principle of avoiding security by obscurityThreat: Secrets are easily discoveredMitigation RecommendationDon’t Store SecretsTip: Use Windows AuthenticationEncrypt secretsFor .NET 1.1 consider Enterprise LibraryFor .NET 2.0 use Enterprise Library or System.Security.Cryptography.ProtectedDataFor SQL Server 2005 use EncryptByKey / DecryptByKey
  • 55.
    Storing SecretsHackers usesearch engines to locate secretsSearch engines will find anything you have hidden
  • 56.
    Storing SecretsMySQL DataDumpsConfig Files on *nix systems
  • 57.
  • 58.
    Never create yourown encryption
  • 59.
    Never create yourown encryption
  • 60.
    Never create yourown encryption
  • 61.
    Why not useeasy passwords?Because they are easily broken by brute force attacksThreat: Attacker guesses or brute forces password to access secretsMitigation:Enforce a strong password policy
  • 62.
    Enable password policyenforcement on SQL Server
  • 63.
    Uses Windows Server2003 policyBrute Force Dictionary Attacks
  • 64.
    Password PolicySQL Server2005 Management Studio Tool Shown
  • 65.
    Why not concatenatearguments?Violates the principle of All Input Is Evil (Until Proven Otherwise)Threat: Code is subject to luring attacks via SQL InjectionMitigation RecommendationReduce Attack Surface
  • 66.
  • 67.
    Create stored proceduresand grant access only to the stored procedure
  • 68.
  • 69.
    Disable unneeded SQLServer FeaturesUsing Parameters and Sprocs
  • 70.
  • 71.
    Reduce SQL SurfaceAreaIf you don’t connect in a sysadmin role the account used by xp_cmdshell will be the one defined by xp_cmdshell_proxy_account which may have reduced privilege
  • 72.
    Evil Input Attack- HotmailOctober 2001 an XSS vulnerability which allowed an attacker to steal a user's Microsoft .NET Passport session cookies. Exploit for this vulnerability consisted of sending a malicious email to a Hotmail user, which contained malformed HTML. The script filtering code in Hotmail's site failed to remove the broken HTML and Internet Explorer's parsing algorithm happily interpreted the malicious code.
  • 73.
    Security Fix: ValidateInputConstrainLook for valid data and reject everything else
  • 74.
  • 75.
    Use Regular Expressionsto permit only what you want
  • 76.
    Integer expression: “^[0-9]{0,5}$”RejectRejectthings you know are badSanitizeUse SQL Parameters
  • 77.
    HTMLEncode outputdiscussion: WhiteListing vs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)
  • 78.
    discussion: White Listingvs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”
  • 79.
    discussion: White Listingvs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”“deldeleteete”
  • 80.
    discussion: White Listingvs Black Listing Input“Look for valid data and reject everything else”SQL Example: string.Replace(“delete”, “”)“deldeleteete”“deldeleteete”“delete”
  • 81.
    demo: SQL InjectionSanitizingUser InputSelect Count(*) From UsersWhere User Name = ‘’ OR1+1=2; -- ‘ and password = ‘’
  • 82.
  • 83.
  • 84.
    Why not revealall exceptions?Most users won’t understand the details anywayThreat: Code is subject to information disclosure threatsMitigation RecommendationMap low level error messages to meaningful messages for your users
  • 85.
    Never disclose secretsin error messagesMeaningful Error MessagesWhat this error really means…No SmartCard inserted in card reader
  • 86.
  • 87.
  • 88.
    Threat Model ChecklistNodesign is complete without a threat model!
  • 89.
    Capture your workin a threat model document
  • 90.
  • 91.
    Track and prioritizevulnerabilities through to mitigation and testing
  • 92.
    Take advantage ofsecurity guidance http://msdn.microsoft.com/securityguidancevulnthreatasset
  • 93.
    Architects MustUnderstand securityterminology and best practicesPay attention to what is happening in the industryInstill security thinking throughout the application lifecycle Ensure that the team has an up to date threat modelEnsure that the team has operational procedures that will ensure ongoing security
  • 94.
    exercise: Use theThreat Analysis & Modeling Tool
  • 95.
  • 96.
  • 97.
  • 98.

Editor's Notes

  • #56 “Search engines will find anything you have hidden” We could say “could, or might find”… but we need to think of this as WILL find anything that we have hidden.