wiki:devel:security
Различия
Показаны различия между двумя версиями страницы.
Следующая версия | Предыдущая версия | ||
wiki:devel:security [2025/01/03 17:02] – создано vladpolskiy | wiki:devel:security [2025/01/03 17:48] (текущий) – [Reporting Security Issues] vladpolskiy | ||
---|---|---|---|
Строка 1: | Строка 1: | ||
- | ====== | + | ====== |
- | Creating | + | Создание |
- | :!: Improvement of this page is always welcome. It's in a very raw state and should be extended with more indepth info, links and examples. | + | :!: Улучшение этой страницы всегда приветствуется. Она находится в очень сыром состоянии и должна быть расширена более подробной информацией, ссылками и примерами. |
- | ===Summary=== | + | ===Краткое содержание=== |
- | A list of the most common security issues and how to avoid them can be found on this page. A short summary: | + | Список наиболее распространенных проблем безопасности и способы их избежания можно найти на этой странице. Краткое резюме: |
- | * Cross Site Scripting (XSS) -- inserts malicious code into website to manipulate site in browser of user | + | |
- | * Cross Site Request Forgery (CSRF) -- tricks to let you do unknowingly harmful actions on your site | + | |
- | * Remote Code Inclusion -- includes code on server that's executed there | + | |
- | * Information leaks -- there is too much information shown | + | |
- | * SQL injection -- one can do unwanted requests on your data | + | |
- | Also there is added a note about [[# | + | * Межсайтовый скриптинг (XSS) — вставляет вредоносный код на веб-сайт для манипулирования сайтом в браузере пользователя. |
+ | * Подделка межсайтовых запросов (CSRF) — уловки, | ||
+ | * Удаленное включение кода – включает код на сервере, | ||
+ | * Утечка информации – отображается слишком много информации | ||
+ | * SQL-инъекция – можно выполнить нежелательные запросы к вашим данным | ||
+ | Также добавлено примечание о [[# | ||
- | ===== Cross Site Scripting (XSS) ===== | ||
- | This is probably the most common vulnerability to be found in DokuWiki plugins. | + | ===== Межсайтовый скриптинг (XSS) ===== |
- | Cross Site Scripting refers to an attack where malicious JavaScript code is introduced into a website. This can be used to redirect innocent users to malicious websites or to steal authentication cookies. | + | Это, вероятно, |
- | DokuWiki' | + | Cross Site Scripting относится к атаке, при которой вредоносный код JavaScript внедряется на веб-сайт. Это может использоваться для перенаправления невинных пользователей на вредоносные веб-сайты или для кражи аутентификационных cookie-файлов. |
- | ===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 [[request vars]] like '' | + | ===Проверка входных данных=== |
+ | Всегда проверяйте все ваши входные данные. Используйте белые списки, фильтры, | ||
+ | Также ознакомьтесь с нашей главой об обработке [[wiki: | ||
- | ==See also:== | ||
- | * [[wp> | + | ==Смотрите также:== |
- | * [[http:// | + | |
- | ==== Typical Vulnerability Examples ==== | + | * [[wp> |
+ | * FIXME[[http:// | ||
- | Below are some very common problems shown. The examples are very simple to make the general problem clear. Your plugin is probably more complicated, | + | ==== Типичные примеры уязвимостей ==== |
- | === Syntax Bodies === | + | Ниже показаны некоторые очень распространенные проблемы. Примеры очень просты, |
- | Many simple syntax plugins will take some user input and format it in custom HTML. | + | === Синтаксис Тела === |
- | Example: Here is a abridged syntax plugin to wrap a given input in a bold tag. | + | Многие простые плагины синтаксиса принимают часть введенных пользователем данных и форматируют их в виде пользовательского HTML . |
+ | |||
+ | Пример: Вот плагин сокращенного синтаксиса, | ||
<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) { | ||
Строка 65: | Строка 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) { | ||
Строка 88: | Строка 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: | + | Представьте себе плагин, |
< | < | ||
Строка 129: | Строка 130: | ||
</ | </ | ||
- | In the render method of this syntax there might be code like this: | + | В методе рендеринга этого синтаксиса может быть такой код: |
<code php> | <code php> | ||
- | $renderer-> | + | $renderer-> |
. htmlspecialchars($message) | . htmlspecialchars($message) | ||
. '</ | . '</ | ||
Строка 138: | Строка 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-> | ||
Строка 150: | Строка 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 = ''; | ||
Строка 163: | Строка 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> | ||
Строка 195: | Строка 196: | ||
</ | </ | ||
- | Then you process this form as follows: | + | Затем вы обрабатываете эту форму следующим образом: |
<code php> | <code php> | ||
Строка 205: | Строка 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> | ||
Строка 212: | Строка 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> | ||
Строка 231: | Строка 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> | ||
Строка 241: | Строка 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.1735912946.txt.gz · Последнее изменение: — vladpolskiy