19. 向 DOM 中插入 HTML 19
错误做法(一)
关闭自动转义
// Within the controller
// Disables strict auto escaping
$sce.enabled(false);
$scope.html = "Hello <b>" + userInput +
"</b>!";
// Within the view
<div>{{html}}</div>
20. 向 DOM 中插入 HTML 20
错误做法(二)
使用 element.html() 插入 HTML
// Within the controller
angular.element(someElement)
.html("Hello <b>" + userInput + "</b>!")
21. 向 DOM 中插入 HTML 21
错误做法(三)
使用 ngBindHtml + trustAsHtml
// Within the controller
$scope.html = $sce.trustAsHtml("Hello <b>"
+ userInput + "</b>!");
// Within the view
<div>{{html}}</div>
22. 向 DOM 中插入 HTML 22
错误做法(四)
使用 ngBindHtml + trustAsHtml
然后自己写 XSS 过滤函数
// Within the controller
var escapedUserInput =
escapeForHtml(userinput);
$scope.html = $sce.trustAsHtml("Hello <b>"
+ escapedUserInput + "</b>!");
// Within the view
<div>{{html}}</div>
23. 向 DOM 中插入 HTML 23
正确做法
使用 ngBindHtml + sanitizer
<body>
<script src="../1.5.7/angular.js"></script>
<script src="../1.5.7/angular-sanitize.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-bind-html="html"></p>
</div>
<script>
var userInput = 'test<svg/onload=alert(1)>';
var myApp = angular.module('myApp', ["ngSanitize"]);
var controller = myApp.controller('myCtrl',
function($scope) {
$scope.html = "Hello <b>" + userInput + "</b>!"
});
</script>
</body>
24. 混用第三方库时的风险 24
开发时往往会用到很多第三方库
单独使用时可能没有漏洞,
但与 AngularJS 混合使用时就出现
问题了。
<script>
// A non angular-related library.
// Secure without Angular. Insecure with
Angular.
document.write(escapeForHTML(userInput));
</script>
<script
src="../angularjs/1.5.7/angular.min.js"></script>
29. AngularJS 校验 URL 的方式 29
错误做法(一)
在协议处使用通配符
// Whitelist all possible schemes
"**://example.org/*"
● Exploit 1:
http://evil.com/?ignore=://example.org/a
● Exploit 2:
javascript:alert(1);//example.org/a
// Less permissive, but still bad
"*://example.org/*"
● Exploit 1:
javascript://example.org/a%0A%0Dalert(1)
注释 换行
30. AngularJS 校验 URL 的方式 30
错误做法(二)
在域名里使用 ** 通配符
// Whitelist all possible subdomains
"https://**.example.org/*"
● Exploit 1:
https://evil.com/?ignore=://example.org/a
// Whitelist all possible top level domains
"https://example.**"
● Exploit 1:
https://example.evil.com
● Exploit 2:
https://example.:foo@evil.com
31. AngularJS 校验 URL 的方式 31
错误做法(三)
使用正则表达式
// Use a RegEx to whitelist a domain
/http://www.example.org/g
● Exploit 1:
// (dots are not escaped)
http://wwwaexample.org
● Exploit X:
All the wildcard-based exploits can be
applied as well