wiki:devel:security
Различия
Показаны различия между двумя версиями страницы.
Предыдущая версия справа и слеваПредыдущая версияСледующая версия | Предыдущая версия | ||
wiki:devel:security [2025/01/03 17:07] – [Security Guidelines for Plugin Authors] vladpolskiy | wiki:devel:security [2025/01/03 17:48] (текущий) – [Reporting Security Issues] vladpolskiy | ||
---|---|---|---|
Строка 18: | Строка 18: | ||
- | ===== Cross Site Scripting | + | ===== Межсайтовый скриптинг |
- | This is probably the most common vulnerability to be found in DokuWiki | + | Это, вероятно, |
- | Cross Site Scripting | + | Cross Site Scripting |
- | DokuWiki's plugin mechanism gives plugin developers a great deal of flexibility. In the case of syntax plugins in particular, the framework gives plugins the ability to work with raw unprocessed output. This means the wiki page data which reaches your plugin has not been processed at all. And there will be no further processing on the output after it leaves your plugin. | + | Механизм плагинов |
- | ===Escaping output=== | + | ===Выход из режима экранирования=== |
- | At an absolute minimum the plugin should ensure any raw data output has all HTML special characters converted to HTML entities using the [[phpfn> | + | Как минимум, |
- | Also any wiki data extracted and used internally | + | Кроме того, следует с подозрением относиться к любым данным вики, извлеченным и используемым внутри компании |
- | ===Input checking=== | + | ===Проверка входных данных=== |
- | Check always all your input. Use whitelists, filters, conversions to the exact data type you mean e.g. from a number inputted as mixed php value to integer and more to ensure you have __only__ data you allowed. | + | Всегда проверяйте все ваши входные данные. Используйте белые списки, фильтры, преобразования в точный тип данных, |
- | Please also refer to our chapter on processing | + | Также ознакомьтесь с нашей главой об обработке |
- | ==See also:== | + | ==Смотрите также:== |
- | * [[wp> | + | * [[wp> |
- | * [[http:// | + | * FIXME[[http:// |
- | ==== Typical Vulnerability Examples | + | ==== Типичные примеры уязвимостей |
- | Below are some very common problems shown. The examples are very simple to make the general problem clear. Your plugin is probably more complicated, but you need to keep track of the same vulnerabilities. | + | Ниже показаны некоторые очень распространенные проблемы. Примеры очень просты, |
- | === Syntax Bodies | + | === Синтаксис Тела |
- | Many simple syntax plugins will take some user input and format it in custom | + | Многие простые плагины синтаксиса принимают часть введенных пользователем данных и форматируют их в виде пользовательского |
- | Example: Here is a abridged syntax plugin to wrap a given input in a bold tag. | + | Пример: Вот плагин сокращенного синтаксиса, |
<code php> | <code php> | ||
class syntax_plugin_bold extends DokuWiki_Syntax_Plugin { | class syntax_plugin_bold extends DokuWiki_Syntax_Plugin { | ||
- | // common plugin functions ommited | + | // общие функции плагина опущены |
public function connectTo($mode) { | public function connectTo($mode) { | ||
Строка 66: | Строка 66: | ||
public function render($format, | public function render($format, | ||
if($format != ' | if($format != ' | ||
- | $renderer-> | + | $renderer-> |
} | } | ||
} | } | ||
</ | </ | ||
- | As you can see, the raw input data captured in the lexer pattern is just passed on to the render method, where no escaping at all is done. Malicious users could introduce what ever JavaScript | + | Как вы можете видеть, необработанные входные данные, захваченные в шаблоне лексера, |
- | The fix is simple: proper escaping. | + | Решение простое: правильный побег. |
<code php> | <code php> | ||
class syntax_plugin_bold extends DokuWiki_Syntax_Plugin { | class syntax_plugin_bold extends DokuWiki_Syntax_Plugin { | ||
- | // common plugin functions ommited | + | // общие функции плагина опущены |
public function connectTo($mode) { | public function connectTo($mode) { | ||
Строка 89: | Строка 89: | ||
public function render($format, | public function render($format, | ||
if($format != ' | if($format != ' | ||
- | $renderer-> | + | $renderer-> |
} | } | ||
} | } | ||
</ | </ | ||
- | === Forms === | + | === Формы |
- | When your plugin provides a form it is very common to validate the input and redisplay the form with the received user input when a validation error occurs. | + | Когда ваш плагин предоставляет форму, очень часто требуется проверить вводимые данные и повторно отобразить форму с полученными данными пользователя в случае возникновения ошибки проверки. |
- | Example: The following shows a form vulenerable to an XSS attack because it does not escape the user provided input correctly: | + | Пример: ниже показана форма, уязвимая для атаки |
<code php> | <code php> | ||
<form action="" | <form action="" | ||
<input type=" | <input type=" | ||
- | <input type=" | + | <input type=" |
</ | </ | ||
</ | </ | ||
- | Providing | + | Предоставление данных |
- | To fix the form use the [[phpfn> | + | Для исправления формы используйте функцию |
<code php> | <code php> | ||
<form action="" | <form action="" | ||
<input type=" | <input type=" | ||
- | <input type=" | + | <input type=" |
</ | </ | ||
</ | </ | ||
- | In general it is recommended to not hand-craft forms, but use DokuWiki' | + | В целом рекомендуется не создавать формы вручную, а использовать |
- | === Classes and other Attributes | + | === Классы и другие атрибуты |
- | Often plugins will accept multiple parameters and options that are used to modify the output of the plugin. | + | Часто плагины принимают несколько параметров и опций, которые используются для изменения выходных данных плагина. |
- | Imagine a plugin accepting the following input to display a message box: | + | Представьте себе плагин, |
< | < | ||
Строка 130: | Строка 130: | ||
</ | </ | ||
- | In the render method of this syntax there might be code like this: | + | В методе рендеринга этого синтаксиса может быть такой код: |
<code php> | <code php> | ||
- | $renderer-> | + | $renderer-> |
. htmlspecialchars($message) | . htmlspecialchars($message) | ||
. '</ | . '</ | ||
Строка 139: | Строка 139: | ||
</ | </ | ||
- | As you can see the message itself is properly escaped, but the class is not. Instead of escaping it might be more sensible to use a whitelist of allowed classes instead with a default fallback: | + | Как вы видите, само сообщение правильно экранировано, |
<code php> | <code php> | ||
- | $allowed = [' | + | $allowed = [' |
if(!in_array($class, | if(!in_array($class, | ||
- | $class = ' | + | $class = ' |
} | } | ||
$renderer-> | $renderer-> | ||
Строка 151: | Строка 151: | ||
</ | </ | ||
- | ===input URLs === | + | ===входные URL-адреса |
- | When a plugin accepts URLs as input you need to make sure, users can not pass the '' | + | Когда плагин принимает URL-адреса в качестве входных данных, необходимо убедиться, |
- | Here is an example how a very simple check could look like, to make sure only http and https URLs are used. | + | Вот пример того, как может выглядеть очень простая проверка, |
<code php> | <code php> | ||
- | // empty URL on protocol mismatch | + | // пустой |
if(!preg_match('/ | if(!preg_match('/ | ||
$url = ''; | $url = ''; | ||
Строка 164: | Строка 164: | ||
</ | </ | ||
- | ===== Cross Site Request Forgery | + | ===== Подделка межсайтовых запросов |
- | This vulnerability often appears into plugins due to the lack of understanding of this issue, often confused with the XSS. | + | Эта уязвимость часто появляется в плагинах из-за отсутствия понимания этой проблемы, ее часто путают с XSS. |
- | Cross Site Request Forgery refers to an attack where the victim' | + | Подделка межсайтовых запросов относится к атаке, при которой вредоносный сайт обманывает браузер жертвы, |
- | ===Adding security token=== | + | ===Добавление токена безопасности=== |
- | DokuWiki | + | DokuWiki |
- | It is your resposibility as the plugin author to actually check the token before executing authorized actions using the [[xref>checkSecurityToken()]] | + | Вы как автор плагина несете ответственность за фактическую проверку токена перед выполнением авторизованных действий с использованием функции |
==See also== | ==See also== | ||
- | * [[wp> | + | * [[wp> |
- | * [[https:// | + | * [[https:// |
- | ==== Typical Vulnerability Example | + | ==== Типичный пример уязвимости |
- | Below is the simplest example to start. You may have a more complicated plugin of your own to secure, here is just a simple example based on form. | + | Ниже приведен простейший пример для начала. У вас может быть более сложный плагин для защиты, вот простой пример на основе формы. |
- | Imagine you want to know something which can be answered to Yes or No, you would have a form of this type: | + | Представьте, что вы хотите узнать что-то, |
<code html> | <code html> | ||
Строка 196: | Строка 196: | ||
</ | </ | ||
- | Then you process this form as follows: | + | Затем вы обрабатываете эту форму следующим образом: |
<code php> | <code php> | ||
Строка 206: | Строка 206: | ||
</ | </ | ||
- | So a user is connected to answer this question, but he doesn' | + | Итак, пользователь подключен, |
- | Now the user is visiting a malicious website, one which know, or not, that the user may be connected to your DokuWiki. | + | |
<code html> | <code html> | ||
Строка 213: | Строка 212: | ||
</ | </ | ||
- | What will the user's browser do then? | + | Что тогда будет делать браузер пользователя? |
- | The browser will process this image as any other and will send a request to this URL. Your plugin will then see that '' | + | Браузер обработает это изображение как любое другое и отправит запрос на этот |
- | That's one of the examples of CSRF. Now, how to fix this security hole? | + | Это один из примеров |
- | ==== Prevent | + | ==== Предотвращение |
- | Remember your form above? Let's add an input in it: | + | Помните вашу форму выше? Давайте добавим в нее ввод: |
<code html> | <code html> | ||
Строка 232: | Строка 231: | ||
</ | </ | ||
- | Do you see the first input? Yes? Good. Now you have to check the security token when you receive the form, before processing it: | + | Видите первый ввод? Да? Хорошо. Теперь вам нужно проверить токен безопасности при получении формы, перед ее обработкой: |
<code php> | <code php> | ||
Строка 242: | Строка 241: | ||
</ | </ | ||
- | As the malicious website will never find the value of the " | + | Поскольку вредоносный веб-сайт никогда не найдет значение скрытого ввода «sectok», ваша форма больше не уязвима для |
- | **Note:** If the security token is not valid, the '' | + | **Примечание**: Если токен безопасности недействителен, '' |
- | ===== Remote Code Inclusion | + | ===== Удаленное включение кода |
- | This attack allows an attacker to inject | + | Эта атака позволяет злоумышленнику внедрить код |
- | **Always filter any input** that will be used to load files or that is passed as an argument to external commands. | + | **Всегда фильтруйте любые входные данные**, которые будут использоваться для загрузки файлов или которые передаются в качестве аргумента внешним командам. |
- | ===== Information leaks ===== | + | ===== Утечка информации |
- | This attack may lead to the exposure of files that should usually be protected by DokuWiki' | + | Эта атака может привести к раскрытию файлов, |
- | **Always filter any input** that will be used to load files or that is passed as an argument to external commands. | + | **Всегда фильтруйте любые входные данные, |
- | **Always use DokuWiki' | + | **Всегда используйте функции проверки |
- | ===== SQL injection | + | ===== SQL-инъекция |
- | This attack is rarely relevant in DokuWiki | + | Эта атака редко актуальна в DokuWiki, поскольку база данных не используется. Однако, |
- | More info: | + | Дополнительная информация: |
- | * [[wp>SQL injection]] | + | * [[wp>SQL injection|SQL-инъекция]] |
- | ===== Reporting Security Issues | + | ===== Сообщение о проблемах безопасности |
- | If you encounter an issue with a plugin please inform the author of the plugin via email, optionally putting | + | Если у вас возникли проблемы с плагином, сообщите об этом автору плагина по электронной почте, при желании указав |
- | Additionally a '' | + | Дополнительно к [[wiki:lugin: |
- | Once the issue was fixed and a new release was made, this field should be removed again. | + | После устранения проблемы и выпуска новой версии это поле следует снова удалить. |
wiki/devel/security.1735913270.txt.gz · Последнее изменение: — vladpolskiy