
Санирование недоверенного HTML (для предотвращения XSS) с конфигурацией, задаваемой белым списком

xss — это модуль, используемый для фильтрации пользовательского ввода с целью предотвращения XSS-атак.
(Что такое XSS-атака?)
Домашняя страница проекта: http://jsxss.com
Попробовать онлайн: http://jsxss.com/en/try.html
xss() из модуля [email protected]: 6.9 MB/sТестовый код см. в каталоге benchmark.
npm install xss
bower install xss
Или
bower install https://github.com/leizongmin/js-xss.git
var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);
Вы можете использовать filterXSSWithResult, чтобы получить как очищенный HTML, так и список удалённых тегов/атрибутов:
var xss = require("xss");
var result = xss.filterXSSWithResult('<script>alert("xss");</script><a href="#" onclick="evil()">click</a>');
console.log(result.html);
// Output: "<script>alert(\"xss\");</script><a href=\"#\">click</a>"
console.log(result.removed);
// Output: [
// { type: "tag", tag: "script", html: "<script>", isClosing: false },
// { type: "tag", tag: "script", html: "</script>", isClosing: true },
// { type: "attr", tag: "a", attr: "onclick", value: "evil()" }
// ]
Режим Shim (эталонный файл test/test.html):
<script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
// apply function filterXSS in the same way
var html = filterXSS('<script>alert("xss");</scr' + "ipt>");
alert(html);
</script>
Режим AMD — shim:
<script>
require.config({
baseUrl: "./",
paths: {
xss: "https://rawgit.com/leizongmin/js-xss/master/dist/xss.js",
},
shim: {
xss: { exports: "filterXSS" },
},
});
require(["xss"], function (xss) {
var html = xss('<script>alert("xss");</scr' + "ipt>");
alert(html);
});
</script>
Примечание: пожалуйста, не используйте URL https://rawgit.com/leizongmin/js-xss/master/dist/xss.js в производственной среде.
Вы можете использовать инструмент командной строки xss для обработки файла. Использование:
xss -i <input_file> -o <output_file>
Пример:
xss -i origin.html -o target.html
Выполните следующую команду, после чего вы сможете вводить HTML-код в командной строке и проверять отфильтрованный вывод:
xss -t
Для получения более подробной информации выполните $ xss -h.
При использовании функции xss() второй параметр можно использовать для указания
пользовательских правил:
options = {}; // Custom rules
html = xss('<script>alert("xss");</script>', options);
Чтобы не передавать options каждый раз, можно также сделать это более быстрым способом,
создав экземпляр FilterXSS:
options = {}; // Custom rules
myxss = new xss.FilterXSS(options);
// then apply myxss.process()
html = myxss.process('<script>alert("xss");</script>');
Параметры в options описаны ниже.
Указав whiteList, например { 'tagName': [ 'attr-1', 'attr-2' ] }. Теги
и атрибуты, отсутствующие в белом списке, будут отфильтрованы. Например:
// only tag a and its attributes href, title, target are allowed
var options = {
whiteList: {
a: ["href", "title", "target"],
},
};
// With the configuration specified above, the following HTML:
// <a href="#" onclick="hello()"><i>Hello</i></a>
// would become:
// <a href="#"><i>Hello</i></a>
Для белого списка по умолчанию обратитесь к xss.whiteList.
Также поддерживается allowList, и он выполняет ту же функцию, что и whiteList.
Указав функцию-обработчик с помощью onTag:
function onTag(tag, html, options) {
// tag is the name of current tag, e.g. 'a' for tag <a>
// html is the HTML of this tag, e.g. '<a>' for tag <a>
// options is some addition informations:
// isWhite boolean, whether the tag is in whitelist
// isClosing boolean, whether the tag is a closing tag, e.g. true for </a>
// position integer, the position of the tag in output result
// sourcePosition integer, the position of the tag in input HTML source
// If a string is returned, the current tag would be replaced with the string
// If return nothing, the default measure would be taken:
// If in whitelist: filter attributes using onTagAttr, as described below
// If not in whitelist: handle by onIgnoreTag, as described below
}
Путём указания функции-обработчика с помощью onTagAttr:
function onTagAttr(tag, name, value, isWhiteAttr) {
// tag is the name of current tag, e.g. 'a' for tag <a>
// name is the name of current attribute, e.g. 'href' for href="#"
// isWhiteAttr whether the attribute is in whitelist
// If a string is returned, the attribute would be replaced with the string
// If return nothing, the default measure would be taken:
// If in whitelist: filter the value using safeAttrValue as described below
// If not in whitelist: handle by onIgnoreTagAttr, as described below
}
Путём указания функции-обработчика с помощью onIgnoreTag:

Открытая платформа XDR и SIEM для обнаружения угроз, анализа журналов, мониторинга целостности файлов, оценки уязвимостей и управления соответствием требованиям на конечных точках и в облачных нагрузках.

Движок сетевой IDS/IPS/NSM с открытым исходным кодом для инспекции трафика в реальном времени, обнаружения и предотвращения вторжений, анализа протоколов и охоты за угрозами на основе правил.

Zeek — это мощный фреймворк для анализа сети, который сильно отличается от типичных IDS, которые вы, возможно, знаете.