前端XSS攻击

2019-06-03  本文已影响0人  南蓝NL

什么是XSS攻击

XSS也称为跨脚本攻击,是一种恶意脚本,可以获取用户得cookie、token、session

XSS攻击的分类

  1. 尽量少使用appenChidinnerHTMLouterHTML等标签,而使用innerTexttextContentsetAttribute
  2. 前端过滤

url: 可以使用encodeURIComponent 进行转义

encodeURIComponent('http://www.baidu.com')
"http%3A%2F%2Fwww.baidu.com"

非url

encodeHtml(str) {
      if(str.length == 0) return "";
    return str.replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/&/g,'&amp;')
}

document.write("<script>alert('我是恶意代码')</script>")
document.write(encodeHtml("<script>alert('我是恶意代码')</script>"))

当然这是一个简单的demo,我们常使用AngularVueReact框架都帮我们做好了
比如Angular

import { DomSanitizer } from '@angular/platform-browser';

export class myPage1{
  constructor(private sanitizer: DomSanitizer) {
  }

  onInit():void{
      this.html = this.sanitizer.bypassSecurityTrustHtml('html代码');
     // this.sanitizer 还有很多方法
  }
}

Vuev-textv-html

当然实际情况会跟更复杂,通常对于发生与用户交付的行为,比如input的输入,前端一定要做好校验,限制用户输入的长度、格式等

上一篇 下一篇

猜你喜欢

热点阅读