Top Ten Tips for Tenacious Defense in ASP.NET Alex Smolen Senior Consultant SoCal Code Camp , 2008
1. Cross-Site Request Forgery
CSRF Attacker entices victim to view an HTML page containing a malicious image tag (hosted by an “accomplice”) Victim unknowingly submits a request to a server of the attacker’s choosing - using the victim’s credentials Effects can vary Log the user out Execute a transaction Post a message Modify settings on an intranet device with a web interface
CSRF - Examples <!--Buy shares of Microsoft in the background-->   < img   src = &quot;http://stocks.com/buy.aspx?sym=MSFT&shares=500&quot;> <!--Open up a firewall port-->   < img  src =&quot;http://firewall/openPort?portNumber=5344&quot;>
CSRF - Defense The root cause is “Ambient Authority” Cookies, NTLM Creds, HTTP Auth automatically sent by browser Site needs to provide another form of secret that attacker can’t guess
CSRF Defense Referer ViewStateUserKey Secret token CAPTCHA Password Re-authentication
CSRF Defense - Referer Check the HTTP referer to make sure that the user just came from the right page Misspelling intentional Referer isn’t always sent Privacy settings Difficult to tell who referer will be Can be faked with vulnerable versions of Flash
CSRF Defense - ViewStateUserKey ViewStateUserKey is combined with ViewState ViewStateMac check will fail if ViewStateUserKey is different Can be used to ensure that ViewState is unique between users Set the value to session ID
CSRF Defense – ViewStateUserKey There are problems with this solution Have blogged about this What if ViewStateMac isn’t enabled? The action isn’t a postback? You don’t want to use ViewState at all?
CSRF Defense -  Secret Token This is a more flexible approach The form (or URL, potentially) contains a secret token that is required Could be the same or based on session ID Page checks for this token as well as session ID in cookie Ambient authority is superseded
CSRF Defense – Secret Token Both CSRFGuard from OWASP and AntiCsrf from Barry Dorrans use this approach http://www.owasp.org/index.php/CSRF_Guard http://www.codeplex.com/AntiCSRF/ Need to watch GET versus POST Idempotency and verb agnositicty, oh my!
CSRF Defense - CAPTCHA CAPTCHA theoretically requires a human to solve Bleh… They work, but aren’t very user-friendly CSRF is possible for a lot of actions Maybe if it’s Asirra… http://research.microsoft.com/en-us/um/redmond/projects/asirra/
CSRF Defense – Password Re-authentication Simply require users to re-authenticate to perform an action The most secure, hopefully Can be done for BIG DEAL transactions, like cashing out an account or changing password (this is usually done anyways) Example: Amazon Shopping Cart
2. Session Fixation
Session Fixation Let’s say… You visit a web site You enter your username and password You continue browsing to other pages The web site continues to knows who you are How?
Session Fixation Sessions! An identifier is passed with each request (usually in a cookie) I can steal your session if I know your session identifier Session identifiers are like a temporary password
Session Fixation Session fixation occurs when I force you to use a known session identifier Shared terminal At a library, hotel, etc I visit a site, note the session ID, wait for someone else to login Click a link http://site.com/index.aspx?ASPSESSIONID=hack If you click on my link, I know your session ID
Session Fixation Defense To defend against this, regenerate the session ID after login You probably don’t do this There’s no good way to regenerate the session ID in ASP.NET If you use Forms authentication, you’re OK…sorta FormsAuthenticationTicket is used in addition to cookie and can’t be preset However I may be able to access your information with my FormsAuthenticationTicket and your session identifier
Session Fixation - Defense You could do something like this: Gross   Use an extra authentication cookie if you don’t use Forms Authentication Make sure all requests to a session are from the right authentication user according to the authentication cookie
3. Real World Crypto
Real-World Crypto cryptography:security::concurrency:programming Truly understood by few, screwed up by almost everyone People like cryptography because it is a  security feature A lot of times, they don’t know what it does Magic fairy dust
 
Read-World Crypto People will use hash functions, random numbers, encryption algorithms, for all sorts of reasons There building blocks, are there are very specific purposes for each of them!
Real-World Crypto Random Data Properties: Difficult to guess Uses: Generated passwords or links, session identifiers, cryptographic keys How people mess this up: Use System.Random() Not good enough! Use a predictable seed Don’t use enough bits
 
