10
头图
It is true that there are not many high-frequency knowledge points in one interview question, but there is indeed a magic introduction - browser security can connect 12 front-end hard-core knowledge points in series, let's take a look! ! !

I. Overview

1.1 Web page security

When it comes to web page security, what problems come to your mind?
  1. What is homology, what is homology strategy, and what is the performance of homology strategy?
  2. What security does the browser give away from the same-origin policy?
  3. What are the cross-domain solutions?
  4. How is JSONP implemented?
  5. What do you know about CORS?
  6. What are the common attack methods (XSS, CSRF) for web page security?

    1.2 Browser Network Security

    When it comes to browser network security, what questions come to your mind?
  7. What is a request message?
  8. What is a response message?
  9. Disadvantages of HTTP
  10. HTTPS basics
  11. HTTPS process

    1.3 Browser system security

    When it comes to browser system security, what problems do you think of?
  12. Security Sandbox

2. Web page security

2.1 Same Origin Policy

img

2.1.1 Homology

The essence of cross-domain means that two addresses have different origins. The opposite of different origins is not the same origin. The same origin means that if the protocol, domain name and port number of two URLs are the same, then they are two URLs of the same origin.
// 非同源:协议不同
http://www.baidu.com
https://www.baidu.com

// 同源:协议、域名、端口号都相同
http://www.baidu.com
http://www.baidu.com?query=1

2.1.2 Same Origin Policy

The same-origin policy is an important security policy that restricts how a document of one origin, or a loaded script it loads, can interact with resources from another origin. It is mainly to protect the security of user information and prevent malicious websites from stealing data.

2.1.3 Performance of the Same Origin Policy

Since the same-origin policy is the protection done by the browser at the web page level, which locations need to be protected at this level? To sum up, it mainly includes three levels: DOM level, data level, and network level.
  1. DOM level

The same-origin policy restricts the read and write operations of the current DOM object by JavaScript scripts from different origins.

  1. data plane

The same-origin policy restricts sites from different origins from reading data such as cookies, IndexedDB, and localStorage of the current site.

  1. network level

The same-origin policy restricts sending the site's data to sites of different origins through XMHttpRequest and other methods.

2.1.4 What security of the same-origin policy does the browser give away?

2.2 Cross-domain classification

The same-origin policy ensures the security of the browser, but if these three levels are strictly restricted, it will make the development work of programmers difficult, so the browser needs to make some concessions under the strictest restrictions of the same-origin policy. These concessions are more of a trade-off between security and convenience. In fact, the cross-domain method can be considered as a compromise method adopted by the browser under the premise of giving some security or complying with the browser's same-origin policy.

2.2.1 DOM level and data level classification

According to the same-origin policy, if two pages are from different sources, they cannot operate the DOM and access data with each other, but it is a common situation to communicate between two different source pages. A typical example is the communication between the iframe window and the parent window. As history goes by, there are various ways to implement communication between DOM layers, as follows:
  1. fragment identifier
The core principle of fragment identifier is to realize data transmission by monitoring the change of hash in url. The idea is really clever.
// 父页面parentHtml.html
<!DOCTYPE html>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>
        我是父页面
        <button id='btn'>父传给子</button>
        <iframe src="./childHtml.html" id="childHtmlId"></iframe>
    </body>
    <script>
        window.onhashchange = function() {
            console.log(decodeURIComponent(window.location.hash));
        };
        document.getElementById('btn').addEventListener('click', () => {
            const iframeDom = document.getElementById('childHtmlId');
            iframeDom.src += '#父传给子';
        });
    </script>
</html>
// 子页面childHtml.html
<!DOCTYPE html>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>
        我是子页面
        <button id='btn'>子传给父</button>
    </body>
    <script>
        window.onhashchange = function() {
            console.log(decodeURIComponent(window.location.hash));
        };

        document.getElementById('btn').addEventListener('click', () => {
            parent.location.href += '#子传给父';
        });
    </script>
</html>
  1. window.name
