Upload
julie-sims
View
247
Download
4
Tags:
Embed Size (px)
Citation preview
Writing Secure Code – Writing Secure Code – Best PracticesBest Practices
Nigel WatlingNigel WatlingSenior Developer ArchitectSenior Developer ArchitectEMEA Developer Strategy GroupEMEA Developer Strategy Group
What We Will CoverWhat We Will Cover
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
Session PrerequisitesSession Prerequisites
Development experience with MicrosoftDevelopment experience with MicrosoftVisual Basic® , Microsoft Visual C++® , Visual Basic® , Microsoft Visual C++® , or C#or C#
Level 200Level 200
AgendaAgenda
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
Improving the Application Improving the Application Development ProcessDevelopment Process
Consider securityConsider securityAt the start of the processAt the start of the process
Throughout developmentThroughout development
Through deploymentThrough deployment
At all software review milestonesAt all software review milestones
Do not stop looking for security bugs Do not stop looking for security bugs until the end of the development until the end of the development processprocess
SDSD33
Secure Secure by Designby Design
Secure Secure by Defaultby Default
Secure in Secure in DeploymentDeployment
Secure architecture and codeSecure architecture and codeThreat analysisThreat analysisVulnerability reductionVulnerability reduction
Attack surface area reducedAttack surface area reducedUnused features turned off by Unused features turned off by defaultdefaultMinimum privileges usedMinimum privileges used
Protection: Detection, defense, Protection: Detection, defense, recovery, and managementrecovery, and managementProcess: How to guides, Process: How to guides, architecture guidesarchitecture guidesPeople: TrainingPeople: Training
The SDThe SD33 Security Framework Security Framework
Secure Product Development Secure Product Development TimelineTimeline
TestTest PlansPlansCompleteComplete
DesignsDesignsCompleteComplete
ConceptConcept CodeCodeCompleteComplete
ShipShip Post-ShipPost-Ship
Test for security vulnerabilities
Assess security knowledge when
hiring team members
Determine security sign-off
criteria
Send out for external review
Analyze threats
Learn and refine
Perform security team review
Train team members
Test for data mutation and least privilege
Resolve security issues, verify code against security guidelines
=ongoing
Secure By DesignSecure By Design
Raise security awareness of design Raise security awareness of design teamteam
Use ongoing trainingUse ongoing training
Challenge attitudes - “What I don’t know Challenge attitudes - “What I don’t know won’t hurt me” does not apply!won’t hurt me” does not apply!
Get security right during the design Get security right during the design phasephase
Define product security goalsDefine product security goals
Implement security as a key product Implement security as a key product featurefeature
Use threat modeling during design phaseUse threat modeling during design phase
AgendaAgenda
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
What Is Threat Modeling?What Is Threat Modeling?
Threat modeling is a security-based Threat modeling is a security-based analysis that:analysis that:
Helps a product team understand where Helps a product team understand where the product is most vulnerablethe product is most vulnerableEvaluates the threats to an application Evaluates the threats to an application Aims to reduce overall security risksAims to reduce overall security risksFinds assetsFinds assetsUncovers vulnerabilitiesUncovers vulnerabilitiesIdentifies threatsIdentifies threatsShould help form the basis of security Should help form the basis of security design specificationsdesign specifications
Benefits of Threat ModelingBenefits of Threat Modeling
Helps you understand your application Helps you understand your application betterbetter
Helps you find bugsHelps you find bugs
Identifies complex Identifies complex design bugsdesign bugs
Helps integrate new Helps integrate new team membersteam members
Drives well-designed Drives well-designed security test planssecurity test plans
Threat
Vulnerability
Asset
The Threat Modeling ProcessThe Threat Modeling Process
Identify Assets1
Create an Architecture Overview2
Decompose the Application3
Identify the Threats4
Document the Threats5
Rate the Threats6
Threat Modeling Process
Threat Modeling Process Threat Modeling Process Step 1: Identify AssetsStep 1: Identify Assets
Build a list of assets that require Build a list of assets that require protection, including:protection, including:
Confidential data, such as customer Confidential data, such as customer databasesdatabases
Web pagesWeb pages
System availabilitySystem availability
Anything else that, if compromised, would Anything else that, if compromised, would prevent correct operation of your prevent correct operation of your applicationapplication
Threat Modeling Process Threat Modeling Process Step 2: Create An Architecture Step 2: Create An Architecture OverviewOverview
Identify what the application doesIdentify what the application doesCreate an application architecture diagramCreate an application architecture diagram
Identify the technologiesIdentify the technologies
NTFS Permissions(Authentication)
File AuthorizationURL Authorization
.NET Roles(Authentication)
User-Defined Role(Authentication)
SSL(Privacy/Integrity)
Trust Boundary
AliceMaryBob IISIIS
AnonymousAuthentication
FormsAuthentication
IPSec(Private/Integrity)
Trust Boundary
ASPNET(Process Identity)Microsoft
ASP.NETMicrosoft ASP.NET
Microsoft Windowsr
Authentication
MicrosoftSQL Server™
Threat Modeling Process Threat Modeling Process Step 3: Decompose the ApplicationStep 3: Decompose the Application
Break down the Break down the applicationapplication
Create a security profile Create a security profile based on traditional based on traditional areas of vulnerabilityareas of vulnerability
Examine interactions Examine interactions between different between different subsystemssubsystems
Use DFD or UML Use DFD or UML diagramsdiagrams
Identify Trust BoundariesIdentify Trust Boundaries
Identify Data FlowIdentify Data Flow
Identify Entry PointsIdentify Entry Points
Identify Privileged CodeIdentify Privileged Code
Document Security ProfileDocument Security Profile
Threat Modeling Process Threat Modeling Process Step 4: Identify the ThreatsStep 4: Identify the Threats
Assemble team Assemble team
Identify threatsIdentify threatsNetwork threatsNetwork threats
Host threatsHost threats
Application threatsApplication threats
Types of threats
•Examples
Spoofing Forging e-mail messages Replaying authentication packets
•Tampering Altering data during transmission Changing data in files
•Repudiation Deleting a critical file and deny it Purchasing a product and deny it
•Information disclosure
Exposing information in error messages Exposing code on Web sites
•Denial of service
Flooding a network with SYN packetsFlooding a network with forged ICMPpackets
•Elevation of privilege
Exploiting buffer overruns to gain system privilegesObtaining administrator privileges illegitimately
Threat Modeling Process Threat Modeling Process Identify the Threats by Using STRIDEIdentify the Threats by Using STRIDE
Threat #1 (I)View payroll data
1.1Traffic is unprotected
1.2Attacker viewstraffic
1.2.1Sniff traffic with protocol analyzer
1.2.2Listen to routertraffic
1.2.2.1Router is unpatched
1.2.2.2Compromise router
1.2.2.3Guess routerpassword
1.0 View payroll data (I) 1.1 Traffic is unprotected (AND) 1.2 Attacker views traffic 1.2.1 Sniff traffic with protocol analyzer 1.2.2 Listen to router traffic 1.2.2.1 Router is unpatched (AND) 1.2.2.2 Compromise router 1.2.2.3 Guess router password
Threat Modeling Process Threat Modeling Process Identify the Threats by Using Attack Identify the Threats by Using Attack TreesTrees
Threat Modeling Process Threat Modeling Process Step 5: Document the ThreatsStep 5: Document the Threats
Document threats by using a template:Document threats by using a template:
Leave Risk blank (for now)Leave Risk blank (for now)
Threat Description Injection of SQL CommandsThreat target Data Access Component
RiskAttack techniques Attacker appends SQL commands
to user name, which is used to form a SQL query
Countermeasures Use a regular expression to validate the user name, and use a stored procedure with parameters to access the database
Threat Modeling Process Threat Modeling Process Step 6: Rate the ThreatsStep 6: Rate the Threats
Use formula: Use formula: Risk = Probability * Damage PotentialRisk = Probability * Damage Potential
Use DREAD to rate threatsUse DREAD to rate threatsDDamage potential amage potential
RReproducibility eproducibility
EExploitability xploitability
AAffected users ffected users
DDiscoverability iscoverability
Threat Modeling Process Threat Modeling Process Example: Rate the ThreatsExample: Rate the Threats
Threat #1 (I)View payroll data
1.1Traffic is unprotected
1.2Attacker viewstraffic
1.2.1Sniff traffic with protocol analyzer
1.2.2Listen to routertraffic
1.2.2.1Router is unpatched
1.2.2.2Compromise router
1.2.2.3Guess routerpassword
•Damage potential•Affected Users-or-•Damage
•Reproducibility•Exploitability•Discoverability-or-•Chance
Coding to a Threat ModelCoding to a Threat Model
Use threat modeling to helpUse threat modeling to helpDetermine the most “dangerous” portions Determine the most “dangerous” portions of your applicationof your application
Prioritize security push effortsPrioritize security push efforts
Prioritize ongoing code reviewsPrioritize ongoing code reviews
Determine the threat mitigation techniques Determine the threat mitigation techniques to employto employ
Determine data flowDetermine data flow
AgendaAgenda
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
Risk Mitigation OptionsRisk Mitigation Options
Option 1: Do NothingOption 1: Do Nothing
Option 2: Warn the UserOption 2: Warn the User
Option 3: Remove the ProblemOption 3: Remove the Problem
Option 4: Fix ItOption 4: Fix It Patrolled
Risk Mitigation ProcessRisk Mitigation Process
Threat Type(STRIDE)
Mitigation Technique Mitigation Technique
Technology Technology Technology Technology
Spoofing Authentication
NTLMX.509 certsPGP keysBasicDigestKerberosSSL/TLS
1.1. Identify categoryIdentify categoryFor example: For example: SpoofingSpoofing
2.2. Select techniquesSelect techniquesFor example: For example: Authentication or Authentication or Protect secret dataProtect secret data
3.3. Choose technologyChoose technologyFor example: For example: KerberosKerberos
Sample Mitigation TechniquesSample Mitigation Techniques
Client Server
PersistentData
AuthenticationData
ConfigurationData SSTTRRIDIDEE
STSTRRIDEIDE
STRISTRIDDEE
SSTTRRIIDEDESSTRIDTRIDEE
SSL/TLS IPSec RPC/DCO with
Privacy
Firewall Limiting
resource utilization for anonymous connections
Strong access control
Digital signatures Auditing
InsecureNetwork
AgendaAgenda
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
Run with Least PrivilegeRun with Least Privilege
Well-known security doctrine:Well-known security doctrine:““Run with just enough privilege to get the Run with just enough privilege to get the job done, and no more!”job done, and no more!”
Elevated privilege can lead to Elevated privilege can lead to disastrous consequencesdisastrous consequences
Malicious code executing in a highly Malicious code executing in a highly privileged process runs with extra privileged process runs with extra privileges tooprivileges too
Many viruses spread because the recipient Many viruses spread because the recipient has administrator privilegeshas administrator privileges
Demonstration 1Demonstration 1 ASP.NET Applications SecurityASP.NET Applications Security
Investigating ASP.NET Application PrivilegesInvestigating ASP.NET Application Privileges
Restricting ASP.NET Applications Trust Restricting ASP.NET Applications Trust LevelsLevels
Sandboxing Privileged CodeSandboxing Privileged CodeUsing Sandboxed AssembliesUsing Sandboxed Assemblies
Reduce the Attack SurfaceReduce the Attack Surface
Expose only limited, well documented Expose only limited, well documented interfaces from your applicationinterfaces from your application
Use only the services that your Use only the services that your application requiresapplication requires
The Slammer and CodeRed viruses would The Slammer and CodeRed viruses would not have happened if certain features were not have happened if certain features were not on by defaultnot on by default
ILoveYou (and other viruses) would not ILoveYou (and other viruses) would not have happened if scripting was disabledhave happened if scripting was disabled
Turn everything else offTurn everything else off
Do Not Trust User InputDo Not Trust User Input
Validate all inputValidate all inputAssume all input is harmful until proven otherwiseAssume all input is harmful until proven otherwise
Look for valid data and reject everything elseLook for valid data and reject everything else
Constrain, reject, and sanitize user input withConstrain, reject, and sanitize user input withType checksType checks
Length checksLength checks
Range checksRange checks
Format checksFormat checksValidator.ValidationExpression =
"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
Demonstration 2Demonstration 2 Windows Forms ValidationWindows Forms Validation
Viewing a Non-Validating ApplicationViewing a Non-Validating Application
Adding Input ValidationAdding Input ValidationValidating the Complete FormValidating the Complete Form
Defense in Depth (1 of 3)Defense in Depth (1 of 3)Use Multiple GatekeepersUse Multiple Gatekeepers
SSL
ISA Firewall
IIS
SQL Server
ISA FirewallIPSec
Defense in Depth (2 of 3)Defense in Depth (2 of 3)Apply Appropriate Measures for Each Apply Appropriate Measures for Each LayerLayer
Check security
Check security
Application.dll
Application.exe
Check security
Check security
Secure resource with an ACL
Application.dll
Defense in Depth (3 of 3)Defense in Depth (3 of 3)Use Strong ACLs on ResourcesUse Strong ACLs on Resources
Design ACLs into the application from Design ACLs into the application from the beginningthe beginning
Apply ACLs to files, folders, Web pages, Apply ACLs to files, folders, Web pages, registry settings, database files, registry settings, database files, printers, and objects in Active Directoryprinters, and objects in Active Directory
Create your own ACLs during Create your own ACLs during application installationapplication installation
Include DENY ACEsInclude DENY ACEs
Do not use NULL DACLsDo not use NULL DACLs
Do Not Rely on Security by Do Not Rely on Security by ObscurityObscurity
Do not hide security keys in filesDo not hide security keys in files
Do not rely on undocumented registry Do not rely on undocumented registry keyskeys
Always assume an attacker knows Always assume an attacker knows everything you knoweverything you know
Use Data Protection API Use Data Protection API (DPAPI) to Protect Secrets(DPAPI) to Protect Secrets
Two DPAPI functions:Two DPAPI functions:CryptProtectDataCryptProtectData
CryptUnprotectDataCryptUnprotectData
Two stores for data encrypted with Two stores for data encrypted with DPAPI:DPAPI:
User storeUser store
Machine storeMachine store
Demonstration 3Demonstration 3 DPAPIDPAPI
Storing Connection Strings in Web.configStoring Connection Strings in Web.configEncrypting Connection Strings with DPAPIEncrypting Connection Strings with DPAPI
Installing the Aspnet_setreg UtilityInstalling the Aspnet_setreg UtilityUsing Encrypted Attributes in a Using Encrypted Attributes in a
Configuration FileConfiguration FileGranting Permissions on Registry KeysGranting Permissions on Registry Keys
Fail Intelligently (1 of 2)Fail Intelligently (1 of 2)
If your code does fail, make sure it fails If your code does fail, make sure it fails securelysecurely
DWORD dwRet = IsAccessAllowed(…);
if (dwRet == ERROR_ACCESS_DENIED) {
// Security check failed.
// Inform user that access is denied
} else {
// Security check OK.
// Perform task…
}
What if IsAccessAllowed()
returns ERROR_NOT_
ENOUGH_MEMORY?
What if IsAccessAllowed()
returns ERROR_NOT_
ENOUGH_MEMORY?
Fail Intelligently (2 of 2)Fail Intelligently (2 of 2)
Do not:Do not:Reveal information in error Reveal information in error messagesmessages
Consume resources for lengthy Consume resources for lengthy periods of time after a failureperiods of time after a failure
Do:Do:Use exception handling blocks to Use exception handling blocks to avoid propagating errors back to the avoid propagating errors back to the callercaller
Write suspicious failures to an event Write suspicious failures to an event loglog
<customErrors mode="On"/>
Test SecurityTest Security
Involve test teams in projects at the Involve test teams in projects at the beginningbeginning
Use threat modeling to develop security Use threat modeling to develop security testing strategytesting strategy
Think Evil. Be Evil. Test Evil.Think Evil. Be Evil. Test Evil.Automate attacks with scripts and low-level Automate attacks with scripts and low-level programming languagesprogramming languages
Submit a variety of invalid dataSubmit a variety of invalid data
Delete or deny access to files or registry entriesDelete or deny access to files or registry entries
Test with an account that is not an administrator Test with an account that is not an administrator accountaccount
Know your enemy and know yourselfKnow your enemy and know yourselfWhat techniques and technologies will hackers What techniques and technologies will hackers use?use?
What techniques and technologies can testers What techniques and technologies can testers use?use?
Learn from MistakesLearn from Mistakes
If you find a security problem, learn If you find a security problem, learn from the mistakefrom the mistake
How did the security error occur?How did the security error occur?
Has the same error been made elsewhere Has the same error been made elsewhere in the code?in the code?
How could it have been prevented?How could it have been prevented?
What should be changed to avoid a What should be changed to avoid a repetition of this kind of error?repetition of this kind of error?
Do you need to update educational Do you need to update educational material or analysis tools?material or analysis tools?
Session SummarySession Summary
Secure Development ProcessSecure Development Process
Threat ModelingThreat Modeling
Risk Mitigation Risk Mitigation
Security Best PracticesSecurity Best Practices
Next StepsNext Steps1.1. Stay informed about securityStay informed about security
Sign up for security bulletins:Sign up for security bulletins:
http://www.microsoft.com/security/security_bulletins/alerts2.ahttp://www.microsoft.com/security/security_bulletins/alerts2.aspsp
Get the latest Microsoft security guidance:Get the latest Microsoft security guidance: http://www.microsoft.com/security/guidance/http://www.microsoft.com/security/guidance/
2.2. Get additional security trainingGet additional security training Find online and in-person training seminars:Find online and in-person training seminars: http://www.microsoft.com/seminar/events/http://www.microsoft.com/seminar/events/
security.mspxsecurity.mspx Find a local CTEC for hands-on training:Find a local CTEC for hands-on training: http://www.microsoft.com/learning/http://www.microsoft.com/learning/
For More InformationFor More Information
Microsoft Security Site (all audiences)Microsoft Security Site (all audiences)http://www.microsoft.com/securityhttp://www.microsoft.com/security
MSDN Security Site (developers)MSDN Security Site (developers)http://http://msdn.microsoft.commsdn.microsoft.com/security/security
TechNet Security Site (IT professionals)TechNet Security Site (IT professionals)http://www.microsoft.com/http://www.microsoft.com/technettechnet/security/security