In the Internet era, data security and personal privacy has always been a concern of everyone. How to protect our applications and data? The previous article has analyzed the various means of attack, now we have a look at how to defend! πŸ€—

preface

By the end of this article you will be rewarded

  • βœ… Most of the defense measures against XSS (Cross-site Scripting) attacks
  • βœ… Most defense measures against Cross Site Request Forgery (CSRF) attacks
  • βœ… Injected Injection attack defense measures
  • βœ… Other defense measures and security suggestions for individual users

XSS defenses

Defense scheme

1. Never trust user submissions 🚫, input filtering should be done

For example: email, phone number, username, password… Such as input format check, users can only input in accordance with the specified format.

Remove DOM attributes uploaded by users, such as onError, and remove style nodes, script nodes, and iframe nodes uploaded by users

Filtering is not only required on the front end, but also on the back end, because an attacker can bypass normal input and send information directly through the relevant interface.

2, do not directly insert user submitted content into the page, it is recommended to do some HTML escape operations

Cookies set HttpOnly

This prevents JavaScript from reading certain sensitive cookies that an attacker cannot steal once XSS injection is complete.

4. Verification code: Prevents scripts from submitting dangerous operations by pretending to be users ❗❗❗

5. Use.innerhtml,.outerhtml, document.write() and other methods to insert HTML directly instead of.textContent,.setAttribute() and more secure methods

Avoid injecting malicious scripts written by attackers into your code

6. Use inline event listeners in the DOM, such as location, onclick, onError, onload, onmouseover, etc. JavaScript eval(), setTimeout(), setInterval(), etc

Because they can both run strings as code. If untrusted data is concatenated into strings and passed to these apis, security risks can easily arise

7. Enable CSP protection. To enable this, set CSP to Content-security-policy: script-src ‘self’.

Content Security policies (CSP) are designed to defend against XSS attacks. When enabled, sites will not allow inline scripting, outfield code loading, or outfield commits. Although it can effectively prevent XSS attacks, it may cause certain restrictions on its own business development because it is too strict πŸ‘‰ MDN CSP

Use off-the-shelf tools

  • Mainstream frameworks defend against XSS by default
  • Or use third-party libraries to help filter, such as DOMPurify (a FAST, dom-only, highly fault tolerant XSS filter for HTML, MathML, and SVG)

Instances that may be attacked by XSS

1. Converting srting to DOM using DOMParser may carry execution scripts (need filtering)

2. When users upload SVG images, SCTIPT tags can be embedded in SVG (filtering required)

3, allow users to customize the jump link, a tag jump link can be written in JS code, so it is best not to allow

4. Let the user customize the style, for example, if there is such an option group

Its selection is written like this

When the user selects the specified option, the background switches to one, and the background sends a GET request with a selected message, which is vulnerable to XSS attacks

So first of all, don’t! Don’t write like that! Don’t write like that! πŸ‘», secondly, we need to pay attention to the attributes like background, which can send requests. Finally, we must use it and remember to filter it!! πŸ₯Ά

CSRF defense

1. Use captcha to force the user to interact with the application before completing the final request

If the verification code is used too often, the user experience is poor πŸ’₯, so it is only used for special operations.

[The process of CSRF attack often happens without the user’s knowledge, and the network request is constructed without the user’s knowledge]

2. Check HTTP Referer

According to the HTTP protocol, there is a field called Referer in the HTTP header, which records the source address of the HTTP request. If we can determine the source address of the current HTTP request and only allow the request from this website to access, then the CSRF attack will be invalid. However, it is important to know that the Referer value in some browsers can be tampered with.

[CSRF attacks are usually from third-party websites]

3, Use token, token verification CSRF defense mechanism is recognized as the most appropriate solution

The backend randomly generates a token and stores the token in the session state. At the same time, the backend sends the token to the front-end. When the front-end page submits a request, it adds the token to the request data or header information and sends it to the back-end. The back-end verifies whether the token sent from the front-end is consistent with the session, and rejects the request if it is inconsistent.

The reason why CSRF attack can be successful is that the attacker can forge the user’s request and all the user authentication information in the request is stored in the cookie, so the attacker can directly use the user’s cookie to pass the security authentication without knowing the user authentication information.

Tokens should be bound to user information, because attackers can also obtain tokens by registering users. Tokens should be set to expire;

4. SameSite attribute of Cookie πŸ‘‰SameSite attribute

5. Otherwise, the get request does not modify the data. X-frame-options response header is set on the server side to prevent the page from being embedded.

Injection of defense

1. Data verification, again, never trust the user’s input 🚫

Verify user input, either through regular expressions or by limiting the length; Converts single quotes to double “-” and so on.

2. Do not use dynamic assembled SQL

Data query access can be performed using parameterized SQL or directly using stored procedures.

3. Strict permission management (minimum permission principle)

Strictly restrict the operation permissions of Web application databases, and only provide users with the minimum permissions to meet their work requirements, thus minimizing the harm of injection attacks on databases

4. Do not store confidential information directly

Encrypt or hash out passwords and sensitive information.

5. Escape special characters

Special characters (‘,”, <,>,&,*,; Etc.) for escape processing, or code conversion

6. Use Prepared Statement to query SQL

Defense against DoS and DDoS

Not quite understand not to elaborate πŸ˜—

SYN attack defense (a type of DDoS) :

  1. Shorten SYN Timeout
  2. Increase the maximum number of connections
  3. Filtering gateway Protection

Hahaha 🀣 hackers launched a DDoS attack on Github to force it to remove anti-censorship project Greatfire

GitHub was hit by the worst DDoS attack in its history

Defensive middleman

The browser and server are not unauthenticating each other, opening the way for a man-in-the-middle attack, so only one more secure channel is needed to transmit information. HTTPS can be used to defend against man-in-the-middle attacks.

If you don’t completely turn off HTTP access, there are ways in which an attacker can degrade HTTPS to HTTP to implement a man-in-the-middle attack.

Web security recommendations for individual users

🎨 Don’t ignore the certificate warning that pops up in your browser! You may be visiting a phishing site or a fake server.

🎨 recommends avoiding public Wi-Fi as much as possible, as man-in-the-middle attacks are likely to occur. If you are communicating with sensitive information, you are completely exposed to the attacker.

🎨 Make sure you use HTTPS before logging into your account on any website;

🎨 Browsing email or news using the web version of email also poses an additional risk, as viewing email or news messages can lead to malicious code attacks.

🎨 try not to open suspicious links, and be sure to open them using an unusual browser.

conclusion

The simple summary of defense is this

  • Filter! Filter! Filter!
  • Check! Check! Check!

twitter

Most of the attacks are for profit. It is impossible for us to ensure that our applications can never be attacked. However, as long as the cost of attacking us is far greater than the profit he can obtain, hackers will not attack us. Strong protection such as Alipay, QQ and other products, have also been reported vulnerabilities, so defense is not absolute, we can only think of ways to make our application more secure. πŸš€

References: DOM based XSS Prevention Cheat Sheet XSS Filter Evasion Cheat Sheet Cross-site scripting Cross-site request forgery Cross Site Request Forgery (CSRF

If any of the above is wrong, please point out in the comments section!


If there is a harvest, leave a thumbs-up to encourage it! 🍜