The browser window has the window.name property. The biggest feature of this property is that, no matter whether it is the same origin or not, as long as the previous web page sets this property in the same window, the latter web page can read it. If the communication between the parent page and the cross-domain child page needs to be realized, a child page with the same origin as the parent page is required as an intermediary to transmit the information in the cross-domain child page. (It’s so troublesome, it is strongly not recommended to use it, so I won’t write the corresponding code here)
  1. document.domain
document.domain is the host name of the server where the document is stored. It can be set to the current domain name or the superior domain name by manual setting. When the page with the same document.domain is on the server with the same domain name, if its domain name and port With the same number, cross-domain data access can be achieved.
  1. postMessage (highly recommended)
window.postMessage is a new cross-document communication API in HTML5. This API allows cross-window communication, regardless of whether the two windows are of the same origin.
// 父页面
<!DOCTYPE html>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>
        我是父页面
        <button id='btn'>父传给子</button>
        <iframe src="http://127.0.0.1:5500/024/childHtml.html" id="childHtmlId"></iframe>
    </body>
    <script>
        window.addEventListener('message', function(event) {
            console.log('父页面接收到信息', event.data);
        });
        document.getElementById('btn').addEventListener('click', () => {
            const iframeDom = document.getElementById('childHtmlId');
            iframeDom.contentWindow.postMessage('我是执鸢者1', 'http://127.0.0.1:5500/024/childHtml1.html');
        });
    </script>
</html>
// 子页面
<!DOCTYPE html>
<html lang="zh">
    <head>
        <title></title>
    </head>
    <body>
        我是子页面
        <button id='btn'>子传给父</button>
    </body>
    <script>
        window.addEventListener('message', function(event) {
            console.log('子页面接收到信息', event.data);
        });

        document.getElementById('btn').addEventListener('click', () => {
            parent.postMessage('我是执鸢者2', 'http://127.0.0.1:5500/024/parentHtml1.html');
        });
    </script>
</html>

2.2.2 Network layer

According to the same-origin policy, browsers do not allow XMLHttpRequest objects to access resources from different sites by default, which will greatly restrict productivity. Therefore, it is necessary to break this restriction and achieve cross-domain access to resources. There are three main methods that are widely used at present (Note: The specific code is not given in this article, and there will be a special Hundred Questions to elaborate in detail later):
2.2.2.1 Implemented by proxy
The same-origin policy is a policy formulated by the browser for security, so there is no such restriction on the server side, so that we can make requests to the same-origin server, and then proxy to the final server through the same-origin server, so as to achieve Purpose of cross-origin request. For example, through Nginx, Node middleware, etc.
2.2.2.2 JSONP method
JSONP is a technology that uses script elements to achieve cross-domain. It does not use the XMLHttpRequest object. Its ability to achieve cross-domain is mainly due to the two characteristics of script:

(1) The src attribute can access any URL resource and is not restricted by the same-origin policy;

(2) If the accessed resource contains JavaScript code, it will be automatically executed after downloading.

Let's implement JSONP together
  1. Globally mount a function that receives data;
  2. Create a script tag and mount the corresponding handler functions on the onload and onerror events of its tag;
  3. Mount the script tag to the page and initiate a request to the server;
  4. The server receives the passed parameters, and then outputs the callback function and data in the form of calls;
  5. When script elements receive affected script code, they are automatically executed.
function createScript(url, charset) {
    const script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    charset && script.setAttribute('charset', charset);
    script.setAttribute('src', url);
    script.async = true;
    return script;
}

