118
A Primer on Application Security Brandon McMillon [email protected] Academic Developer Evangelist Microsoft Corporation

A Primer on Application Security Brandon McMillon [email protected] Academic Developer Evangelist Microsoft Corporation Brandon McMillon [email protected]

Embed Size (px)

Citation preview

A Primer on Application Security

Brandon [email protected] Developer EvangelistMicrosoft Corporation

Why Security is Hard (For Some)Why Security is Hard (For Some)

“Security is boring”Often seen as something that disables technology or “gets in the way”Difficult to measureNot usually the primary skill or interest of the designers and developers“The Attacker’s Advantage”

“Security is boring”Often seen as something that disables technology or “gets in the way”Difficult to measureNot usually the primary skill or interest of the designers and developers“The Attacker’s Advantage”

The Attacker’s Advantage and the Defender’s Dilemma

The Attacker’s Advantage and the Defender’s DilemmaPrinciple #1 The Defender must

defend all points; the Attacker will choose the weakest pointPrinciple #2 The Defender must be constantly vigilant; the Attacker will strike at willPrinciple #3 The Defender can only defend what he/she knows about; the Attacker will study for vulnerable points

Principle #1 The Defender must defend all points; the Attacker will choose the weakest pointPrinciple #2 The Defender must be constantly vigilant; the Attacker will strike at willPrinciple #3 The Defender can only defend what he/she knows about; the Attacker will study for vulnerable points

Challenges When Implementing SecurityChallenges When Implementing Security

Attacker needs to understand only one security issue

Defender needs to secure all entry points

Attacker has unlimited time

Defender works with time and cost constraints

Attacker needs to understand only one security issue

Defender needs to secure all entry points

Attacker has unlimited time

Defender works with time and cost constraintsAttackers vs. Defenders

Developers and management think that security does not add any business value

Cost of addressing security issues only increases as software design lifecycle proceeds

Developers and management think that security does not add any business value

Cost of addressing security issues only increases as software design lifecycle proceeds

Security As an Afterthought

Do I need security

Secure systems are more difficult to use

Complex and strong passwords are difficult to remember

Users prefer simple passwords

Secure systems are more difficult to use

Complex and strong passwords are difficult to remember

Users prefer simple passwordsSecurity vs. Usability

Why Security MattersWhy Security Matters

Much more expensive to fix later on – Microsoft estimates that each security bulletin costs $100k. For every software company, fixing an issue after release is 50 to 200 times more expensive than fixing it earlier in the cycleBad PR – Your face on magazines!People shy away from your productsConsultants look to build their reputation by “victimizing” easy targets like you

Much more expensive to fix later on – Microsoft estimates that each security bulletin costs $100k. For every software company, fixing an issue after release is 50 to 200 times more expensive than fixing it earlier in the cycleBad PR – Your face on magazines!People shy away from your productsConsultants look to build their reputation by “victimizing” easy targets like you

Developer Role in Application SecurityDeveloper Role in Application Security

Developers must:Work with designers/architects, testers and systems administrators to ensure application securityContribute to security by:

Adopting good application security development practicesUsing secure programming techniquesKnowing where security issues occur and how to avoid themHave an “organizational awareness” of security processes and the people involved

Developers must:Work with designers/architects, testers and systems administrators to ensure application securityContribute to security by:

Adopting good application security development practicesUsing secure programming techniquesKnowing where security issues occur and how to avoid themHave an “organizational awareness” of security processes and the people involved

Developer Role in Application Security (cont.)

Developer Role in Application Security (cont.)To develop a secure application:

Need a secure design/architectNeed to be tested for security

Developers need to work withDesigners/architectsTesters

To develop a secure application:Need a secure design/architectNeed to be tested for security

Developers need to work withDesigners/architectsTesters

Holistic Approach to SecurityHolistic Approach to Security

Security must be considered at:All stages of a project

Design Development Deployment

All layers Network Host Application

Security must be considered at:All stages of a project

Design Development Deployment

All layers Network Host Application

“Security is only as good as the weakest link”

Who is Threat Modeling?Who is Threat Modeling?

Threat ModelingThreat ModelingPrinciple: Can’t build a secure system until you’ve identified all the threats against it

Provide capability where teams can

Define – information relevant to application securityModel – Threats, Attacks, Vulnerabilities and MitigationsMeasure – Impact, Probability, Cost, Benefit

What does this new capability provide?

Provides a security strategyPrioritize security featuresUnderstand value of mitigationsTranslates technical risk to business impact

Principle: Can’t build a secure system until you’ve identified all the threats against it

Provide capability where teams can

Define – information relevant to application securityModel – Threats, Attacks, Vulnerabilities and MitigationsMeasure – Impact, Probability, Cost, Benefit

What does this new capability provide?

Provides a security strategyPrioritize security featuresUnderstand value of mitigationsTranslates technical risk to business impact

Areas of Security ConcernAreas of Security Concern

AuthenticationAuthentication11

Asset HandlingAsset Handling33

Input IssuesInput Issues44

Auditing & LoggingAuditing & Logging55

AuthorizationAuthorization22

Threat Classification (STRIDE)Threat Classification (STRIDE)

SpoofingForging an identity of a service or user

TamperingCompromising integrity of data

RepudiationCan’t prove an action committed by an entity

Information DisclosureUnintended disclosure of information

Denial of ServiceCompromising availability of a service

Elevation of PrivilegesAn identity can gain unauthorized privileges

SpoofingForging an identity of a service or user

TamperingCompromising integrity of data

RepudiationCan’t prove an action committed by an entity

Information DisclosureUnintended disclosure of information

Denial of ServiceCompromising availability of a service

Elevation of PrivilegesAn identity can gain unauthorized privileges

A Few Common Attack PatternsA Few Common Attack Patterns

“Man in the Middle” (MitM) Attack“Man in the Middle” (MitM) Attack

User

www.IBuySpy.com

Attacker

Convince User youare www.IBuySpy.com

Convince www.IBuySpy.comyou are User

A Few Common Attack Patterns (cont.)A Few Common Attack Patterns (cont.)

Replay AttackReplay Attack

User

www.IBuySpy.com

Attacker

Request

Request

Attacker gets hold of the User Requestand replays it on the www.IBuySpy.comserver

A Few Common Attack Patterns (cont.)A Few Common Attack Patterns (cont.)

Dictionary AttackDecipher a secret using words from a dictionary

Brute Force AttackDecipher a secret by enumerating through all possibilities

Dictionary AttackDecipher a secret using words from a dictionary

Brute Force AttackDecipher a secret by enumerating through all possibilities

CryptographyCryptography

Idea: Make the cost of unauthorized retrieval of a message significantly higher than the value of the messageEncryption is the process of making information unreadable by unauthorized persons Cryptographic algorithms can be:

AsymmetricSymmetricOne-way (Hash algorithm)

Idea: Make the cost of unauthorized retrieval of a message significantly higher than the value of the messageEncryption is the process of making information unreadable by unauthorized persons Cryptographic algorithms can be:

AsymmetricSymmetricOne-way (Hash algorithm)

