Security
HTTP Strict-Transport-Security (HSTS)
Makes the site HTTPS only.
HTTP header Strict-Transport-Security: max-age=31536000; includeSubDomains
(units in seconds; this is a year).
It is ignored in an HTTP site. The setting is saved when you use HTTPS, and is enforced until the age expires.
If you have never visited https://site and go to http://site, the header is ignored. You have to redirect to https in server code. Google has a preload service, so you can the initial HTTP vulnerability.
Content-Security-Policy: upgrade-insecure-requests;
. Note all links, including third party links, become https and will fail if they're not...
Content Security Policy (CSP)
Stops XSS by whitelisting script sources.
ref Http header Content-Security-Policy or <meta http-equiv="Content-Security-Policy"
Content-Security-Policy: default-src 'self' *.mysite.com
All img/script/frame/style from same source (can be a url) plus subdomains
After the default, add whitelisted script-src; img-src; style-src
Inline script/css will be blocked. If you can't remove them, use the workarounds: script-src 'unsafe-inline'; style-src 'unsafe-inline'
Note inline events are blocked as well <button onclick="alert('hi')" >
Subresource Integrity (SRI)
Add a secure hash for scripts/styles, particularly from a CDN, so you are sure they are unaltered.
Ref.
- Add a CSP (see above)
Content-Security-Policy: require-sri-for script; require-sri-for style;
- Add "integrity" attribute to <script> and <link> tags:
<script src="https://cdn/jquery.js" integrity="sha384-h2..." >
Cross-Origin Resource Sharing (CORS)
Ajax (XMLHttpRequest and Fetch) have a same-origin policy; CORS relaxes it (so http://website/ can get data from http://api/).
Ref. Note the browser (not your javascript) is doing the process in ajax calls.
- If simple GET or POST with standard HTTP headers
- The browser ajax automatically adds HTTP header "Origin" with the current site.
- The server returns "Access-Control-Allow-Origin" with the allowed site. If it's not "*" and doesn't match the current site, the browser errors.
- If custom headers (eg authentication) do a "preflight request"
- Browser sends HTTP OPTIONS with Origin, Access-Control-Request-Method (http method) and Access-Control-Request-Headers.
- Server responds with Access-Control-Allow-Origin, Access-Control-Allow-Headers and -Methods, all of which must match.
The server must know what specific calling sites, methods and headers (or use "*", for non-secure access).
By default, no credentials are passed cross-origin. To send credentials:
- JavaScript: xhr.withCredentials = true; or jQuery xhrFields: {withCredentials: true }
- Configure server.
- For .net webapi, indicate in attribute- [EnableCors(origins: "...", SupportsCredentials = true)] Origin of "*" is not allowed.
- For .net Core, in ConfigureServices services.AddCors(o=> o.AddPolicy("name", b=>b.WithOrigins("...").AllowCredentials()))
- Server responds with Access-Control-Allow-Credentials.