preface
Year after year job-hopping season, ready to start from the interview content to see the front-end related knowledge points, aimed at exploring a series of knowledge points, ability within the scope of in-depth exploration. Focus on practice, for the primary front-end and prepare for the interview of the students, strive to attach actual code examples and related questions ~ series name is used [bald broken front-end] — because the circle of consensus, technology and hair is proportional to the amount. 😄 hope we can break the bottleneck as soon as possible ~
There are too many articles about interview questions or certain knowledge points. Here I just want to record my personal summary in the form of code warehouse and output the article. After all, theory is not equal to practice
Related series of articles of the same type:
- Bald front end interviews – HTTP && HTTPS
- Bald front end interview – Web security related
- Bald front End Interview — A summary of cross-field practice
- More bald rags series
The same-origin policy
Two urls are homologous if they have the same protocol, domain name, and port. 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 restricts how documents or scripts loaded from the same source can interact with resources from another source. This is an important security mechanism for isolating potentially malicious files.
XSS (Cross Site Scripting)
XSS(Cross-site Scripting) is a kind of attack with a wide range of damage in the front-end domain.
The abbreviation for cross-site Stripting should be CSS, but to avoid confusion with the ABBREVIATION of the CSS concept, Cross is represented by an X in the shape of a Cross.
The attack duration can be divided into persistent and non – persistent
The attack mode can be divided into reflection type, storage type and DOM-XSS.
I don’t see any specific differences between DOM-XSS and reflective XSS, so I’m going to refer to both as non-persistent reflective XSS because of their similarity.
Reflex XSS attack – non-persistent
A user submits a request containing malicious code to the Web server. When the Web server receives the request, the malicious code is reflected back to the browser. This is a reflective XSS attack. In real life, hackers often induce users to click on these malicious links through QQ groups or emails.
Let’s give a quick Demo:
// We can start a service app.get('/hello', (req, res) => {
const { name } = req.query;
res.send(`<h1>Hello, ${name}</h1>`);
});
Copy the code
The /hello path takes a name argument and responds to the page for display. The effect looks like this:
If we write a malicious script for the parameters, then the page will execute, well, you might think, it’s just a popover, why attack. But we have to think, a popover = a piece of JS code, since it is JS code, then the attacker can put a script, such as get your cookie information, account information, etc.
But I think there’s a problem here. How do I define this? To be honest, this is not pure front-end security, my example uses Nodejs. In fact, this is often the case with PHP/JSP. For example, what if it’s a jump to the front page?
<script>
function getUrlParam (name) {
const reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)");
const r = window.location.search.substr(1).match(reg);
if(r ! = null)return unescape(r[2]); return null;
}
window.onload = function() {
const name = getUrlParam('name');
document.getElementById('name').innerHTML = name;
}
</script>
Copy the code
This code is pure front-end to get the URL parameter and add it to the page:
As you can see, the browser doesn’t do that, but of course if you’re using innerHTML you’re rendering the string as an HTML tag, whereas if you’re using innerText you’re processing it as a string.
But that’s not going to happen either. So when we’re talking about XSS as the front end, there’s more or less a backend correlation involved.
Attack direction: Browser (URL) -> Background -> single user
Non-persistent reflection XSS attack, the attack direction is to input THE URL, the background accepts the attack code and responds the code back to the front end, which means that the attack is only effective to the user who opens the attack link, the page is closed, the impact of the attack does not exist, so it is not persistent.
Stored XSS attack
Exploit the vulnerability to submit malicious JavaScript code, such as filling in a script in the input and Textare fields. This script will be executed when the user saves and then opens the preview page. Then upload user-related information (such as cookies) to the server of the other party.
Attack direction: Browser -> Background -> Database -> Background -> Users (all users)
Persistent storage TYPE XSS attack, this attack will attack code stored in the database, the page closed, if there is no security measures, then all users of the system, as long as enter the attack page, will be attacked, data does not disappear, the attack is permanently effective.
The simplest example is form storage. For example, in a blog system, an attacker enters a malicious comment, and as soon as the article is displayed, the comment is rendered to attack the user who is visiting it. In order to provide a simple code demonstration, I have written a rough Demo here, after all, not all scenarios are suitable for imaginary code, many have to be practical.
- The storage type needs to be stored in a database
I’m going to use the file stream to read and write the db.txt file on the back end.
/** * Save user comments to db.txt */ app.post('/comment', (req, res) => {
fs.writeFile(
path.resolve(__dirname, './db.txt'),
`${req.body.comment}\n`,
{ flag: 'a', encoding: 'utf-8' },
(err) => {
if (err) console.log(err);
res.status(200).json({
message: 'success'
});
});
});
Copy the code
- Front-end data entry
async function postComment() {
const comment = document.getElementById('comment').value;
const data = {
author: 'luffy',
comment
};
const res = await fetch('http://127.0.0.1:3000/comment', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const resData = await res.json();
// do something
}
Copy the code
The final effect is as follows:
As you can see why the stored type is persistent, after the above code runs, the attack code is stored in the database and the attack script is executed wherever and whenever anyone accesses the link.
Prevention strategies
-
Set sensitive information such as cookies to httpOnly and prohibit Javascript from obtaining document.cookie.
-
Strictly check all input, especially on the server side, and filter out any illegal input, such as mobile phone numbers that must be numeric.
-
Clean and filter out unnecessary HTML tags such as
-
Escape single quotes, double quotes, Angle brackets and other special characters, you can use HTML encode encoding or filter out these special characters.
The front end verifies the validity of the input, and the back end verifies the security of the input. As mentioned above, in fact, it doesn’t matter whether the front end does it or not. Malicious script code will not execute, but the back end (Java, Node.js, PHP, etc.) should do this.
CRSF Cross Site Request Forgery
Lure the user to open the hacker’s site, in the hacker’s site, using the user’s login status to initiate a cross-site request. There are three requirements for launching a CSRF attack:
- The target site must have CSRF vulnerability;
- The user must have logged in to the target site, and keep the login status of the site on the browser;
- Requires the user to open a third party site, such as a hacker’s site, etc.
CRSF has a lot of requirements. It not only needs to open the attack site when the user logs in, but also needs the attack site to have a detailed understanding of the relevant content of the website that the user logs in (including API and parameters), so it is not very good to demonstrate the code, so I will not simulate the scene here.
For example, in the blog website with CSRF vulnerability, http://blog.com?postId=111&delete=1 means to delete the user’s article with ID =111. Of course, this condition is that the user has logged in to the website, and then the attacker creates a new page. The page content is an image . When the user opens the page, the deletion operation is performed, which is impossible to guard against, and even more deadly is the bank account transfer operation.
Prevention strategies
Verify the source of the request – very important
If it is a sensitive request, you can determine the Origin and Referer of the request. Referer is a field in the HTTP request header that records the source address of the HTTP request, while the O rigin attribute only contains the domain name information, not the specific URL path. This is a major difference between Origin and Referer. 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.
Take advantage of cookiesSameSite
attribute
The SameSite option usually has Strict, Lax, and None values.
-
The value of SameSite is Strict, so the browser completely disallows third-party cookies.
-
Lax is a little looser. In the cross-site scenario, cookies are carried both by opening a link from a third-party site and by submitting a Get form from a third-party site. However, if you use the Post method in a third-party site, or if you load urls through tags like IMG or IFrame, these scenarios do not carry cookies.
-
If None is used, Cookie data is sent in any case
Using token Authentication
All requests are authenticated using tokens. For details about why token is used, you can check out how token works.
Other security-related scenarios
Feel the interview often asked is XSS and CSRF these two, as for the following, do not write the Demo, a simple understanding of it can, if the interviewer smelly shameless asked, we are modest, say do not know the way to consult, also can 😄.
Click on the hijacked
- Tricking the user into clicking a seemingly innocuous button (which is actually clicking a button in a transparent IFrame).
- Monitor mouse movement events so that the danger button is always under the mouse.
- Use HTML5 drag and drop techniques to perform sensitive operations (such as deploy key).
Click hijacking is generally a sensitive operation using captcha is the easiest solution.
Prevention strategies:
- The server adds the X-frame-options response header, an HTTP response header to defend against clickjacking attacks nested with iframe, so that the browser blocks the rendering of the embedded web page.
- JS determines whether the domain name of the top-level viewport is consistent with the domain name of this page. If the domain name is not consistent, operation is not allowed.
top.location.hostname === self.location.hostname
; - Sensitive operations use more complex steps (captcha, enter the project name to delete).
window.opener
Security issues
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 page of the phishing site, such as jump to a fake shopping page, when back to the shopping page, it is difficult to find that the address of the shopping site has been modified, this time your account may be phishing. Prevention strategies:
Solution Set rel properties
<a href="https://xxxx" rel="noopener noreferrer"< a > > outside the chainCopy 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.
-
The outer chain can be opened by widow.open.
Related topics
1. What is XSS attack?
2. What is a CSRF attack?
3. How to prevent front-end attacks?
conclusion
To be honest, from the perspective of interview, it is easy to understand and grasp, but in summary, the feeling is that security problems occur in the front end (whether URL or form), and the solution is in the background.
Web security related knowledge we may not care about a lot in the actual use of writing, generally there are problems, or the company’s security department found that the problem was raised, will think to solve. In fact, Web security for front-end development is really very important, now look back at the previous code, feel a chill back, as if it is not very safe ah, hurry back to reinforce ~ 😄
Bald broken series code address