Symmetric CryptographySymmetric Cryptography

Uses one key to:Encrypt the data

Decrypt the data

Is fast and efficientDecrypt(Encrypt(“secret”, Key), Key) = “secret”Decrypt(Encrypt(“secret”, Key), OtherKey) = <garbage>

Uses one key to:Encrypt the data

Decrypt the data

Is fast and efficientDecrypt(Encrypt(“secret”, Key), Key) = “secret”Decrypt(Encrypt(“secret”, Key), OtherKey) = <garbage>

Asymmetric CryptographyAsymmetric CryptographyUses two mathematically related keys:

When one key encrypts the data…Only other key can decrypt the data

Is slower than symmetric encryptionSeparation of keys facilitates better management and exchange of keysDecrypt(Encrypt(“secret”, publicKey), privateKey) = “secret”Decrypt(Encrypt(“secret”, privateKey), publicKey) = “secret”Decrypt(Encrypt(“secret”, publicKey), publicKey) = <garbage>Decrypt(Encrypt(“secret”, privateKey), privateKey) = <garbage>

Uses two mathematically related keys:When one key encrypts the data…Only other key can decrypt the data

Is slower than symmetric encryptionSeparation of keys facilitates better management and exchange of keysDecrypt(Encrypt(“secret”, publicKey), privateKey) = “secret”Decrypt(Encrypt(“secret”, privateKey), publicKey) = “secret”Decrypt(Encrypt(“secret”, publicKey), publicKey) = <garbage>Decrypt(Encrypt(“secret”, privateKey), privateKey) = <garbage>

The Untrustworthy CourierThe Untrustworthy Courier

You want to send a diamond to your friend

You have a lock and a keyYour friend has a lock and a key

You can only use an untrustworthy courier who will provide you a box into which you can place your diamond

Fact: if the box is not locked, the courier will run off with its contents!

How do you transfer the diamond?

You want to send a diamond to your friend

You have a lock and a keyYour friend has a lock and a key

You can only use an untrustworthy courier who will provide you a box into which you can place your diamond

Fact: if the box is not locked, the courier will run off with its contents!

How do you transfer the diamond?

The Untrustworthy Courier (cont.)The Untrustworthy Courier (cont.)

Sharing a Secret using Asymmetric EncryptionSharing a Secret using Asymmetric Encryption

Private Key Private/Public

Key Pair

Public Key

Encrypt(“secret”, PublicKey) = <EncryptedBlob>“secret”“secret”<EncryptedBlob>Decrypt(<EncryptedBlob>, PrivateKey) = “secret”

Symmetric Key Symmetric Key

Cryptographic Hash AlgorithmCryptographic Hash Algorithm

Uses no keys at allGenerates a fixed-size output (“hash value” or “message digest”)…and is therefore not reversibleThe hash values should also be collision-free

It should be (practically) impossible to discover another input that maps to the same output

Uses no keys at allGenerates a fixed-size output (“hash value” or “message digest”)…and is therefore not reversibleThe hash values should also be collision-free

It should be (practically) impossible to discover another input that maps to the same output

Areas of Security ConcernAreas of Security Concern

FundamentalFundamental00

AuthorizationAuthorization22

Asset HandlingAsset Handling33

Input IssuesInput Issues44

AuthenticationAuthentication11

Auditing & LoggingAuditing & Logging55

Authentication & AuthorizationAuthentication & Authorization

AuthenticationVerifies the identity of a principal“Who’s There?”

AuthorizationConfirms that an authenticated principal is allowed access to specific resources or carry out a specific action“What would you like?”

AuthenticationVerifies the identity of a principal“Who’s There?”

AuthorizationConfirms that an authenticated principal is allowed access to specific resources or carry out a specific action“What would you like?”

Authentication – Authentication MethodsAuthentication – Authentication Methods

BasicDigestIntegrated

Kerberos v5NTLM

Digital signatures and digital certificates Microsoft .NET PassportASP.NET Forms AuthenticationBiometricsSmart Cards

BasicDigestIntegrated

Kerberos v5NTLM

Digital signatures and digital certificates Microsoft .NET PassportASP.NET Forms AuthenticationBiometricsSmart Cards

Basic AuthenticationBasic Authentication

Is simple……and also insecure

Is supported by all majorbrowsers and serversIs easy to program andset upManages user credentials

Is simple……and also insecure

Is supported by all majorbrowsers and serversIs easy to program andset upManages user credentials

How Basic Authentication WorksHow Basic Authentication Works

Username and password encoded using Base64 encoding and sent to server

YWxpY2U6UGFzc3dvcmQxMjM= alice:Password123

Username and password encoded using Base64 encoding and sent to server

YWxpY2U6UGFzc3dvcmQxMjM= alice:Password123

