====== Безпека ====== DokuWiki - це веб-застосунок, який часто використовується на публічних серверах, доступних з Інтернету. Це означає, що він перебуває у великому ризику бути атакованим зловмисними особами, ніж, наприклад, локальний застосунок на вашій робочому столі. DokuWiki розроблено з урахуванням безпеки. Ми намагаємося знайти баланс між зручністю для користувачів та безпекою, але віддаємо перевагу безпеці, коли неможливо знайти задовільний компроміс. Ця сторінка повинна надати вам огляд того, на що варто звернути увагу, щоб забезпечити безпеку вашої DokuWiki. ===== Звітування та сповіщення ===== Коли ви виявляєте проблему безпеки в DokuWiki, будь ласка, повідомте нас. Найбажаніші способи цього зробити: * Повідомлення через [[https://www.huntr.dev/repos/splitbrain/dokuwiki|huntr.dev]] * Подання [[:bugs|звіту про помилку]] * Відправка листа на [[:mailinglist]] * Відправлення приватного листа на [[andi@splitbrain.org]] * Перші два способи повинні бути віддані перевагу, за винятком дуже серйозних помилок, де оприлюднення помилки перед виходом патча може піддати ризику встановлення DokuWiki по всьому світу. Попередні проблеми безпеки можна побачити в [[https://github.com/dokuwiki/dokuwiki/issues?q=label%3ASecurity+|системі відстеження помилок]]. Залежно від серйозності виявленої проблеми безпеки, вона буде виправлена у майбутньому випуску (у випадку дуже незначних проблем) або буде створено виправлення. У останньому випадку користувачі будуть проінформовані через механізм [[:update check]]. Ви повинні **завжди** використовувати найновіший випуск DokuWiki, оскільки для старших версій не видаються виправлення безпеки. ===== Безпека доступу через веб-інтерфейс ===== DokuWiki зберігає конфігураційні дані та дані сторінок у файлах. Ці файли ніколи не повинні бути доступні напряму з Інтернету. Дистрибутивний архів містить набір файлів ''.htaccess'', які зазвичай вказують веб-серверу Apache відмовляти в доступі до певних каталогів. **IЯкщо ви не використовуєте веб-сервер Apache або ваш Apache не використовує файлів ''.htaccess'', вам потрібно вручну захистити свій веб-сайт**I Наступні каталоги не повинні бути доступні з Інтернету: * ''data'' * ''conf'' * ''bin'' * ''inc'' (не є небезпечним, коли доступний, хоча) * ''vendor'' (розкриває інформацію про ваше середовище) Щоб перевірити, чи потрібно налаштувати права доступу, спробуйте отримати доступ до ''%%http://yourserver.com/data/pages/wiki/dokuwiki.txt%%''. Ви не повинні мати доступ до цього файлу таким чином. [[:admin_window|Адміністративний інтерфейс]] також перевірить це за вас і відображатиме попередження, якщо щось не так. Зверніть увагу, що це не має нічого спільного з [[install:permissions|правами доступу до файлів]]. Веб-доступ - це налаштування, специфічне для вашого веб-сервера. Якщо ваші каталоги не захищені належним чином, прочитайте наступні підрозділи про те, як це зробити. ==== Deny Directory Access in Apache ==== The simplest way is to enable ''.htaccess'' support in your Apache configuration. Please see the [[http://httpd.apache.org/docs/2.2/howto/htaccess.html|Apache .htaccess Tutorial]]. DokuWiki already comes with correctly configured ''.htaccess'' files. The contents of a ''.htaccess'' file to block all access to the directory it is in should be as follows (valid for both Apache 2.2 and 2.4): Order deny,allow Deny from all Require all denied Please note that many distributions have .htaccess support disabled by default. To enable it you need to set the [[https://httpd.apache.org/docs/current/mod/core.html#allowoverride|AllowOverride]] directive from ''None'' to ''All'' for the directory your wiki is installed in. Check this [[https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles|detailled tutorial for Ubuntu]]. Configuration for Apache on other distributions is very similar. Alternatively you can use the [[https://httpd.apache.org/docs/current/mod/core.html#locationmatch|LocationMatch]] directive to prevent access to the mentioned directories without enabling .htaccess support. This has better performance, but you may need to update the directive in the future when new directories are added in DokuWiki. An example may look like this: Order allow,deny Deny from all Satisfy All ==== Deny Directory Access in IIS ==== Access to the mentioned directories can be disabled in IIS' configuration settings. === In IIS 8+ === (Windows 8(.1) and Servers 2012 and 2012R2): - select "IIS Request Filtering" - go to the "URL" tab - click on "Deny Sequence..." - enter "/data/" in the popup box and click "OK" - Repeat the "Deny Sequence..." instruction for the /conf/ /bin/ /inc/ and /vendor/ directories === In IIS 7 === - select "IIS Request Filtering" - go to the "URL" tab - click on "Deny Sequence" - enter "/data/" in the popup box Note: By default, the Management Console snap-in for Internet Information Services 7 does not have UI access to "IIS Request Filtering" section. However, can be enabled by installing "IIS Administration pack 1.0" by using the [[http://www.microsoft.com/web/downloads/platform.aspx|Web Platform Installer]]. Also note: Ensure you enter "/data/" and NOT just "/data", otherwise pages that start with "data" will be inaccessible. === Alternatives for IIS 7+ === If you can't access IIS configuration options (as in shared hosting sites), you can use one of the following methods //Alternative 1:// You can place the following file in your dokuwiki root: //Alternative 2:// You can put the following web.config file in the directories you have to protect. * ''data'' * ''conf'' * ''bin'' * ''inc'' (isn't dangerous when accessible, though) * ''vendor'' === IIS 6.5 and below === - Open the configuration tool: Start -> Settings -> Control Panel -> Administrative Tools -> Internet Information Services - Navigate to the directory you want to protect: Local Computer -> Web Sites -> Default Web Site → //path to directory// - Right-Click the folder and chose Properties -> Directory Security -> IP address and domain name restrictions -> Edit... - Choose "By default, all computers will be: Denied access" - Repeat this for /data/ /conf/ /bin/ /inc/ and /vendor/ directories ==== Deny Directory Access in Lighttpd ==== Using a [[https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModRewrite||URL re-write]] you can deny access to the above directories. In your /etc/lighttpd/lighttpd.conf file adding the following URL rewrite rule should be sufficient to keep people out. It supposes your Dokuwiki files are installed under http://yourwebsite.tld/dokuwiki/. url.rewrite-once = ( "^/dokuwiki/(data|conf|bin|inc|vendor)/+." => "/nonexistentfolder" ) Don't forget to uncomment or add “mod_rewrite” in the server.modules section of /etc/lighttpd/lighttpd.conf. It should look like this: server.modules += ( "mod_compress", "mod_dirlisting", "mod_staticfile", "mod_rewrite", ) Unfortunately it does not keep people out who are using Vivaldi and probably other Chromium based browsers. When combined with “[[https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModAccess|mod_access]]” it does keep people out. More mod_access examples are available [[https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModAccess|here]].\\ In /etc/lighttpd/lighttpd.conf "mod_access" should be in the "server.modules = (" section. Also add $HTTP["url"] =~ "^/dokuwiki/(data|conf|bin|inc|vendor)/+." { url.access-deny = ("") } to /etc/lighttpd/lighttpd.conf.\\ \\ Restart lighttpd with systemctl reload-or-restart lighttpd and check the status with systemctl status lighttpd ==== Deny Directory Access in Nginx ==== Access to aforementioned directories can be disabled in DokuWiki server section of Nginx configuration file. In your host configuration file (for example, /etc/nginx/sites-available/default) or nginx.conf file add the following location to prevent access to secure directories. :!: Make sure that the rule is processed before other rules that control access to certain files.((See this [[https://forum.dokuwiki.org/d/21122-security-warning-persists/9|forum thread]] and [[https://stackoverflow.com/questions/76369813/why-are-my-jpg-and-png-files-accessible-despite-nginx-access-restriction|stackoverflow]])) location ~ /(data|conf|bin|inc|vendor)/ { deny all; } Note: if you are using [[config:xsendfile|xsendfile]], the above rules will break sendfile functionality. Consider the following: location ~ /(conf|bin|inc|vendor)/ { deny all; } location ~ /data/ { internal; } ==== Deny Directory Access in Cherokee ==== It is relatively easy to forbid access to those directories using Cherokee. In cherokee-admin, select the virtual server where dokuwiki is installed and select rules management. then add a new "Regular Expression" rule and put the following in it (supposing that dokuwiki sits on the root directory): /(data|conf|bin|inc|vendor)/ Remember to set it as "NON FINAL", because if not, some code under those directories may still being executed under certain circumstances ("Extensions php" rule as "NON FINAL" present, for example). Then go in "Handler" section and select HTTP Error. Finally select "403 Forbidden" in HTTP Error. ==== Deny Directory Access in Caddy ==== Here is an example Caddyfile for a wiki served with [[https://caddyserver.com|Caddy]]: wiki.example.com { log /var/log/caddy/dokuwiki.log root /var/www/dokuwiki/ # Assuming install/config of php-fpm # to listen on localhost:9000 fastcgi / 127.0.0.1:9000 php # This block below sends an HTTP 401 message when # a client attempts to access the secured directories. status 401 { /data /conf /bin /inc /vendor } } ==== Move Directories out of DocRoot ==== The most secure way to avoid any access to the mentioned directories is to move them outside the so called "Document Root" of your Webserver. This is usually not needed if you followed the guides above and requires a bit more understanding on how webserver and DokuWiki works. None-the-less it is the safest way to secure your DokuWiki install regardless of the used webserver. **__WARNING:__** If you are planning to use the [[installer]], you need to install your wiki executing the install.php script first before you can do this step. If the Move Directories operation is done before, the installer execution will fail. === data Directory === - Move the ''data'' directory (and all its contents) out of the document root - Edit the [[config:savedir]] setting to point to the new location of the ''data'' directory. For example, if the ''data'' directory is moved to ''/home/yourname/data'', add the following line to ''conf/local.php'': $conf['savedir'] = '/home/yourname/data'; === conf Directory === - Move the ''conf'' directory (and all its contents) out of the document root - Create a file named ''preload.php'' inside the ''inc'' directory and set the ''DOKU_CONF'' define to the new location of the ''conf'' directory. For example, if the ''conf'' directory is moved to ''/home/yourname/conf'', create the following ''inc/preload.php'': === bin Directory === The bin directory contains [[CLI]] tools. If you don't have shell access on your server anyway you can simply delete the directory and its contents. Otherwise just move it out of the document root. No further configuration needed. === inc Directory === There is currently no easy way to move this directory out of the document root. But since it doesn't contain any sensitive data it isn't worth the effort to try anyway. ===== DokuWiki Configuration Settings ===== DokuWiki contains several configuration settings that have an impact on various security aspects of the installation. Please refer to the documentation of each setting to learn what they do and what suggested settings are. * [[config:allowdebug]] -- disabling debugging output to avoid system information leakage :!: * [[config:fmode]], [[config:dmode]] -- set the file permissions of DokuWiki created files, also read info on setting up [[permissions]] * [[config:fetchsize]] -- configure caching of external data * [[config:fullpath]] -- showing full path names for pages * all [[auth|authentication settings]] * [[config:usewordblock]] -- prevent spam through a blocklist * [[config:mailguard]] -- avoid mail address harvesting robots * [[config:iexssprotect]] -- protect against a XSS problem within Internet Explorer * [[config:htmlok]] -- enable HTML * [[config:phpok]] -- enable PHP * [[config:hidepages]] -- hide certain pages from indexes and search * [[config:safemodehack]] -- work around safe mode restrictions * [[config:disableactions]] -- disable certain actions, e.g. registration or view source * [[config:baseurl]] -- set a fixed server name the wiki should use to avoid server name spoofing attacks ===== Plugin Security ===== DokuWiki has [[plugins|lots of community contributed plugins]]. Plugins add new functionality to DokuWiki by adding new code. This means the code has practically any access to your server. Additionally plugins are distributed separately from DokuWiki in an entirely ad-hoc manner. They are not subject to the same degree of attention and review that the core DokuWiki code base gets. So security precautions are necessary before installing a plugin. Here are some tips to help you with choosing the plugins you install. * If you can, review the plugin source code yourself, //before// installing it. * If in doubt, ask on the [[mailinglist|mailing list]]. * Plugins are installed under the DokuWiki ''lib'' directory, which is directly accessible from the outside. Review what a plugin contains and if access is appropriate, plugins shouldn't store sensitive info in their own directory. * Plugins are authored by developers not directly related to the DokuWiki project - they may be inexperienced, have malicious intent or may host the plugin source code on a server that has been compromised. Be careful whom you trust! * Review the plugin page for mentioned security warnings and upgrade the plugin when new releases become available. * If in doubt, let plugins be reviewed by a professional first. See [[faq:support]]. See also: [[devel:security#reporting_security_issues|How to report security issues in plugins]] ===== Access Control ===== With [[acl|Access Control Lists (ACL)]] you can restrict which pages and/or namespaces users have access to. You can give read and write permissions depending on the user group or single users. ===== Additional Reading ===== Here are a few more internal and external pages related to security. * [[tips:httpslogin|Force login via HTTPS]] * [[install:php|PHP Configuration for DokuWiki]] * [[tips:clean_acl|Remove ACL rules for deleted pages]] * [[https://www.feistyduck.com/library/apache-security/|Apache Security]]