Re: [討論] 為什麼SQL注入和XSS漏洞會這麼氾濫?
※ 引述《dp2046 (Kevin)》之銘言:
: 推 vencil: XSS本來就難防了 就連知名的框架也是不少見被挖出來 02/05 13:10
防 XSS 的重點在於要把 escape 搞懂:在不同的情境下要用不同的 escape
function,不是每個都拿同樣的 escape function。
搞懂就沒有很難防,大多數人只是沒有下功夫。
拿 PHP 來說好了,先假設要傳的 $data 是個不安全的字串,這些情境下要用哪些
escape function:
1. 在 html5 裡,某個 table 裡要呈現的資料:
<!doctype html>
<head>
<meta charset="utf-8"/>
</head>
<html>
...
<body>
<table>
<tr>
<td><?= $data ?></td>
</tr>
</table>
</body>
</html>
2. 在 html5 裡,某個 a link 裡的連結 (連結當然是個字串):
<!doctype html>
<head>
<meta charset="utf-8"/>
</head>
<html>
...
<body>
<a href="<?= $data ?>">link</a>
</body>
</html>
3. 在 html5 裡,某個 a link 裡的連結,裡面的 query string 變數:
<!doctype html>
<head>
<meta charset="utf-8"/>
</head>
<html>
...
<body>
<a href="https://example.com/api?foo=<?= $data ?>"</a>
</body>
</html>
然後這邊假設 $data 是個二維 array,裡面都是字串 (像是
[["a", "b"], ["c", "d"]] 這樣):
4. 在 html5 裡,inline js 的變數:
<!doctype html>
<head>
<meta charset="utf-8"/>
</head>
<html>
...
<body>
<button onclick="javascript:f(<?= $data ?>);">test</button>
</body>
</html>
5. 在 html5 裡,js block 的變數:
<!doctype html>
<head>
<meta charset="utf-8"/>
</head>
<html>
...
<body>
<script>
<!--
var data = <?= $data ?>;
//-->
</script>
</body>
</html>
橘子時間:
1. htmlspecialchars($data) 或是 htmlentities($data)。
2. htmlspecialchars($data) 或是 htmlentities($data)。
3. htmlspecialchars(urlencode($data)) 或是 urlencode($data)。
4. htmlspecialchars(json_encode($data))。
5. json_encode($data)。
附註一下,5. 這邊一定要是 html5 + <!-- 的情況下才能這樣用,原因跟我之前
在 stackoverflow 上問的問題有關:
https://bit.ly/39U38Wz
https://stackoverflow.com/questions/20942452/why-does-script-cause-a-dom-tree-break-on-the-browser
--
Resistance is futile.
https://blog.gslin.org/ & <gslin@gslin.org>
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.116.104.21 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1582437563.A.6F7.html
推
02/23 14:20,
4年前
, 1F
02/23 14:20, 1F
推
02/23 14:36,
4年前
, 2F
02/23 14:36, 2F
→
02/23 15:43,
4年前
, 3F
02/23 15:43, 3F
推
02/23 16:15,
4年前
, 4F
02/23 16:15, 4F
推
02/23 16:17,
4年前
, 5F
02/23 16:17, 5F
→
02/23 16:17,
4年前
, 6F
02/23 16:17, 6F
推
02/23 17:27,
4年前
, 7F
02/23 17:27, 7F
→
02/23 18:04,
4年前
, 8F
02/23 18:04, 8F
→
02/23 18:04,
4年前
, 9F
02/23 18:04, 9F
討論串 (同標題文章)