Real-World Crypto Hashing Properties: One-way Uses: Verify knowledge of something (e.g. passwords), verify integrity of something How people mess this up: Use hash for authentication Verify this hacked file download with this hacked file hash! Use hash for something else (random data) Use insecure algorithm (not really an issue for most scenarios, but easy enough to fix)
 
Real-World Crypto Symmetric cryptography Properties: Keeps a big secret with a smaller secret Uses: Keep sensitive data confidential How people mess this up: The key has to be a secret Don’t lose the key Use the DPAPI! Key management for free! You can build your own as well, just be careful
 
Real-World Crypto That’s it! Not really, cryptography is really complicated If you’re doing anything with certificates, SSL, digital signatures, WS-Security, get a book
 
4. The AntiXss Library
The AntiXSS Library XSS is an issue Has been for a while Really hard to stop The problem is the browser Also, we end up putting user-modifiable data in weird places, such as ASP.NET doesn’t help us too much
Control Behavior Literal None by default. HTML Encoded if Mode property is set to  LiteralMode.Encode Label None TextBox Single-line text box is not encoded. Multiline text box is HTML encoded Button Text is attribute encoded LinkButton None Hyperlink Text is not encoded.  NavigateUrl  is URL path encoded, unless it is JavaScript, in which case it is attribute encoded DropDownList  and  ListBox Option values are attribute encoded.  Option display texts are HTML encoded. CheckBox  and  CheckBoxList Value is not used.  Display text is not encoded. RadioButton  and  RadioButtonList Value is attribute encoded. Display text is not encoded. GridView  and  DetailsView Text fields are HTML encoded if their  HtmlEncode  property is set to true. Null display text is never encoded.
The Anti-XSS Library Data needs to be encoded Fully With the right context User data could be output to… HTML HTML attribute JavaScript XML Etc…
Method Description HtmlEncode More robust version of the  HttpUtility.HtmlEncode  method. HtmlAttributeEncode Encoding for dynamically created HTML attributes (i.e src=“”) XmlEncode/ XmlAttributeEncode Encoding for XML elements and attributes UrlEncode Encoding for dynamically constructed URLs JavaScriptEncode/ VisualBasicEncode Encoding for dynamically generated JavaScript or VBScript
5. Stop Injection!
Stop Injection! Injection occurs when: We treat data as code? We fail to properly validate input? We fail to properly encode output? Like, all the time? Yes
Stop Injection! How do we stop  SQL injection Command injection Path manipulation XML injection LDAP injection Who-knows-what-else
 
Stop Injection! Two things we can do: Validate Make sure all request data looks the way it’s supposed to Uh, that’s all data (cookies, headers, hidden fields) Encode Make sure all data is properly encoded for it’s destination SqlCommand with SqlParameters does this for SQL Otherwise, you are on your own
 
