An overview

This article is a summary of browser security protocols, common Web attacks and Cookie mechanisms

  1. Browser security Protocols: What is SOP/CORS/CSP? Why can THE CORS protocol guarantee the security of the browser or the server?
  2. Common Web attacks: what are XSS /XSRF attacks? What are their types and how can they be prevented
  3. What is the function of the Cookie, and what is the impact of its SameSite default being changed in 2020?

Browser Security protocol

Same Origin policy SOP

Same-origin policy Same-Origin policy is the most strict, basic, and core security policy in page security

Same-origin: The protocol, domain name, and port of the URL are the same

  • DOM level: Limits how Javascript scripts from different sources can read and write to the current DOM object
  • Data level: The Cookie, Indexdb, Localstorage and other data of the current site can be read by sites with different sources.
  • Network level: Cross-domain requests cannot be made directly using Xmlhttprequest or Fetch
    1. Cross-origin writes: Links, redirects, and form submissions are generally allowed.
    2. Cross-origin embedding: generally allowed, links, redirection and form submission
    3. * Cross-origin reads: * Are generally not allowed, but can often be accessed subtly with embedded resources. For example, you can read the height and width of an embedded image and call the methods of an embedded script

However, this restriction is too strict in practice, so the actual security policy is relaxed

  1. Cross-document messaging mechanisms

    DOM level constraints are relaxed: The DOM of two different sources cannot manipulate each other, but can communicate with each other more securely

  2. Content security policy CSP

    Loosens the constraints at the data level: let the server decide what resources the browser can load and whether it can execute inline Javascript code

  3. Cross-domain resource sharing CORS

    The constraints on the network level are relaxed (cross-domain read operations): cross-domain access control is implemented to ensure secure cross-domain data transmission

Cross-domain resource sharing CORS

Why does CORS guarantee the security of cross-domain communication? Is it browser security or server security?

The previous development encountered CORS, are trying to do everything possible to eliminate the browser console error, successfully get the data

But I never thought: why does the server add a simple access-Control-allow-origin in the corresponding header to ensure communication security? Whose safety is that guaranteed

Cors is a set of mechanism of the browser. There is no such restriction on the communication between servers, so some people say that CORS is to protect the security of the browser. But what’s the point of this mechanism if the browser still gets the malicious data as long as the malicious site adds this response header to all of its resources?

In fact, the real significance of CORS is that the browser guarantees the success of malicious attacks, not its negligence.

The browser is also called user Agent. As a container, it makes [malicious sites + victims + target sites] have the opportunity to meet. If left unchecked, malicious sites can use browsers to attack.

