Enterprise Library Enterprise Library Cryptography Cryptography Application Block Application Block Tim Shakarian Tim Shakarian Software Design Engineer Software Design Engineer Avanade Avanade Ron Jacobs Ron Jacobs Product Manager Product Manager Microsoft Microsoft Scott Scott Densmore Densmore Software Design Software Design Engineer Engineer Microsoft Microsoft
48
Embed
Enterprise Library Cryptography Application Block Tim Shakarian Software Design Engineer Avanade Ron Jacobs Product Manager Microsoft Scott Densmore Software.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Writing the same code over and over Writing the same code over and over for the plumbing around cryptography for the plumbing around cryptography (streams, initialization vectors, strings (streams, initialization vectors, strings to byte array conversions, etc.) to byte array conversions, etc.)
Fretting over which algorithm to use in Fretting over which algorithm to use in your application code, knowing that your application code, knowing that changing algorithms will force changing algorithms will force application code changes application code changes
Wrestling with how to manage Wrestling with how to manage cryptography keyscryptography keys
Poll: When it comes to Poll: When it comes to CryptographyCryptography
[Live Meeting Multiple Choice Poll. Use [Live Meeting Multiple Choice Poll. Use Live MeetingLive Meeting > > Edit Slide Properties...Edit Slide Properties... to edit.] to edit.]
I have struggled with these issuesI have struggled with these issues
I know how to use I know how to use System.Security.CryptographySystem.Security.Cryptography
I know I need to do crypto but I worry I know I need to do crypto but I worry about getting it rightabout getting it right
What is cryptography?What is cryptography?
Why Cryptography?Why Cryptography?
ConfidentialityConfidentiality To ensure data remains private. To ensure data remains private. Confidentiality is usually achieved using Confidentiality is usually achieved using encryption. encryption.
DataData integrityintegrity To ensure data is protected from To ensure data is protected from accidental or deliberate (malicious) accidental or deliberate (malicious) modification. modification.
AuthenticationAuthentication To assure that data originates from a To assure that data originates from a particular party. particular party.
Cryptography NeedsCryptography Needs
A simple way of hashing data and A simple way of hashing data and comparing hashed valuescomparing hashed values
A simple way of encrypting and A simple way of encrypting and decrypting datadecrypting data
The ability to encrypt information The ability to encrypt information without using keys, for use on a without using keys, for use on a single machinesingle machine
The ability to write the same The ability to write the same application code for different application code for different cryptography providerscryptography providers
An easy way to adjust and validate An easy way to adjust and validate the cryptography configuration the cryptography configuration settingssettings
Common Application Threats Common Application Threats with Cryptography with Cryptography CountermeasuresCountermeasuresConfiguration ManagementConfiguration Management
Retrieval of plaintext configuration Retrieval of plaintext configuration secretssecrets
Sensitive DataSensitive DataAccess to sensitive data in storageAccess to sensitive data in storageNetwork eavesdroppingNetwork eavesdroppingData tamperingData tampering
Session ManagementSession ManagementMan in the middle attacks Man in the middle attacks
Improving Web Application SecurityThreats and Countermeasures Chapter 2 – Threats and Countermeasureshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Cryptography Threats and Cryptography Threats and CountermeasuresCountermeasures
Threat: Poor key generation or key Threat: Poor key generation or key managementmanagement CountermeasuresCountermeasures
Use built-in encryption routines that include secure key managementUse strong random key generation functions and store the key in a restricted locationEncrypt the encryption key using DPAPI for added securityExpire keys regularly
Improving Web Application SecurityThreats and Countermeasures Chapter 2 – Threats and Countermeasureshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Cryptography Threats and Cryptography Threats and CountermeasuresCountermeasures
Threat: Threat: Weak or custom encryptionCountermeasuresCountermeasures
Do not develop your own custom algorithmsUse the proven cryptographic services provided by the platformStay informed about cracked algorithms and the techniques used to crack them
Improving Web Application SecurityThreats and Countermeasures Chapter 2 – Threats and Countermeasureshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Cryptography Threats and Cryptography Threats and CountermeasuresCountermeasures
Threat: Threat: Checksum SpoofingDo not rely on hashes to provide data integrity for messages sent over networks. Hashes such as Safe Hash Algorithm (SHA1) and Message Digest compression algorithm (MD5) can be intercepted and changed.
CountermeasuresCountermeasuresUse a message authentication code (MAC) or hashed message authentication code (HMAC)
Improving Web Application SecurityThreats and Countermeasures Chapter 2 – Threats and Countermeasureshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Provides a simplified approach to Provides a simplified approach to implementing common implementing common cryptography scenarioscryptography scenarios
Improve SecurityImprove SecurityConsiders threats and Considers threats and countermeasures countermeasures
Ease of use increases likelihood of Ease of use increases likelihood of adoptionadoption
Other application blocks designed to Other application blocks designed to work with the Cryptography work with the Cryptography Application BlockApplication Block
SecuritySecurity
CryptoCrypto
ConfigurationConfiguration
Data Data AccessAccess LoggingLogging
CachingCaching ExceptionsExceptions
Enterprise Library v1Enterprise Library v1
Legend
Dependency
Plug-in
ConfigConfigToolTool
Implementing CryptoImplementing Crypto
...in 2 easy steps...in 2 easy steps
Step 1: Define your Step 1: Define your configurationconfiguration
You will need an app.config (or web.config) file for your applicationYou will need an app.config (or web.config) file for your application
Use the Enterprise Library Configuration tool to create the Use the Enterprise Library Configuration tool to create the configuration for the Cryptography Application Blockconfiguration for the Cryptography Application Block
Use a post-build step to copy config files to the runtime directoryUse a post-build step to copy config files to the runtime directory
See See http://www.ronjacobs.com/TipPostBuild.htmhttp://www.ronjacobs.com/TipPostBuild.htm
StepStep 2: Call the Appropriate 2: Call the Appropriate Cryptography MethodCryptography Method
Static method interfaceStatic method interface
Enterprise Library Cryptography Application Enterprise Library Cryptography Application Block uses the Block uses the PluginPlugin [Fowler] pattern to [Fowler] pattern to create providers.create providers.// Encrypt using the named providerstring encyrptedValue = Cryptographer.EncryptSymmetric("symproviderName", "StringToEncrypt");
// Generate a hash value using the named providerstring hashedValue = Cryptographer.CreateHash("hashprovider", "MySecret");
View/Application Share: View/Application Share: Demonstration of Demonstration of Cryptography BlockCryptography Block[Live Meeting View/Application Share. Use [Live Meeting View/Application Share. Use Live MeetingLive Meeting
> > Edit Slide Properties...Edit Slide Properties... to edit.] to edit.]
Going deeper...Going deeper...
...this is where it gets interesting...this is where it gets interesting
Threats and CountermeasuresThreats and Countermeasures
Disclosure of Configuration DataDisclosure of Configuration DataThe most sensitive configuration data used by data access The most sensitive configuration data used by data access code is the database connection string. If a compromised code is the database connection string. If a compromised connection string includes a user name and password, the connection string includes a user name and password, the consequences can be greater still.consequences can be greater still.
VulnerabilitiesVulnerabilitiesUse of SQL authentication, which requires credentials to be Use of SQL authentication, which requires credentials to be specified in the connection string specified in the connection string Embedded connection strings in code Embedded connection strings in code Clear text connection strings in configuration files Clear text connection strings in configuration files Failure to encrypt a connection string Failure to encrypt a connection string
CountermeasuresCountermeasuresUse Windows authentication so that connection strings do Use Windows authentication so that connection strings do not contain credentials. not contain credentials. Encrypt the connection stringsEncrypt the connection strings and restrict access to the and restrict access to the encrypted data. encrypted data. Improving Web Application Security
Threats and Countermeasures Chapter 14 – Building Secure Data Accesshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Storing SecretsStoring Secrets
Typical examples of secrets include:SQL connection stringsCredentials used for SQL application rolesFixed identities in Web.configProcess identity in Machine.configKeys used to store data securelySQL Server session state Passwords used for Forms authentication against a database
Building Secure ASP.NET Applications Chapter 8 – ASP.NET Securityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/secnetlpMSDN.asp
Options for Storing SecretsOptions for Storing Secrets
Pick and choose from platform options
.NET cryptography classesData Protection API (DPAPI)CAPICOMCrypto API
Or use the Enterprise Library and the Cryptography Application Block for simplified and best practice use of the platform!
Encryption AlgorithmsEncryption Algorithms
Selecting an Algorithm Selecting an Algorithm Some encryption algorithms perform better than others while some provide stronger encryption. Typically, larger encryption key sizes increase security.
A Common MistakeA Common MistakeDeveloping your own encryption algorithmsDeveloping your own encryption algorithms
Improving Web Application SecurityThreats and Countermeasures Chapter 7 – Building Secure Assemblieshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
StoringStoring Passwords
For security reasons, you should not store passwords (clear text or encrypted) in the database.You should avoid storing encrypted passwords because it raises key management issues — you can secure the password with encryption, but you then have to consider how to store the encryption key. If the key becomes compromised, an attacker can decrypt all the passwords within your data store.
Building Secure ASP.NET Applications Chapter 8 – ASP.NET Securityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/secnetlpMSDN.asp
StoreStore One-way Password Hashes (with Salt)
The preferred approach is to:Store a one way hash of the password. Re-compute the hash when the password needs to be validated.Combine the password hash with a salt value (a cryptographically strong random number). By combining the salt with the password hash, you mitigate the threat associated with dictionary attacks.
Building Secure ASP.NET Applications Chapter 8 – ASP.NET Securityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/secnetlpMSDN.asp
Configuring the Hash ProviderConfiguring the Hash Provider
Using the Configuration ConsoleUsing the Configuration Console
Configuring Hash Provider to Configuring Hash Provider to use Saltuse Salt
Each provider has the option to use saltEach provider has the option to use saltSalt value is generated by application blockSalt value is generated by application block
Call Call CreateHashCreateHash with the name of the with the name of the hash provider and the value to be hash provider and the value to be hashedhashed
Sample hash resultSample hash result
Comparing Hash ValuesComparing Hash Values
boolean matched =
Cryptographer.CompareHash("hashprovider",
"MyValue“.
hValue);
Call Call CompareHashCompareHash with the name of with the name of the hash provider, comparison value, the hash provider, comparison value, and the original hashed valueand the original hashed value
Salt Under the CoversSalt Under the Covers
Default salt length is 16 bytes Default salt length is 16 bytes (providers can override)(providers can override)
Uses Uses RNGCryptoServiceProviderRNGCryptoServiceProvider (not (not RandomRandom) to decrease likelihood of ) to decrease likelihood of repeated salt valuesrepeated salt values
Salt combined with value, then hashedSalt combined with value, then hashed
Salt and hash are returned by Salt and hash are returned by CreateHashCreateHash
CompareHash extracts salt and uses it CompareHash extracts salt and uses it to compute comparison hashto compute comparison hash
No worries: the application block takes No worries: the application block takes care of all this for you!care of all this for you!
Configuring a Symmetric Configuring a Symmetric Encryption ProviderEncryption Provider
Using the Configuration ConsoleUsing the Configuration Console
Symmetric Key CreationSymmetric Key CreationGenerate creates key of appropriate length for algorithm providerGenerate creates key of appropriate length for algorithm providerDisplayed as hex string valueDisplayed as hex string valueImport allows you to use an existing keyImport allows you to use an existing key
Key StorageKey StorageFailing to secure encryption keys is one of the most common mistakes made when using cryptographyFailing to secure encryption keys is one of the most common mistakes made when using cryptographyUse the following techniques to help prevent key storage vulnerabilities:
Use DPAPI to avoid key management Do not store keys in codeRestrict access to persisted keys
Improving Web Application SecurityThreats and Countermeasures Chapter 7 – Building Secure Assemblieshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/ThreatCounter.asp
Symmetric Key Symmetric Key ManagementManagementKey is saved in securityCryptographyConfiguration.config file as Base 64 encoded stringKey is saved in securityCryptographyConfiguration.config file as Base 64 encoded string
Protecting the config fileProtecting the config fileFile system access controlFile system access controlEncrypting File System (EFS)Encrypting File System (EFS)The Configuration Console allows you to encrypt the config file using DPAPIThe Configuration Console allows you to encrypt the config file using DPAPI
Exporting the Symmetric Exporting the Symmetric KeyKey
Saves the key to a text fileSaves the key to a text fileIf supplied, password is used to encrypt the exported keyIf supplied, password is used to encrypt the exported keyProtect your keys!Protect your keys!
Using the DPAPI ProviderUsing the DPAPI ProviderAvoids key management (managed by operating system)Avoids key management (managed by operating system)User and machine modeUser and machine modeEntropy is saved to config fileEntropy is saved to config file
Encrypting a SecretEncrypting a Secret
Dim encryptedString As String = _
Cryptographer.EncryptSymmetric(“symmProvider”, _
“MySecret")
"Iu3A8HVNSIcXMHWUc79DRALf5vwm9XTquE90kyfalvo="
Call EncryptSymmetric with the name of Call EncryptSymmetric with the name of the provider and the value to be the provider and the value to be encryptedencrypted
Return value is Base 64 encoded stringReturn value is Base 64 encoded string
Decrypting a SecretDecrypting a Secret
Dim decryptedString As String = _
Cryptographer.DecryptSymmetric(“symmProvider”, _
encryptedString)
“MySecret"
Call DecryptSymmetric with the name Call DecryptSymmetric with the name of the provider and the value to be of the provider and the value to be encryptedencrypted
Return value is unencrypted stringReturn value is unencrypted string
Common Cryptography Common Cryptography FunctionalityFunctionality
Enterprise Library includes simple Enterprise Library includes simple cryptography capability in a cryptography capability in a common assemblycommon assemblyNot externally configurableNot externally configurableDoes not require Cryptography Does not require Cryptography Application Block (it is used by the Application Block (it is used by the block)block)Allows Configuration Console to Allows Configuration Console to encrypt/decrypt configuration encrypt/decrypt configuration settings without requiring settings without requiring Cryptography Application BlockCryptography Application Block
Enterprise Library provides Enterprise Library provides applied applied guidanceguidance through proven practices through proven practices engineered in codeengineered in codeConnection strings are managed Connection strings are managed through configuration with the through configuration with the Configuration Application BlockConfiguration Application BlockWith the default XML Storage ProviderWith the default XML Storage Provider
Connection strings are saved in the file Connection strings are saved in the file dataConfiguration.config dataConfiguration.config Configuration files are saved as plain text by Configuration files are saved as plain text by defaultdefault
Enterprise Library includes the Enterprise Library includes the Cryptography Application Block which Cryptography Application Block which can be used to encrypt the connection can be used to encrypt the connection string automatically string automatically
The encryption configuration The encryption configuration determines determines how how the application block the application block configuration will be encrypted configuration will be encrypted
Step 1a: Set Encryption Step 1a: Set Encryption SettingsSettings
Step 1b: Set Encryption Step 1b: Set Encryption SettingsSettings
Step 2: Mark the Step 2: Mark the configuration section as configuration section as encryptedencryptedWhetherWhether to encrypt configuration to encrypt configuration
information is determined by each information is determined by each application block’s configuration application block’s configuration settingssettings
Plus…Plus…Anything and everything – you have the source code!Anything and everything – you have the source code!
Please post extensions and suggestions to the communityPlease post extensions and suggestions to the communityhttp://workspaces.gotdotnet.com/entlibhttp://workspaces.gotdotnet.com/entlib
Additional ResourcesAdditional ResourcesImproving Web Application SecurityImproving Web Application Securityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/
dnnetsec/html/ThreatCounter.asp
Improving .NET Application Performance and Improving .NET Application Performance and ScalabilityScalabilityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
dnpag/html/scalenet.aspdnpag/html/scalenet.asp
Application Architecture for .NETApplication Architecture for .NEThttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/http://msdn.microsoft.com/library/default.asp?url=/library/en-us/