function jsonp(url, onsuccess, onerror, charset) {
    const hash = Math.random().toString().slice(2);
    window['jsonp' + hash] = function (data) {
        if (onsuccess && typeof(onsuccess) === 'function') {
            onsuccess(data);
        }
    }

    const script = createScript(url + '?callback=jsonp' + hash, charset);

    // 监听加载成功的事件,获取数据,这个位置用了两个事件onload和onreadystatechange是为了兼容IE,因为IE9之前不支持onload事件,只支持onreadystatechange事件
    script.onload = script.onreadystatechange = function() {
        //若不存在readyState事件则证明不是IE浏览器,可以直接执行,若是的话,必须等到状态变为loaded或complete才可以执行
        if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
            script.onload = script.onreadystatechange = null;
            // 移除该script的DOM对象
            if (script.parentNode) {
                script.parentNode.removeChild(script);
            }

            // 删除函数或变量
            window['jsonp' + hash] = null;
        }
    };

    script.onerror = function() {
        if (onerror && typeof(onerror) === 'function') {
            onerror();
        }
    }

    // 添加标签,发送请求
    document.getElementsByTagName('head')[0].appendChild(script);
}
2.2.2.3 CORS method

Cross-Origin Resource Sharing (CORS), this mechanism can perform cross-domain access control, so that cross-domain data transmission can be carried out securely. (A way to implement a cross-domain request, where the html access URL is http://127.0.0.1:8009 ; the server listening port is: 8010)
1. The overall process

The communication process of CORS is completed automatically by the browser without user participation. The core point is the server. As long as the server implements the CORS interface, cross-source communication can be realized. Although it is done automatically by the browser, the browser is actually divided into simple requests and non-simple requests according to the different fields at the time of the request. The following is a brief introduction to the two.

  1. simple request
    (1) Definition
It is a simple request as long as the following two conditions are met:

1) The request method is one of the following three methods: HEAD, GET, POST;
2) HTTP header information does not exceed the following fields: Accept, Accept-Language, Content-Language, Last-Event-ID, Content-Type (the value of which is application/x-www-form-urlencoded, multipart/form- one of the three data, text/plain).

(2) Process

image-20210703182139849.png

The entire flow of a simple request can be boiled down to the following steps:

1) The browser sends a CORS request directly. Specifically, an Origin field is added to the header information. This field is used to indicate which source (protocol + domain name + port) the request comes from. The server decides whether to agree to the request according to this value. ;
2) When the server receives the request, it determines whether the specified source is within the permitted range according to Origin.
3) If it is not within the scope of permission, the server will return a normal HTTP response. The browser finds that the header information of the response does not contain the Access-Control-Allow-Origin field, and knows that an error has occurred, thus throwing an error and being XML onerror Callback function capture. (Note: Due to the normal response, the status code is 200, so the error cannot be identified by the status code)
4) If the domain name specified by Origin is within the permitted scope, there will be several more header fields (Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Expose-Header, etc.) in the response returned by the server. .

(3) Key fields

1) Access-Control-Allow-Origin

Required field, the value is either the value of the Origin field of the request, or a * (indicating that requests for any domain name are accepted).

2)Access-Control-Allow-Credentials

Optional field whose value is a boolean value indicating whether cookies are allowed to be sent. The default is to not send the cookie value. When set to true, it means that the server explicitly allows the cookie to be included in the request and sent to the server. (Note: Two points should be paid attention to when sending cookies: on the one hand, the withCredentials attribute needs to be set in the Ajax request; on the other hand, the Access-Control-Allow-Origin cannot be set to *, and a clear domain name consistent with the requested webpage needs to be specified)

3)Access-Control-Expose-Header

Optional field. When a CORS request is made, the getResponseHeader() method of the XMLHttpRequest object can only get 6 basic fields (Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma), if you want to get other Fields must be specified in Access-Control-Expose-Header.

  1. non-simple request

(1) Definition

Not a simple request is a non-simple request. A non-simple request is a request that has special requirements for the server, such as the request method is PUT or Delete, or the type of the Content-Type field is application/json.

(2) Process

image-20210703211106355.png

A non-simple request is more complicated than a simple request. Before a formal request is initiated, a pre-check request is made, and the result of the pre-check request is used to decide whether to carry out subsequent formal communication.

