# XSS

# 什么是XSS

  • Cross-site scripting 跨网站指令码,是代码注入的一种, 是一种网站应用程式的安全漏洞攻击

# 如何攻击

  • 修改HTML节点 或 执行JS代码来攻击网站 (反射型)
    <!-- 通过url获取某些参数 -->
    <!-- http://www.domain.com?name=<script>alert(1)</script> -->
    <div>{{name}}</div> 
    
    1
    2
    3

# 如何防御

  • 转义输入输出的内容
    function escape(str) {
      str = str.replace(/&/g, "&amp;");
      str = str.replace(/</g, "&lt;");
      str = str.replace(/>/g, "&gt;");
      str = str.replace(/"/g, "&quto;");
      str = str.replace(/'/g, "&##39;");
      str = str.replace(/`/g, "&##96;");
      str = str.replace(/\//g, "&##x2F;");
      return str
    }
    
    escape('<script>alert(1)</script>')
    ==> &lt;script&gt;alert(1)&lt;&##x2F;script&gt;
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // 富文本: 白名单过滤
    var xss = require("xss");
    var html = xss('<h1 id="title">XSS Demo</h1><script>alert("xss");</script>');
    // -> <h1>XSS Demo</h1>&lt;script&gt;alert("xss");&lt;/script&gt;
    
    1
    2
    3
    4
  • cookie如何防御
    • 在HTTP头部设置set-cookie
    • httpOnly: 禁止js脚本访问cookie
    • secure: 告诉浏览器仅在请求为https时发送cookie

# 具体案例

# 反射型

访问localhost:8080/goods?category=

const express = require('express')
const path = require('path')
const app = express()
const goods = {
  'book': [{ name: '红楼梦' }, { name: '水浒传' }],
  'computer': [{ name: 'apple' }, { name: 'thinkpad' }]
}

app.use(express.static(path.resolve(__dirname, '../')))

app.get('/goods', (req, res) => {
  let { category } = req.query
  let currentGoods = goods[category]
  let detail = '';
  if (currentGoods) {
    detail = currentGoods.map(item => `<li>${item.name}</li>`).join('')
  } else {
    detail = '无商品'
  }

  res.setHeader('Content-Type', 'text/html;charset=utf8')
  res.send(`
    <h1>您选择的类别是${category}</h1>
    <ul>${detail}</ul>
  `)
})
app.listen(8080)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 存储型

  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h2>欢迎评论</h2>
          </div>
          <div class="panel-body">
            <ul class="list-group" id="comments"></ul>
          </div>
          <div class="panel-footer">
            <form onsubmit="addCommit(event)">
              <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" id="username" class="form-control">
              </div>
              <div class="form-group">
                <label for="content">内容:</label>
                <input type="text" id="content" class="form-control">
              </div>
              <div class="form-group">
                <input type="submit" class="btn btn-primary">
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script>
    $(function () {
      $.get('/api/comments').then(res => {
        if (res.code == 0) {
          let html = res.comments.map(comment => `<li class="list-group-item">
            <div class="media">
              <div class="media-left">
                <a href="#">
                  <img class="media-object" src="${comment.avatar}">
                </a>
              </div>
              <div class="media-body">
                <h4 class="media-heading">${comment.username}</h4>
                <p>${comment.content}</p>
                <p>${comment.time}</p>
              </div>
            </div>
          </li>`).join('')
          $('#comments').html(html)
        } else {
          alert('获取失败')
        }
      })
    })
    function addCommit(event) {
      event.preventDefault();
      let username = $('#username').val()
      let content = $('#content').val()
      $.post('/api/comments', { username, content }).then(res => {
        if (res.code == 0) {
          location.reload();
        } else {
          alert('评论失败')
        }
      })
    }
  </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//server.js
const bodyParser = require('body-parser')
const express = require('express')
const path = require('path')
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.use(express.static(path.resolve(__dirname, '../')))

let defaultComment = { time: new Date().toLocaleString(), avatar: 'https://www.gravatar.com/avatar/836875012qq.com.png' }
let comments = [
  { username: '张三', content: '今天下雨了', ...defaultComment },
  { username: 'lisi', content: '今天下雨了', ...defaultComment }
]
app.get('/api/comments', (req, res) => {
  res.json({ code: 0, comments })
})

app.post('/api/comments', (req, res) => {
  let comment = req.body
  comments.push({
    ...comment,
    ...defaultComment
  })
  res.json({ code: 0 })
})

app.listen(8080)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31