Writing in the front
- Introduction to books: Web front-end hacker attack and defense technology is a very novel and interesting hacking technology, mainly including Web front-end security cross-site scripting (XSS), cross-site request forgery (CSRF), interface operation hijacking these three categories. The knowledge points involved cover trust and trust relationship, Cookie security, Flash security, DOM rendering, character set, cross-domain, original ecological attack, advanced fishing, worm thought, etc., which are all necessary knowledge points for those who study front-end security. The author of this book deeply analyzes many classic attack and defense skills, and gives many unique security insights.
- My quick comment: This book was published several years ago (13 years old), and many of the HTML, CSS, JavaScript and browser bugs written in it have now been fixed. But the topic of Web front-end security is still a very important one for us developers, especially those working on large corporate projects. And the understanding of Web front-end hacker technology reflects the technical level of a technical staff and enthusiasm for technology and study degree. Therefore, it is highly recommended that you read this book.
- !!!!! Bonus: PDF book at the end of the article, mind map notes, packaged with the book code download address oh! To see all the articles in the book Intensive Series, please go to
Chapter 1 Key points of Web security
1.1. Data and instructions
- When we open a website with a browser, we will see data stored on the server side (such as database, memory, file system, etc.), stored on the client side (such as local Cookies, Flash Cookies, etc.), in transmission (such as JSON data, XML data, etc.), and text data (such as: HTML, JavaScript, CSS, etc.), multimedia data (such as Flash, Mp3, etc.), image data, etc.
- Two examples of attack scenarios: 1.SQL injection attack; 2. 2. Occurrence of XSS cross-site scripting attacks
- Cross-site attacks occur on the browser client, while SQL injection attacks target databases. Generally, databases are on the server. Therefore, SQL injection attacks occur on the server
1.2. Same-origin policy for browsers
- The local computer is on a different plane from the Web, where the Web world (commonly referred to as the Internet domain) runs on the browser and is limited to reading and writing directly to local data (commonly referred to as the local domain)
- The same Origin policy stipulates that client scripts in different domains cannot read and write resources of each other without authorization. There are a few keywords: different domains, client scripts, authorization, read and write, resources
- 1. Different domain or same-domain: Same-domain requires that the two sites have the same protocol, domain name, and port
- 2. Client-side script: it mainly refers to JavaScript (the script language supported by all browsers), ActionScript (the script language of Flash), and the ECMAScript script standard that both JavaScript and ActionScript follow
- 3. Authorization: As mentioned in the new HTML5 standard regarding Ajax cross-domain access, cross-domain access is not allowed by default, only the target site explicitly returns HTTP response headers
- 4. Read and write permission: There are many resources on the Web. Some resources have only read permission, while others have both read and write permission. For example, Referer (the source of the request) in the HTTP header is only readable, while document.cookie is read and write
- 5. Resources in the same-origin policy refer to resources on the Web client. In general, resources include HTTP headers, the entire DOM tree, browser storage (e.g., Cookies, Flash Cookies, localStorage, etc.)
1.3. Trust and trust relationships
- Safety is similar to the barrel principle, the short board determines how much water the barrel can actually hold. For a Web server, if the sites on it do not have proper separation of permissions and trust relationships, the overall security is determined by the least secure site
- Many websites embed third party access statistics scripts by using
<script>
If a third-party statistical script is hung by hackers, then these websites will also be compromised
1.4. Role of social engineering
- Common social worker auxiliary skills are: Google Hack, SNS vertical search, various collected database collection query, etc
1.5. Attack and defense are not single
- CSRF will borrow the target user’s permissions to do something (” borrow “, not “steal” the target permissions) and then do something bad, which is usually XSS’s favorite thing to do
Chapter two front-end foundation
2.1.W3C’s World Law
- The roles of Web security events are as follows: W3C, browser vendor, Web vendor, attacker (or hacker), victim (or user)
2.2. The URL
- One of the Internet’s greatest innovations is the URL, which is often referred to as a link, a URL request that leads to a unique resource
- URL has a key is the encoding method, there are three types: escape, encodeURI, encodeURIComponent, corresponding decoding function is: unescape, decodeURI, decodeURIComponent
2.3. The HTTP protocol
- The request protocol of URL is almost HTTP. It is a stateless request response, that is, after each request response, the connection will be immediately disconnected or delayed (with a certain connection validity period). After disconnection, the next request will be re-established
- User-agent is important to indicate identity (who I am). You can view the operating system, browser, browser kernel, and corresponding version
- Session tracking is done through Cookies, and Cookies set in the first response are sent on each subsequent request. Cookies can also include identity information after login authentication
- There are different parsing methods for different resource types, which may affect the way the browser parses the resources in the response body, which may cause security problems. Character sets can also affect how browsers decode, which can also pose security issues
2.4. Loose HTML world
- HTML can have scripts, styles and other content embedded, as well as images, multimedia and other resources reference
- HTML is made up of many tags, and there are corresponding attributes in the tags. These tags can be case insensitive, and some may not need to be closed. Attribute values can be enclosed in single, double, backsingle quotes, or even without quotes. Extra Spaces and tabs do not affect HTML parsing. HTML can be embedded with CSS, JavaScript, etc., without stressing separation, etc
- Many front-end security problems are caused by looseness
- 1.DOM tree: A lot of data exist in DOM tree, through the operation of DOM tree can be very easy to obtain our private data; Private data may be stored in the following places (in HTML content, in browser local storage, such as Cookies, in URL addresses)
- 2. Iframe embedded an open world: Iframe tag is a very important tag in HTML and one of the tags with the highest frequency in Web security. Many websites embed third-party content through IFrame; Iframe tag brings a lot of convenience, but also brings a lot of risks. For example, after an attacker invents a website, he or she can embed iframe into his or her own webma page. After the user visits the website, the embedded webma page will execute. If the parent page and child page are in the same domain, this is easy. The parent page can manipulate the DOM tree of the child page by calling its contentWindow, and the child page can manipulate the DOM tree of the parent page by calling its contentWindow. If they are different domains, the same origin policy must be followed, but the child page can still write to the parent page’s location so that the parent page can be redirected to another page. However, the operation of location is only write permission, but not read permission, so that you can not get the content of the parent page location URL, otherwise it may cause privacy data leakage;
- 3.HTML embedded script execution: JavaScript scripts in addition to appearing in JS format files, embedded and executed, can also appear in HTML
<script></script>
In the tag, in the HTML tag on event, and in the pseudo protocol (javascript:, etc.) of the href and SRC attributes of some tags;
2.5. Cross-site Spirit -JavaScript
- With XSS vulnerability, it means that arbitrary JavaScript can be injected. With JavaScript, it means that any operation of the attacked person can be simulated and any private information can be obtained
- DOM tree operation: 1. Obtain private data in HTML content; 2. Obtain the browser’s Cookies data (Cookies save the user’s session information, which can be obtained through Document. cookie, but not all Cookies can be obtained); 3. Obtain data from the URL address
- AJAX risk: AJAX is a must-have technology for front-end hacking; Ajax attacks are spooky and silent; Not all request headers can be set using JavaScript. The W3C has a blacklist of headers; If the destination domain is not set to access-Control-allow-origin, the browser will report a permission error, but the privacy number is actually received by the target domain code. By default, these cross-domains cannot bring the session (Cookies, etc.) in the target domain. Therefore, you need to set the withCredentials attribute of XHR instances to True (IE does not support these attributes yet). When the access-control-allow-credentials parameter is set to true, access-Control-allow-origin cannot be set to the * wildcard. This is for security.
- Simulate a user initiating a browser request: The XMLHttpRequest object is a very convenient way to simulate form submission. It can be asynchronous or synchronous. The difference is that the third parameter in the open method of the XMLHttpRequest instantiated object XHR, true, means asynchronous, false means synchronous. Is the Ajax; In front-end hacker attacks, for example, XSS often needs to launch various requests (such as stealing Cookies, worm attacks, etc.). The above methods are commonly used in XSS attacks, while the last form self-submission method is often used in CSRF attacks.
- Cookie security: Cookie is an amazing mechanism that every request made by the browser in the same domain is accompanied by a Cookie. No matter what resource is requested, the Cookie appears in the Cookie field of the request header. The set-cookie field in the server response header can add, modify, and delete cookies. In most cases, the client can also add, modify, and delete cookies through JavaScript. Cookies are often used to store user Session information. After the user logs in to the authenticated Session, the request sent in the same domain will carry the authenticated Session information, which is very convenient. Attackers are particularly fond of stealing cookies, which is equivalent to stealing user rights on the target website;
- Local storage risk: the main risk of local storage is to be implanted with advertising tracking marks, some want to delete may not be able to delete clean; Known as Evercookie, The following stores are also used (Silverlight’s IsolatedStorage, PNG Cache, and similar PNG Cache mechanisms such as HTTP Etags, Web Cache, Web History, window.name);
- The messy world of E4X: For JavaScript, e4x is currently supported only by Firefox, which uses XML as a JavaScript object; Using E4X technology, you can obfuscate JavaScript code and even bypass some filtering rules;
- JavaScript function hijacking: JavaScript function hijacking is very simple. In general, you just need to override the function before the target function fires. Browsers hijacked Document. write and Document. writeln in the same way;
2.6. A World in Disguise -CSS
- CSS is a cascading style sheet, used to control the presentation style of a web page, such as color, font, size, height, width, transparency, offset, layout, etc. By flexibly using CSS skills, attackers can disguise the desired effect of the web page, so as to carry out phishing attacks
- CSS fault tolerance
- Style camouflage: UI effects that are camouflaged feel real
- CSS pseudo-class: once appeared relatively long CSS History attack is :visited pseudo-class skills, the principle is very simple, isto prepare a number of commonly used links, plus :visited{background: URL (XXXXX)} style; If a link has been visited before (that is, it exists in a record), then: Visited fires and sends a unique request to the target address, which tells you whether the target has a link in its history, but this has been fixed by the browser. But there are also pseudo classes that are valid. For example, the :: Selection pseudo-class, which triggers :: Selection when the specified object region is selected, works in Chrome.
- CSS3 property selector: CSS can also embed script execution
2.7. Another ghost -ActionScript
- ActionScript (AS for short) follows the ECMAScript standard just like JavaScript. ActionScript is executed by the Flash script VIRTUAL machine. The running environment is in Flash Player, and Flash Player has two main running environments: Native to the browser and operating system, Flash has its own security sandbox that limits ActionScript’s ability to do dangerous things through ActionScript otherwise
- Flash security sandbox: The Flash security sandbox is used to make ActionScript game rules; Security sandboxes include remote sandboxes and local sandboxes. The sandbox model is similar to the same origin policy in the browser. Resources in the same domain are placed in a security group, which is called a security sandbox.
- HTML embedded flash security-related configuration
- Cross-site Flash: Cross-site Flash is also called Cross Site Flash (XSF). It is used to load third-party Flash files through ActionScript. If attackers can control this process, they can make the target Flash load malicious Flash files, resulting in XSF attacks.
- Parameter passing
- Embedded HTML in Flash: Embedded HTML in Flash is not arbitrary and supports limited tags.
- Communicate with JavaScript: 1. GetURL () and navigateToURL(); 2. The ExternalInterface;
- Network communication: URLLoader and URLRequest combination for text data request, which is AS3 excellent combination, GET/POST data are very convenient, if only send data out, and do not need to GET a response, then directly use sendToURL function +URLRequest combination; If you want to use socket requests, you can use the socket class or the XMLSocket class. The Action Message Format (AMF) is a common binary encoding mode used for communication between Flash and server. It has high transmission efficiency and can be transmitted over HTTP. Some plug-ins are analyzed, some are specialized in simulating AMF messages for various malicious operations;
- Other security issues: Some important data or logical operations of the Flash are directly performed locally. This is incorrect, you can get ActionScript code by using some popular decompiling tools such as HP swfdump.exe. Remember that important data or calculations should not be performed locally;
Chapter 3 XSS of front-end hacker
3.1. XSS overview
- XSS, or cross-site scripting, occurs at the browser level of the target user in the target website. XSS occurs when an unexpected script instruction is executed during the rendering of the entire HTML document by the user’s browser
- The focus of cross-site scripting is not on cross-site, but on script
- XSS can be summarised colloquially as follows: do whatever it takes to get your script content parsed and executed on the browser of the target user on the target site
3.2. XSS type
- There are three types of XSS: reflective XSS (also known as non-persistent XSS), storage XSS (also known as persistent XSS), and DOM XSS
- Reflective XSS: When a request is made, the XSS code appears in the URL and is submitted to the server as input. After the server parses and responds, the XSS code appears in the response content and is parsed and executed by the browser
- The difference between stored XSS and reflective XSS is simply that committed XSS code is stored on the server (whether database, memory, file system, etc.) and is not committed the next time the target page is requested
- The most typical example is the message board XSS. Stored XSS attacks are the most insidious
- The difference between DOM XSS and reflective and stored XSS is that THE XSS code of DOM XSS does not require the direct involvement of the server parsing response. Instead, it is the browser-side DOM parsing that triggers XSS, which can be considered entirely client-side
- The DOM XSS processing logic is on the client side
3.3. Where can XSS attacks occur
- XSS involves a wide range of scenarios, now more and more client software support HTML parsing and JavaScript parsing, such as: HTML documents, XML documents, Flash, PDF, QQ, some music players, some browser functional interface, etc
3.4. What are the hazards
- Hang a horse
- Steal users’ cookies
- Dos (Denial of Service) client browser
- Fishing attack, advanced fishing skills
- Write targeted XSS virus, delete target articles, maliciously tamper with data, blame others
- Hijack user Web behavior, or even further infiltrate the Intranet
- Web 2.0 worm outbreak
- Worm DDoS attacks
- Worm type hangs a horse to attack, brush advertisement, brush flow, destroy data on the net
Chapter 4 CSRF of front-end hacker
Writing in the front
- CSRF stands for Cross Site Request Forgery
- CSRF is of great concern for open source sites, multi-user sites, social networking sites, etc. CSRF can directly attack the administrator background or other users
4.1. CSRF overview
- For CSRF, there are two key points about its request: the cross-site request and the request are forged
- Consider this: if the request is not made by the user’s will, then the request is a forgery
- This attack has three key points: a GET request is issued across domains, it can be done without JavaScript, and the request is authenticated
4.2. CSRF type
- According to the attack methods, CSRF can be divided into HTML CSRF attack, JSON HiJacking attack and Flash CSRF attack, etc
- Any tag in HTML that can set a link address such as SRC /href can initiate a GET request
- There are also GET requests from JavaScript dynamically generated label objects or CSS objects, while POST requests can only be made through form submission
- The Flash world also follows the same origin policy, and CSRF attacks are launched through ActionScript scripts
- When you think of Flash CSRF, two things usually come to mind: cross-domain access to private data; Submit data operations across domains, requests for operations such as add, delete, edit, etc
4.3. What are the hazards
- Tampering with user data on the target website
- Steal user privacy data
- As an auxiliary attack technique for other attack vectors
- Propagate the CSRF worm
Chapter five front-end hacker interface operation hijacking
5.1. Overview of interface hijacking
- Interface operation hijacking attack is a Web session hijacking attack based on visual spoofing. It through the visible input controls on web pages covering an invisible box (iframe), allowing users mistook the operating visible controls, but in fact the operation of the user behavior was hijacked by the invisible box, implement the malicious code, hijacked in invisible box to complete the user unbeknownst to steal sensitive information, tampering with data, and so on
- From its technical development stage analysis, can be divided into the following three: click hijacking, drag and drop hijacking, touch screen hijacking
- Click hijacking: its first hijacking is the user’s mouse click operation, its main hijacking target is the page with important session interaction
- Drag and drop hijacking: In browsers, drag and drop operations are not restricted by the same origin policy, and users can drag and drop content from one domain to a different domain
- Touchscreen hijacking: Smart mobile devices have become a new target for hackers
5.2. Principle analysis of interface operation hijacking technology
- Transparent layer + IFrame: The “overlay” is the hierarchical relationship between the accusation position, “invisible” means the page transparency is zero, and “box” refers to the IFrame tag. So. “Cover an invisible box” can be interpreted as “transparent layer” + “iframe”
- Through page transparency + IFrame, the visual deception to the user is realized, that is, the operation object seen by the user is inconsistent with the actual operation object, thus providing a technical means for interface operation hijacking attack
- The dataTransfer appears as an attribute of the Event object and is used to pass strings from the dragged object to the placing object
- After the setData operation is completed, the data to be transmitted is stored in the system clipboard. The transmitted data is divided into two types: text data and URL data. In HTML5 extensions, it allows you to specify any MIME type
- Drag-and-drop hijacking is a slightly more complicated operation. The number of drag-and-drop objects in the browser continues to grow. Images, links, and text can all be dragged
- The IPhone Safari browser has a special feature that adds web pages to the IOS desktop as a program icon
- On these touchscreen mobile devices, it is also possible to use transparency + IFrame, and then use the API functions of the touchscreen device to launch touchscreen hijacking attacks
5.3. Example of interface operation hijacking
- Click hijacking: An example of a twitter follow button
- Drag and drop hijacking: a little game
5.4. What are the hazards
- Interface hijacking actually breaks CSRF’s defense strategy. It can cause great harm, such as deleting and tampering with data, stealing privacy Settings outbreak worms
Chapter VI Excavation of Loopholes
Writing in the front
- A vulnerability can be caused by a number of factors, such as browser differences (or browser features), browser bugs, character set issues, vulnerability objects, scenarios, etc
- CSRF vulnerability mining only needs to confirm the following: whether the target form has a valid token random string; Whether the target form has a verification code; Whether the target judges the Referer source; Allow-access-fromdomain in crossdomain. XML is a wildcard; The target JSON data seems to be customizable for callback functions, etc.
- For vulnerability mining of interface operation hijacking, you only need to confirm the following: Whether the target HTTP response header is set with x-frame-options; Whether the target has a Frame Busting mechanism for JavaScript; It is easier to embed iframe into the target website. If successful, the vulnerability exists.
6.1. Automatic mining of common XSS vulnerabilities
- Automated XSS vulnerability mining can be complex and difficult. This depends on the requirements of the XSS vulnerability mining tool we want to implement, whether it is efficiency (with breadth but not depth) or detection rate (with both breadth and depth, with a large number of vulnerabilities and high accuracy).
- The idea of tool automation is a common XSS vulnerability mining idea for reflective XSS, storage XSS, header XSS, CookieXSS and so on
- 2. A common pattern of urls:
<scheme>://<netloc>/<path>? <query>#<fragment>
; - HTML mystery: Two special types of tags
<script>
and<style>
, they can’t nest tags, and the payload structure is more flexible. SRC /href/action; 2. Output within the on* event; 3. Output in the style property; For IE, as long as the expression keyword can be injected into the tag’s style attribute and properly closed, we can consider that the target has XSS. - A “spy request” is a harmless request that comes and goes before the actual payload attacks it. Not detected by the site’s filtering mechanism, just like a normal request; The purpose of the “detector” is as follows: (1) Whether the target parameter value appears in the response. If it does not, the payload request and analysis are not necessary; XSS is treated differently by different parts of the HTML, and the requested payload is also different.
- About stored XSS mining: This is typically the submission of a form, which goes into server-side storage and is eventually printed on a page
6.2. Magic DOM rendering
- HTML and JavaScript self-decoding mechanism: The HTML encoding is automatically decoded before JavaScript is executed.
- Tags with HTmlencode functionality: HTML in
<textarea>
Is not parsed. Other such tags include title, iframe, noscript, noframes; Textarea is heavily weighted in HTML, allowing HTML tags to appear in<textarea><textarea>
Between; - Url encoding differences
- Dom modification formal rendering: view-source the “HTML code” seen like this is actually static; Press F12 key to open the corresponding debugging tools, these debugging tools to view the source is dynamic results; Browsers make various modifications to DOM rendering, and the modifications may vary from browser to browser. This modified rendering can be used to bypass the browser’s XSS Filter;
- A dom Fuzzing technique: Fuzzing;
6.3. The DOM XSS mining
- Static approach: Manual analysis of pages as soon as suspicious features are found is the cost of the static approach, which requires a high level of human involvement
- Dynamic method: Dynamic method is difficult to perfect the implementation of the detection engine, this is actually a dynamic JavaScript source audit process
6.4. The Flash XSS mining
- XSF is Cross Site Flash; Flash players on many websites have XSF risks because they need the flexibility to load third-party Flash resources for playback.
- Google Flash XSS mining: Google does a good job of separating their domains and putting all the irrelevant content on other domains, so that XSS is useless.
6.5. XSS due to character set defects
- The ASCII character set could not express Latin characters, let alone East Asian characters, so various character sets evolved, such as ISO8859, GB2312, GBK, GB18030, BIG5, Shift_JIS, until the emergence of Unicode character set, the dawn of world peace was seen. However, these character sets are still used in various countries, and it is impossible to clean up and start from scratch, so the character world is still confused
- The encoding modes of the Unicode character set are UTF-8, UTF-16, UTF-32, utF-7, and UTF-8 and UTF-7
- The goal of encoding is to eventually convert these characters correctly into computer-readable binary, and the corresponding decoding is to finally decode the binary into human-readable characters
- Security problems caused by wide character encoding: mainly eating ASCII characters (one byte) phenomenon; In the process from front end to back end, inconsistent character set encoding processing may lead to a series of security problems such as SQL injection and command execution.
- Utf-7 problem: UTF-7 is an encoding of the Unicode character set, but it is not recommended by the standard. Utf-7 XSS (1. Utf-7 encoding is automatically selected; 2. Use iframe to invoke the utF-7 encoded HTML file. But now IE limits
<iframe>
Only utF-7 encoded files in the same domain can be embedded; 3. Invoke the utF-7 encoded CSS file in link mode. 4. Specify the BOM header. BOM stands for Byte Order Mark. The BOM appears at the beginning of the file. The software identifies the BOM of the file to determine its Unicode character set encoding mode. In actual attack scenarios, the following functions can be used to control the beginning of the target web page (user-defined CSS style files; JSON Callback type link;) - The security issue with browsers dealing with character set coding bugs: Standards are always too good to be true, such as character set standards, but every browser doesn’t always implement them well, so don’t trust them with bugs
6.6. Bypass the browser XSS Filter
- At present, Internet Explorer and Chrome have XSS Filter mechanism, it is impossible to have a perfect Filter
- XSS Filter is mainly aimed at reflective XSS. Generally, it adopts a heuristic detection. According to the parameters submitted by users, it determines whether potential XSS features are found, and re-renders the response content to ensure that potential XSS features will not be triggered
- Response header CRLF injection bypass
- Homodome-specific whitelisting: Strictly speaking, homodome-specific whitelisting is not a bypass, but rather a browser property that facilitates the use of reflective XSS. IE and Chrome differ in this mechanism; IE will determine whether the Referer source is local, if so, XSS Filter does not take effect. Chrome’s same-domain whitelist mechanism is completely different from IE’s. If it is
<script>
XSS Filter does not defend against js files embedded in the same domain. This is affected by the CSP policy. - Scenarios with high dependency bypasses
6.7. Confusing code
- In order to improve the success rate of vulnerability mining, we often need to obfuscate various codes to bypass the filtering mechanism
- Common base confusions in browsers include octal, decimal, and hexadecimal; Strings that can be executed directly through eval in JavaScript are encoded in octal and hexadecimal; It should be noted that these two representations cannot directly encode multi-byte characters (such as Chinese characters, Korean characters, etc.). If Chinese characters are used and the code is encoded in hexadecimal Unicode, only hexadecimal Unicode can be used. JavaScript itself comes with two functions that handle this: Char. ToString (jinzhi) (char is the single word that needs to be encoded, jinzhi is the base that needs to be encoded, you can fill in 2, 8, 10, 16 or other such numbers), string. fromCharCode(code, jinzhi);
- Browser code common sense: in JavaScript, there are three sets of encoding/decoding function: the escape/unescape, encodeURI/decodeURI, encodeURIComponent/decodeURIComponent; In addition to the three encryption/decryption methods provided by JavaScript, we also need to understand HTMLEncode, URLEncode, JSEncode, UTF-7 coding, Base64 coding related knowledge;
- HTML code injection techniques: Complete HTML code is divided into: tag name, attribute name, attribute value, text, comment. These can be JavaScript events, resource links, or data objects; 1. Tags :(due to the looseness of the HTML language and the different priorities of each tag, we can create a lot of code obfuscation or bypass ways; There is also a special comment: IE HTML conditional Control statement); 2. Attributes :(attributes in HTML tags are also case insensitive, and attribute values can be enclosed in double quotes, single quotes, or even without quotes is grammatically correct in HTML; In addition, there is no limit to the number of Spaces, newlines (CHR (13)), carriage returns (CHR (10)), or TAB (CHR (9)) between labels and attributes, between attribute names and equal signs, or between equal signs and attribute values. It is also important to know that events defined by attributes in HTML are executed with HTMLDecode); 3.HTML events (Another special HTML attribute is the event attribute, which generally starts with on. It inherits all the features of normal HTML attributes: case insensitive, quote insensitive, etc.)
- Tips for code injection in CSS: Like HTML, CSS can be divided into selectors, property names, property values, rules, and declarations. Similar to HTML, CSS syntax is case-insensitive, attribute values are insensitive to single quotes, and resource attributes are insensitive to single, double, and no quotes in the URL. Tabs, carriage returns, and newlines can also be parsed by browsers where Spaces can be used. 1.CSS resource class attributes :(similar to HTML resource class attributes, the XSS utilization of some CSS resource class attributes is also completed through pseudo protocol, this utilization mode can only be implemented under IE, and IE9 has been able to defend; CSS also has a class of resource class attributes that can be embedded in XML, CSS, or JavaScript, such as Firefox2’s -moz-binding, IE’s behavior, and the rule @import). 2. Expression :(expression is a CSS property unique to IE, which is used to insert a piece of JavaScript code); 3. CSS code obfuscation using UTF-7 encoding (Introduced monyer online encryption and decryption tool, mentioned two encryption/decryption: UTF7Encode and UTF7Decode. Encoding the page UTF7, which makes it easy to obfuscate our code and bypass their filters)
- Code injection techniques in JavaScript
- Breaking URL filtering: You can use the following techniques to bypass filtering: URL encoding, decimal, hexadecimal, octal, mixed encoding, no HTTP: protocol, and finally a dot;
- More classic confusion checklists: Through a large number of fuzzy tests, many strange XSS utilization points can be found. There are a large number of subtle differences between browsers, making it difficult to summarize perfect rules. You can refer to the collated Checklist on html5sec.org. There is also an online Fuzzing platform (shazzer.co.uk) led by Gareth Heyes.
6.8. Other Case sharing -GmailCookieXSS
- FireCookie is a plug-in for Firefox browser extension Firebug. It is specially used for various operations of cookies, which is very convenient
Chapter VII Exploitation of Loopholes
- To exploit a vulnerability perfectly, it is necessary to ensure that the exploitation process is original, meaning that the victim cannot tell the difference, even after the attack for a long time or never know that such a thing happened
7.1. Preparation before penetration
- 1. Target environment: The penetration of open source CMS can be understood through white box and black box, which greatly facilitates subsequent penetration. For closed source CMS, we can only use black box, will be more troublesome, need to take several steps
- 2. Target users: The target users can play various roles, such as CMS administrator, customer service, common user, hacker or security personnel
- 3. Expected effect: Finally, clarify the effect of each stage in the infiltration process, such as obtaining cookies, adding an article, spreading the Internet, stealing passwords, destroying data, etc
7.2. Theft of private data
- XSS probe: XSSprobe: it can obtain the general data of the target page; Using this common data sometimes allows us to directly obtain the permissions of the target user (exploited through Cookies);
- Referer: Referer refers to the source of the request. Many websites use this to determine which page/website the user came from. Referer is public, so there is no information related to identity authentication or other privacy in the Referer.
- Plain text passwords remembered by browsers: In 2010, the ability to remember passwords was introduced in various browsers (Firefox, Chrome, Internet Explorer, Opera, Safari, etc.), as opposed to the old method of remembering login status. “Remember login state” mainly sets persistent cookies, which are not browser-dependent, but are set by the Web service itself; Remembering a password is more dangerous than remembering the contents of a form, because the password is available through the DOM and is in clear text; This POC can be used in XSS utilization to obtain the plaintext password of the user. Since the password form items are different in different Web environments, you only need to change the value of the related form items.
- Keyloggers: Keyloggers are not really useful as much as the various events that hijack form items;
7.3. Intranet penetration technology
- Intranet penetration is a separate science, and penetration through the Web (mostly JavaScript) is actually a very shallow type of penetration, but it can be very powerful
- Obtaining an Intranet IP address: Currently, you can obtain an Intranet IP address through a Java Applet, which requires JRE
- Obtaining Intranet IP port: When the Image object requests, onError event will be triggered when the resource is obtained (because the resource is not a normal Image), and timeout mechanism will be entered if the resource is not obtained. By this principle, whether the target IP address and port exist can be determined, but this function is not stable. You can also try to obtain IP ports through cross-domain AJAX techniques or Web Socket methods.
- Obtaining Intranet host survival status: the skills of obtaining Intranet host survival status are very good. The essence is to judge through cross-domain AJAX requests, which is relatively stable.
- Enable the remote access capability of a router: By default, remote management IP address is 0.0.0.0. If 255.255.255.255 is set, remote Web management is enabled for any IP address on the Internet. That is, you can log in to the FAST through a browser and enter the user name and password.
- Fragile web application control on the Intranet: The address of the Intranet Web application may be disclosed by Referer, that is, the type of the web application may be guessed by judging the Referer, and the possible web application on the Intranet can also be guessed by fuzzing. Common types of Intranet Web applications include BBS, Blog, Trac, Wiki, OA, WebMail, project management, customer service background, and Web application environment with vulnerabilities.
7.4. Attack technology based on CSRF
- Attack technology based on CSRF is also a relatively common idea: Attack technology based on CSRF is also a relatively common idea
- Including the following contents: SQL injection based on CSRF; Csrf-based command execution; XSS attack based on CSRF;
7.5. Browser hijacking
- Browser hijacking refers to the process of hijacking the user to click the link and inject the attacker’s JavaScript script when opening a new window, so as to extend the XSS threat to other pages in the same domain
7.6. Some cross-domain operation techniques
- Ie RES: cross-domain protocol
- CSS String injection cross-domain: A very interesting cross-domain skills, @ import way import the outland CSS file itself is a normal behavior, and then through the document. The IE body. CurrentStyle. FontFamily way to access the target style the font-family property, Its value is everything after font-family, which is due to the high fault tolerance of CSS
- Browser privilege area risk
- Risk of browser extension: To enrich its own functions, a browser allows third-party plug-ins or extensions. However, if the permissions of these extensions are not properly controlled, serious consequences may occur
- Cross-subdomain: document.domain technical skills: cross-subdomain: Document domain technique is very useful, belongs to the nature of the browser; One legal property is that the page can set document.domain to the current subdomain or to a higher level than the current subdomain.
- More classic cross-domain indexes: 1. Use UNC “cross-domain” : code over the Internet domain (HTTP protocol), e.g
<iframe>
The tag uses the File protocol to call the local XSS vulnerability page and execute arbitrary JavaScript code through the local XSS. Due to the File protocol, it has more permissions. For example, it uses AJAX to read local files. 2. MHTML: cross-domain protocol;
7.7. XSS Proxy technology
- XSS Proxy technology is used in remote control based on browser, which is a very good idea. At present, many XSS frameworks such as XSS Shell, BeEF, Anehta and other remote control frameworks are based on XSS Proxy
- To realize remote control, the following two conditions must be met: the remote control command must be executed in real time on the target browser; The execution results should be visible to the control side
- Four ideas of XSS Proxy technology, each has its own strengths
- The browser
[script]
Request:<script>
Tag request content can cross domain, which is a legal function, the requested data must be a legal JavaScript syntax format; This includes data content such as JSON+CallBack functions (this cross-domain data communication is called JSONP); - Browser Cross-domain Ajax requests: Cross-domain Ajax requests also require the browser setInterval to initiate a server instruction interface request. The only benefit is that the request is made asynchronously and is quieter;
- Server websocket push directive: Strictly speaking, WebSocket technology is not HTML5. It is an innovation of HTTP stateless connection, essentially a persistent socket connection. After the browser client initiates the connection through JavaScript, You can listen to related events and call the socket method to read and write the message on the server side;
- PostMessage push instruction: THE postMessage mechanism of HTML5 is very perfect, which is the most direct cross-document transmission method of the client. It is generally used for cross-domain communication between the parent page and the child page in iframe. This technique can be tricky to use with XSS proxies, where an attacker needs to dynamically generate and transfer instructions across domains on the client side. That’s one way of thinking, but it’s not good;
Chapter 8 HTML5 Security
- HTML5 is now jointly developed by the WHATWG, W3C and IETF
8.1. New tags and attributes bypass the blacklist policy
- Whitelist and blacklist filter policies are important methods to defend against XSS attacks
- Blacklist policy in cross-site
- New element breaks the blacklist policy: One way to circumvent this blacklist policy is for cross-site developers to use morphed code to bypass the semantic range of regular expressions. The other is the new tags and attributes of HTML5, which are mentioned below; 1. New tags available in HTML5 include audio tags
<audio>
And video tags<video>
; 2. New attributes available in HTML5 include formation, onFormchange, onForminput, autofocus, etc.
8.2. New methods in HistoryAPI
- Pushstate () and replacEstate () : Two new methods, pushstate() and replacEstate (), have been added to HTML5’s History API. You can add and modify history entries without refreshing the page
- Short address +history new method = Perfect hide URL malicious code: short address service refers to a long url into a concise URL; When the user clicks the short address, does not know where it points to, at this time the attacker can use the short address feature, the injection of malicious code into the site into the short address, the user clicks the short address, will be attacked; You can now use History’s new methods, pushState() and replaceState(), to change the URL in the address bar without refreshing the page, so that users can’t see the malicious code;
- Falsify history: Use history.pushState to falsify browser history, and you can also launch a Dos attack on history
8.3. Botnets under HTML5
- Botnet (also known as Botnet in English) is an attack network that can send instructions directly to a large number of computers by planting specific malicious programs on a large number of computers through various means
- The use of Web worker: Web worker in HTML5 can enable Web applications to have background processing capabilities, such as parallel computing and background I/O operations for workers, and it supports multithreading very well. Web workers will not cause browser UI to stop responding, and temporary Worker operations will not be noticed by users. However, if a large number of Worker operations are performed for a long time, the CPU cycle will be consumed and the system will slow down, and users may see that the CPU always stays high.
- Cors sends cross-domain requests to any web site: CORS ‘security policy is only about allowing clients to retrieve data returned by the server, but it does not block requests sent by clients
- An HTML5 botnet example: How to control more zombie nodes? Worms can turn an infected user’s browser into a zombie node
8.4. Geolocation reveals your location
- Using the HTML5 Geolocation API, you can ask the user to share their location, and if the user agrees, the application can locate the user’s location
- Privacy protection mechanism: This privacy mechanism is completely controlled by the browser; Users need to pay attention to the function of remembering the sharing Settings, especially when users choose to allow sharing location, which may expose their location all the time.
- Location theft via XSS: It’s easy to get real geographic information like this. Also, combined with native social work skills, the attack is more likely to succeed
Chapter 9 Web Worms
- One of the characteristics of worms is propagation. For Web worms, the medium of propagation is the browser client of Web2.0 website, and the cornerstone of propagation is the vast number of users
9.1.Web worm ideas
- Web worms mainly include XSS worm, CSRF worm and Clickjacking worm. These three worms are related to specific vulnerability risks and can be easily distinguished by name
- The idea of Web worms is simple: user participation, and Web2.0 sites fit the bill
- From the XSS worm to the CSRF worm to the Clickjacking worm to the text worm, the social worker component grows
9.2. XSS worm
- Principle + A story: The two main properties of worms are as follows: transmissible, viral behavior; The following conditions are required for the XSS worm to occur (the target site has key features of Web2.0: user-driven content; XSS vulnerability exists in all of them. The infected user is in the login state, so XSS permission is the login permission, can perform more malicious operations; The key function of XSS worm propagation is content propagation.
- Hazards: XSS worm has large permissions (in general, it has as many permissions as Web users have); 1. Perform arbitrary operations on user data (after the XSS worm spreads, it can perform malicious operations on user data in batches). 2. Denial of service attack (XSS worm can carry out large-scale denial of service attack on target website services, resulting in users unable to use website functions normally); 3. Distributed denial of service attack (the target of distributed denial of service attack is other websites, and each infected user of XSS worm may be geographically distributed in various locations in the country, or even in various locations in the world); 4. Spread advertisements; 5. Communication Web Trojan (under normal circumstances, the horse is using the browser and browser plug-in holes (one of the most notorious zhao is IE ActiveX control) locally, the binary data within the network horse or script virus embedded operating system, local execution on the Web level of threat, spread through these holes to the operating system level. At the operating system level, the permissions of the virus are at least those of the operating system user account); 6. Spread public opinion
- Worms need to pursue native: the framework encapsulates too many excellent functions, for XSS, just call it, can save a lot of custom code trouble, and can greatly reduce the size of XSS worms, such XSS worms are native; 1. Primitive code: A few lines of code can initiate A GET or POST request, and the advantage of using a primitive framework is that it helps us deal with various browser compatibility issues; 2. Original ecology of attack effect: those DIV boxes and UI components can be generated by directly calling some highly packaged JavaScript functions;
9.3. CSRF worm
- About principle and harmfulness: The principle of CSRF worm is basically similar to that of XSS worm, except that CSRF is used here. The attack code exists in the attacker’s page, and the content transmitted by the target website contains the URL of the attacker’s page, so that the attacked on the target website can be tempted to open the attacker’s page, and then CSRF can be triggered. CSRF will continue to publish content containing the attacker’s page URL across domains for dissemination; Unlike the XSS worm, the XSS worm’s attack code is essentially stored on the target website, even if it is
<script>
Referenced from the attacker domain and, for JavaScript context, also belongs to the target website; The dangers of CSRF worm are mostly the same as those of XSS worm, such as obtaining user privacy, maliciously operating user data, spreading advertisements, spreading web Trojan horse, spreading public opinion, etc. - CSRF worm: The attack code can be very covert, plus the Referer judgment. The worm code relies on this Referer value for subsequent operations. Because Ajax cannot fetch resources on third-party servers across domains, server-side proxies are used to fully fetch data across domains (use of microsoft.xmlHTTP controls); It should be emphasized that the premise of worm propagation is that the target user logs in to the target website, and then can see the message and be fooled. The subsequent propagation must bring the target user’s memory Cookie, so this process is not limited to the declaration of the local CookieP3P policy under IE.
- Fanfou CSRF worm – Evil Flash game: Fanfou CSRF worm uses Flash to spread, essentially the ActionScript in the Flash file initiates a CSRF request to Fanfou; There are two types of CSRF requests: One is a Get request to obtain attacker privacy data. The second is the POST request to submit data, so that the victim automatically sends a microblog message and a private message to all his friends. These Web worms are based on the user group, need a lot of user participation, amid the user interaction and communication, and has a relationship of trust between users, in general, if it is your friends send messages to yourself, will go to see, because trust each other,, the worms to spread the use of this feature;
- Analysis of the possibility of the existence of CSRF worm: As the name implies, CSRF worm is a Web worm that uses CSRF technology to spread. The former Yeeyan CSRF worm and related analysis articles explain the fact of the existence of CSRF worm. This CSRF of Yeeyan website is driven by users, and the worm code is stored on another website. The most critical issue to be solved is the transmissibility of the CSRF worm, that is, user-driven transmissibility (active or passive); Several ways to get data across domains: The problem CSRF worm propagation must face is how to get the various necessary unique values. There are three methods: server-side proxy technology, FlashAS cross-domain request technology, JSONHijacking technology; Through the analysis of the propagation principle of CSRF worm, many Web2.0 websites with CSRF vulnerability are facing the threat of CSRF worm. Web2.0 worms are user-driven (passive or active), and with some social work skills, it’s hard to defend against;
9.4. ClickJacking worm
- ClickJacking: The “Don’t Click” worm on Twitter in early 2009;
- ClickJacking worm principle analysis, technology analysis: first, the attacker using ClickJacking technology make worms page, the page URL address use now being short turn to http://tinyurl.com/amgzs6; Design points: CSS style Settings for IFrame and Button label, the layer where iframe label is placed as transparent layer, so that the layer where IFrame label is located is directly above the layer where button label is located; To launch a ClickJacking worm attack, the following two requirements are met: (In a SNS social network, find a page that can submit data directly using HTTP GET; This page can be
<iframe>
The tag contains;) - Facebook LikeJacking: The LikeJacking worm attack on Facebook; Facebook has a plugin service called “Like Button.” Users can add “Like Button” to their blogs or websites, and when visitors browse, they can click this Button to show that they Like the article. When the click is over, the clicked status information is displayed on the visitor’s Facebook page as a status update; An attacker can trick visitors into clicking on the “Like Button” using ClickJacking techniques;
- GoogleReader’s ShareJacking worm: a very popular “one-click sharing” plugin; This kind of plug-in can let the user see in the network of good articles or good resources directly in the form of broadcast news published to their community and friends to share; In addition to the ShareJacking worm attack in Google Reader, this worm attack was also found in Tencent Weibo, Tencent Space, Tencent Friends, Sohu Weibo, Renren and Taojiang River.
- ClickJacking worm outbreak potential: Sharing has become an important part of social content in current SNS networks. ClickJacking worms can be used to attack any community with a shared nature. Twitter share a key page http://twitter.com/intent/tweet has joined in the HTTP header keyword X – FRAME – the OPTIONS to resist ClickJacking attack, Facebook share a key in the page http://www.facebook.com/sharer/sharer.php USES the Frame Busting scripts to resist;
Chapter 10 is about defense
10.1. Browser Vendor Defenses
- X-header of the HTTP response: The extended header field of the HTTP response starts with x-header, which is used to distinguish the standard header field. The header fields related to front-end Security are as follows: X-frame-options, X-Xss-protection, and x-Content-security-Policy. 1. The x-frame-options values are DENY (prohibit loading into any Frame) and SAMEORIGIN (allow loading into only frames in the same domain). 2. The value of x-xss-protection can be: 0 (disable), 1 (by default, make some flags or changes to dangerous scripts to prevent rendering execution in the browser, Chrome and IE behave differently in this area), 1:mode=block (force no rendering, jump to blank page in Chrome, return a # symbol in IE);
- Late CSP strategy: The Web front-end chaos mentioned above, such as THE EXPRESSION of CSS in IE can be written in JavaScript, and HTML tags
<script>
, tag on event, tag style attribute, tag SRC /href/action and other attributes can be embedded JavaScript execution; HTML just does HTML stuff, JavaScript/CSS is executed by loading separate files. The domain where the JavaScript/CSS standalone files reside can be whitelisted, which effectively prevents the loading of related resource files on the attacker domain. This greatly increases the difficulty of XSS attacks, which is the primary purpose of the CSP strategy; The CSP strategy for making the Web front end more orderly, and therefore more secure, is a good trend, and the W3C has been pushing it hard; Currently, Chrome supports the X-WebKit-CSP header instead of the standard X-Content-security-Policy. Here are a few scenarios where CSP is used (1) No external resources are allowed to load, and embedded scripts are allowed to execute; 2. Only external resources of the whitelist are allowed to be loaded, not embedded scripts;)
10.2.Web Vendor Defense
- Domain separation: A good example of domain separation is Google, which has moved some content with little business relevance to unrelated domains
- Secure transport: Many of Google’s most important businesses support SECURE TRANSPORT over HTTPS perfectly (including search). Secure transmission can effectively prevent plaintext packet capture in the local area
- Secure cookies: Like Google, some authentication related cookies must be strictly set to HTTPS transfer, must be HttpOnly flag, so that XSS even if stolen cookies, can not be used correctly
- Good CAPtchas: Captchas certainly degrade the user experience, but the threshold is manageable; Google’s verification code is generally considered to be relatively safe (letters connected, distorted, smooth lines, no noise, etc.). It is very difficult to crack by force, which also brings embarrassment to user experience. It shows that Google attaches great importance to security and would rather sacrifice a little user experience.
- Beware of third-party content: the security of third-party content is often mentioned by everyone, common in the following forms:
<script>
Reference third-party JS files;<iframe>
References to third-party HTML files;<object>
Reference third-party resources such as Flash - XSS defense scheme: some defense policies (input verification: length limit, value type is correct, and contains special characters). Output encoding: encoding according to the output location, such as HTML encoding, JavaScript encoding, URL encoding;)
- CSRF defense scheme: Used to defend against CSRF attacks (1. Check whether the HTTP Referer field is co-domain; 2. Limit the lifetime of Session cookies. 3. Use the verification code. 4. Use one-time tokens;) ; Generally, there are three methods to defend against CSRF: Referer, verification code and token; The disadvantages of captchas are obvious: they affect users; The problems of token are: timeliness cannot be guaranteed; The principle of token protection against CSRF is as follows: The token value in outdomain pages cannot be obtained through AJAX, and XMLHttpRequest must comply with the same origin policy of the browser. The principle of temporary cookies is as follows: Cookies can only be set between parent domain and child domain, and also comply with the same origin policy.
- Interface hijacking defense: The attack mode based on interface hijacking is to use clever visual deception to hijack Web sessions. The attack mode based on interface hijacking is to hijack Web sessions by clever visual deception. Currently, the following defenses can be used to prevent interface hijacking (1. X-frame-options defense: One way to prevent interface hijacking, as proposed by Microsoft, is for Web developers to add an X-frame-options header to the HTTP response header. The browser will use the x-frame-options field to determine whether the page can be embedded with an IFrame. 2.Frame Busting script defense: Use JavaScript scripts to control the page so that the page cannot be embedded by iframe, such a defense script is called Frame Busting script; 3. Use token to defend: in the industry’s mainstream defense interface operation hijacking attack method, it seems that there is no mention of defending against tokens in CSRF;) ; Both the X-frame and Frame Busting methods provide a defense against interface action hijacking. Comparatively speaking, x-frame-options is still safer than Frame Busting. X-frame-options are embedded in the browser, while Frame Busting is scripting control. This means that JavaScript code can always be broken;
10.3. User Defense
- Use the secure browser combination: Firefox +NoScript plugin: NoScript plug-in is mainly developed by Giorgio Maone, a Web front-end security leader. Many contributions in this field can be described as the boutique of security plug-ins, which can defend DOM and reflective XSS, ClickJacking, can force HTTPS requests, etc. It also blocks JavaScript, Flash, Java, etc. from all websites by default
- Follow the principle of minimum trust
10.4. Evil SNS communities
- Attacks in SNS revolve around trust relationship, which is characterized by: people tend to trust people they are familiar with, and the level of trust generally depends on the degree of familiarity and the credibility of the target itself
Write in the back
- PDF books, notes a mind map, along with the book code package download address: pan.baidu.com/s/1CItemx1h…
- Purchase address: u.jd.com/R5ve7p (it is recommended to use paper books to study)
- In order to facilitate the view on the mobile phone, I will post these notes to the public account “Pai SAN Pai Si”, you can scan the code to pay attention, welcome to pay attention.