6. Authorization Woes
Authorization Woes Who is allowed to do what? Well, we don’t know… Draw an authorization matrix! Think about horizontal and vertical privilege escalation! I’m serious!
Authorization Woes Orders Products /admin … Customers View View No … Managers View, Modify View, Modify, Add No … Administrators View, Modify, Add, Delete View, Modify, Add, Delete Yes … … … ... ... …
Authorization Woes Role-based access control works well here Group users by role Some users will need additional privileges Can use finer-grained model Some authorization concerns rely on state “ After 5PM, traders cannot place orders greater than the sum of the previous weeks total, minus exemptions…” This becomes business logic
Authorization Woes User logs in, clicks on “My Account” URL http://www.bank.com/accouts.aspx?id=123-456-7890 What if I got my neighbors statement by mistake? http://www.bank.com/accouts.aspx?id=-098-765-4321 I shouldn’t be seeing their statement Horizontal privilege escalation
7. Mind Your Cookies!
Mind Your Cookies Don’t use cookies! Let ASP.NET do the session stuff for you What else could you possibly need to use cookies for? OK, OK, so maybe you can use them sometimes Don’t base security decisions off the data!
Mind Your Cookies There are two tags that can be added to the set-cookie response header Secure Do not transmit this cookie over non-SSL connections HttpOnly Do not allow JavaScript to access this cooke
Mind Your Cookies Domain Think about what sub-domains need access Path You can limit what parts of your application cookies are sent to Expiration Don’t go crazy
Mind Your Cookies URL Rewriting Pass the session ID as a URL argument http://site.com/a.aspx? sessionid=123123123 Bad idea Ends up in history, bookmarks, links sent to friends Originally for users with cookies disabled Probably a small enough minority to ignore
Session State in ASP.NET <httpCookies httpOnlyCookies=&quot; true &quot;>  Mark all container issued cookies as HttpOnly <sessionState cookieless=&quot; UseCookies &quot;>  Prevent URL rewriting <forms requireSSL=&quot; true &quot;> Marks Forms Authentication as secure
8. Password Potpourri
Password Potpourri Make your passwords strong Eight characters, one letter, one number, one symbol Actually this could be totally inappropriate, depends on your security requirements Hash and salt stored passwords Salting prevents rainbow table attacks if password table compromised
Password Potpourri Think about your password reset scheme Could send link to reset page in a email, but what if email is hacked? Could ask secret question and answer, but what if their answer is really easy (“Your dog’s name is… Fido”) Use both Lockout brute forcers Just for a little bit
9. Users, users, users
Users, users, users They (some of them) are dumb! Don’t trust them… to recognize your sites with the right domain and SSL cert to not have malware installed Assume the worst can happen
10. Full Trust Exercise
Full Trust Exercise Full trust is ASP.NET mode that allows code to do anything it wants Sound dangerous? It is! It’s also the default and the way a LOT of ASP.NET sites run Consider placing your application in Medium trust It could prevent the attacks you don’t know about!
Top Ten Tips For Tenacious Defense In Asp.Net

