First, browser security
First understand front-end Web security knowledge, than the foundation of the Same Origin Policy is unavoidable, Same Origin Policy is a convention, it is the most core and the most basic security function of the browser, if the lack of the Same Origin Policy, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy.
Definition of the Same Origin policy (MDN) : Two urls are homologous if they have the same protocol, port (if specified), and host.
In browsers, tags such as Script, IMG, iframe, and link can load resources across domains without being restricted by the same origin policy. Each time these “SRC” tags are loaded, the browser actually makes a GET request. Unlike XMLHttpRequest, browsers limit JavaScript’s permissions to read and write returned content from resources loaded through the SRC attribute.
In the case of XMLHttpRequest, it can access the content from the same origin object. However, XMLHttpRequest is restricted by the same origin policy and cannot access resources across domains, especially in the development of AJAX applications. If XMLHttpRequest is able to access resources across domains, then sensitive data, such as tokens for CSRF, can be compromised, leading to security issues. But the Internet is open, with the development of business, the demand for cross-domain request is more and more urgent, so the W3C committee developed the XMLHttpRequest cross-domain access standard. It requires the HTTP header returned by the target domain to authorize cross-domain access, and since HTTP headers are generally unmanageable for JavaScript, it is thought that this scheme can be implemented. Note: The basis of security for this cross-domain access scheme is the trust that “JavaScript cannot control this HTTP header”, and if this trust is broken, the scheme is no longer secure.
Browser sandbox
The practice of inserting a piece of malicious code into a web page and using a browser vulnerability to execute arbitrary code, known in hacker circles as “mount”, is a major threat to browsers. In recent years, independent of antivirus software, browser manufacturers have developed some anti-mount technologies based on the characteristics of mount. For example, in Windows, the browser closely combines with the protection technologies provided by operating systems such as DEP, ASLR, and SafeSEH to defend against memory attacks. At the same time, the browser also developed a multi – process architecture, from the security has been greatly improved.
The multi-process architecture of the browser separates each function module of the browser and each instance of the browser. When one process crashes, other processes are not affected. Google Chrome was the first browser to adopt a multi-process architecture. The main processes of Google Chrome are the browser process, rendering process, plug-in process, and extension process. Plug-in processes such as Flash, Java, PDF, and so on are strictly isolated from browser processes and do not interfere with each other.
The rendering engine is isolated by the Sandbox, and the web code that communicates with the browser kernel process, and with the operating system, goes through the IPC channel, where some security checks are made. Sandbox is a synonym for resource isolation module. Sandboxes are typically designed to allow untrusted code to run in an environment that restricts untrusted code from accessing resources outside the quarantine. If data exchange must occur across Sandbox boundaries, it can only be done through designated data channels, such as encapsulated apis, where requests are rigorously checked for validity.
Cross-site scripting attacks XSS
Definition of XSS:
Cross Site Script, originally abbreviated as CSS, but called “XSS” in the security world to distinguish it from Cascading Style Sheets (CSS).
An XSS attack is an attack in which hackers tamper with web pages through “HTML injection” and insert malicious scripts to gain control of users’ browsers while they browse. In the beginning, a demonstration case of this attack was cross-domain, so it was called “cross-site scripting.” However, nowadays, because of the powerful function of JavaScript and the complexity of the front-end application of the website, whether cross-domain is no longer important. But for historical reasons, the name XSS stuck.
XSS can be divided into the following categories depending on the effect.
The first type: reflective XSS
Reflective XSS simply “reflects” user input data back to the browser. In other words, hackers often need to trick users into “clicking” on a malicious link in order to succeed. Reflective XSS is also called “non-persistent XSS”.
Attack steps of reflective XSS:
- The attacker constructs a special URL that contains malicious code.
- When a user opens a URL with malicious code, the web server takes the malicious code out of the URL, splices it into HTML and returns it to the browser.
- When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
- Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
Reflective XSS vulnerabilities are common in functions that pass parameters through urls, such as website search, jump, etc. Because users need to take the initiative to open malicious URL to take effect, attackers often combine a variety of means to induce users to click.
Reflective XSS can also be triggered by the contents of a POST, but the trigger condition is more stringent (the form submission page needs to be constructed and the user is directed to click), so it is very rare.
How to Defend against reflective XSS attacks:
Encodes a string.
The second type: storage XSS
Storage XSS “stores” user-entered data on the server side. This XSS is very stable. A common scenario is when a hacker writes a blog post that contains malicious JavaScript code, and when the blog post is published, all users who visit the blog post will execute the malicious JavaScript code in their browsers. Hackers save malicious scripts to the server, so this TYPE of XSS attack is called “stored XSS”. Storage XSS is often referred to as “Persistent XSS” because of its longevity in effect.
Malicious scripts are permanently stored on the target server. When the browser requests data, the script is sent back from the server and executed, with greater impact than reflective and DOM XSS. Storage XSS attacks are still caused by poor data filtering: data is not filtered properly when the front-end submits data to the server; The server receives data without filtering it before storing it. The front end requests data from the server without filtering output.
Storage XSS attack steps:
- The attacker submits malicious code to the database of the target website.
- When the user opens the target website, the website server takes the malicious code out of the database, splices it into HTML and returns it to the browser.
- When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
- Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
This kind of attack is common in website functions with user-saved data, such as forum posts, product reviews, and user messages.
How to Defend against stored XSS attacks:
- Escape/filter the front-end data before passing it to the server (can’t prevent packet capture and modification of data)
- The server receives the data and escapes/filters it before storing it in the database
- The front end receives the data from the server and escapes/filters it before presenting it to the page
- See examples of storage-type XSS attacks (see Readme tips)
In addition to careful escape, there are several other ways to protect against XSS attacks:
1.Content Security Policy
Use HTTP content-Security-Policy headers on the server side to specify policies, or set meta tags on the front end. For example, the following configuration allows only resources in the same domain to be loaded:
Content-Security-Policy: default-src 'self'
Copy the code
<meta http-equiv="Content-Security-Policy" content="form-action 'self';" >Copy the code
Setting CSP on the front-end and server has the same effect, but meta cannot use report
Strict CSP can play the following roles in XSS prevention:
- Prohibit loading outfield code to prevent complex attack logic.
- Prohibit submission from the outdomain. After a website is attacked, user data will not be leaked to the outdomain.
- Forbid inline script execution (strict rules, currently found to be used on GitHub).
- Disable unauthorized script execution (new feature, in use with Google Map Mobile).
- Proper use of reports can discover XSS in a timely manner, which helps to rectify problems as soon as possible
2. Control the length of input content
Untrusted input should be limited to a reasonable length. While you can’t completely prevent XSS from happening, you can make XSS attacks more difficult.
3. Limit the input content
For partial input, you can restrict it to not contain special characters or to enter only numbers.
4. Other safety measures
- Http-only Cookie: Disables JavaScript from reading certain sensitive cookies. Attackers cannot steal these cookies after XSS injection.
- Verification code: Prevents scripts from posing as users to submit dangerous operations.
The third type: DOM Based XSS
In fact, this type of XSS is not divided by whether the data is stored on the server. Dom-based XSS is also reflective in effect. It was singled out because DOM Base XSS was formed for a particular reason, and was specifically proposed by the security experts who discovered it. For historical reasons, it is a separate classification. XSS formed by modifying the DOM node of the page is called DOM Based XSS
Dom-type XSS attacks are essentially the result of sloppy front-end JavaScript code that inserts untrusted content into the page. Be careful when using apis like.innerhtml,.outerhtml,.appendChild, document.write(), etc., not to insert untrusted data into the page as HTML, Try to use.innertext,.textContent,.setAttribute(), etc.
DOM XSS attack steps:
- The attacker constructs special data that contains malicious code.
- The user’s browser executed malicious code.
- Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.
How do I defend against DOM XSS attacks
The key to defending against DOM-type XSS attacks is to escape the input (inline event listeners and link jumps in the DOM can both run strings as code and check their contents).
- For URL links (such as image SRC attributes), escape them directly using encodeURIComponent.
- Non-url, we can encode it like this:
function encodeHtml(str) { return str.replace(/"/g, '" ') .replace(/'/g, '' ') .replace(/</g, '< ') .replace(/>/g, '> '); }Copy the code
DOM TYPE XSS attack, taking out and executing malicious code is completed by the browser side, which belongs to the security vulnerability of front-end JavaScript itself.
XSS attack advanced
The previous article covered several categories of XSS. Next, experience the power of XSS from an attack perspective. After the XSS attack is successful, the attacker can implant malicious scripts on the page that the user is currently browsing to control the user’s browser. These malicious scripts, used to perform various specific functions, are called xsspayloads.
XSS Payload is actually a JavaScript script (or a Flash or other rich client script), so XSS Payload can do anything a JavaScript script can do. One of the most common types of XSS Payload is a “cookiejacking” attack that reads a browser’s Cookie object. Cookies generally encrypt the login credentials of the current user. If the Cookie is lost, it usually means that the user’s login credentials are lost. In other words, an attacker can log directly into a user’s account without using a password.
Cookie hijacking doesn’t work all the time. Some sites may embed the HttpOnly identifier for key cookies in set-cookie; Some sites may bind cookies to the client IP, rendering the cookies stolen by XSS meaningless.
Cross-site Request Forgery (CSRF)
Cross-site Request Forgery (CSRF) : An attacker induces the victim to access a third-party website and sends cross-site request to the attacked website. Using the victim in the attacked website has obtained the registration certificate, bypassing the background user authentication, to impersonate the user to perform a certain operation on the attacked website.
Typical CSRF attack flow:
- The victim logs in to site A and retains his login credentials (cookies).
- The attacker induced the victim to visit site B.
- Site B sends A request to site A, and the browser carries site A’s Cookie by default.
- After receiving the request, site A verifies the request and confirms that it is the victim’s credentials, mistakenly believing that the request was sent by an innocent victim.
- Site A executes site B’s request on behalf of the victim.
- The attack is complete. The attacker impersonates the victim to complete the attack without the victim’s knowledge.
The characteristics of CSRF
1. Attacks are usually launched on third-party websites, such as site B in the figure. Site A cannot prevent attacks.
2. The attack uses the login credentials of the victim on the attacked website to submit operations as the victim; It doesn’t get cookies (cookies have same-origin policy)
3. Cross-site requests can be made in various ways: image urls, hyperlinks, CORS, Form submissions, etc. (don’t click on links from unknown sources)
CSRF Attack defense
1. Add a verification code (Poor experience)
The verification code can defend against CSRF attacks, but it is impossible for us to need the verification code for every interaction, otherwise the user experience will be very bad. However, we can add the verification code in the operation of transfer and transaction to ensure the security of our account.
2. Determine the source of the request: check the Referer(not secure, Referer can be changed)
The most common use of Referer Check on the Internet is to prevent image theft. In the same way, RefererCheck can be used to check whether a request is from a legitimate “source.”
For common Internet applications, there is a certain logical relationship between pages, which makes the Referer of each normal request have a certain rule. For example, a “forum Posting” operation, under normal circumstances, you need to log in to the user background, or visit the page with Posting function. When submitting a “post” form, the value of the Referer must be the page on which the post form is located. If the value of the Referer is not the page, or even the domain of the Posting site, it is most likely a CSRF attack.
Even if we can determine whether a user has been attacked by CSRF by checking whether the Referer is valid, sufficient conditions for defense are only met. The flaw with Referer Check is that the server doesn’t always have access to the Referer. Many users restrict Referer for privacy reasons. Browsers also don’t send referers in certain situations, such as going from HTTPS to HTTP, for security reasons.
'Referer' can be used as an auxiliary means to determine whether the source of the request is safe, but since 'Referer' itself can be modified, because 'Referer' cannot be relied on aloneCopy the code
3. Use tokens (mainstream)
The CSRF attack succeeds because the server mistook the request sent by the attacker for the user’s own request. Then we can require all user requests to carry a Token that a CSRF attacker cannot obtain. The server verifies that the request carries the correct Token to distinguish the normal request from the attack request. It’s like a captcha, but the user doesn’t know it.
- The server generates a token for the user, encrypts it, and sends it to the user
- Users need to carry this token when submitting requests
- The server verifies that the token is correct
4. Samesite Cookie attribute
In order to solve this problem from the source, Google drafted a draft to improve the HTTP protocol, adding the Samesite attribute to the set-cookie response header, which is used to indicate that the Cookie is a “peer Cookie”, and the peer Cookie can only be used as a first-party Cookie. Cannot be a third-party Cookie, Samesite has two property values, Strict and Lax.
It is simple to deploy and can effectively defend against CSRF attacks, but compatibility problems exist.
Samesite=Strict
Samesite=Strict is referred to as Strict mode, indicating that this Cookie cannot be used as a third-party Cookie under any circumstances and is capable of preventing all CSRF attacks. At this point, we launch any request to site A under site B, and the Cookie of site A will not be included in the Cookie request header.
**Samesite=Lax** 'Samesite=Lax is called loose mode, which is relaxed compared to Strict to allow sending secure HTTP methods with cookies, such as' Get'/' OPTIONS ', 'HEAD' requests. However, insecure HTTP methods such as' POST ', 'PUT', and 'DELETE' cannot be used as cookies for third-party links when requestedCopy the code
To better defend against CSRF attacks, we can use a combination of the above defenses.
The essence of CSRF
Why can CSRF attack successfully? The essential reason is that all parameters of important operations can be guessed by the attacker. An attacker can successfully construct a forged request only by predicting all the parameters and parameter values of the URL. Otherwise, the attacker will not succeed. For this reason, one solution is to encrypt the parameters or use random numbers so that an attacker cannot guess their value. This is an application of the principle of unpredictability.
Click hijacking
Clickjacking is a form of visual deception. The attacker uses a transparent, invisible IFrame to overlay a web page and then trick the user into doing something on that page, where the user unknowingly clicks on the transparent IFrame page. By adjusting the position of the iframe page, you can trick the user into hitting some functional buttons on the iframe page.
Typical clickjacking attack flow
- The attacker has created a very attractive page.
- Place the attacked page in the iframe of the current page
- Use styles to superimpose iframe on top of very attractive content
- Set iframe to 100% transparent
- You were tricked into clicking on web content, thinking you were clicking on ***, when in fact, you were successfully attacked.
Click hijack defense
It is often possible to write a piece of JavaScript code to disallow the nesting of iframes. This method is called framebusting. Take this code for example:
1. frame busting
if ( top.location ! = window.location ){ top.location = window.location }Copy the code
Note that the sandbox property of IFrame in HTML5, the Security property of Iframe in IE, and so on, can limit the execution of JavaScript scripts in iframe pages, thereby disabling frame busting.
2. X-Frame-Options
X-frame-options is an HTTP header proposed by Microsoft to defend against clickjacking attacks using nested iframe. It works well with IE8, Firefox3.6, Chrome4 and beyond.
You can set the following values:
DENY: denies any domain loading
SAMEORIGIN: allows loading in the SAMEORIGIN domain
Allow-from: allows the page address to be loaded by frame
5. HTML5 security
HTML 5 new tags
New label XSS
Iframe sandbox
The IFrame tag has long been criticized. It can be seen infamously in attacks like Hang Horse, XSS, ClickJacking, etc. Browser vendors have been working on ways to limit iframe’s ability to execute scripts, such as limiting cross-window access and limiting script execution with security tags in IE. In HTML 5, a new attribute called sandbox was defined specifically for iframe. Using the sandbox property, the content loaded by the tag is treated as a separate “source” (see “same Origin Policy” for the concept of a source), in which scripts are prohibited from executing, forms are prohibited from submitting, plug-ins are prohibited from loading, and links to other browsing objects are prohibited. The Sandbox property allows for more precise control with parameters.
There are several values to choose from:
- ❍ allow-same-origin: allows same-origin access.
- ❍ allow-top-navigation: allows access to top-level Windows;
- ❍ allow-forms: allows submission of forms;
- ❍ allow-scripts: allows scripts to be executed.
Link Types: noreferrer
A new Link type was defined in HTML 5 for a tags and area tags :noreferrer. As the name implies, when a tag specifies a noreferrer, the browser will no longer send the Referer when requesting the address specified by the tag. This is designed to protect sensitive information and privacy. Because through Referer, some sensitive information may be leaked. This tag needs to be added manually by the developer to the page tag, for the required tag can choose to use the Noreferrer.
Security scanning tool
1. Arachni
Arachni is an open source, comprehensive and high-performance vulnerability scanning framework based on Ruby. Arachni provides a simple and fast scanning method. You only need to enter the URL of the target website to start scanning. It can evaluate the accuracy of vulnerability identification and avoid misjudgment by analyzing the information obtained during scanning.
Arachni integrates a large number of detection tools by default, which can implement code injection, CSRF, file inclusion detection, SQL injection, command line injection, path traversal and other attacks.
At the same time, it also provides a variety of plug-ins, can achieve form blasting, HTTP blasting, firewall detection and other functions.
For large web sites, the tool supports session persistence, browser clustering, and snapshots to help users better perform penetration testing.
2. Mozilla HTTP Observatory
Mozilla HTTP Observatory is a web security analysis tool released by Mozilla to encourage developers and system administrators to enhance their web security. Usage is simple: Enter a web URL, access and analyze the web HTTP header, and then provide numerical scores and alphabetical security levels for web site security.
The main areas of inspection include:
- Cookie
- Cross-source Resource Sharing (CORS)
- Content Security Policy (CSP)
- HTTP Public Key Pinning
- HTTP Strict Secure Transport (HSTS) status
- Whether there is automatic HTTP to HTTPs redirection
- Subresource Integrity
- X-Frame-Options
- X-XSS-Protection
3. w3af
W3af is a Python-based Web application security scanner. Helps developers and helps developers and testers identify vulnerabilities in Web applications.
The scanner is able to identify more than 200 vulnerabilities, including cross-site scripting, SQL injection, and operating system commands.