Notes: The OWASP Top 10 Web Application
These are my notes from OWASP The Open Web application Security Project
About how to implement the top 10 in asp.NET
Overview
No-one is safe. 90% of sites have security flaws.
Be pragmatic
Making a site unhackable is unfeasible
Organizations should balance between,
- cost to protect,
- value of assets,
- likelihood of exploit.,
- impact of exploit
The categories of attackers
Different risk profits mean different required investments to protect.
- Hacktivists
- social interests
- Online criminals
- cash
- Nation states
- cyber warfare
OWASP
The Open Web application Security Project
- Non-profits
- Top 10 lists are language agnostic
The OWASP Top 10
- Injection
- Cross-Site Scripting
- Broken Authentication and Session Management
- Insecure Direct Object References
- Cross-site request forgery
- Security Misconfiguration
- Insecure Cryptographic Storage
- Failure to Restrict URL Access
- Insufficient Transport Layer Protection
- Unvalidated Redirects and Forwards.
The Security Matrix
- Threat Agents
- Attack Vectors
- Security Weaknesses
- Security Controls
- Technical Impact (Dependant on asset)
- Business Impact (dependent on nature of data)
OWASP grading system Traffic light rating system
Color | Threat Agent | Attack Vector | Weakness Prevalence | Weakness Detectability | Technical Impact | Business Impact |
Purple | Very Widespread | |||||
Red | Easy | Widespread | Easy | Severe | ||
Orange | Average | Common | Average | Moderate | ||
Yellow | Difficult | Uncommon | Difficult | Minor |
Security depth
Security is layered
Top 10 is the starting point not the end…
Injection
The Matrix
Threat Agents
Anyone who send untrusted data to the system.
Attack Vectors red
Simple text based attack
Security Weaknesses
Prevalence orange
- Very prevalent, esp. in legacy code.
- Include SQL, LDAP, XPath queries, OS commands.
Detectability orange
- Easy in code,
- Hard in testing
Technical Impact (Dependant on asset) red
- Data loss/corruption
- Lack of accountability
- Denial of access
- Host take over
Security Controls
Business Impact (dependent on nature of data)
- With regards to
- theft,
- modification
- deletion
- Consider value of
- affected data
- the platform running the interpreter
Notes:
- Can gets additional data from the system. IE. table names by querying
sysobject
&xtype=char(85)
- Blind sql injection - executing with output bubbling up into the web interface.
- integrity is not verifiable
- intent may be malicious
- possible payloads:
- sql injection
- cross site scripting
- binaries containing malware
- Sources:
- url/query string
- form values
- cookies
- request headers
- external service (external web service)
- own database (eg. user submitted data)
Security in Depth
Security in depth: Protection in layers.
Protect from db back to web tier.
The principle of least privilege
Principle of least Privilege :: every modules in a system must be able to access only the information and resources that are necessary for it's legitimate purpose.
Update sql user permissions to be only what is needed.
dbowner
is too permissive.- Give access to only tables needed.
SQL Parametrization
Stop breaking out of data context (IE input parameter) into the query context. IE. can only change data, not the query
- Remove online string concatenation.
- Use
new SqlCommand().Parameters.Add()
method instead.
Stored Procedures
- Always parameterized value by default.
- Still possible to run injection if just running an
exec!
in the storedProc. eg. building a like.- use
sp_executesql
notexec
- use
Whitelist
- alway validate data
- explicit filter out anything not truster
Whitelist is a more future proof alternative than a blacklist
Approaches
- Type conversion
eg.
int.TryParse
the string value coming in. - Regular Expression
- List of known good values.
ORM
- Automates parameterization.
Automation Tools
Automation reduces the bar to entry. IE makes injection easier.
Summary
- Apply principle of least privilege
- parameterize untrusted data
- stored proces offer protection via parameterization
- always validate untrusted data against a whitelist
- ORM parameterize nativly
- Remember automated tools are easy to use
Cross Site Scripting (XSS)
The Matrix
Threat Agents
Anyone who send untrusted data to the system.
Attack Vectors orange
Simple text based attack
Security Weaknesses
Prevalene purple
- most common on web
- Stored
- Refleced
- DOM based
Detectability easy
- Easy via code
- Easy via testing
Technical Impact (dependand on asset) red
- Execute scripts in victems browser
- hijack session
- deface web sites
- insert hostile content
- redirect users
- hijack via malware
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- affected system
- all data it processes
- Include in consideration impact of
- public exposure of exploit
Notes:
XSS attacks are possilbe from the payload breakout from the data context to a output encoded context.
- Data that manipulates the markup context. IE. Data has broken out of data context onto the markup context.
- Power of xss is to send the dom element elsewhere. Eg. cookies.
Security in depth
Output encoding
XSS mitigation is making sure untrusted data is rendered the same whay it was entered.
- Use output encoding, (eg.
html encoding
) for display the characters. - CSS
- HTML, HTML attribute, HTML form url
- Javascript
- LDAP distungished name, LDAP filter
- URL, URL path
- XML, XML attribute
- Frameworks encoding actions
- WebForms: Different controls will encode differently.
- ASP.MVC: Razor encodes everything by default.
Persistent XSS is stored in the datbase.
Each encoding context required different encoding sequences.
Using a proven library is the right approach. Do not roll your own
Whitelist against string
- regex is a viable option against string data
- Be careful not to miss valid chars. eg. ~@"\p{L} \.\+$"~ ~ misses quotes.
Default secure validation
Requestion validation is on by default in ASP.NET so attacks will be caught before request hits usercode.
Returns A potentially dangerous...
error is returned.
<configuration> <system.web> <!-- explictly enable request validation, `validateRequest` attribute will be missing and `true` by default --> <pages validateRequest="true"> ... </pages> </system.web> </configuration>
-
validateRequest
can be disabled - Pre-ASP.NET 4.5 - done on the page level. eg. for a WYSIWYG editor.
- ASP.NET 4.5 - done at control level, or code behind.
- ASP.MVC - The decorator
AllowHtml
can be set on a Model value.
<%@ Page Title="disabled request validation" ValidateRequest="false" Language="C#..." />
Code as if request validation doesn't exist. It is a last line of defense.
Browser defense
- Some browers blocked thing on their own.
- Custom headers provide a method to control browser behaviour.
- Cannot rely on brower implementations
Obuscating the Attack
- Encode the entire url.
- Use a url shortener.
Summary
- Output encoding is base of XSS protection
- Default Encoding is performed differently be different frameworks
- Whitelist are important
- Request validation isa safetly net
- Code as if XSS is in the database
- brower defenses are inconsistent
- Expect attack obfuscation to occur
Broken Authentication and Session Management
The Matrix
Threat Agents
Anonymous external attackers trying to steal accounts, Insiders wanting to hide their actions
Attack Vectors orange
Leaks/flaws in authentication/session management functions to impersonate users
Security Weaknesses
Prevalene orange
- from custom auth and session management schemes
Detectability orange
- Hard because of uniquieness of each scheme
Technical Impact (dependand on asset) red
- Allow all account to be attacked
- Full priveleages of attacked user
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- affected data
- application functions
- Include in consideration impact of
- public exposure of vunerability
Notes:
Never have sensitive information in the url.
Security in depth
Session Persistence
Url Session Persistence
This is unsecure
HTTP is a stateless protocol, putting the session in the url is a hack to get around this.
- Problem is the session would be stored via
- sharing on social media
- Logging
- Browser history
Session Persistence in a cookie
Works by sending the cookie with the request. The cookie is not shared via url
Problem is if cookies are not enabled in the browser.
ASP.NET Types
- UseUri
- UseCookies (default)
- UseDeviceProfile - Cookies with fallback.
- AutoDetect
It may be worth not allowing uses without cookies enabled.
Broken Authentication
Rolling your own authentication is hard. The recommendation is to use pre-rolled.
Eg. ASP.NET's MembershipProvider
Session and forms timout
Timeout is a balance between the convenience between
- user remaining logged in and
- session becoming hijacked.
- ASP Default
- Session : 20 minutes
- 30 minutes
By default, A new ASP.NET Forms application will increase the timeout to 2 days
- Types
- Sliding -
<forms sliding="false" />
- Ends XX time after inactivy. - Fixed -
default
- Explict duration.
- Sliding -
Other Needed Patterns.
- Cryptographically secure password credential storage.
- Robust minimum password criteria.
- Never send password by email.
- Protect session IDs in cookies.
Summary
- Keep session IDs out of Url, use cookies
- Use ASP.NET membership provider
- Customise session & forms timeout
- Disable sliding forms authentication if possible
- Broken auth is a broad risk and is highly related to other top 10.
Insecure Direct Object References
The Matrix
Threat Agents
Users with partial access
Attack Vectors easy
Authorised user changes a parameter value, and get access to another object the user isn't aithourized for.
Security Weaknesses
Prevalene orange
- when the user is used page, application don't always validate the user.
Detectability red
- Testers can easily manipulate values to detect such flaws
Technical Impact (dependand on asset) red
- Compromise all data referenced by the parameter
- Commonly all data of that type
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- exposed data
- Include in consideration impact of
- public exposure of vunerability
Notes
It's about gaining access to other user accounts.
- Direct Object Reference
- Observable key use to identify an individual database record.
- Risk
- Manipulation of a direct object reference
- Direct reference are often
- Patterns (incrementing
- Natural Keys/Logicdata (username)
- Discoverable data (social security numbers)
- Direct object references can then be brute forced/scripted for access.
Security in Depth
Access Controls
Correct access control makes sure users can only access the appropriate records.
Heart of Indirect Object Reference Access is a lack Access controls.
Indirect Object Reference Map
An abstration between what is publicly obwservable and the individual database record.
- Map internal records to temporary, user specific, random record.
- Server maintains a map between the the temp record and the internal value
- Temporary
- User specific
- Indirect reference is random
- Multiple front ends?
- Potential overhead?
Obfuscation via Undiscoverable surrogate keys
- INterger and natural string types can be enumerated
- Non pattern bases surrogate keys add further obfuscation (eg GUID)
- Security through obscurity,
- There are tradeoffs.
- Not real proper access control
Summary
- Insecure direct object reference are aboutaccess control
- Indirect references can be used to conceal internal keys
- Surrogate keys can assist in obfuscation
Cross Site Request Forgery (CSRF, XSRF)
The Matrix
Threat Agents
Anyone who can trick users into submitting a request to your site.
Attack Vectors orange
Attecker create forged HTTP request and tricks user into submitting them. If the user is authenticated the attack succeeds.
Security Weaknesses
Prevalene red
- malicious request are indishtinushable from legitimate requests
Detectability red
- Easy via pen testing or code analysis
Technical Impact (dependand on asset) orange
- Change any data the victen can change
- Perform any function the victem can perform
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- affected data or application functions
- Imagine not being sure if the user performed the actions
- Include in consideration impact on
- customer
- reputation
Notes
CSRF is about getting the browser to reconstruction of a legitimate request with a malicious payload.
The CSRF process
- Authenticated session are persisted via cookie
- Attacking site recreates a legitimately formed request
- Browser is tricked into makeing the request.
Security in Depth
Antiforgery tokens
A CSRF token is a random string known to both legitimate page where the form is and the browser via cookie.
The token is know to the page and is validated against the value in the cookie
CSRF Falicies
- Implement referrer checking wil restrict cross-domain request Partially helpful, but this does not address the risk introduced by XSS.
- Disable HTTP GET on at-risk pages Attacker can still construct POST requests
- Valida the IP address from loading page to POSTing IP. Does not help since it will be the client's IP each time
The only real defense is CSRF tokens.
Browser Defense
- CRSF risk may be exploited by Cros-Origin-Resource Sahring (CORS)
- Drifferent vrowsers provide variting levels against CORS
- Should never be relied on.
Summary
- All about browser being tricked into a legitimate request with amlicious payload
- it's the authenticated user state that is abused
- Only real mitigation is anti-forgery token.
- Request always seem legitimate
- Browser defnese should not be relied on.
Security Misconfiguration
The Matrix
Threat Agents
- Anonymous external attackers, users withown accounts, insiders trying to hide actions.
Attack Vectors red
- acccesses default accounts, unused pages, unpathed flaes unprotected files,
- to gain access/knowlege of the system
Security Weaknesses
Prevalene orange
- HAppen at any level, devs and admin need to work together
Detectability red
- Automatic scanners are usefull for checking missing patches, misconfigurations, default accounts, unnecessary services
Technical Impact (dependand on asset) orange
- Unauthorized access to system data or functionality
- Complete system compromises
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- complete system
- all data
- Include in consideration impact on
- complete compromise without knowledge of it
- recovery costs
- modification of data over time
Notes
- YSOD is a Security Misconfiguration. Internal exceptions should not be public
Probe application ith data outside of expected range
- Unsecured ELMAR is a commonly misconfigured
Security in Depth
Configure Custom Errors
To stop automated tools fromscrapping for errors:
- Enabling Custom Errors - (Hide internal implementation details)
- Rediret to 404/Error page, (Hide the custom error 500)
- Rewrite the response - (Hide url/response code from displaying the error)
<configuration> <system.web> <customErrors mode="On" defaultRedirect="Error.aspx" responseRewrite="true"/> </system.web> </configuration>
Typical Risks
Trace
Tracing should be disabled/remove due to the sensitive information
<configuration> <system.web> <trace mode="false"/> </system.web> </configuration>
Keep Libraries Updated
- NuGet Modules upgrades should be reviewed.
Storing Sensitive Information
- Encypting the data on the web.config using the encryption key on the server. It is tied then to the box.
# encrypt /c/windows/microsoft.net/vxx> aspnet_regiis -site "site" -app "/" -pe connectionStrings decrypt /c/windows/microsoft.net/vxx> aspnet_regiis -site "site" -app "/" -pd connectionStrings
Config Transforms
Remove the dangerous configuration setting in the web.release.config. Transform must be done through the publish process.
Retail Mode
MAchine level override, safety net for config mistakes.
<configuration> <system.web> <deployment retail="true"/> </system.web> </configuration>
Summary
- Small changes can product large security issue.
- Have a strategy for keeping frameworks current
- Protect sensitive data in Web.config
- Automate scrubbing of sensitive information in configs
- retailMode can be used as a safetly net.
Insecure Cryptographic Storage
The Matrix
Threat agents
- user of your system
- internal administrators
Attack Vectors yellow
- Attackers don't ussually break crypto
- They break something else to get keys, copies of data, or access data via automatic decryption channels
Security Weaknesses
Prevalene yellow
- Most common flaw is not encrypting data that should be.
- When encryption is used: unsafe key gen, not rotating keys, or weak algorithms, is common
- Weak or non-salted password
Detectability yellow
- Difficult remotlely
- Ussually needs to exploit something else first.
Technical Impact (dependand on asset) red
- Frequently compromises all data that should be encrypted
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- lost data
- Include in consideration impact of
- reputation
- legal implocations
Notes
- Attackers use tools and dictionaries.
- OclHashCat is a cracking tool
- hashkiller.com.dlc
The ASP.NET default password provider is basically useless.
Cyrptographioc storage is the final line of defense.
- 3 common password storage
- Plain text
- Encrypted
- Hashed
- (no term)
- Encryption is reversible, decyrpting with the same key is symetric encryption.
In reality the goal is making it not feasible to crack the passwords in the first place.
Hashing
- is one way
- keyless
- is a deterministic algorithm
- result is the same
- System never uses real passwords.
- List of hashs and values
- Are a simple way to find hashes.
- Precomputed
- Get large fast
Salting
- Without salt the password hashes are easy to find
- Salt is random byte to add to a password
- Store Hashed password + salt.
- Forces rainbow tables and google useless.
- Still crackable but it takes time.
- GPUs are very good at this
- Dictionaries imporve cracking hit rate.
Not encryption
- Rot13 / Base64 is not cryptographic.
One ought design systems under the assumption that the enemy will immediately gain full familiarity with the,
– Kerchhoffs' principle
Security in Depth
Hashing
Decrease the rate the MembershipProvider calculates hashes.
- PBDK2 : Password Based Key Derivation Function 2
- Default ASP.MVC
- ASP.MVC4 Hashes the password 1000 times. This values is not changable.
- BCrypt.Net
- BCrypt allows increaseing the workload to generate the password fo the site.
- Zetetic
- Defaults to 5000 computations of PBDK2
Other considerations
- Overload for server, possible opportunity for DDOS attack
- Is a good balance for now good for tomorrow.
- Web Servers hash with the CPU but cracking is done via GPU.
- Can alway upgrade the hashing algorithm, but passwords need to be upgraded. (Track hashing algo next to passwords)
There is no one size fits all. Balance, resource to risk.
Encryption
- Symetric encryption use a single password for encryption and decryption
- Asymetric using a public prive key pair
- Is reversible for both cases.
- encryption is useless is private key is known
- most compromised datastores, often include the source files with the private keys
Data Protection API (DPApi
- Uses the machine key for encryption
- Included in
System.Security.Cryptography.ProtectedData
namespace- Processes can share data with
LocalMachine
- Processes can share data with
Summary
- Cryptographic storeage is the last line of defnese
- HAshing is about slowing attackers down
- Key management is the issues in encryption
- Some things just are not encryption (base64 / rot13)
Failure to restrict URL Access
The Matrix
Threat Agents
- Anyone with network access to send a request to the application
Attack Vectors red
- Changes to a url grants access to privileged page.
Security Weaknesses
Prevalene yellow
- Not always protecting page request properly,
- routes misconfigured, devs forget backend checks.
Detectability orange
- Testing is easy, finding which pages to exist is hard
Technical Impact (dependand on asset) orange
- Allows attackes unauthorized functionaliy
- Admin functions are key targets
Security Controls
Business Impact (dependent on nature of data)
- Consider value of
- exposed functions
- data exposed by the functions
- Include in consideration impact of
- reputation if publicised
Notes
Example is insufficient access controls on administrative pages Similar to Insecure Direct Reference Objects
Security in Depth
Access Controls in ASP.net
- Path level in web.config
location
element, andRoles
(location level is pretty heavy handed) - Method level in class using
principal
permissions - Entire MVC controller with
Authorize
attirubue - MVC controller action with
Authorize
attribute - Any point in code using ASP.NET
Identity
andRole
Feature
Gotchas
- Overlooked URLs (api endpoints, resources (docs, pdf))
- Obfuscation is not access control (urls, ips…)
- Urls with credential (caching, proxies, included https…)
Summary
- Many authorization method in ASP.NET
- Roles base is simple using ASP.NEDT native features
- There are gotchas with overlooked and obfuscated urls
Insufficuent Transport Layer Protection
The Matrix
Threat Agents
- Anyone who can monitor network traffic
Attack Vectors yellow
- Difficulty comes from monitoriing while the user is using the website
Security Weaknesses
Prevalence orange
- App use ssl/tls during authentication but not elsewhere.
Detectability red
- Detecting basic flaws is easy. THe more sublte flaws involves looking at desing of application and configuration of the server
Technical Impact (dependand on asset) orange
- Accoutn theft
- Facilitation of phishing, and Man in the middle attacks
Business Impact (dependent on nature of data)
- Consider value of
- data exposed on the communications channel
- Include in consideration impact of
- confidentiality
- integrity needed by both pariticpants.
Notes
Attacker is a rogue access point the victem connects to. The attack then just passes stuff through.
Attacker can capture the packers with Wireshark.
- Filter by HTTP
- TCP stream give the details (.aspxcookie) of requests.
Certificates must be fetch by an authentic Certificate Authority
Security in Depth
Enable Secure Cookies
Cookies with Secure flag set will not be sent to non-http requests. The Secure flag will only be set by the server, The browsers does not send the cookie with the flag.
Different level of cookie security
- Enable SSL for the authentication cookie
- Enable SSL for all cookies
- Keep a cookie as non-secure
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login/" timeout="2880" requireSSL="true" /> </authentication> <system.web>
<system.web> <<httpCookies requireSSL="true" /> </system.web>
Response.Cookies.Add(new HttpCookie("UnsecureCookie"){ Value = "cookie-value", Secure - false; });
Force HTTPS
For Web Forms,
/* On Page_Load */ // Be careful that the box actually runnning this is handling the cert (ie. NOT behind a load balancer) if (Request.IsSecureConnection()) { var secureUrl = GetUrl().replace("http", "https"); Response.RedirectPermanent(secureUrl); }
For ASP.MVC, just use an attribute per action,
[RequireHttps] public ActionResult SomeActionTheMustBeHTTPSListRegister() { return View(); }
https is for confidence and integrity. If a single resource is not http all confidence and integrity is lost. Hence the Mixed content warning in browsersn
Protocol Relative Content
Browser load content relative URL using the parent pages scheme.
<!-- Note the // --> <script src="//ajax.com/jquery.js" type="text/javascript" ></script>
Using HTTP strict transport security (HSTS)
Stop browser from making any unsecure request with HSTS header. HSTS header stops man in the middle requests.
HttpContext.Current.Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
HSTS Restrictions
- Header will only be observed if sent with https response
- Certificate must be trusted
- User needs to send http request first that doesn't get hijacked
- Browser Support is patch. Some browser force some sites out of the box (eg. chrome, amazon)
Insuficient TLS patterns
- Loading login from http, but post to https
- https form inside https inside a http iframe
- Allowing http when there is no use case where it ever should be
- Passing sensitive information in a https url.
Https considerations.
- SSL comes at a cost. but it was a 1% cpu load, and 2% network overhead for google in 2010.
- Inital unsecure requests can always be picked up be man in the middle attacks. eg MithM attacks like
sslstrip
then fake the https. - Intergirty of the Certificate Authenticaties is paramount to the whole https landscape.
Summary
- There are many methods of implementing HTTPS insuficuently
- Cookies can be sensitive because of what they allow the user to do
- Resource that require secure connection shouldn't be loaded over insecure connectiosn
- Loading insecure resource destroy the integrity of secure pages in included in the load
- Use HSTS for secure sites, but support is limited
- Avoid antipatterns of, login forms over http, insecure pages embedding secure login forms, sensitive dat in the secure urls.
- SSL have overhead, just not much
- SSL is not fool proof.
Unvalidated Redirects and Forwards (Open redirects
The Matrix
Threat Agents
- any one who can trick users into submitting requests
Attack Vectors orange
- links to unvalided redirect and trick victent to clicking it.
Security Weaknesses
Prevalene yellow
- Appl frequenly redirect users, or use internal forwards, sometimes the page is specified in an unvalidated parameter
Detectability red
- Easy to find, anywhere you can set the full url
- Unchecked forwards are harder, since they target internal pages
Technical Impact (dependand on asset) orange
- Attempts to install malware, phishing, disclosing sensitive information
- Unsafge forwards may allow access controll bypass
Business Impact (dependent on nature of data)
- Consider value of
- retaining users trust
- Include in consideration impact of
- client getting owned
- attackers access internal only functions
Notes
Use a legitimate domain to serve malicious urls.
Attack exploits trust in the target site. Includes users, and also for bots. Victim is focussed on the domain.
- Delivering 'loaded' URLs
- Distribute Malicious payload
- Automated tools (spam filters,…) struggle with the url due to legitimate domain.
- URLs are often trucated to the legitimate domain only
- URL encoding every character obfuscated the actual path
Security in Depth
Perform checksd on the request.
- Whitelist the redirect
- Check to see is a user is coming from own own site.
var url = Request.QueryString["redirectTo"]; // 2. Check to see is a user is coming from own own site. var referrer = Request.UrlReferrer; if (referrer.?Host != Request.Url.Host) { throw new ApplicationException("Referrer is not this site."); } // 1. Whitelist the redirect var db = new TrustedUrlsContext(); if (!db.TrustedUrls.Any(x => x.Url == url)) { throw new ApplicationException("URL not trusted"); } Response.Redirect(url);
Other Concerns
- Often viewed as a light risk, used as a launchpad
- Google does not pay bug bounties for the risk.
- Risk is about reputation
Summary
- Unvalidated redirect pose value by posing legitamacy to launch an attack
- Redirecting users is valid ussually only if the target is trusted
- Referrer checking can mitigate but is not foolproof
- Often not viewed as a major risk, but the risk is to reputation