Top Ten Tips For Tenacious Defense In Asp.Net

  • 1.
    Top Ten Tipsfor Tenacious Defense in ASP.NET Alex Smolen Senior Consultant SoCal Code Camp , 2008
  • 2.
  • 3.
    CSRF Attacker enticesvictim to view an HTML page containing a malicious image tag (hosted by an “accomplice”) Victim unknowingly submits a request to a server of the attacker’s choosing - using the victim’s credentials Effects can vary Log the user out Execute a transaction Post a message Modify settings on an intranet device with a web interface
  • 4.
    CSRF - Examples<!--Buy shares of Microsoft in the background--> < img src = &quot;http://stocks.com/buy.aspx?sym=MSFT&shares=500&quot;> <!--Open up a firewall port--> < img src =&quot;http://firewall/openPort?portNumber=5344&quot;>
  • 5.
    CSRF - DefenseThe root cause is “Ambient Authority” Cookies, NTLM Creds, HTTP Auth automatically sent by browser Site needs to provide another form of secret that attacker can’t guess
  • 6.
    CSRF Defense RefererViewStateUserKey Secret token CAPTCHA Password Re-authentication
  • 7.
    CSRF Defense -Referer Check the HTTP referer to make sure that the user just came from the right page Misspelling intentional Referer isn’t always sent Privacy settings Difficult to tell who referer will be Can be faked with vulnerable versions of Flash
  • 8.
    CSRF Defense -ViewStateUserKey ViewStateUserKey is combined with ViewState ViewStateMac check will fail if ViewStateUserKey is different Can be used to ensure that ViewState is unique between users Set the value to session ID
  • 9.
    CSRF Defense –ViewStateUserKey There are problems with this solution Have blogged about this What if ViewStateMac isn’t enabled? The action isn’t a postback? You don’t want to use ViewState at all?
  • 10.
    CSRF Defense - Secret Token This is a more flexible approach The form (or URL, potentially) contains a secret token that is required Could be the same or based on session ID Page checks for this token as well as session ID in cookie Ambient authority is superseded
  • 11.
    CSRF Defense –Secret Token Both CSRFGuard from OWASP and AntiCsrf from Barry Dorrans use this approach http://www.owasp.org/index.php/CSRF_Guard http://www.codeplex.com/AntiCSRF/ Need to watch GET versus POST Idempotency and verb agnositicty, oh my!
  • 12.
    CSRF Defense -CAPTCHA CAPTCHA theoretically requires a human to solve Bleh… They work, but aren’t very user-friendly CSRF is possible for a lot of actions Maybe if it’s Asirra… http://research.microsoft.com/en-us/um/redmond/projects/asirra/
  • 13.
    CSRF Defense –Password Re-authentication Simply require users to re-authenticate to perform an action The most secure, hopefully Can be done for BIG DEAL transactions, like cashing out an account or changing password (this is usually done anyways) Example: Amazon Shopping Cart
  • 14.
  • 15.
    Session Fixation Let’ssay… You visit a web site You enter your username and password You continue browsing to other pages The web site continues to knows who you are How?
  • 16.
    Session Fixation Sessions!An identifier is passed with each request (usually in a cookie) I can steal your session if I know your session identifier Session identifiers are like a temporary password
  • 17.
    Session Fixation Sessionfixation occurs when I force you to use a known session identifier Shared terminal At a library, hotel, etc I visit a site, note the session ID, wait for someone else to login Click a link http://site.com/index.aspx?ASPSESSIONID=hack If you click on my link, I know your session ID
  • 18.
    Session Fixation DefenseTo defend against this, regenerate the session ID after login You probably don’t do this There’s no good way to regenerate the session ID in ASP.NET If you use Forms authentication, you’re OK…sorta FormsAuthenticationTicket is used in addition to cookie and can’t be preset However I may be able to access your information with my FormsAuthenticationTicket and your session identifier
  • 19.
    Session Fixation -Defense You could do something like this: Gross  Use an extra authentication cookie if you don’t use Forms Authentication Make sure all requests to a session are from the right authentication user according to the authentication cookie
  • 20.
  • 21.
    Real-World Crypto cryptography:security::concurrency:programmingTruly understood by few, screwed up by almost everyone People like cryptography because it is a security feature A lot of times, they don’t know what it does Magic fairy dust
  • 22.
  • 23.
    Read-World Crypto Peoplewill use hash functions, random numbers, encryption algorithms, for all sorts of reasons There building blocks, are there are very specific purposes for each of them!
  • 24.
    Real-World Crypto RandomData Properties: Difficult to guess Uses: Generated passwords or links, session identifiers, cryptographic keys How people mess this up: Use System.Random() Not good enough! Use a predictable seed Don’t use enough bits
  • 25.
  • 26.
    Real-World Crypto HashingProperties: One-way Uses: Verify knowledge of something (e.g. passwords), verify integrity of something How people mess this up: Use hash for authentication Verify this hacked file download with this hacked file hash! Use hash for something else (random data) Use insecure algorithm (not really an issue for most scenarios, but easy enough to fix)
  • 27.
  • 28.
    Real-World Crypto Symmetriccryptography Properties: Keeps a big secret with a smaller secret Uses: Keep sensitive data confidential How people mess this up: The key has to be a secret Don’t lose the key Use the DPAPI! Key management for free! You can build your own as well, just be careful
  • 29.
  • 30.
    Real-World Crypto That’sit! Not really, cryptography is really complicated If you’re doing anything with certificates, SSL, digital signatures, WS-Security, get a book
  • 31.
  • 32.
  • 33.
    The AntiXSS LibraryXSS is an issue Has been for a while Really hard to stop The problem is the browser Also, we end up putting user-modifiable data in weird places, such as ASP.NET doesn’t help us too much
  • 34.
    Control Behavior LiteralNone by default. HTML Encoded if Mode property is set to LiteralMode.Encode Label None TextBox Single-line text box is not encoded. Multiline text box is HTML encoded Button Text is attribute encoded LinkButton None Hyperlink Text is not encoded. NavigateUrl is URL path encoded, unless it is JavaScript, in which case it is attribute encoded DropDownList and ListBox Option values are attribute encoded. Option display texts are HTML encoded. CheckBox and CheckBoxList Value is not used. Display text is not encoded. RadioButton and RadioButtonList Value is attribute encoded. Display text is not encoded. GridView and DetailsView Text fields are HTML encoded if their HtmlEncode property is set to true. Null display text is never encoded.
  • 35.
    The Anti-XSS LibraryData needs to be encoded Fully With the right context User data could be output to… HTML HTML attribute JavaScript XML Etc…
  • 36.
    Method Description HtmlEncodeMore robust version of the HttpUtility.HtmlEncode method. HtmlAttributeEncode Encoding for dynamically created HTML attributes (i.e src=“”) XmlEncode/ XmlAttributeEncode Encoding for XML elements and attributes UrlEncode Encoding for dynamically constructed URLs JavaScriptEncode/ VisualBasicEncode Encoding for dynamically generated JavaScript or VBScript
  • 37.
  • 38.
    Stop Injection! Injectionoccurs when: We treat data as code? We fail to properly validate input? We fail to properly encode output? Like, all the time? Yes
  • 39.
    Stop Injection! Howdo we stop SQL injection Command injection Path manipulation XML injection LDAP injection Who-knows-what-else
  • 40.
  • 41.
    Stop Injection! Twothings we can do: Validate Make sure all request data looks the way it’s supposed to Uh, that’s all data (cookies, headers, hidden fields) Encode Make sure all data is properly encoded for it’s destination SqlCommand with SqlParameters does this for SQL Otherwise, you are on your own
  • 42.
  • 43.
  • 44.
    Authorization Woes Whois allowed to do what? Well, we don’t know… Draw an authorization matrix! Think about horizontal and vertical privilege escalation! I’m serious!
  • 45.
    Authorization Woes OrdersProducts /admin … Customers View View No … Managers View, Modify View, Modify, Add No … Administrators View, Modify, Add, Delete View, Modify, Add, Delete Yes … … … ... ... …
  • 46.
    Authorization Woes Role-basedaccess control works well here Group users by role Some users will need additional privileges Can use finer-grained model Some authorization concerns rely on state “ After 5PM, traders cannot place orders greater than the sum of the previous weeks total, minus exemptions…” This becomes business logic
  • 47.
    Authorization Woes Userlogs in, clicks on “My Account” URL http://www.bank.com/accouts.aspx?id=123-456-7890 What if I got my neighbors statement by mistake? http://www.bank.com/accouts.aspx?id=-098-765-4321 I shouldn’t be seeing their statement Horizontal privilege escalation
  • 48.
    7. Mind YourCookies!
  • 49.
    Mind Your CookiesDon’t use cookies! Let ASP.NET do the session stuff for you What else could you possibly need to use cookies for? OK, OK, so maybe you can use them sometimes Don’t base security decisions off the data!
  • 50.
    Mind Your CookiesThere are two tags that can be added to the set-cookie response header Secure Do not transmit this cookie over non-SSL connections HttpOnly Do not allow JavaScript to access this cooke
  • 51.
    Mind Your CookiesDomain Think about what sub-domains need access Path You can limit what parts of your application cookies are sent to Expiration Don’t go crazy
  • 52.
    Mind Your CookiesURL Rewriting Pass the session ID as a URL argument http://site.com/a.aspx? sessionid=123123123 Bad idea Ends up in history, bookmarks, links sent to friends Originally for users with cookies disabled Probably a small enough minority to ignore
  • 53.
    Session State inASP.NET <httpCookies httpOnlyCookies=&quot; true &quot;> Mark all container issued cookies as HttpOnly <sessionState cookieless=&quot; UseCookies &quot;> Prevent URL rewriting <forms requireSSL=&quot; true &quot;> Marks Forms Authentication as secure
  • 54.
  • 55.
    Password Potpourri Makeyour passwords strong Eight characters, one letter, one number, one symbol Actually this could be totally inappropriate, depends on your security requirements Hash and salt stored passwords Salting prevents rainbow table attacks if password table compromised
  • 56.
    Password Potpourri Thinkabout your password reset scheme Could send link to reset page in a email, but what if email is hacked? Could ask secret question and answer, but what if their answer is really easy (“Your dog’s name is… Fido”) Use both Lockout brute forcers Just for a little bit
  • 57.
  • 58.
    Users, users, usersThey (some of them) are dumb! Don’t trust them… to recognize your sites with the right domain and SSL cert to not have malware installed Assume the worst can happen
  • 59.
  • 60.
    Full Trust ExerciseFull trust is ASP.NET mode that allows code to do anything it wants Sound dangerous? It is! It’s also the default and the way a LOT of ASP.NET sites run Consider placing your application in Medium trust It could prevent the attacks you don’t know about!