1) The browser initiates a preflight request, the request method of the request is options, and the request is used to ask;
2) After the server receives the "preflight" request, it checks the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers fields, confirms that cross-origin requests are allowed, and then responds.
3) If the browser rejects the "preflight" request, it will return a normal HTTP response, but without any CORS-related header fields, then the browser will determine that the server does not agree with the preflight request and trigger an error;
4) If the browser passes the "preflight" request, each normal CORS request of the browser will be the same as a simple request, there will be an Origin header information field, and the server's response will also have an Access-Control-Allow-Origin header information field;

(3) Key fields

1)Access-Control-Request-Method

Required field to list which HTTP methods will be used by the browser for CORS requests.

2)Access-Control-Request-Headers

This field is a comma-separated string that specifies additional header fields that browser CORS requests will send.

3)Access-Control-Allow-Methods

Required field, the value is a comma-separated string to indicate all cross-domain request methods supported by the server.

4)Access-Control-Allow-Headers

The value is a comma-separated string indicating all header fields supported by the server.

5)Access-Control-Max-Age

The validity period used to request the preflight request, in seconds.

  1. Simple implementation

(1) HTML page content

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>test CORS</title>
    </head>
    <body>
        CORS
        <script src="https://code.bdstatic.com/npm/axios@0.20.0/dist/axios.min.js"></script>
        <script>
            axios('http://127.0.0.1:8010', {
                method: 'get'
            }).then(console.log)
        </script>
    </body>
</html>

(2) Server-side code

const express = require('express');

const app = express();

app.get('/', (req, res) => {
    console.log('get请求收到了!!!');
    res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8009');
    res.send('get请求已经被处理');
})
app.listen(8010, () => {
    console.log('8010 is listening')
});

2.3 Two attack methods

2.3.1 XSS

2.3.1.1 Definitions
Cross Site Scripting (XSS; Cross Site Scripting) refers to a method in which hackers inject malicious scripts into HTML files or DOM, so as to use the injected malicious scripts to attack users when users browse pages.
2.3.1.2 Impact
The main effects of XSS attacks are: stealing cookie information, monitoring user behavior, modifying the DOM, and generating floating window advertisements in the page.

image-20210801203139567.png

2.3.1.3 Injection method
XSS injection methods include stored XSS attacks, reflected XSS attacks, and DOM-based XSS attacks.

image-20210801203233465.png

2.3.1.4 What is prone to XSS attack
There are two main locations where XSS attacks are prone to occur:
  1. Data comes into a web application from an unreliable link
  2. Dynamic content that is not filtered out malicious code is sent to web users

image-20210801203615476.png

2.3.1.5 How to prevent XSS attacks
There are three main ways to prevent XSS attacks:
  1. The server filters or transcodes the input script;
  2. Make full use of CSP;
  3. Use the HttpOnly attribute

image-20210801203703649.png

2.3.2 CSRF

2.3.2.1 Definitions
Cross-site request forgery (CSRF; Cross-site request forgery) refers to a hacker enticing a user to open a hacker's website. In the hacker's website, a cross-site request initiated by the user's login status
2.3.2.2 Making an impact
The main impacts are as follows:

image-20210801204412612.png

2.3.2.3 Attack principle

clipboard.png

2.3.2.4 Prerequisites for an attack
There are three main prerequisites for an attack:

image-20210801204503978.png

2.3.2.5 Attack Mode
There are three main ways to implement CSRF attacks:
  1. Automatically initiate a Get request;
  2. Automatically initiate a POST request;
  3. lure users to click links
    image-20210801204525665.png
2.3.2.6 Strategies to Prevent CSRF Attacks
There are three main strategies to prevent CSRF attacks:
  1. Make full use of the SameSite attribute of cookies;
  2. Verify the origin site of the request on the server side;
  3. CSRF Token。

image-20210801204552365.png

3. Browser Security

3.1 Request message

The HTTP request message mainly includes: the request line, the request header and the requested data (entity). Let's take a look at its composition:

3.1.1 Request Line

