During the interview, you will be asked about some safety knowledge, so sort it out in depth and correct any mistakes you make. Give it a thumbs up if you think it helps
HTTPS Security
http
HTTP: hypertext transfer protocol (HTTP) is a request – and response-based, stateless, connectionless application-layer protocol, usually based on TCP/IP protocol data transfer.
HTTP in the process of data transmission, all data is in plain text transmission, relatively simple, fast, flexible.
Some solutions to HTTP statelessness:
- Through the Cookie/Session technique
- HTTP/1.1 Keep-alive (HTTP keep-alive) : The TCP Connection is kept as long as either end does not explicitly request the disconnection. Connection: keep-alive in the request header indicates that a persistent Connection is used.
https
HTTPS encrypts data, authenticates the identity of the peer, and protects data integrity over SSL or TLS based on the HTTP protocol.
Difference between HTTP and HTTPS
HTTPS = HTTP + SSL / TLS
-
security
HTTP data is transmitted in plaintext and is not encrypted, resulting in poor security. HTTPS encrypts data during transmission, ensuring high security.
-
Response speed
HTTPS is slower than HTTP because of the added layer of security, which makes the connection more complex and requires more data to be exchanged.
-
The cost of
HTTPS requires a CA certificate. A more powerful certificate costs more.
-
Server resources
Since HTTPS is an HTTP protocol based on SSL/TLS, it consumes more server resources than HTTP, and websites with a large number of visitors need to invest more costs.
-
The port number
The HTTP port number is 80 and the HTTPS port number is 443.
How does HTTPS ensure communication security
The entire HTTPS communication process can be divided into two phases: certificate verification and data transmission. The data transmission phase can be divided into asymmetric encryption and symmetric encryption.
The whole process of HTTPS communication:
1. The client requests the HTTPS url and connects to port 443 of the server.
2. The HTTPS server must have a digital CA certificate.
A certificate is an e-certificate issued by a dedicated digital Certificate Authority (CA) after a very rigorous review. A private key and a public key are generated when a certificate is issued. The private key is kept by the server itself and cannot be disclosed. The public key is attached to the information of the certificate and can be made public. The certificate itself also comes with an electronic signature of the certificate, which verifies the integrity and authenticity of the certificate and prevents tampering.
3. The server responds to the client’s request and sends the certificate to the client.
(The certificate contains the public key and a lot of other information, such as certificate authority information, company information, and certificate expiration date.)
4. The client parses the certificate and authenticates it.
(If the certificate is not issued by a trusted authority, the domain name in the certificate is different from the actual domain name, or the certificate has expired, a warning is displayed to the visitor and the visitor can choose whether to continue the communication.)
If there is nothing wrong with the certificate, the client retrieves the server’s public key A from the server certificate. The client also generates A random code KEY and encrypts it using the public KEY A.
5. The client sends the encrypted random KEY to the server as the symmetric encryption KEY.
6. After receiving the random KEY, the server uses the private KEY B to decrypt it.
After these steps, the client and server finally establish a secure connection.
7. The server uses the random KEY to symmetrically encrypt data and sends the data to the client. The client uses the same KEY to decrypt data. Both parties use symmetric encryption to transmit all data.
Data transfer stage
HTTPS uses encryption algorithms to solve data transmission security problems. Specifically, it is a mixture of symmetric encryption and asymmetric encryption.
Symmetric encryption — data
Both encryption and decryption use the same key. Common symmetric encryption algorithms include DES, 3DES, and AES.
Advantages: Open algorithm, small amount of calculation, fast encryption speed, high encryption efficiency, suitable for encrypting large data.
Disadvantages:
- Because both sides of the transaction need to use the same key, the key must be transmitted. However, the key cannot be intercepted during the transmission. Therefore, the security of symmetric encryption cannot be guaranteed.
- Each pair of users needs to use a unique key unknown to others every time they use a symmetric encryption algorithm, which makes the number of keys owned by both the sender and the receiver increase dramatically, and key management becomes a burden for both parties.
During data transmission, encrypted data becomes random garbled characters. Even if intercepted by a third party, the data cannot be decrypted without a key, ensuring data security.
But there is a fatal problem. Since both parties want to use the same key, it must be passed from one party to the other before the data can be transmitted, in which case the key can be intercepted and the encrypted data can be easily decrypted.
So how do you ensure that the key is secure during transmission? This is where asymmetric encryption comes in.
Asymmetric encryption — key
Encryption and decryption require two different keys: a public key and a private key. The common asymmetric encryption algorithm is RSA algorithm.
The public key and private key are a pair. If the public key is used to encrypt data, only the corresponding private key can be used to decrypt data. If data is encrypted with a private key, only the corresponding public key can be used to decrypt it.
The basic process of asymmetric encryption algorithm to realize confidential information exchange is as follows:
Party A generates a pair of keys and discloses one of them as a public key; After obtaining the public key, Party B uses the public key to encrypt the confidential information before sending it to Party A; Party A then uses its own private key to decrypt the encrypted information.
Advantages: The algorithm is open, encryption and decryption use different keys, the private key does not need to be transmitted over the network, high security.
Disadvantages: the amount of calculation is relatively large, so the encryption and decryption speed is much slower than symmetric encryption.
In the process of KEY transmission, the client generates a random code (represented by a KEY, which is the KEY used for symmetric encryption by both parties) after obtaining the public KEY of the server. The client encrypts the KEY with the public KEY and sends it to the server. The server decrypts the KEY with the private KEY. In this way, the two parties have the same KEY, and then the two parties use the KEY to symmetrically encrypt the interactive data.
In asymmetric encryption transmission, even if a third party obtains the public KEY and encrypted KEY, it cannot crack the KEY without the private KEY (the private KEY is stored on the server and the risk of disclosure is minimal), thus ensuring the security of the following symmetric encryption data.
SSL/TLS and SSL/TLS handshake
SSL and TLS provide identification and authentication channels for communication parties to ensure communication confidentiality and data integrity.
SSL (Secure Socket Layer), a protocol Layer between reliable connection-oriented network Layer protocols and application Layer protocols.
TLS :(Transport Layer Security).
The relationship between the two: The latest version of TLS is a new protocol developed by Internet Engineering Task Force (IETF). It is based on the SSL 3.0 protocol specification and is the subsequent version of SSL 3.0. There are significant differences between TLS and SSL3.0, mainly in the encryption algorithms they support, so TLS and SSL3.0 are not interoperable.
TLS three-way handshake details
During the TLS handshake, the communication parties exchange messages to verify each other, confirm each other, and establish the encryption algorithm and session key they want to use.
-
“Client Hello” message: The client sends a “Client Hello” message to the server to initiate a handshake request. This message contains TLS versions supported by the client and password combinations for the server to select, as well as a “Client Random” random string.
-
“Server Hello” message: The server responds to the client with a “Server Hello” message containing a digital certificate, a password combination selected by the server, and a “Server Random” random string.
-
Authentication: The client authenticates the certificate sent by the server to ensure the identity of the peer. The authentication process can be divided into the following steps:
- Checking digital signatures
- Validation certificate chain
- Check the validity of the certificate
- Check the revocation status of the certificate (revocation means the certificate is invalid)
-
“Premaster secret” string: The client sends the server another random string “premaster secret”, which is encrypted by the server’s public key and can only be decrypted by the corresponding private key.
-
Private key decryption Premaster key: The server uses the private key to decrypt “premaster secret”.
-
Generating a shared KEY: Both the client and server use Client Random, Server Random, and Premaster Secret, and use the same algorithm to generate the same shared KEY.
-
Ready: The client sends a FINISHED message encrypted with the shared KEY.
-
Ready: The server sends a FINISHED message encrypted with the shared KEY.
-
Secure communication: The handshake is completed and the two parties communicate securely using symmetric encryption.
Is HTTPS necessarily secure?
-
HTTPS protocol encryption scope is also relatively limited, in hacker attacks, denial of service attacks, server hijacking and other aspects of almost no role
-
The credit chain system of SSL certificates is not secure, especially if some countries can control the CA root certificate, and man-in-the-middle attacks are just as feasible
A man-in-the-middle attack (MITM attack) is when a hacker intercepts and tampers with communication data in a network. It is divided into passive MITM and active MITM. Passive MITM only steals communication data without modifying it, while active MITM can not only steal data, but also tamper with communication data. The most common man-in-the-middle attacks occur on public wifi or public routes.
How can I ensure that the public key delivered by the server to the client is a real public key, not a forged public key by a middleman?
The verification of certificates during HTTPS handshake is to identify the validity and uniqueness of certificates. Therefore, man-in-the-middle attacks do not exist in HTTPS strictly. The prerequisite for the existence of man-in-the-middle attacks is that certificates are not strictly verified or certificates are forged artificially.
Procedure for verifying certificate security:
After receiving the certificate, the client uses the public key of the locally configured authority to decrypt the certificate to obtain the public key of the server and the digital signature of the certificate. The digital signature is decrypted by the CA public key to obtain the certificate information summary.
Then use the method of certificate signature to calculate the information summary of the current certificate and compare it with the received information summary. If the information summary is the same, it indicates that the certificate must be issued by the server and has not been tampered by the middleman. Because intermediary, although have authority’s public key, can resolve the certificate content is tampered with, but tampering after broker needs the certificate to encryption, but there is no authority to the private key middlemen, cannot be encrypted, forced encryption will only lead to the client cannot decrypt, if middlemen to modify the certificate, will lead to certificate content and signature does not match.
Can third-party attackers make their certificates display information that is also a server?
(Disguised server configuration) Obviously this is not possible, because when a third-party attacker goes to CA to seek authentication, CA will require it to provide whoIS information of the domain name, domain name management email, etc., to prove that you are the owner of the server domain name. A third party attacker can’t provide that information so he can’t fool the CA that he owns the domain name of the server.
reference
Segmentfault.com/a/119000002…
Blog.csdn.net/xiaoming100…
OAuth2.0
Of a hole
Browser Same-origin Policy
If the protocol, domain name, and port number of two urls are the same, they are the same. Browsers have same-origin restriction, which is a security feature of browsers. Client scripts from different sources cannot read or write resources from each other without explicit authorization. The same origin policy ensures user information security and prevents malicious websites from stealing data.
The browser also specifies that submitting forms is not restricted by the same origin policy.
If not homologous, there are three behaviors that are restricted.
- Cookie, LocalStorage, and indexDB cannot be read
- Document.domain shared cookie (LocalStorage and IndexDB cannot use this method to avoid the same origin policy)
- DOM not available
- Set document.domain to retrieve DOM
- Ajax requests cannot be sent
- jsonp
- The Websocket protocol does not implement the same origin policy
- CORS cross-domain resource sharing
- Setup server proxy
Reference:
www.ruanyifeng.com/blog/2016/0… Browser same origin policy and its circumvention method
Cookie and Session and token
HTTP is stateless and does not remember users. Even if you have just logged into the system with an account and password, the next time you make a request, your identity will be verified again. Common authentication methods include session and token, while cookie serves as a data storage carrier.
session
Session is for the server, there is no Session for the client. Session means that the server adds the client connection mark when establishing a connection with the client, and finally the server software (Apache, Tomcat, JBoss) converts it into a temporary Cookie and sends it to the client. When the client makes the first request, the server will check whether it carries the Session (temporary Cookie). If it does not, it will add the Session. If it does, it will take out the Session to do relevant operations.
The certification process
- You have logged in to the server using the account and password
- The server generates a session object and the corresponding session ID to record user session information and returns the session ID to the browser. The browser can use cookies, localStorage, or sessionStorage to store the sessionid
- The next time the browser sends a request to the server, it carries the sessionID
- After receiving the sessionID, the server checks whether the corresponding session object exists. If yes, the authentication succeeds and data is returned. If no, the server requires re-login
Session objects are stored on the server. After the client logs in, each request can be authenticated with the sessionID. However, if the server is distributed or clustered, the user logs in on server A and has to log in again the next time the request is sent to another server B. This is unacceptable. The solution is as follows:
Session retention: Ensures that each client accesses the same server. Session replication: Replicates all session objects to all servers. Session sharing: stores all sessions on the same server
Either way, there is an additional cost and, as the number of users increases, the server will create a large number of session objects, which is a burden on the server.
token
Token is the authentication method of user identity, we usually call it: token. The simplest tokens consist of: UID (the unique identity of the user), time(the timestamp of the current time), and sign(the signature, which is a hexadecimal string compressed by hashing the first few digits of the token plus salt to prevent malicious third parties from concatenating token requests to the server). You can also put unchanging parameters into tokens to avoid multiple library checks.
The certification process
- You have logged in to the server using the account and password
- The server uses a specific algorithm to generate a signed token that is stored in the database and returned to the client
- After receiving the token, the client stores it locally and carries the token with each subsequent request
- After receiving the request, the server retrieves the token and compares it with the token in the database
- If the two tokens have the same value, the user is currently logged in
- If there is no token value, the login has not been completed or failed
- If the two tokens are different, the original login status is invalid and the user can log in again
The Session status is stored on the server, and the client has only the Session ID. The Token state is stored on the client. At this point, the pressure to use token servers does not increase dramatically as the number of users increases.
cookie
A Cookie is a text file stored in the browser’s directory on the computer that takes effect in RAM while the browser is running (such Cookies are called Session Cookies). Once the user logs out of the site or server, Cookies can be stored on the user’s local hard disk (called Persistent Cookies).
Cookies are not an authentication mechanism. They are in the same class as localStorage and sessionStorage. Since cookies are automatically attached to each HTTP request, they are often used to store user authentication data. The CSRF problem can be solved by not storing user authentication information in cookies.
Refer to the link
Juejin. Cn/post / 694488…
XSS
Cross Site Scripting is a Scripting attack that exploits vulnerabilities in web development and allows users to load and execute malicious scripts by injecting unsafe scripts into web pages.
Common scenarios
-
Using scripts to steal the user’s Cookie value, the victim unknowingly helps the attacker to send malicious requests.
-
Some sites with user comment function. For example, attacker A writes an attack code in the message, which is sent to the server without escape filtering. When user B visits the web page, user B obtains this code and executes it directly, which results in an XSS attack.
type
-
DOM xss
XSS is triggered by browser-side DOM parsing without the direct involvement of server parsing.
-
Reflective XSS (non-persistent XSS)
It is characterized by its immediacy. It can be attacked by cleverly constructing a URL with malicious code and then guiding the user to click to visit without having to store it in the server.
For example, a page that puts the parameter content above the URL into the web page without filtering the Query directly inserts the query parameter content into the DOM. If the query content is a malicious script, or something like q=
-
Stored XSS (Persistence XSS)
If the comment area of a website is not filtered, then we can submit the malicious script to the background server to receive and store it in the way of comments, and then any user who visits the comment page will execute this code, so as to achieve the purpose of attack.
Because it is stored in a database, it is persistent. And there is no need to induce users to click malicious links, easier to achieve the purpose of attack, so the harm is stronger.
How to prevent
-
Set the HttpOnly
Set the HttpOnly attribute in cookie to disallow Javascript from obtaining document.cookie.
-
filter
-
Input inspection
It is used to check the input format, for example, email address, phone number, user name, and password.
Filtering checks are required on both the front and back ends because an attacker may bypass the normal input process and send Settings directly to the server using the relevant interface.
-
HtmlEncode
Clean and filter out unnecessary HTML tags. When the user enters , the final save result is < script> window.location.href=” http://www.baidu.com” < /script> When rendered, the browser converts these characters into text rather than executable code.
-
JavaScriptEncode
Backslashes the following characters.
-
-
CSP content security policy
Web sites set content-security-Policy in the HTTP header to tell the browser what is authorized and what needs to be prohibited. The essence of CSP is whitelisting. The developer clearly tells the client which external resources can be loaded and executed, which is equivalent to providing a whitelist. Its implementation and execution are all done by the browser, and the developer only needs to provide the configuration. More can be found in this blog at blog.csdn.net/qq_37943295…
Refer to the link
Juejin. Cn/post / 684490…
CSRF
CRSF Cross Site Request Forgery is the act of posing as a user to initiate a Request (without the user’s knowledge), or to accomplish something that the user does not want (such as modifying the user’s information, deleting initial comments, etc.).
A CSRF attack exploits the fact that the browser does not know whether the user making the request is the real user. That is, simple authentication can only guarantee that the request was sent from a user’s browser, but not that the request itself was voluntarily made by the user.
Attack process
1. The victim logs in to the target website A;
2. The victim was somehow exposed to a link to the malicious website B;
3. The victim clicks the link to visit website B, js code in website B executes, and secretly sends A request to target website A;
4. Since the victim had logged in to website A, the request carried the relevant cookie credentials of website A, and finally the request was successfully executed;
During this process, due to cross-domain restrictions of browsers, malicious websites can initiate requests to target websites in the following two ways:
-
For GET requests, the IMG tag link is not subject to the cross-domain constraints of the browser, so the request can be initiated directly as IMG.
-
For POST requests, you can use the CORS method.
How to prevent
CSRF attacks can forge user information, but such requests are made from third-party websites and do not pass through the website itself. Therefore, there is no way for the client to prevent the request from being initiated by code, but a key step is that malicious request initiation requires identity credentials in order for the request to be approved and executed.
-
SameSite – Strict attributes
Set the samesite-strict attribute to forbid third-party websites from carrying cookies.
-
The Referer field
Since CSRF is initiated by third-party websites, if we can determine which websites the server receives each request from, we can filter the requests from those websites with security risks and reduce the risk of attack.
Referer and Origin are one of the header fields in an HTTP request that indicate which page the request is linked from. The Origin attribute only contains domain name information and does not contain a specific URL path, which is a major difference between Origin and Referer.
The background server can check whether the field is from its own website to prevent third-party websites from launching CSRF attacks. The server’s policy is to judge Origin first, and if the request header does not contain the Origin attribute, then determine whether to use the Referer value according to the actual situation.
-
Verification code
A feature of CSRF is that the forged request will not pass through website A, so we can add the verification means of website A, such as graphic verification code or SMS verification code, so that only the request that passes the verification can be considered legitimate.
However, this scheme has two limitations, one is to increase the development cost, the other is to reduce the user experience.
-
token
The CSRF can only bring the Cookie when the browser initiates a request, but cannot manipulate the Cookie to obtain the Token and add it to the parameter or request header of the HTTP request. Therefore, the Token can prevent CSRF attacks.
The specific process of this scheme was mentioned in the previous section about tokens, so you can check it out.
Mysql injection
SQL injection refers to the modification of the original URL of the Web page, the form field or the input parameters of the data package into SQL statements, which are passed to the Web server, and then to the database server to execute the database command. When the Web application developer directly transfers the data entered by the user to the database without filtering or verifying it, the spliced SQL may be executed to obtain the database information and claim rights, which is called SQL injection attack.
How to prevent
-
Input validation
Check the validity of user input, limit user input to special symbols as much as possible, and ensure that the input content contains only valid data. Data checking should be performed on both the client and server sides. Server-side authentication is performed to compensate for the weak security of client-side authentication mechanisms.
-
Parameterize SQL or stored procedures to execute all queries
Never use dynamically assembled SQL statements. You can use parameterized SQL or directly use stored procedures for data query access.
-
Access control
Never use database connections with administrator privileges. Use separate, limited database connections for each application.
-
Error message handling
Application exception information should provide as little information as possible. It is better to use custom error information to wrap the original error information and store the exception information in a separate table.
Interface operation hijacking attack
Interface operation hijacking attack is a web session attack based on visual spoofing. It overwrites an invisible box (IFrame) on the visible control of the page, making the user mistakenly believe that he is operating the visible box, and thus induces the user to tamper with data and steal information without his/her knowledge.
There are three main types of interface hijacking attacks:
Click hijacking. Drag and drop hijacking. 3. Touchscreen hijacking.
Common scenarios
-
Hackers create a web page using iframe to contain the target website;
-
Hide the target website, the user can not detect the existence of the target website;
-
Construct web pages, mutate users to click on specific buttons;
-
Users unknowingly click buttons that trigger commands to execute malicious web pages.
How to prevent
-
X-FRAME-OPTIONS
X-frame-options HTTP response headers are flags used to indicate to the browser whether to allow a page to be displayed in < FRAME >,
-
JS determines whether the domain name of the top-level viewport is the same as the domain name of the page. If the domain name is not the same, the operation is not allowed, but it can be easily cracked.
function locationTop(){
if(top.location ! = self.location) { top.location = self.location;return false;
}
return true;
}
locationTop();
/ / crack:
// Put the code in the top-level window
var location = document.location;
/ / or
var location = "";
Copy the code
XS-Leaks
Cross-station leakage. Xs-leaks exploits the mechanism of querying HTTP caches to infer information about current users from resource caches.
Because the browser cache resources are not limited by domain names, all sites share the cache resources, which can be used to detect whether a user has visited a particular site: a malicious site can infer a user’s browsing history by making a request for a particular resource and determining whether the resource came from the cache. For example, if I request an image of the Nuggets LOGO on my website, if I determine that the image is from cache, THEN I know that the user has visited the Nuggets website.
Xs-leaks works in a similar way, using the same mechanism used to query HTTP caches to retrieve user data by detecting whether a query has a result. The main process of XS-LEAKS attack is as follows:
-
Deletes cached resources for a specific site.
// You can clear the browser's cache of the image by making a POST request. FETCH POST http://xxx.com/user/helloWorld.jpg Copy the code
-
Force the browser to refresh the site or re-enter the site.
Make a stealthier request to visit the original site via iframe or , then simply request the resource again to determine whether it is from the cache, and if so, infer the corresponding information.
-
Check that the browser caches the resource deleted in (1).
How do you tell if a request is coming from the cache?
One way to determine if the image is from the cache is to read the width and height attributes of img:
const img = new Image(); img.onload = () = > { // If img is not from the cache, the actual WITDH value is not available until onload is triggered after the image is loaded console.log(img.width); } img.src = 'http://xxx.com/user/helloWorld.jpg'; If there is a cache, the witDH value of the image can be read immediately here, otherwise 0 will be printed console.log(img.width); Copy the code
At this point an XS-Leaks attack is complete. We can also request some links with permissions to determine whether the user has a privileged identity of a site, etc.
How to prevent
Xs-leaks attacks from third-party websites by making requests to targeted sites, much like CSRF. CSRF defenses can also make XS-LEAKS less dangerous by invalidating authenticated requests for access. Of course, sometimes this attack does not require authentication to achieve the purpose, so CSRF’s defense is not perfect against, so it is necessary to increase the browser level cache partition.
- Set the SameSite
- Token
- Browsers support cache partitioning
window.opener
Window.opener indicates who opens the parent form of the current form page.
For example, if A new page B is opened with A tag of A with target=”_blank” on page A, the window.opener value on page B is the window object of page A.
Generally speaking, open the same origin (same domain name) page, there is no problem.
However, for external links that cross domains, there is a risk of being phished. For example, you are browsing a shopping website and open an external link from the current page. On the opened external page, you can rewrite the address of the source site through window.opener. Take advantage of this, rewrite the source site to the phishing site page, such as jump to a fake shopping page, it is difficult to find that the shopping site’s address has been modified, this time your account may be phishing.
How to prevent
- Setting rel Properties
<a href="https://xxxx" rel="noopener noreferrer">Outside the chain<a>
Copy the code
Rel =”noopener noreferrer” specifies that new pages are prohibited from passing the address of the source page. The window.opener value is null for pages opened by links with this property set.
Replace the external link with an internal redirect to the internal address and then the server redirect to the external link.
Refer to the link
Juejin. Cn/post / 684490…