The front end must know the computer network knowledge series article:
- DNS server and cross-domain problems
- Layered models of computer networks
- IP address and MAC address
- Computer networking knowledge that the front end must know – (cross domain, proxy, local storage)
- Computer network knowledge the front-end must know — (TCP)
- What the front end must know about computer networking — (HTTP)
- Computer network knowledge that the front-end must know — (XSS, CSRF, and HTTPS)
Why is HTTP not secure
- Possible eavesdropping:
- HTTP does not provide encryption. HTTP packets are sent in plain text
- Because the Internet is made up of network facilities that connect all parts of the world, all data sent and received through some device can be intercepted or accessed. (For example, Wireshark, a well-known packet capture tool, is used to capture packets.) Even if the packets are encrypted, the packets can be detected. However, it is difficult or impossible to crack the packets
- Authentication problem
- Unable to confirm that the server you are sending to is the real target server (probably disguised)
- It is not possible to determine whether the client returned is the one received with true intent (possibly a disguised client)
- It is impossible to determine whether the other party is communicating has access permission. Some important information on the Web server will be accepted even if it is meaningless request only to be sent to a specific user. Denial of Service (DoS) attacks on massive requests cannot be prevented.
- May be tampered with
- A man-in-the-middle attack (MITM) in which an attacker intercepts and modifies a request or response in transit.
XSS attacks
XSS, or Cross Site Scripting, is a Chinese name for cross-site Scripting. The emphasis of cross-site Scripting is not on “cross-site”, but on “scripts”. The main method of most XSS attacks is to embed a piece of REMOTE or third-party domain JS code, which is actually executed under the scope of the target website.
Reflective XSS (non-persistent XSS)
Features: Like a mirror reflection, the browser emits a URL with XSS and the server reflects it back
- When the browser makes a request, the XSS code appears in the request URL and is submitted to the server as a parameter,
- The server parses and responds, and the response contains the XSS code,
- Finally, the browser parses and executes.
Example: Form submission
//test.html
<body>
<textarea name="txt" id="txt" cols="80" rows="10">
<button type="button" id="test"</button> <script> vartest = document.querySelector('#test')
test.addEventListener('click'.function () {
var url = `/test?test=${txt.value}Var XHR = new XMLHttpRequest() xhr.onreadyStatechange =function () {
if (xhr.readyState === 4) {
if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { // 3. The client parses JSON and executes var STR = json.parse (xhr.responsetext).test var node =${str}`
document.body.insertAdjacentHTML('beforeend', node)
} else {
console.log('error', xhr.responseText)
}
}
}
xhr.open('GET', url, true)
xhr.send(null)
}, false)
</script>
</body>
Copy the code
//server.js
var express = require('express');
var router = express.Router();
router.get('/test'.function(req, res, next) {// 2. The server parses to JSON and responds with res.json({test: req.query.test
})
})
Copy the code
Now we add an attack-purpose img tag to the textarea:
Storage XSS (Persistent XSS)
Features: The hacker sends XSS code to the server and then spreads it through the server
- The hacker sends XSS code to the server (whether database, memory, file system, etc.).
- Other people will bring XSS code with them when they request the page.
Case study: The most typical is the message board XSS.
- The hacker submitted a message containing XSS code to the database.
- When the target user queries messages, the contents of those messages are parsed and loaded from the server.
- The browser finds XSS code and executes it as normal HTML and JS parsing. An XSS attack occurs.
The DOM model XSS
Features: DOM XSS code does not require direct participation in the server-side parsing response, but is entirely browser-side DOM parsing.
- The browser code includes eval, new Function, and so on to execute string content
- Example of embedding a string that can execute XSS code in an executed string:
test.addEventListener('click'.function () {
var node = window.eval(txt.value)
window.alert(node)
}, false<img SRC = "<img SRC ='null' onerror='alert(123)' />
Copy the code
XSS hazards
- Steal cookies through Document. cookie
- Using JS or CSS to break the normal structure and style of the page
- Traffic hijacking (locating to another page by accessing a segment with window.location.href)
- Dos attack: The use of reasonable client requests to occupy too many server resources, so that legitimate users cannot get a response from the server.
- Use iframe, Frame, XMLHttpRequest, or the above Flash method to perform administrative actions as the (attacked) user, or perform general operations such as tweeting, adding friends, and sending private messages.
- By taking advantage of the fact that the domain that can be attacked is trusted by other domains, the trusted source requests some operations that are not normally allowed, such as improper voting activities.
XSS defenses
As can be seen from THE XSS attack, the data input by the user cannot be directly saved to the server as is, and some data processing is required:
- Filter dangerous DOM nodes. For example, script has the ability to execute scripts, IMG has the ability to display ads and pornographic pictures, link and style has the ability to change styles, and iframe, frame and other element nodes have embedded pages.
- Filter dangerous attribute nodes. Such as on-, style, SRC, href, etc
- Setting httpOnly for cookies, but also prevents the foreground from manipulating cookies, is not recommended.
CSRF
Cross-site Request Forgery (CSRF), an attacker steals your identity and sends malicious requests on your behalf.
- Log in to trusted website A and generate cookies locally.
- Visit dangerous site B without logging out of trusted site A.
- A dangerous site sends A request to A trusted site and carries A locally generated Cookie from trusted site A (interface to the same domain with the same browser)
Case study:
// Phishing site, use the user's cookie for permission transfer <body onload="steal()">
<iframe name="steal" display="none">     <form method="POST"name="transfer"  action="http://www.myBank.com/Transfer.php">         <inputtype="hidden" name="toBankId" value="11">             <inputtype="hidden" name="money" value="1000">         </form>     </iframe> </body>Copy the code
The harm of CSRF
- Tampering with user data on target websites;
- Steal user privacy data;
- As the auxiliary attack tactics of other attack vectors;
- Propagate the CSRF worm.
CSRF defense
- Verification code, because the verification code must be sent to the browser on the trusted website, and the forged website and the trusted website are not the same source, so there is no way to obtain the session sent by the trusted website, so the verification code cannot be forged.
- Refer, identifies the source of the currently requested page. Bogus sites can be tampered with as trusted site sources without insurance
- Token, because it is a token sent to the client through the service and stored in the localstorage of the browser, token cannot be tampered with easily due to the same-origin policy and token verification rules.
Token and JWT
The characteristics of the Token
- Session is transmitted through cookies, and each visit to the website will be automatically carried, so there are security problems and wasted bandwidth. Token is stored in localStorage and can be selectively sent to the background due to the same-origin policy, which has high security
- The server must have a SessionQ list. Tokens do not need to store the list. They share a key and can be shared by sending tokens
- After the session is destroyed, it will disappear from the list. It is difficult to cancel the token. There is no list to prove that the token cannot be used, so a blacklist is used to mark it
JWT
JWT is a way to implement a token. A token is divided into three parts, with “between”. Number for separation:
- Header: The header is base64
- Payload: The payload is a string of base64 characters
- Signature: visa hader+ Payload is encrypted by the key
EXP:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflK xwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- JWT principle:
letJWT = {decode(token,secret){let [header,content,sign] = token.split('. ');
let h = JSON.parse(this.formBase64ToString(header));
let c = JSON.parse(this.formBase64ToString(content));
if(sign ! == this.sign([header,content].join('. '),secret){
throw new Error ('Not allowd')}returnC}, // encode(payload,secret){let header = this.toBase64(JSON.stringify({'type':'JWT',alg:'HS25' }));
let content = this.toBase64(JSON.stringify(payload));
let sign = this.sign([header,content].join('. '),secret);
return [header,content,sign].jion('. '); } // convert toBase64 toBase64(STR){return Buffer.from(str).toString('base64'); } // sign(STR,secret){return require('crypto').createHmac('sha256',secret).update(str);
}
}
module.exports = jwt;
Copy the code
- JWT background:
const express = require('express');
const bodyParser = require('body-parser')
const jwt = require('jwt-simple')
const userList=[
{id:1,username:'kbz',password:'123456'}
]
const SECRET = 'MISS';
letapp = express(); app.use(bodyParser.json); // Since the request header contains the Authorization field, this is the same as setting the name transmission parameter in the cross-domain. Please refer to: / / the front must understand the knowledge of computer networks - (cross-domain, agency, local storage) / / https://juejin.cn/post/6844903686775242760 app. Use (function(req,res,next){
res.setHeader('Access-Control-Allow-Origin'."*");
res.setHeader('Access-Control-Allow-Headers'."Content-Type,Authorization");
res.setHeader('Access-Control-Allow-Methods'."GET,POST,OPTIONS");
if(req.method === 'OPTIONS'){ res.end(); } next(); }) // Send token app.post('/login'.function(req,res,next){
let user = req.body;
userList.find(person=>(person.id === user.id));
if(user){
jwt.encode({
id:user.id,
username:user.username
},SECRET)
res.json({
code:0,
data:{
token
}
})
}else{
res.json({
code:1,
data:'User does not exist'// Protocol header Authorization: false token app.get('/order'.function(req,res,next){
let authorization = req.headers['authorization'];
if(authorization){
let token = authorization.split(' ') [1]; try{let user = jwt.decode(token,SECRET);
req.user = user;
}catch(e){
res.status(401).send('Not Allowed')}}else{
res.status(401).send('Not Allowed')
}
})
app.listen(3000);
Copy the code
- JWT at the front desk
//login.html
<input type="text" id='username' class="form-control">
<input type="text" id='password' class="form-control">
<span onclick='login()'></span>
<scrpipt>
axios.post('/user').then(res=>{
localStorage.setItem('token',res.data.data.token)
location.href='/order'
})
</script>
//order.html
<scrpipt>
axios.interceptors.request.use(function(config){
let token = localStorage.getItem('token');
if(token){
config.headers.Authorization = 'Bearer '+ token
}
})
axios.get('/order').then(res=>{
console.log(res);
})
</script>
Copy the code
HTTPS(HTTP+TLS/SSL)
TLS/SSL
TLS/SSL function implementation mainly relies on three basic algorithms:
- Asymmetric encryption implements identity authentication and key negotiation
- Symmetric encryption algorithm uses the negotiated key to encrypt data
- The hash function verifies the integrity of information against the insecurity of key disclosure
Based on the characteristics of the three algorithms, the basic working mode of TLS is as follows:
- The client communicates with the server using asymmetric encryption, authenticates and negotiates the key used for symmetric encryption
- The symmetric encryption algorithm uses the negotiated key to encrypt and communicate the information and the information abstract. Different nodes use different symmetric keys to ensure that the information can only be obtained by both parties
Symmetric encryption
- The same key can be used for information encryption and decryption. Only by mastering the key can information be obtained and information eavesdropping can be prevented. The communication mode is 1 to 1(the previous message indicates that the key is not leaked).
- The algorithm is open, the computation is small, the encryption speed is fast, the encryption efficiency is high
- Both the client and server need to maintain a large number of keys, which is costly to maintain
- Because the security level of each client and server is different, the key is easy to be leaked. As both parties of a transaction use the same key, the security is not guaranteed
Asymmetric encryption
- Characteristics of asymmetric encryption algorithms Encryption and decryption use different keys, the client uses the public key to encrypt the requested content, the server uses the private key to decrypt the content, and vice versa.
- The encryption and decryption speed is relatively slow. Asymmetric encryption takes some time to encrypt and decrypt data, which reduces the data transmission efficiency
- The public key is public. Therefore, hackers can use the public key to decrypt the information encrypted by the private key
- The public key does not contain information about the server. Asymmetric encryption algorithms cannot ensure the validity of the server identity, and there is a risk of man in the middle attack. The public key sent by the server to the client may be intercepted and tampered with by a man in the process of transmission
Integrity verification algorithm
- Common functions include MD5, SHA1, and SHA256. This type of function is characterized by one-way irreversible function, very sensitive to input, and fixed output length. Any modification of data will change the result of the hash function to prevent information tampering and verify the integrity of data
- In the process of information transmission, the hash function cannot independently achieve information tamper-proof, because in plaintext transmission, the middleman can modify the information and recalculate the information summary, so the transmitted information and the information summary need to be encrypted
Key agreement
The authentication
Because asymmetric encryption does not ensure the legitimacy of the server’s identity, there is a risk of man-in-the-middle attacks, such as:
- Client C communicates with server S, and the intermediate node M intercepts the communication between them
- Node M computes itself to generate a pair of public key pub_M and private key pri_M
- When C requests the public key from S, M sends its public key pub_M to C
- The data encrypted by C using the public key pub_M can be decrypted by M, because M has the corresponding private key pri_M, while C cannot determine the identity of the server according to the public key information, so a “trusted” encryption connection is established between C and M
- A legitimate connection is established between the intermediate node M and server S, so THAT M can fully master the communication between C and S, and M can eavesdrop and tamper with information.
- The Server submits the public key, organization information, and personal information (domain name) to the third-party CA and applies for authentication.
- CA verifies the authenticity of the information provided by the applicant through various online and offline means, such as whether the organization exists, whether the enterprise is legal, whether it has the ownership of the domain name, etc.
- If the information is approved, CA will issue a certificate to the applicant. The certificate contains the following information: the public key of the applicant, the organization information and personal information of the applicant, the information about the issuing authority (CA), the validity time, and the serial number of the certificate, and contains a signature. The algorithm of signature generation is as follows: first, hash function is used to calculate the summary of the plaintext information, then CA’s private key is used to encrypt the summary, ciphertext is signature;
- When the Client sends a request to the Server, the Server returns a certificate file.
- The Client reads the plaintext information in the certificate and uses the same hash function to calculate the summary of the information. Then, the Client decrypts the signature data using the public key of the CORRESPONDING CA and compares the summary of the information with that of the certificate. If the summary of the information is the same, the certificate is valid.
- The client also verifies the domain name and validity period of the certificate. The client has the certificate information (including the public key) of the trusted CA built in. If the CA is not trusted, the corresponding CA certificate cannot be found and the certificate is judged to be invalid.
- The client certificate is built into the host once it is produced
Set up an HTTPS server
Set up an HTTPS server
conclusion
The front end must understand the computer network knowledge series has all ended, welcome everyone to study and discuss!