For example, in the absence of CORS, how can a malicious website make use of the user login credentials stored in the browser cookie to initiate a transfer request to the fraud account:

  1. After a user logs into a target web site, the target web site returns a login credential (set-cookie = ‘loginToken= 1kQA23M6; domain=victim.com; path=/; sameSite:none; secure; ‘
  2. A user accidentally enters the malicious site evil.com and initiates a request through a script. Automatically originate a request. because the request’S URL victimization rules are matched, cookies are carried, and, with a simple hack, change the referer in the request header from evil.com to victim.com
  3. Eventually victim site was caught

This is a CSRF attack

Browsers are responsible for this attack.

Because if there is no browser, malicious sites even forge the request to modify the referer, but without user credentials, the server will not judge the request to be successful

So browsers enforce the cORS mechanism. The key is Origin. Origin cannot be victimized by user code, but only by the site it belongs to. It honestly tells a victim.com site that this request comes from a malicious site, Evil.com

The victim.com server then victimizes it to verify that evil.com does not victim.com recognize evil.com as a trusted source. In the example above, the cross-domain request will fail in the Preflight pre-check phase, the actual POST transfer request will not occur, and no loss will occur

Therefore, except for get and form POST requests with no side effects, there will be a pre-check process, and for simple requests without a pre-check process, if the CORS check is not passed. The request has been sent and the server is responding normally. But the browser decided it wasn’t safe and blocked it

To deal with

  1. A simple request

    • The request method is one of the following three: HEAD GET POST
    • The request header information does not exceed the following fields: Accept/ accept-language/content-language/last-event-id /Content-Type Only three values are allowed [application/x-www-form-encoded;multipart/form-data;text/plain]

    Send a CORS request directly and add an Origin field in the header information to indicate which source the request comes from

    The server decides whether or not to agree based on Origin: origin specifies a source that is not covered by the license, and the server returns a normal HTTP response.

    Browser checks access-Control-allow-Origin >> If the source Origin specified by the browser is not within the licensed range, an error is thrown, caught by the ONError callback function of Xmlhttprequest.

The error cannot be identified by the status code: the status code of the HTTP response might be 200.

  1. Non-simple request

    • The request method is PUT or DELETE
    • Or the content-type is application/json

    Before the official communication, the preflight browser asks the server whether the origin domain name of the current web page is allowed to use the access-Control-request-method header When they get a positive response, browsers send formal Xmlhttprequest requests and return errors if they don’t.

    Precheck request response: If the server denies the precheck request, it will return a normal HTTP response without any CORS related header fields

    Browser formal request and response: After a “precheck” request is passed, each request will have the same origin header field as a simple request, and the response will have an Access-Controll- Allow-Origin

Field Origin: indicates the protocol domain name port. Access-control-request-headers: indicates the header field sent by the browser for CORS requests. Access-control-request-methods: Indicates the HTP Methods used by the browser for CORS requests WithCredentials: Carrying HTTP authentication information, such as cookies, across domains. Access-control-allow-credentials: Whether cookies are allowed to be sent By default, cookies are not included in CORS requests. If this parameter is set to true, Cookies can be included in a cross-domain cookie access-Control-allow-Origin request: must, either the request is the value of the Origin field or an *, indicating that any cross-domain cookie can be accepted Access-control-expose-headers: This field is optional. In CORS requests, the getresponseHeader () method of the Xmlhttprequest object takes only six basic fields: Cache-contro1, Content-language, Content-ype, Expires, Last-Modified, Pragma. If you want to get other fields, you must specify them in access-contro1-expose-headers. The above example specifies that getres ponseHeader (‘ Foobar’) can return the value of the Foobar field. Access-control-max-age specifies the validity period of the precheck request, in seconds. During this period, no other precheck request is sent. Access-control-allow-methods indicates that all cross-domain request Methods supported by the server avoid multiple “precheck” requests. Access-control-allow-header Specifies all Header fields supported by the server, not limited to those requested by the browser in precheck. Application/X-www-form-encoded Image upload Multipart/form-datajson object Application /json Simple request

Cookie carrying across domains:

To send cookies to the server, specify the access-controll – allow-credentials field when the server agrees. On the other hand, the request header sets the Withcredentials attribute.

Note that access-controll – allow-origin cannot be set to an asterisk if cookies are to be sent. Origin must be specified explicitly

Form cross-domain

Forms have historically been able to make cross-domain requests even under more stringent SOP protocols. Content-type design does this for form-compatibility, and Cross-domain design for AJAX means that AJAX can post directly as long as the form can post.

Two major Web attacks

CSRF attack — Cross-site request Forgery

Two requirements for a CSRF attack

  1. Get the user’s login credentials at the target site
  2. Initiates a request to a target site under a malicious site

Why you can get user login credentials: Before the sameSite for cookies, cookies were bound by browsers to urls. That is, a browser from a evil.com site sends a request to a victim.com site :victim.com/transfer_to… Because a request’s host and path match a cookie’s retrieval rule (no matter who victim.com originates the request, a cookie will come with it), the request will come with the user’s login credentials from a victim.com site

How to initiate a request: Of course, the return site does not implant a malicious request on its own negative side, so it is common to open a malicious site from the target site and initiate a request on the malicious site

Email bug: David accidentally opened an email in Gmai and clicked a link in the email. A few days later, David found out that his domain name had been stolen. However, after a few twists and turns, David got his domain name back and figured out that his domain name was stolen because of the link he accidentally clicked. First, David initiates a request to log in to Gmail, and then the Gmail server returns some login status to David’s browser, including cookies, Session, etc. In this way, The Gmail is logged in to David’s browser. The hacker then enticed David to open his link through various means, such as hacker.com. On the hacker.com page, [the hacker wrote an email filter and set up a new email filtering feature through the HTTP Settings interface provided by Gmail All of David’s emails were forwarded to the hacker. All of this will be assumed to have been done by David himself because with David’s email, the hacker can go to the domain name service provider and reset David’s domain name account password, and once the password is reset, it can be transferred to the hacker’s account

type

Automatically initiates a POST request

Automatically initiates Get requests

Entice users to click on links

This way the attack can be launched at the target site

The prevention of

Let’s look at the reasons for this danger:

  1. You can reference any third party resource in your page,

  2. Let XmlhttpRequest and Fetch request resources across domains.

You can find preventive measures

  • Cookie – Samesite properties

  • Cers-origin Specifies the site from which the server validates the request

  • CSRF Token/ double cookie

Css. attack – never trust user input

The difference between XSS and CSRF is as follows :CSRF attacks do not need to inject malicious code into the user’s page. Only the vulnerability of the server and the login status of the user cannot be obtained.

Injecting malicious code into HTML files

harm

  1. Stealing Cookie information

    Malicious Javascript can obtain cookie information through “document. cookie” and send the data to the malicious server using Xmlhttprequest or Fetch plus CORS. Once the malicious server gets hold of the user’s Cookie information, it can simulate the user’s login on other computers and perform operations such as transferring money.

  2. Monitoring user behavior

    Malicious Javascript can use the ‘AddeventListener’ interface to listen for keyboard events, such as credit card information entered by the user, and send it to a malicious server. With that information, hackers can do a lot of illegal things

  3. Modify the DOM

    Used to trick users into entering information such as username and password

    Generate floating window ads within the page

type

Storage, reflection, and DOM based

Web servers do not store malicious scripts for reflective XSS attacks, which is different from stored XSS attacks

  1. Stored XSS attack

    First, the hacker takes advantage of the vulnerability of the site to submit a piece of malicious Javascript code to the database of the website. Then, the user requests a page containing malicious Javascript script to the website. When the user browses the page, the malicious script will upload the user’s Cookie information and other data to the server.

  2. Reflex XSS attack

    Malicious Javascript scripts are part of a request that a user sends to a web site, which then sends malicious Javascript scripts back to the user. When malicious Javascript scripts are executed in user pages, hackers can make use of the scripts to do some malicious operations. Hackers often induce users to click on these malicious links through QQ groups or emails

  3. DOM based XSS attack

    Hacker isn’t related to the page of the Web server through various means to inject malicious scripts user’s page, such as through the network to hijack the page change the contents of the HTML page in the process of transmission, the hijacked type many, have hijacked by WiF I routers, have hijacked by local malware, they have in common is in the transmission process or in the Web resources Users modify data on the Web page when using the page.

The prevention of

Both storage and reflection are handled by the server. These are server-side security vulnerabilities. DOM based is all done in the browser side, so it is a front-end security vulnerability

The process is to inject a malicious script into the browser, and then send user information to the malicious server through the malicious script

  1. Blocking malicious messages:

    • HttpOnly attribute

      Since many XSS attacks are designed to steal cookies, you can also use Httponly. Property to protect our cookies.

    • Adding a Verification Code

      Prevent scripts from posing as user submissions

  2. Prevent script injection:

    • Take full advantage of CSP

      Restrict the loading of resource files in other domains, so that even if hackers insert a Javascript file, the Javascript file cannot be loaded (do not submit data to third party domains, so that user data is not leaked; Prohibit execution of inline scripts and unauthorized scripts; It also provides a reporting mechanism, which helps us find XSS attacks as quickly as possible so that problems can be fixed as quickly as possible)

    • The server filters or transcodes the input script

      Original code:

      code:<script>alert('?? xss??? ')</script>Copy the code

      Filtering:

      Transcoding:

Take full advantage of CSP restrictions to load resource files in other domains, so that even if a hacker inserts a Javascript file, the Javascript file cannot be loaded

cookie

About cross-site and cross-domain/cross-source

Stations and domains are different

Same-site/cross-site is equivalent to first-party/third-party.

But “same-origin” and “cross-origin” in the browser’s same-origin policy (SOP) are different concepts

Same site: as long as the eTLD(valid top-level domain name)+1 of two urls is the same, no need to consider the protocol and port.

Valid top-level domains (Public Suffix/eTLD) Maintained by Mozilla, such as.com,.co. UK, and github

For example, taobao.com is a single station, www.taobao.com and www.baidu.com are cross-stations, www.taobao.com and static.taobao.com are co-stations;

.github. IO and b.github. IO are cross-site

Source: Indicates that the protocol, host name, and port of two urls are the same.

The same origin policy, as the security cornerstone of the browser, is strict in its “same origin” judgment. The same site does not necessarily have the same origin, and different sites must have different sources

attribute

  • Expire/max-age >> Life cycle

    If both Expires and max-age are present, max-age takes precedence

    Session cookie: The simplest, it is automatically deleted after the browser is closed, that is, it is only valid for the duration of the session. You do not need to specify the expiration time or set the validity period to max-age :Session

    It should regenerate and resend session cookies, even those that already exist. This technique helps prevent session fixation attacks, in which a third party can reuse a user’s session. >>

    Persistent cookie: Life cycle depends on expiration or max-age

    Expires: When a Cookie Expires, the date and time are only relevant to the client, not the server

    Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
    Copy the code

    Max-age: specifies the number of seconds that must pass before the Cookie expires.

    Set-Cookie: id=a3fWa; Max-Age=604800;
    Copy the code

    If the max-age attribute is positive, the browser persists it by writing it to the corresponding Cookie file. When the max-age attribute is negative, it indicates that the Cookie is only a session Cookie. When max-age is 0, the Cookie is deleted immediately.

  • Secure/HttpOnly >> Restrict access

    Secure: Only HTTPS is used for transmission to prevent man-in-the-middle attacks. SameSite= None is not supported for HTTP interfaces

    But even if Secure flags are set, sensitive information should not be transmitted through cookies because cookies are inherently insecure and Secure flags do not provide a real guarantee of security, for example, that someone with access to a client’s hard drive can read it.

    Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly >>
    Copy the code

    HTTP only: Persistent server-side session cookies do not need to be available to Javascript as long as they are of httpOnly type and cannot be retrieved from the console via document. Cookie and cannot be modified.

    Can prevent (XSS) attacks

  • Domain path/SameSite >> scope

    This determines when a cookie is automatically added to the request header by the browser and sent out

    Neither parent domain name nor parent path can be used

    Domain: specifies the URL that can carry the cookie.

    Set: If this parameter is not specified, the default value is the domain name of the web page where the cookie is set. The domain name cannot be other than the current domain name or its parent domain name. But it cannot be a public suffix

    For example, www.baidu.com, domain can be set to www.baidu.com or baidu.com, but not.com or.com.

    Most browsers currently follow the RFC6265 port and do not need to add a leading point when setting a Domain. Browsers that do not follow the specification need to add a leading dot, for example: Domain=,mozi11a.org >>

    Use: This domain name and its subdomains. If this domain name is not specified, origin is used by default, but the subdomain name is unavailable. If Domain is specified as Origin, subdomain names are included.

    For example, if you set Domain=mozilla.org, cookies are also included in the subdomain (e.g. Developer.mozilla.org). Therefore, specifying the Domain is less restrictive than omitting it

    Path: Identifies which paths under the host can accept cookies

    Settings: The default is the path to the request URI. The URL path must exist in the request URL. Path should end with a “/”

    Use: the path to the request URI by default; If the path value of the URI ends with a slash (/), it is directly set to the path value of the cookie. If the path value of the URI does not end in a slash (/), check whether the path value contains a slash (/). If there is a “/”, just intercept the last “/” and set it to the path value of the cookie.

If there is no “/”, set the path of the cookie to “/”. . Does not affect subpaths like domains do

  • SameSite >>

    Limiting third-party/cross-site cookies: Cookies can be prevented from being sent during cross-site requests, thus preventing cross-site request forgery attacks

    Modified: previously the beast id was None, Chrome80 will default to Lax.

    Impact: Form, IFrame, AJAX, and Image will not be sent, instead of sending three-party cookies across sites

    The values

    1. Strict allows only one party to request with cookies, that is, the browser will only send cookies that are requested by the same site, that is, the current web URL is exactly the same as the requested target URL

    2. Lax allows some third-party requests to carry cookies

    3. None sends cookies whether it is cross-site or not

    HTTP interfaces do not support SameSite= None; To add the SameSite= None attribute, the Cookie must also have the Secure attribute, indicating that the Cookie will only be sent under HTTPS

  • Name/Value: When using Javascript to manipulate cookies, pay attention to encodeURIComponent for Value

    Cookie prefix :Name is prefixed with __ Secure- or __Host. This parameter is applicable only to domains that use Secure connections (HTTPS). Secure is prefixed with __Host-. The value of the path attribute must be “/” (indicating the entire site) and cannot contain the domain attribute. // When the response comes from a secure domain (HTTPS), both can be accepted by the client

Set-Cookie: __Secure-ID=123; Secure; Domain=example.com Set-Cookie: __Host-ID=123; Secure; Set-cookie: __secure-id =1 // Set-cookie: __host-id =1; Setcookie: __host-id =1; Secure; Path=/; domain=example.comCopy the code
A vulnerable application on a subdomain can use the Domain attribute to set the cookie so that it can access that cookie on all other subdomains. This mechanism can be abused in session fixation attacks.Copy the code