The request line contains: method field, URI field and protocol version
  1. method field

    GET (request to get content);

    POST (submit form);

    HEAD (request resource response message header);

    PUT (transfer file);

    DELETE (request to delete the resource pointed to by the URI);

    OPTIONS (query methods supported by the resource specified for the request URI);

    TRACE (trace request through the path);

    CONNECT (requires a tunneling protocol to connect to the proxy).

  2. URI field
  3. Protocol version

    Refers to the HTTP protocol version of the request, such as HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2.0, HTTP/3.0.

3.1.2 Request headers

Common headers are: Connection header (connection management), Host header (specify the host of the requested resource), Range header (byte range of the request entity), User-Agent header (contains the requesting user information), Accept header (preferred media type), Accept-Language (preferred natural language)

clipboard.png

3.1.3 Request entity

The body of the HTTP request is mainly used for submitting form scenarios. In fact, the body of the http request is relatively free, as long as the body sent by the browser is approved by the server. Some common body formats are:
  • application/json
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/xml

Using the HTML form tag to submit the generated html request will generate the data format of application/x-www-form-urlencoded by default. When a file is uploaded, it will use multipart/form-data.

3.2 Response message

The HTTP response message is divided into three parts: the status line, the header line and the response body.

3.2.1 Status Line

The status line is composed of version, status code and reason statement. Let's take a look at some commonly used status codes.
  1. 1xx: This type of status code indicates that the request has been accepted and needs to continue processing. This type of response is a temporary response, containing only the status line and some optional response header information, and terminated with a blank line
  2. 2xx: This type of status code indicates that the request has been successfully received, understood and accepted by the server

200---OK/The request has been processed normally;

204---The request was processed successfully, but no resources were returned;

206---Indicates that the client made a range request, and the server successfully executed this part of the GET request;

  1. 3xx: These status codes indicate that further action from the client is required to complete the request. Usually, these status codes are used for redirection, and the subsequent request address (redirection target) is indicated in the Location field of this response

301---Request Permanent Redirect The requested resource has been permanently moved to a new location, and any future references to this resource SHOULD use one of the several URIs returned in this response. If possible, clients with link editing capabilities should automatically modify the requested address to the address returned from the server.

302---Request for temporary redirection Since such redirection is temporary, the client should continue to send subsequent requests to the original address. This response is cacheable only if specified in Cache-Control or Expires.

303---Indicates that since there is another URI for the resource corresponding to the request, the GET method should be used to obtain the requested resource.

304---Indicates that the client sends a conditional request (meaning that the request message using the GET method contains any of If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since first), the server allows the request to access the resource, but the conditions are not met

307---Temporary redirect, the same meaning as 302, but 307 will follow browser standards and will not change from POST to GET

  1. 4xx: This type of status code represents an error in the client class

400---The client request has a syntax error

401---The current request requires user authentication.

403---The server has understood the request, but refused to execute it. Unlike a 401 response, authentication doesn't help

404---The request failed, the requested resource was not found on the server.

405---The request method specified in the request line cannot be used to request the corresponding resource.

  1. 5xx: Error in server class

500---The server encountered an unexpected condition that prevented it from completing the processing of the request.

501---The server does not support a function required by the current request. When the server does not recognize the requested method and cannot support its request for any resource.

503---The server is currently unable to process the request due to temporary server maintenance or overload.

505---The server does not support, or refuses to support, the HTTP version used in the request.

3.2.2 Response header

Common response headers are: Date (response time), Via (intermediate node that the message passes through), Last-Modified (last modification time), Etag (entity tag related to this entity), Connection (connection status), Accept-Ranges (range types that the server can receive), Content-Type (resource types)

clipboard.png

3.2.3 Response body

The response body is the message body of the response. If it is pure data, it will return pure data. If the request is an HTML page, then the returned HTML code, if it is JS, is JS code, etc.

3.2 Disadvantages of HTTP

It is precisely because HTTP has a series of shortcomings that HTTPS appears. So what are the shortcomings of HTTP? How to solve it? Below is a brief overview