GET /SomeBasicSite/ HTTP/1.0Accept: image/gif, image/jpeg, image/pjpeg, */*User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)Host: SomeBasicSiteIf-None-Match: "39d041a8ae3fc51:a28"Authorization: Basic YWxpY2U6UGFzc3dvcmQxMjM=Connection: Keep-Alive

Base64 EncodingBase64 Encoding

Encode a message of n bytesEncode a message of n bytes

Each block of 6 bits gets mapped to one of the possible 26 = 64 values from{A, B, …, Y, Z, a, b, …, y, z, 0, 1, …, 8, 9, +, /}

If n mod 3 = 2 then “=” is used to pad the encoded messageIf n mod 3 = 1 then “==” is used to pad the encoded message

Byte 3Byte 2Byte 1

Bit 1 - 6Bit 1 - 6 Bit 7 - 12Bit 7 - 12 Bit 13 - 18Bit 13 - 18 Bit 19 - 24Bit 19 - 24

How Digest Authentication WorksHow Digest Authentication Works

X$!87ghy5X$!87ghy5Password + noncePassword + nonceClient

Request

Server

Challenge (nonce)

Hash Algorithm

AccountStore

Password

X$!87ghy5X$!87ghy5

11

22

33

44

55

66

Password + noncePassword + nonce

If values match, the user is

authenticated

If values match, the user is

authenticated

Using Basic & Digest AuthenticationUsing Basic & Digest Authentication

Don’t useBasic Authentication!If using Digest, couple with asecure 128-bit SSL channelIf using with IIS (6.0):

Clients need IE 5.0 or laterUsers must have a validWindows user account storedin AD on the DC Requires “reversiblyencrypted” (clear text) password in AD

Don’t useBasic Authentication!If using Digest, couple with asecure 128-bit SSL channelIf using with IIS (6.0):

Clients need IE 5.0 or laterUsers must have a validWindows user account storedin AD on the DC Requires “reversiblyencrypted” (clear text) password in AD

Authentication – Kerberos v5Authentication – Kerberos v5

Initial LogonInitial Logon

Ticket-Granting Ticket TGT

KDC

Client

Service RequestService Request

KDC

Target Service

Client

Service Ticket ST

22

ST

33

ST

Session established

44TGT

cached locally

33

11

22

TGT

11

TGT

Why Kerberos v5 Works?Why Kerberos v5 Works?

Built around symmetric encryptionEvery service and identity on a domain has a unique key that is shared with the KDC (KDC has its own key that is not shared)

Uses the concept of “service tickets”“Service tickets” bind authentication of clients to a specific service (mutual authentication)

Assumptions:Since the target service can read the service ticket presented by a client, it could have only been created by the KDCThe KDC will only give out service tickets to those clients that have been authenticated

Built around symmetric encryptionEvery service and identity on a domain has a unique key that is shared with the KDC (KDC has its own key that is not shared)

Uses the concept of “service tickets”“Service tickets” bind authentication of clients to a specific service (mutual authentication)

Assumptions:Since the target service can read the service ticket presented by a client, it could have only been created by the KDCThe KDC will only give out service tickets to those clients that have been authenticated

Kerberos PKINITKerberos PKINIT

Extension to Kerberos that allows the use of public key cryptography for authenticationUse with Kerberos protocol

Instead of symmetric key that is derived from user’s password, the user supplies a public keyAllows for smartcard authentication implementation

Extension to Kerberos that allows the use of public key cryptography for authenticationUse with Kerberos protocol

Instead of symmetric key that is derived from user’s password, the user supplies a public keyAllows for smartcard authentication implementation

User BUser BUser AUser A

Data

Hash Value

Hash Algorithm

Data

Hash Value

Hash Value

Hash Algorithm

If hash values match, data is valid

If hash values match, data is valid

User A sends data and hash value to User B

User A sends data and hash value to User B

Verifying Data Integrity with HashesVerifying Data Integrity with Hashes

User BUser BUser AUser A

Data

Hash Value

Hash Algorithm

User A Private

Key

Data

Hash Value

User A Public

Key

Hash Algorithm

Hash Value

If hash values match, data came from the owner of

the private key and is valid

If hash values match, data came from the owner of

the private key and is valid

Digital SignaturesDigital Signatures

How Digital Certificates WorkHow Digital Certificates Work Private

Key Private/PublicKey Pair

User

Application

Computer

Service

Certified Administrator

Certification Authority

Public Key

Authentication – Client Digital CertificatesAuthentication – Client Digital Certificates

Used in Web applicationsServer secures communications using SSL/TLS with a X.509 server certificate

Server authenticates clients using data in client X.509 certificate, if required

Certificate authority issues a certificate for which the server holds a root certificate

Used in distributed applicationsApplication uses SSL/TLS communication channel

Client and server applications authenticate using certificates

Can be deployed on smart cards

Used in Web applicationsServer secures communications using SSL/TLS with a X.509 server certificate

Server authenticates clients using data in client X.509 certificate, if required

Certificate authority issues a certificate for which the server holds a root certificate

Used in distributed applicationsApplication uses SSL/TLS communication channel

Client and server applications authenticate using certificates

Can be deployed on smart cards

Authentication – What to use?Authentication – What to use?

Don’t re-invent the wheelUse Integrated Authentication (Kerberos, NTLM) if possibleUse digital certificates if feasibleIf implementing custom authentication

Keep logsImplement a lockout policyEnforce strong passwordsHandle account/password store appropriately

Don’t re-invent the wheelUse Integrated Authentication (Kerberos, NTLM) if possibleUse digital certificates if feasibleIf implementing custom authentication

Keep logsImplement a lockout policyEnforce strong passwordsHandle account/password store appropriately

Areas of Security ConcernAreas of Security Concern

FundamentalFundamental00

AuthorizationAuthorization22

Asset HandlingAsset Handling33

Input IssuesInput Issues44

AuthenticationAuthentication11

Auditing & LoggingAuditing & Logging55

Authorization ModelsAuthorization Models

Role BasedCustom (“Roll Your Own”)

Resource BasedTrusted Subsystem ModelImpersonation/Delegation Model

Role BasedCustom (“Roll Your Own”)

Resource BasedTrusted Subsystem ModelImpersonation/Delegation Model

Authorization – “Roll Your Own”Authorization – “Roll Your Own”

All client requests are serviced by one account / roleAll client requests are serviced by one account / role

Pros & Cons of “Roll Your Own” modelPros & Cons of “Roll Your Own” model

ProsComplete control / flexibleConnection pooling

ConsOne account has complete access to data - high risk from server compromiseAuditingAdministration challengesLots of code

ProsComplete control / flexibleConnection pooling

ConsOne account has complete access to data - high risk from server compromiseAuditingAdministration challengesLots of code

Trusted Subsystem ModelTrusted Subsystem Model

Can Use AD roles to create trust levelsCan maintain user-trust level relationship as part of applicationCan map users to different componentsCan map users to different SQL connection stringsCan use ASP.NET URL authorization

Can Use AD roles to create trust levelsCan maintain user-trust level relationship as part of applicationCan map users to different componentsCan map users to different SQL connection stringsCan use ASP.NET URL authorization

Implementing Trusted Subsystem ModelImplementing Trusted Subsystem Model

Web services running under different identitiesUsing different SQL connection strings

Will need to use SQL authentication

Use .NET serviced components

Web services running under different identitiesUsing different SQL connection strings

Will need to use SQL authentication

Use .NET serviced components

Pros & Cons of Trusted Subsystem ModelPros & Cons of Trusted Subsystem Model

ProsScalability (DB connection pooling)Single tier administrationLess code than “Roll Your Own”

ConsAuditingHigh risk from server compromise (depending on setup)

ProsScalability (DB connection pooling)Single tier administrationLess code than “Roll Your Own”

ConsAuditingHigh risk from server compromise (depending on setup)

Impersonation vs. DelegationImpersonation vs. Delegation

Impersonation is the ability of a thread to execute in a security context different from that of the process owning the thread

Alternate ID accesses local resources only

Delegation is the impersonation of clients over the network

Alternate ID accesses remote resources

Impersonation is the ability of a thread to execute in a security context different from that of the process owning the thread

Alternate ID accesses local resources only

Delegation is the impersonation of clients over the network

Alternate ID accesses remote resources

Constrained DelegationConstrained Delegation

Trusted for DelegationAssert the identity of any user across entire enterpriseDomain Controllers should be the only systems Trusted for Delegation

Constrained DelegationAssert the identity of:

Specific users…To specific machines…For specific services

A new extension in the implementation of the Kerberos protocol in Windows Server 2003 Allows a service to obtain service tickets (under the delegated users identity) to a subset of other services

To enable Constrained Delegation, contact your AD administrator

Trusted for DelegationAssert the identity of any user across entire enterpriseDomain Controllers should be the only systems Trusted for Delegation

Constrained DelegationAssert the identity of:

Specific users…To specific machines…For specific services

A new extension in the implementation of the Kerberos protocol in Windows Server 2003 Allows a service to obtain service tickets (under the delegated users identity) to a subset of other services

To enable Constrained Delegation, contact your AD administrator

Pros & Cons of Impersonation/Delegation Model

Pros & Cons of Impersonation/Delegation Model

ProsLess code!Precision logging

ConsAdministrative challengesHeavily technology dependent (e.g., Kerberos)Reduced scalability (no DB connection pooling)Users have direct access to all tiers (including data)

ProsLess code!Precision logging

ConsAdministrative challengesHeavily technology dependent (e.g., Kerberos)Reduced scalability (no DB connection pooling)Users have direct access to all tiers (including data)

Principle of Least PrivilegePrinciple of Least Privilege

Provide users the minimum set of privileges to get the job doneUse service accounts with minimum set of privilege on required resources needed for the taskIf privileges vary across your code, modularize your code and run under the required context for that module

Provide users the minimum set of privileges to get the job doneUse service accounts with minimum set of privilege on required resources needed for the taskIf privileges vary across your code, modularize your code and run under the required context for that module

Thick-client Authentication & AuthorizationThick-client Authentication & Authorization

Don’t trust the client!Server should do it’s own authenticationIf NTLM/Kerberos, can pass on authenticated identity token:

myWSProxy.Credentials =

System.Net.CredentialCache.DefaultCredentials;

Don’t let the client filter data based on authorization level it establishes for the user

Server should send only the data authorized for the authenticated user

Don’t trust the client!Server should do it’s own authenticationIf NTLM/Kerberos, can pass on authenticated identity token:

myWSProxy.Credentials =

System.Net.CredentialCache.DefaultCredentials;

Don’t let the client filter data based on authorization level it establishes for the user

Server should send only the data authorized for the authenticated user

Authorization – How to Model?Authorization – How to Model?

Utilize platform-supplied authorization facilities

Minimize the code

Authorize as close to the resource as possible

Client should not make authorization decisions

(Threat Model) Identify and implement a single gatekeeper for an asset that performs the authorization

Provides a more scalable solution

Lock down all tiers!E.g., thick client is locked, web service is locked but DB is wide open

Utilize platform-supplied authorization facilities

Minimize the code

Authorize as close to the resource as possible

Client should not make authorization decisions

(Threat Model) Identify and implement a single gatekeeper for an asset that performs the authorization

Provides a more scalable solution

Lock down all tiers!E.g., thick client is locked, web service is locked but DB is wide open

Areas of Security ConcernAreas of Security Concern

FundamentalFundamental00

AuthorizationAuthorization22

Asset HandlingAsset Handling33

Input IssuesInput Issues44

AuthenticationAuthentication11

Auditing & LoggingAuditing & Logging55

What is a Digital Asset?What is a Digital Asset?

Digital AssetInformation of value

Asset ClassificationAsset classification is determined by the value of the asset

Asset HandlingHandling procedure determined by the asset classification

Digital AssetInformation of value

Asset ClassificationAsset classification is determined by the value of the asset

Asset HandlingHandling procedure determined by the asset classification

Types of Digital AssetsTypes of Digital Assets

1. Application DataData your application maintainsE.g., credit card numbers, user profiles, finance data, etc.

2. Application ParametersEncryption keys, database connection strings, list of authorized users, etc.

3. SourceApplication binaries, scripts, libraries, etc.

1. Application DataData your application maintainsE.g., credit card numbers, user profiles, finance data, etc.

2. Application ParametersEncryption keys, database connection strings, list of authorized users, etc.

3. SourceApplication binaries, scripts, libraries, etc.

Asset HandlingAsset Handling

Asset handling is driven by policyExamples:

What kind of authentication is required for access to this asset (e.g., two-factor authentication)What kind of access control is required on this asset (e.g., FTE-Only)Does the asset need to be encrypted or not (e.g., needs to be transferred encrypted but can be stored in clear-text)

Asset handling is driven by policyExamples:

What kind of authentication is required for access to this asset (e.g., two-factor authentication)What kind of access control is required on this asset (e.g., FTE-Only)Does the asset need to be encrypted or not (e.g., needs to be transferred encrypted but can be stored in clear-text)

Asset Handling (cont.)Asset Handling (cont.)

In storageDatabasesFilesMemoryLogs

In transitTo and from users on internet/intranetBetween serversUsing email

In storageDatabasesFilesMemoryLogs

In transitTo and from users on internet/intranetBetween serversUsing email

Asset Handling – In Storage (At Rest)Asset Handling – In Storage (At Rest)

Don’t construct proprietary data storesUse existing technology (SQL Server 2000, Yukon)

Use enterprise software with enterprise-level security

Don’t use Access 2003 database

Lock down your data store!Don’t assume all access is through application interface

Consider protecting application data using EFS

Be aware of performance impact

Don’t construct proprietary data storesUse existing technology (SQL Server 2000, Yukon)

Use enterprise software with enterprise-level security

Don’t use Access 2003 database

Lock down your data store!Don’t assume all access is through application interface

Consider protecting application data using EFS

Be aware of performance impact

Cryptographic Hash AlgorithmCryptographic Hash Algorithm

If you don’t need to be able to decipher the data, use a one-way cryptographic hash algorithm

SHA256No keys to manage

If all you need to do is validate an identity’s knowledge…

A hash is all you need

If you don’t need to be able to decipher the data, use a one-way cryptographic hash algorithm

SHA256No keys to manage

If all you need to do is validate an identity’s knowledge…

A hash is all you need

Cryptographic Hash Algorithm (cont.)Cryptographic Hash Algorithm (cont.)

.NET Supported Asymmetric Algorithms

MD5 (produces 128-bit hash value)Collisions discovered!

SHA1 (produces 160-bit hash value)SHA256 (produces 256-bit hash value)SHA384 (produces 384-bit hash value)SHA512 (produces 512-bit hash value)

.NET Supported Asymmetric Algorithms

MD5 (produces 128-bit hash value)Collisions discovered!

SHA1 (produces 160-bit hash value)SHA256 (produces 256-bit hash value)SHA384 (produces 384-bit hash value)SHA512 (produces 512-bit hash value)

EncryptionEncryption

Never build your own algorithm!What kind of encryption to use?

Symmetric or Asymmetric

What algorithm to utilize?Everything is done for us… all we have to do is manage the Keys and IVs (application parameters)

Never build your own algorithm!What kind of encryption to use?

Symmetric or Asymmetric

What algorithm to utilize?Everything is done for us… all we have to do is manage the Keys and IVs (application parameters)

“Don’t leave your keys by the door”

Symmetric or Asymmetric AlgorithmsSymmetric or Asymmetric Algorithms

Symmetric AlgorithmsComputationally cheaperUsed to exchange or store information in secret

Asymmetric AlgorithmsComputationally more expensiveNormally used to negotiate a symmetric key

Both only require one key to be kept secret

Symmetric AlgorithmsComputationally cheaperUsed to exchange or store information in secret

Asymmetric AlgorithmsComputationally more expensiveNormally used to negotiate a symmetric key

Both only require one key to be kept secret

Symmetric or Asymmetric Algorithms (cont.)Symmetric or Asymmetric Algorithms (cont.)

.NET Supported Symmetric Algorithms

DES (64-bit key)RC2 (64-bit key)3DES (192-bit key)AES (Rijndael) (128-, 192-, or 256-bit key)

.NET Supported Asymmetric Algorithms

RSA (use 1024-bit key or up)DSA (use 1024-bit key)

.NET Supported Symmetric Algorithms

DES (64-bit key)RC2 (64-bit key)3DES (192-bit key)AES (Rijndael) (128-, 192-, or 256-bit key)

.NET Supported Asymmetric Algorithms

RSA (use 1024-bit key or up)DSA (use 1024-bit key)

Encryption – DPAPIEncryption – DPAPI

Data Protection APITwo DPAPI functions:

CryptProtectDataCryptUnprotectData

Two stores for data encrypted with DPAPI:

User storeMachine store

Data Protection APITwo DPAPI functions:

CryptProtectDataCryptUnprotectData

Two stores for data encrypted with DPAPI:

User storeMachine store

Encryption – Trustee & ASPNET_SETREGEncryption – Trustee & ASPNET_SETREG

Tools that utilize DPAPI to store secrets securely

Both tools use machine storeEncrypted secret is stored in the registry (which can be ACL’d)

Trustee can store arbitrary secretsASPNET_SETREG can only store certain specific configuration parameters (next slide)

Trustee can be used with classic ASPRequires .NET Framework

Tools that utilize DPAPI to store secrets securely

Both tools use machine storeEncrypted secret is stored in the registry (which can be ACL’d)

Trustee can store arbitrary secretsASPNET_SETREG can only store certain specific configuration parameters (next slide)

Trustee can be used with classic ASPRequires .NET Framework

ASPNET_SETREGASPNET_SETREG

Only the following configuration settings in ASP.NET 1.1 can be stored encrypted using ASPNET_SETREG:

ASP.NET worker process identity (<processModel>)Impersonation identity (<identity>)Connection string for session state (<sessionState>)

Example:c:\Tools>aspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"yourdomainname\

username" -p:"password"

<identity impersonate="true"userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,userName“password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

Only the following configuration settings in ASP.NET 1.1 can be stored encrypted using ASPNET_SETREG:

ASP.NET worker process identity (<processModel>)Impersonation identity (<identity>)Connection string for session state (<sessionState>)

Example:c:\Tools>aspnet_setreg.exe -k:SOFTWARE\MY_SECURE_APP\identity -u:"yourdomainname\

username" -p:"password"

<identity impersonate="true"userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,userName“password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

Storing Data SecurelyStoring Data Securely

Consider protecting application data using EFSSpecific data elements can be encrypted using a symmetric cipher

Credit card numbersSocial security numbersEtc.

Consider protecting application data using EFSSpecific data elements can be encrypted using a symmetric cipher

Credit card numbersSocial security numbersEtc.

Securing Application ParametersSecuring Application Parameters

Don’t hardcode application parameters inside the application in clear text – this includes web.config

SQL connection strings that use SQL authentication credentialsEncryption keysPasswords

Use TrusteeUse ASPNET_SETREG

Don’t hardcode application parameters inside the application in clear text – this includes web.config

SQL connection strings that use SQL authentication credentialsEncryption keysPasswords

Use TrusteeUse ASPNET_SETREG

Securing SourceSecuring Source

Use appropriate ACLsRemove unnecessary accounts (e.g., Guest)

Remove sharesConsider protecting source code using EFS

Use appropriate ACLsRemove unnecessary accounts (e.g., Guest)

Remove sharesConsider protecting source code using EFS

Asset Handling – In TransitAsset Handling – In Transit

SSLEnforce 128-bit SSLDon’t redirect to SSL

IPSec w/ encryptionWeb Service Security (WSE) encryptionS/MIME

SSLEnforce 128-bit SSLDon’t redirect to SSL

IPSec w/ encryptionWeb Service Security (WSE) encryptionS/MIME

Sending Sensitive Information in EmailsSending Sensitive Information in Emails

Don’t! Provide info through a secure website (for example) insteadIf absolutely necessary…

Evaluate the value of the information being sent or (in case of credentials) the value of the asset being protected by that informationUse S/MIME

Don’t! Provide info through a secure website (for example) insteadIf absolutely necessary…

Evaluate the value of the information being sent or (in case of credentials) the value of the asset being protected by that informationUse S/MIME

Areas of Security ConcernAreas of Security Concern

FundamentalFundamental00

AuthorizationAuthorization22

Asset HandlingAsset Handling33

Input IssuesInput Issues44

AuthenticationAuthentication11

Auditing & LoggingAuditing & Logging55

There are Two Major Kinds of Security DefectsThere are Two Major Kinds of Security Defects1. Input trust issues2. Everything else1. Input trust issues2. Everything else

Consequences of Input IssuesConsequences of Input Issues

Lead to a realization of various attack patterns

Buffer overflow or arithmetic errors (Memory Management issues)Cross-Site Scripting (XSS)SQL Injection One-Click AttacksCanonicalization issuesDenial of Service

Lead to a realization of various attack patterns

Buffer overflow or arithmetic errors (Memory Management issues)Cross-Site Scripting (XSS)SQL Injection One-Click AttacksCanonicalization issuesDenial of Service

Anyone still writing code with direct memory access?

Anyone still writing code with direct memory access?

error_status_t _RemoteActivation(WCHAR *pwszObjectName, ... ) { *phr = GetServerPath( pwszObjectName, &pwszObjectName); ...}

HRESULT GetServerPath(WCHAR *pwszPath, WCHAR **pwszServerPath ){ WCHAR * pwszFinalPath = pwszPath; WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN + 1]; hr = GetMachineName(pwszPath, wszMachineName); *pwszServerPath = pwszFinalPath;

}

HRESULT GetMachineName( WCHAR * pwszPath, WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN + 1]) { pwszServerName = wszMachineName; LPWSTR pwszTemp = pwszPath + 2; while ( *pwszTemp != L'\\' ) *pwszServerName++ = *pwszTemp++;

What’s Wrong with this Code?What’s Wrong with this Code? Port 135 (i.e. The Internet)Port 135 (i.e. The Internet)

The “Core Error” is copying untrusted data…data that is constrained by the source data, rather than the destination size!

What are Buffer Overruns?What are Buffer Overruns?

External data is larger than the destinationOverflowing the destination tramples some sensitive in-memory construct that determines execution flow

Causing the application to change execution flowTo the attacker’s code included in the data

C/C++ code the most common victimDirect access to memory

Cause: trusting input

External data is larger than the destinationOverflowing the destination tramples some sensitive in-memory construct that determines execution flow

Causing the application to change execution flowTo the attacker’s code included in the data

C/C++ code the most common victimDirect access to memory

Cause: trusting input

ExampleExample

void CopyStuff(string data) {char buffer[128];strcpy(buffer,data);

// do other stuff}

If this data is larger than this buffer

Then this functionwill overflow the buffer

How common are BOs?How common are BOs?

Source: Vendor Web SitesTimeframe: 01Jan2003 – 01Oct2003

30

55

100

172

1118

27

62

0

20

40

60

80

100

120

140

160

180

200

Microsoft Sun RedHat Debian

Bulletins (2003) Buffer Overruns

Why are they prevalent?Why are they prevalent?

Lots of C/C++ code out thereLots of legacy C/C++ code that’s now hookedto the internetMany data structures jump to code

Stack addresses, function pointers, exception handlers, C++ class v-tables etc.

Constantly evolving threatsFirst there were stack overrunsThen heap overrunsThen format string overrunsThen “one-byte overruns”Now, integer overflowsWhat’s next?

Developers don’t check the input data!

Lots of C/C++ code out thereLots of legacy C/C++ code that’s now hookedto the internetMany data structures jump to code

Stack addresses, function pointers, exception handlers, C++ class v-tables etc.

Constantly evolving threatsFirst there were stack overrunsThen heap overrunsThen format string overrunsThen “one-byte overruns”Now, integer overflowsWhat’s next?

Developers don’t check the input data!

Integer Arithmetic Vulns Integer Arithmetic Vulns

int ConcatString(char *buf1, char *buf2,

size_t len1, size_t len2){

char buf[256];

if((len1 + len2) > 256) return -1;

memcpy(buf, buf1, len1);

memcpy(buf + len1, buf2, len2);

What if: len1 == 0xFFFFFFFElen2 == 0x00000102

0xFFFFFFFE + 0x00000102 == 0x100

.NET Memory Security Concerns.NET Memory Security Concerns

Buffer overflows can only occur in unmanaged codeBe aware of the limitations of your chosen data typesInteger overflows / underflows can still occur unless safeguards are enabled:

CheckForOverflowUnderflow (C#)RemoveIntegerChecks (VB.NET)

Use the checked & unchecked keyword (C#)

Buffer overflows can only occur in unmanaged codeBe aware of the limitations of your chosen data typesInteger overflows / underflows can still occur unless safeguards are enabled:

CheckForOverflowUnderflow (C#)RemoveIntegerChecks (VB.NET)

Use the checked & unchecked keyword (C#)

What is Cross-Site Scripting?What is Cross-Site Scripting?

A technique that allows attackers to:Appear to rewrite the text of your web siteAbuse the user’s trust in your website to…

Steal Web session information and cookiesHijack client sessionsPotentially access the client computer

A technique that allows attackers to:Appear to rewrite the text of your web siteAbuse the user’s trust in your website to…

Steal Web session information and cookiesHijack client sessionsPotentially access the client computer

XSS Attack PatternsXSS Attack Patterns

XSS attacks can be classified in 2 categories:

PersistentGenerally affects web-based applications (e.g., message forums) which persist user-supplied data for later display

• Non-PersistentGenerally affects web-based applications which echo data back to the client who supplied it

XSS attacks can be classified in 2 categories:

PersistentGenerally affects web-based applications (e.g., message forums) which persist user-supplied data for later display

• Non-PersistentGenerally affects web-based applications which echo data back to the client who supplied it

The XSS Attacker’s Quick ReferenceThe XSS Attacker’s Quick Reference1. <script>[code]</script>

2. <script src=[link to code]></script> 3. <div style=width:

expression([code]);>4. <style>@import "javascript:

[code];";</style> 5. <img src=javascript:[code]> 6. <img src="my.jpg"

onmouseover=[code]> 7. <body onload=[code]> 8. <meta http-equiv="refresh"

content="0;url=javascript:[code]"> 9. <a href=javas&#99;ript&#35; [code]> 10.<form action=javascript:[code]>

1. <script>[code]</script> 2. <script src=[link to code]></script> 3. <div style=width:

expression([code]);>4. <style>@import "javascript:

[code];";</style> 5. <img src=javascript:[code]> 6. <img src="my.jpg"

onmouseover=[code]> 7. <body onload=[code]> 8. <meta http-equiv="refresh"

content="0;url=javascript:[code]"> 9. <a href=javas&#99;ript&#35; [code]> 10.<form action=javascript:[code]>

Defending Against Cross-Site Scripting AttacksDefending Against Cross-Site Scripting Attacks

Do not:Trust user inputEcho client-supplied data without encodingStore secret information in cookies

Do:Take advantage of ASP.NET’s RequestValidationTake advantage of ASP.NET’s ViewStateUserKeyConsider IOSec for data encodingUse the HttpOnly cookie optionUse the <frame> security attribute

Do not:Trust user inputEcho client-supplied data without encodingStore secret information in cookies

Do:Take advantage of ASP.NET’s RequestValidationTake advantage of ASP.NET’s ViewStateUserKeyConsider IOSec for data encodingUse the HttpOnly cookie optionUse the <frame> security attribute

Defending Against XSS (cont.)Defending Against XSS (cont.)

Input validationFirst line of defense – can eliminate many possible vulnerabilities, but doesn’t necessarily eliminate all of them

Output encodingBy encoding user-supplied data at display time, we can ensure that the client browser will interpret it literally

Platform featuresRequestValidation propertyViewStateUserKey property

Input validationFirst line of defense – can eliminate many possible vulnerabilities, but doesn’t necessarily eliminate all of them

Output encodingBy encoding user-supplied data at display time, we can ensure that the client browser will interpret it literally

Platform featuresRequestValidation propertyViewStateUserKey property

Defending Against XSS (cont.)Defending Against XSS (cont.)

Server.HtmlEncode() doesn’t always protect your app…

It only encodes < > & “

Use IOSec (properly implemented)EncodeHtml()EncodeHtmlAttribute()EncodeVbs()AsUrl()

Server.HtmlEncode() doesn’t always protect your app…

It only encodes < > & “

Use IOSec (properly implemented)EncodeHtml()EncodeHtmlAttribute()EncodeVbs()AsUrl()

What is SQL Injection?What is SQL Injection?

SQL injection is:The process supplying carefully crafted input to alter (or create) SQL statementsCan be used by malicious users to compromise confidentiality, integrity or availability of your application:

Probe databasesBypass authorizationExecute multiple SQL statementsCall built-in stored procedures

SQL injection is:The process supplying carefully crafted input to alter (or create) SQL statementsCan be used by malicious users to compromise confidentiality, integrity or availability of your application:

Probe databasesBypass authorizationExecute multiple SQL statementsCall built-in stored procedures

Examples of SQL InjectionExamples of SQL Injection

sqlString = "SELECT HasShipped FROM"+ " OrderDetail WHERE OrderID ='"+ ID + "'";

sqlString = "SELECT HasShipped FROM"+ " OrderDetail WHERE OrderID ='"+ ID + "'";

If the ID variable is read directly from a Web form or Windows form textbox, the user could enter any of the following:

ALFKI1001ALFKI1001' or 1=1 --ALFKI1001'; DROP TABLE OrderDetail --ALFKI1001'; exec xp_cmdshell('fdisk.exe') --

If the ID variable is read directly from a Web form or Windows form textbox, the user could enter any of the following:

ALFKI1001ALFKI1001' or 1=1 --ALFKI1001'; DROP TABLE OrderDetail --ALFKI1001'; exec xp_cmdshell('fdisk.exe') --

Defending Against SQL InjectionDefending Against SQL Injection

Abandon Dynamic SQLUse stored procedures or SQL parameterized queries to access data

Can have SQL Injection in stored procedures

Sanitize all inputConsider all input harmful until proven otherwise – test for valid data and reject everything else

Run with least privilegeNever execute as “sa”

Restrict access to built-in stored procedures

Do not display ODBC errors

Abandon Dynamic SQLUse stored procedures or SQL parameterized queries to access data

Can have SQL Injection in stored procedures

Sanitize all inputConsider all input harmful until proven otherwise – test for valid data and reject everything else

Run with least privilegeNever execute as “sa”

Restrict access to built-in stored procedures

Do not display ODBC errors

What is One-Click Attack?What is One-Click Attack?Site offers persistent sign-in option (cookies)Victim user navigates to (or opens) an HTML page – perhaps a “once in a lifetime offer”One or more actions are carried out using the trust of the victim user which is completely unsuspecting to that user

Site offers persistent sign-in option (cookies)Victim user navigates to (or opens) an HTML page – perhaps a “once in a lifetime offer”One or more actions are carried out using the trust of the victim user which is completely unsuspecting to that user

Defending Against One-Click AttackDefending Against One-Click Attack

Browser’s cross-frame security limits this to a “write-only” attackConcept for defense: require a data element in the request which the attacker can’t supply

(Overkill) Re-authenticate the userCan ask for confirmation

Check Referrer fielddocument.location or window.open() don’t post Referrer

Browser’s cross-frame security limits this to a “write-only” attackConcept for defense: require a data element in the request which the attacker can’t supply

(Overkill) Re-authenticate the userCan ask for confirmation

Check Referrer fielddocument.location or window.open() don’t post Referrer

Defending Against One-Click Attack (cont.)Defending Against One-Click Attack (cont.)

Classic ASPGenerate a unique session ID once user authenticates, encrypt it and bind it to each response sent to user

In .Net 1.1 use ViewStateUserKeyValue assigned to it must be unique to the current user This value is used as a factor in the ViewState MAC

Classic ASPGenerate a unique session ID once user authenticates, encrypt it and bind it to each response sent to user

In .Net 1.1 use ViewStateUserKeyValue assigned to it must be unique to the current user This value is used as a factor in the ViewState MAC

override protected void OnInit(EventArgs e){// ...

ViewStateUserKey = User.Identity.Name;// ...}

override protected void OnInit(EventArgs e){// ...

ViewStateUserKey = User.Identity.Name;// ...}

Denial of ServiceDenial of Service

Most commonly associated with Net attacks, but not necessarily so. DoS just means attacking something (application, computer, web farm, etc) by trying to starve it of necessary resources (CPU cycles, network bandwidth, storage capacity, etc)“Script Kiddies” have made these infamousAt one time, more well-publicized than viruses on the news

Most commonly associated with Net attacks, but not necessarily so. DoS just means attacking something (application, computer, web farm, etc) by trying to starve it of necessary resources (CPU cycles, network bandwidth, storage capacity, etc)“Script Kiddies” have made these infamousAt one time, more well-publicized than viruses on the news

Some DoS ExamplesSome DoS Examples

“The Ping of Death” caused many failures in UNIX boxesCPU Starvation Tactics – Make your program do expensive computations many, many times, such as stripping out a backslash from inputMemory Starvation – Use up all of system memory, since many programmers assume that memory allocs will succeedNetwork bandwidth attacks

“The Ping of Death” caused many failures in UNIX boxesCPU Starvation Tactics – Make your program do expensive computations many, many times, such as stripping out a backslash from inputMemory Starvation – Use up all of system memory, since many programmers assume that memory allocs will succeedNetwork bandwidth attacks

The DoS “Arms Race”The DoS “Arms Race”

Many vulnerabilities are just like an Arms Race, where small, incremental improvements make past defenses obsolete & thus both sides keep competingExample:

Hacker: 1 computer making 100s of requests to a websiteDefense: Ignore that IPHacker: Get driver-level permissions and fake new IP addresses, or get a “zombie army”Defense: Catch “similarly formed” requests

Many vulnerabilities are just like an Arms Race, where small, incremental improvements make past defenses obsolete & thus both sides keep competingExample:

Hacker: 1 computer making 100s of requests to a websiteDefense: Ignore that IPHacker: Get driver-level permissions and fake new IP addresses, or get a “zombie army”Defense: Catch “similarly formed” requests

Defending Against Denial of Service AttacksDefending Against Denial of Service Attacks

Consider security as a design featureDistrust user inputFail intelligentlyTest securityIf accepting file uploads, limit the size of the file

Consider security as a design featureDistrust user inputFail intelligentlyTest securityIf accepting file uploads, limit the size of the file

Canonical RepresentationCanonical Representation

What the !@*%# does “canonical” mean? “In its simplest or standard form” (Random House Webster’s College Dictionary)One of the most irritating causes of hacks on the web, due to the “head slapping effect” of how easy they would have been to protect against

What the !@*%# does “canonical” mean? “In its simplest or standard form” (Random House Webster’s College Dictionary)One of the most irritating causes of hacks on the web, due to the “head slapping effect” of how easy they would have been to protect against

Canonicalization Issues – Example 1: File NamesCanonicalization Issues – Example 1: File Names

1 MyLongFile.txt

2 MyLongFile.txt.

3 MyLong~1.txt

4 MyLongFile.txt::$DATA

http://www.microsoft.com/technet/securityhttp://www.microsoft.com/technet/security

Is the same as -

http://www%2emicrosoft%2ecom%2ftechnet%2fsecurity

http://www.microsoft.com%c0%aftechnet%c0%afsecurity

http://www%25%32%65microsoft.com/technet/security

http://172.43.122.12 = http://2888530444

http://www%2emicrosoft%2ecom%2ftechnet%2fsecurity

http://www.microsoft.com%c0%aftechnet%c0%afsecurity

http://www%25%32%65microsoft.com/technet/security

http://172.43.122.12 = http://2888530444

Canonicalization Issues – Example 2: Character Representation

Canonicalization Issues – Example 2: Character Representation

There are many ways to represent characters on the InternetThere are many ways to represent characters on the Internet

Examples of Canonical ExploitsExamples of Canonical Exploits

AOL Parental Controls – Add a period to the end of the hostname, and it’s “pr0n” time for little Junior! Failure Cause: Their string compare with the host name didn’t succeed with the period, but the browser then removed it b/c it realized it was invalidIIS 4.0 Vulnerability – Active Server Pages were not processed if you appended ::$DATA onto the end of the page name. Failure Cause: IIS’ ASP switch doesn’t recognize the input type, it defaults back to NTFS, which then sends the page out raw

AOL Parental Controls – Add a period to the end of the hostname, and it’s “pr0n” time for little Junior! Failure Cause: Their string compare with the host name didn’t succeed with the period, but the browser then removed it b/c it realized it was invalidIIS 4.0 Vulnerability – Active Server Pages were not processed if you appended ::$DATA onto the end of the page name. Failure Cause: IIS’ ASP switch doesn’t recognize the input type, it defaults back to NTFS, which then sends the page out raw

Common Canonical MistakesCommon Canonical Mistakes

8.3 versus Long filename resolution: “My Secure File.doc” is protected, but “MySec~1.doc” is notNTFS Data StreamsTrailing characters – The extra dot or slash throws off the check, but doesn’t invalidate the requestAbsolute versus Relative pathsCase-Insensitive Filenames

8.3 versus Long filename resolution: “My Secure File.doc” is protected, but “MySec~1.doc” is notNTFS Data StreamsTrailing characters – The extra dot or slash throws off the check, but doesn’t invalidate the requestAbsolute versus Relative pathsCase-Insensitive Filenames

Defending Against Canonicalization IssuesDefending Against Canonicalization Issues

Disable the IIS Parent Paths settingAlways supply your own file path from a fixed valueUse Path.GetFileName() to get a safe filename

When handling uploads, consider assigning a filename of your choice instead of the user’s choice.

Disable the IIS Parent Paths settingAlways supply your own file path from a fixed valueUse Path.GetFileName() to get a safe filename

When handling uploads, consider assigning a filename of your choice instead of the user’s choice.

CryptographyCryptography

Random Numbers are not random!Hackers look for use of random number generators that are “linear congruential functions”, which means that while they generate evenly distributed numbers AND they have a long and complete cycle, they DO NOT produce unpredictable resultsExample: Netscape Navigator used a similar function in generating SSL keys, and attackers were able to easily bypass the security b/c they could guess the keys

Random Numbers are not random!Hackers look for use of random number generators that are “linear congruential functions”, which means that while they generate evenly distributed numbers AND they have a long and complete cycle, they DO NOT produce unpredictable resultsExample: Netscape Navigator used a similar function in generating SSL keys, and attackers were able to easily bypass the security b/c they could guess the keys

The “Arms Race” for RNGsThe “Arms Race” for RNGs

Developers started using “random” keys, but many of these were too easily predictable (most of them using the “time” function)Now, “true(r)” rng’s exist, such as CryptGenRandomDoes the seed work for you, and uses stuff that is hard to guess, i.e. current process ID, current thread ID, ticks since boot, current time, performance counters, hash of the user environment block, & lower-level system info (idle time, kernel time, page read count, interrupt times, etc.)

Developers started using “random” keys, but many of these were too easily predictable (most of them using the “time” function)Now, “true(r)” rng’s exist, such as CryptGenRandomDoes the seed work for you, and uses stuff that is hard to guess, i.e. current process ID, current thread ID, ticks since boot, current time, performance counters, hash of the user environment block, & lower-level system info (idle time, kernel time, page read count, interrupt times, etc.)

Areas of Security ConcernAreas of Security Concern

FundamentalFundamental00

AuthorizationAuthorization22

Asset HandlingAsset Handling33

Input IssuesInput Issues44

AuthenticationAuthentication11

Auditing & LoggingAuditing & Logging55

LoggingLogging

Application Security is more then setting up perimeter defenseKeep a log trail of authentication attempts

Both successful and failed

Keep a log trail of all accesses to assetsLog as close to an asset as possible

SQL Server Stored Procedure

Sometimes… a log trail is the only mitigationIdentify “who, what, where & when”…

Application Security is more then setting up perimeter defenseKeep a log trail of authentication attempts

Both successful and failed

Keep a log trail of all accesses to assetsLog as close to an asset as possible

SQL Server Stored Procedure

Sometimes… a log trail is the only mitigationIdentify “who, what, where & when”…

What you LogWhat you Log

“Fire and Forget” – Asynchronous logging

MSMQ

Don’t write sensitive information in logs

Passwords

Identify the (“who, what, where & when”):

IdentityActionComponent/Service/Object/MethodTimestamp

“Fire and Forget” – Asynchronous logging

MSMQ

Don’t write sensitive information in logs

Passwords

Identify the (“who, what, where & when”):

IdentityActionComponent/Service/Object/MethodTimestamp

How to LogHow to Log

Microsoft Enterprise Instrumentation Framework (EIF)

‘HealthMonitoring’ in .Net 2.0

Design GuidelinesApp should have write access to a local queueRemote service (with read access) should consume elements in queue and persist in log store

Microsoft Enterprise Instrumentation Framework (EIF)

‘HealthMonitoring’ in .Net 2.0

Design GuidelinesApp should have write access to a local queueRemote service (with read access) should consume elements in queue and persist in log store

AuditAudit

Logs identify the “who, what, where & when”Audit the logs to determine “why”Setup a process whereby logs are auditedMonitor & Response Process

Can be automated to some extent

Log files are an asset!

Logs identify the “who, what, where & when”Audit the logs to determine “why”Setup a process whereby logs are auditedMonitor & Response Process

Can be automated to some extent

Log files are an asset!

Wrapping Up

A Best DefenseA Best Defense

Establish a security processConsider security as a product featureReduce your attack surface

Turn the feature offRun with lower privilege

Assume external systems are insecurePlan on failureNever depend on security through obscurity

Establish a security processConsider security as a product featureReduce your attack surface

Turn the feature offRun with lower privilege

Assume external systems are insecurePlan on failureNever depend on security through obscurity

Least Privileges!!!Least Privileges!!!

Windows machines commonly run everything as “Administrator” privileges, which can cause problems b/c users have access to EVERYTHING (formatting drives, accessing any data on the system, changing profiles or configurations, etc.)Applications take this for granted and assume Admin access where none is needed (or can be worked around)Design programs to run with the least amount of privileges possible, and encourage your users to do exactly that!

Windows machines commonly run everything as “Administrator” privileges, which can cause problems b/c users have access to EVERYTHING (formatting drives, accessing any data on the system, changing profiles or configurations, etc.)Applications take this for granted and assume Admin access where none is needed (or can be worked around)Design programs to run with the least amount of privileges possible, and encourage your users to do exactly that!

The Software Security Pendulum - Where we were

The Software Security Pendulum - Where we were

Easy to useLarge attack surface‘Automagic’Internet TimeThings (and attacks) ‘just work’ (OOBE)

Easy to useLarge attack surface‘Automagic’Internet TimeThings (and attacks) ‘just work’ (OOBE)

Usability Usability & &

FeaturesFeatures

Security Security & &

PrivacyPrivacy

The Software Security Pendulum - Where we areThe Software Security Pendulum - Where we are

Reduced attack surfaceOften harder to use“Knee Jerk” securitySlower to marketMany security prompts

Reduced attack surfaceOften harder to use“Knee Jerk” securitySlower to marketMany security prompts

Usability Usability & &

FeaturesFeatures

Security Security & &

PrivacyPrivacy

The Software Security Pendulum - Where we should be

The Software Security Pendulum - Where we should be

Small attack surfaceSecurity & privacy a first-class featureFew security prompts

Transparent where possibleConfigurable where necessary

Securely usable!

Small attack surfaceSecurity & privacy a first-class featureFew security prompts

Transparent where possibleConfigurable where necessary

Securely usable!

Usability Usability & &

FeaturesFeatures

Security Security & &

PrivacyPrivacy

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