1. HTTP communication uses plaintext (not encrypted), and the content may be eavesdropped;

TCP/IP is a network that can be eavesdropped: according to the working mechanism of the TCP/IP protocol family, communication content can be spied on on all lines. Therefore, encryption processing is required to prevent eavesdropping. The encrypted objects are as follows:

(1) Encryption of communication

The HTTP communication content is encrypted by being used in combination with SSL (Secure Socket Layer, Secure Socket Layer) or TLS (Transport Layer Security, Transport Layer Security). After establishing a secure communication line with SSL, HTTP communication can be performed over this line. HTTP combined with SSL is called HTTPS, and in this way the entire communication line is encrypted.

(2) Encryption of content

Since there is no encryption mechanism in the HTTP protocol, the content itself transmitted by the HTTP protocol is encrypted. In order to achieve effective content encryption, the premise is that the client and server are required to have both encryption and decryption mechanisms. This method is different from encrypting the entire communication line, and the content still has the risk of being tampered with.

2. The identity of the communicating party is not verified, so it may be disguised;

(1) Anyone can initiate a request

The HTTP protocol will return a response no matter who sends the request, so if the communication party is not confirmed, there will be the following hidden dangers:

1) It is impossible to determine whether the web server that the request is sent to the target is the one that returns the response according to the real intention, it may be a disguised web server;

2) It is impossible to determine whether the client to which the response is returned is the client that received the response according to its true intention, and it may be a disguised client;

3) It is impossible to determine whether the communicating party has access rights, because some web servers store important information, and only want to send the communication rights to specific users;

4) It is impossible to determine where and who the request is from, even if it is a meaningless request, it will be accepted in full, and it is impossible to prevent Dos attacks (Denial of Service, denial of service attacks) under massive requests.

(2) Identify the certificate of the opponent

SSL not only provides encryption, but also uses a means called a certificate, which can be used to identify the communicating parties. Certificates are issued by trusted third-party authorities to prove that the server and client actually exist. The use of certificates to prove that the communication party is the expected server also reduces the risk of personal information leakage for the user. In addition, the client can complete the confirmation of personal identity by holding the certificate, and can also be used for the authentication of the Web site.

3. The integrity of the message cannot be proven, so it may have been tampered with.

During the period after the request or response is sent until the other party receives it, even if the content of the request or response has been tampered with, there is no way to know. An attack in which an attacker intercepts and tampers with the content of a request or response is called a Man-in-the-Middle attack. Relying on HTTP alone to ensure integrity is very difficult and relies on HTTPS to achieve this. SSL provides authentication and encryption processing and digest functions.

3.3 HTTPS basic knowledge points

HTTPS is not a new protocol at the application layer. It’s just that the HTTP communication interface is replaced by SSL (Secure Socket Layer) and TLS (Transport Layer Security) protocols. In short, HTTP+communication encryption+certificate+integrity protection constitutes HTTPS, which is HTTP in the shell of TLS/SSL. .

image-20210801193609652.png

  1. TLS/SSL function

The TLS/SSL protocol uses the client certificates and CA root certificates of both communicating parties, allowing client/server applications to communicate in a way that cannot be eavesdropped, and establishing a secure and trusted communication channel between the communicating parties.

  1. Symmetric and asymmetric encryption (public key encryption)

(1) Symmetric encryption

Symmetric encryption refers to the key used to encrypt data, which is the same as the key used to decrypt data. The advantages and disadvantages of using this method are:

1) Advantages: encryption and decryption are usually more efficient and faster. Symmetric encryption is usually used when the message sender needs to encrypt a large amount of data. The algorithm is open, the calculation amount is small, the encryption speed is fast, and the encryption efficiency is high.

2) Disadvantages: The data sender and the data receiver need to negotiate, share the same key, and ensure that the key is not leaked to others. In addition, for multiple individuals with data exchange requirements, a key needs to be allocated and maintained between them, and the cost of this is basically unacceptable.

(2) Asymmetric encryption

Asymmetric encryption refers to the key (public key) used to encrypt data, which is different from the key (private key) used to decrypt data. The public key is the public key, which can be found by anyone; the private key is the non-public key, which is generally held by the administrator of the website. There is a certain connection between the public key and the private key: in short, data encrypted by the public key can only be decrypted by the private key; data encrypted by the private key can only be decrypted by the public key.

  1. Problems with asymmetric encryption (public key encryption)

Asymmetric encryption actually has some problems that need to be solved, mainly including the following two: how to obtain the public key and one-way security of data transmission.

  1. How to obtain the public key in asymmetric encryption

In order to obtain the public key, two important concepts need to be involved: certificate, CA (Certificate Authority), and its main uses are as follows:

(1) Certificate: It can be temporarily understood as the ID card of the website. This ID contains a lot of information, including the public key mentioned above. When visiting the corresponding website, he will send the certificate to the browser;

(2) CA: It is used to issue certificates, and the certificate comes from a CA (Certificate Authority).

  1. Possible problems with the certificate

(1) The certificate is forged: it is not issued by CA at all

(2) The certificate has been tampered with: for example, the public key of the XX website is replaced

  1. How to prevent counterfeiting of certificates

Digital signatures and digests are very critical weapons for certificate anti-counterfeiting. "Digest" is a fixed-length string calculated by hash algorithm for the content of transmission. Then, the digest is encrypted with the private key of the CA, and the result obtained after encryption is the "digital signature" (plaintext --> hash operation --> digest --> private key encryption --> digital signature); digital signature The signature can only be decrypted by the CA's public key. The certificate contains: the name of the authority that issued the certificate (CA), the digital signature of the certificate content itself (encrypted with the CA private key), the public key of the certificate holder, the hash algorithm used for the certificate signature, etc.

(1) For a completely fake certificate

In this case the certificate is checked

1) The certificate issuing authority is forged: the browser does not recognize it and directly considers it to be a dangerous certificate

2) The certificate issuing authority does exist, so according to the CA name, find the corresponding built-in CA root certificate and CA's public key. Use the CA's public key to decrypt the digest of the forged certificate, and find that it cannot be solved. considered dangerous certificate

(2) Tampered certificate

1) Check the certificate and find the corresponding CA root certificate and CA's public key according to the CA name.

2) Use the CA's public key to decrypt the digital signature of the certificate to obtain the corresponding certificate digest AA

3) Calculate the digest BB of the current certificate according to the hash algorithm used in the certificate signature

4) Comparing AA and BB, found inconsistent --> judged to be a dangerous certificate

  1. HTTPS issues

(1) Compared with plain text, encrypted communication consumes more CPU and memory resources

1) Since HTTPS also needs to encrypt and decrypt both the server and the client, it will consume hardware resources such as CPU and memory.

2) Compared with HTTP communication, the SSL communication part consumes network resources, and the SSL communication part, because the communication needs to be processed, the time is extended. There are two types of SSL slowness, one refers to slow communication; the other refers to slow processing speed due to a large consumption of resources such as CPU and memory.

(2) There is an expense for purchasing a certificate.

3.4 HTTPS process

1. The client initiates an HTTPS request

2. The server responds and issues a certificate (public key certificate)

3. The client checks the certificate, and if the certificate is OK, it generates a random value, and then encrypts the random value with the certificate (public key).

4. Send the random value encrypted by the public key to the server (asymmetric encryption), and then the communication between the client and the server can be encrypted and decrypted through this random value.

5. After the server decrypts with the private key, it obtains the random value sent by the client, and then encrypts the content symmetrically through this value.

6. Later data transmission is encrypted and decrypted based on the random value.

img

Note: The picture comes from ( https://blog.csdn.net/qq_33840251/article/details/91358884 )

4. Browser system security

Reference content

browser working principle and practice_Li <br/>
Yifeng Cross-domain resource sharing CORS detailed explanation


执鸢者
1.7k 声望2.5k 粉丝

摸摸头,编程使我快乐。