Actions

Installation security hints/ru: Difference between revisions

From LimeSurvey Manual

(Updating to match new version of source page)
(Updating to match new version of source page)
Line 4: Line 4:
=Общее=
=Общее=


LimeSurvey опирается на собственную систему безопасности, которая по-умолчанию активирована. Авторы данного программного обеспечения не несут никакой ответственности и не делают заявлений в отношении уместности или безопасности данной программы. Однако, мы подходим к вопросам безопасности довольно серьезно и быстро реагируем - если Вам известны проблемы в безопасности LimeSurvey, пожалуйста, дайте нам знать: info@limesurvey.org или заведите отчет об ошибке на нашем [http://bugs.limesurvey.org баг-трекере] (пожалуйста, отметьте его как частный).
LimeSurvey relies on its own security, which is activated by default. The authors of this software takes no responsibility and makes no claims in relation to the appropriateness or the security level of this software. However, we take security issues very serious and react quickly - if you know of any security problems with LimeSurvey, please let us know either by sending us an e-mail at [mailto:info@limesurvey.org info@limesurvey.org] or by opening a bug report in our [http://bugs.limesurvey.org bug tracker] (please mark it as private).


==Права на файлы в Linux==
==Права на файлы в Linux==
Line 16: Line 16:
<div class="simplebox">[[File:help.png]] '''Подсказка:''' Установка правильных прав доступа к файлам особенно важна для конфигурационных файлов, содержащих в себе критичные данные, такие как, например, пароли.</div>
<div class="simplebox">[[File:help.png]] '''Подсказка:''' Установка правильных прав доступа к файлам особенно важна для конфигурационных файлов, содержащих в себе критичные данные, такие как, например, пароли.</div>


''При этом хочется отметить, что пользователь 'root' всегда сможет получить доступ к Вашим файлам (вне зависимости какие были выставлены права) т.к. это супер-администратор.''
''Bear in mind that the 'root' account will always be granted permission to access your files (no matter what file permissions you set) as it is the super-admin user.''


Web-сервер (на котором запущена LimeSurvey) обычно работает от учетной записи пользователя (user). В Linux, это обычно 'www','www-data' (в Debian/Ubuntu), 'apache' или 'nobody' пользователи. Однако, некоторые хостинг-компании используют системы (такие как suexec), которые запускают скрипты LimeSurvey от имени Вашего пользователя. Разумеется, пользователь от имени которого работает Web-сервер должен иметь право читать файлы LimeSurvey. В то же самое время лишь немногие каталоги должны быть доступны для записи Web-сервером.
The web server (which runs LimeSurvey) is also running under a given identity (user). On Linux, this is usually the 'www', 'www-data' (on Debian/Ubuntu), 'apache' or 'nobody' user. However, some hosting companies use systems (such as suexec) that make possible the running of LimeSurvey scripts with your personal user. Of course, the web server user must have the right to read LimeSurvey files. However, only a small subset of LimeSurvey sub-directories must be writable by the web server user.


<div class="simplebox">[[File:help.png]] '''Подсказка''': очень полезно явно запретить запись во все каталоги, куда Web-сервер и не должен иметь права записывать данные. В этом случае, даже если и будет обнаружена уязвимость LimeSurvey, то основные файлы будут защищены от несанкционированного изменения благодаря правам на файлы в файловой системе.</div>
<div class="simplebox">[[File:help.png]] '''Hint''': It is very valuable to revoke write permission for the web server user to these LimeSurvey sub-directories that do not require it. Indeed, even if a LimeSurvey vulnerability might be discovered, the main files will still be protected from an illicit modification thanks to the file system permissions.</div>


===Установка прав в управляемой системе Linux===
===Установка прав в управляемой системе Linux===


Если Вы сами управляете Web-сервером и настраиваете операционную систему (Вы владелец физического сервера или арендатор виртуального сервера к которому у Вас есть 'root'-доступ), то Вам нужно следовать этим рекомендациям.
If you're managing your web server and operating system configuration (you are the owner of the physical server or are renting a virtual server on which you have root access), you can follow the following the recommendations from below.


Для начала Вы можете установить владельца и группу владельца на файлы LimeSurvey, что облегчит настройку разрешений для файлов установки.
You can first set the owner and group of your LimeSurvey files so that it will ease the file permissions setup. A possible strategy is to set the owner of the LimeSurvey files to your personal username, and the group of the LimeSurvey files to the web server group. Usually, this web server group only contains the web server account (and possibly another webmaster account). For instance, if your username is 'myaccount' and the webserver user is 'apache' in the 'apache' group, then, from a shell access, you can use the following command: <code>$ chown -R myaccount:apache limesurvey/</code>. Then set the file and sub-directories permissions.


Возможная стратегия заключается в установке владельцем Вашей собственной учетной записи пользователя и группы владельца - учетной записи Web-сервера. Обычно группа Web-сервера содержит в себе только учетную запись Web-сервера (и, возможно, другую учетную запись Web-мастера).
For the script to work properly, the write access to some directories is needed:
 
*The /limesurvey/application/config directory requires ''Read & Write'' for saving the application configuration settings.
Например, если Ваше имя пользователя 'myaccount' и имя пользователя Web-сервера 'apache' находящегося в группе 'apache', то в консоли Вы можете набрать следующую команду:
*The "/limesurvey/tmp" directory and its sub-directories are used for imports/uploads and should be set to ''Read & Write'' for your web server.
 
*The upload/directory and all its sub-directories must also have set ''Read & Write'' permissions in order to enable pictures and media files upload.
$ chown -R myaccount:apache limesurvey/
* All other directories and files can be set to ''Read Only''.
 
Затем настроим права для файлов и подкаталогов.
 
Для корректной работы скрипта необходимо чтобы он имел возможность записи в некоторые директории:
*"/limesurvey/tmp" директория и все подкаталоги используются для импорта/выгрузки файлов и должны быть настроены для ''Чтения и Записи'' Вашим Web-сервером.
*Директория upload/ и все подкаталоги также должны быть настроены для ''Чтения и Записи'' Вашим Web-сервером, чтобы иметь возможность загружать картинки и media-файлы.
*Все остальные директории и файлы должны быть установлены в режим доступа ''Только чтение''


<div class="simplebox">[[File:help.png]] '''Подсказка:''' для следования описанным рекомендациям можно выполнить следующие команды:
<div class="simplebox">[[File:help.png]] '''Подсказка:''' для следования описанным рекомендациям можно выполнить следующие команды:


$ chmod -R o-r-w-x limesurvey/
<code>$ chmod -R o-r-w-x limesurvey/</code>


$ chmod -R -w limesurvey/
<code>$ chmod -R -w limesurvey/</code>


$ chmod -R 770 limesurvey/tmp
<code>$ chmod -R 770 limesurvey/application/config</code>


$ chmod -R 770 limesurvey/tmp
<code>$ chmod -R 770 limesurvey/tmp</code>


$ chmod -R 770 limesurvey/upload
<code>$ chmod -R 770 limesurvey/upload</code>


</div>
</div>


===Настройка файловых разрешений на Web-сервере хостинга===
===Setting file permissions on a hosted web server===


Осуществить стандартную процедуру защиты Web-приложения в окружении хостинга довольно сложно, потому что окружения хостинга могут существенно отличаться.
Giving the difficulty of a standard procedure to secure a web application on a hosted environment, it is rather difficult because hosted environments differ in so many ways.


Для корректной работы скрипта необходимо, чтобы он имел доступ на запись в следующие директории:
In the managed server case, the server needs write access to some directories in order for the script to work properly:
*"/limesurvey/tmp" директория и все подкаталоги используются для импорта/выгрузки файлов и должны быть настроены для ''Чтения и Записи'' Вашим Web-сервером.
*The "/limesurvey/tmp" directory is used for imports/uploads and should be set to ''Read & Write'' for your web server.
*Директория upload/ и все подкаталоги также должны быть настроены для ''Чтения и Записи'' Вашим Web-сервером, чтобы иметь возможность загружать картинки и media-файлы.
*The upload/directory and all its sub-directories must also have ''Read & Write'' for your web server in order to enable pictures and media files upload.
*Все остальные директории и файлы должны быть установлены в режим доступа ''Только чтение''
* The other directories and files should be set to ''Read Only''.


<div class="simplebox">[[File:help.png]] '''Подсказка:'''
<div class="simplebox">[[File:help.png]] '''Hint:'''
*В зависимости от конфигурации Вашего Web-сервера будет необходимо выдать права 755 или 777, чтобы сделать возможным запись туда сервером. Сначала попробуйте 755 - если не сработает, то обновите на 777.
* Depending on your web server configuration, you will have to chmod the rights on the writable folders to 755 or 777 to make it writable for the web server. Try 755 first, if it does not work, 'upgrade' to 777.
*Вы также можете убрать доступ на чтение с файла config.php для всех остальных установив на него права 750 - если ничего не работает, то попробуйте выставить 755.</div>
* You can also try to remove other users' read access to config.php by setting this file's permissions to 750 - if it does not work, 'upgrade' to 755.</div>


==Права доступа к файлам в Windows==
==Права доступа к файлам в Windows==


Если Вы используете Windows сервер, то необходимо убедиться, что каталог admin разрешен для записи процессом Web-сервера, при этом на все остальные файлы могут действовать разрешения только на чтение и выполнение.
If you are using a Windows server, your should ensure that the admin folder allows the owner of the web server process to write files to this directory, The rest of the files can be set to read-only and execute.


==Прочие вопросы безопасности==
==Прочие вопросы безопасности==
Line 77: Line 70:


===SSL usage===
===SSL usage===
In general we recommend the usage of SSL for sensitive survey data.
We generally recommend the usage of SSL for sensitive survey data. You usually enable SSL by configuring your web server correctly and using a SSQL certificate. If you have enabled SSL, you should enforce SSL all the time via the [Global settings] option of LimeSurvey. Additionally, you could set only to use 'secure' cookies by editing/adding the [[Optional_settings#Session_settings|related option]] in config.php.
You usually enable SSL by configuring your webserver correctly and using a SSQL certificate.
If you have enabled SSL you should enforce SSL at all time in  the global settings of LimeSurvey. Additionally you should set only to used 'secure' cookies by using the [[Optional_settings#Session_settings|related option]] in config.php.


=== The access to the config.php file ===


===Доступ к config.php===
{{Alert| You must update application/config/'''config.php''' only after the first installation is done and it works.}}


{{Alert|Вы должны обновить application/config/config.php только когда все установлено и работает. Вы должны обновить следующие config.php файлы.}}
The /application/config/config.php file contains a user name and password for your database server. This poses certain security issues, particularly if you are using a login that has high level administrative access to your database. In the event of some error returning the content of this PHP file to a user's browser, your database password and other details could be compromised (please note, that this is a very unlikely scenario). The best way to minimize risk is to set up a specific login that has specific rights only to your LimeSurvey database.


/application/config/config.php - файл содержит имя пользователя и пароль к базе данных Вашего сервера. Вы рискуете заполучить определенные проблемы безопасности, если в данном файле указан пользователь с высоким уровнем административных прав к Вашей базе. В случае возникновения каких либо ошибок, содержимое данного файла может быть отображено на экране браузера, и конфиденциальные данные могут быть скомпрометированы(хотя, это маловероятный сценарий). Лучшим вариантом будет указать в данном файле пользователя, который имеет полномочия лишь внутри базы данных limesurvey.
Another way to secure this information can be to put the certain information from the /application/config/config.php file in a non-web directory, i.e. for Apache users this is the directory above the htdocs (also known as public_html or www) folder. Basically, you will use config.php, but have one line in it - a line that includes the file with ACTUAL configuration information (ex: <code><?php return include("/home/hostfolder/safedata/configreal.php"); ?></code>). Remove all actual configuration information from /application/config/config.php and paste it into the other file (configreal.php) that is mentioned in the /application/config/'''config.php''' file. This other file should be located in a non-web directory. Then /application/config/config.php will not contain database passwords, etc. - just the name of the file that '''DOES''' contain the database info.  


Другим способом дополнительно обезопасить данную систему может быть расположение информации находящейся в файле /application/config/config.php не в Web-директории, т.е. для пользователя Apache эта директория будет находиться выше каталога htdocs (или public_html или www). Таким образом Вы сможете использовать config.php, но с одной единственной строкой в нем - которая подключает актуальную конфигурацию из внешнего источника (например: <?php return include("/home/hostfolder/safedata/configreal.php"); ?>). Удалите всю актуальную конфигурационную информацию из /application/config/config.php и вставьте ее в другой файл (configreal.php), который в свою очередь подключается в файле /application/config/config.php. Подключаемый файл не должен находиться в Web-директории. Таким образом непосредственно в самом файле /application/config/config.php больше не будут храниться конфиденциальные данные, а лишь имя файла, где это содержится на самом деле. Данная манипуляция позволяет избежать необходимости изменять все файлы, которые подключают /application/config/config.php. При этом, Вам необходимо будет отредактировать файл configreal.php и изменить в нем следующие параметры
This avoids having to change all the other files that include /application/config/config.php, since config.php 're-directs them' towards the configuration file that is located in a non-web directory that includes all the real configuration information. However, you will need to edit configreal.php and change the follow parameters to use absolute directory paths to work properly:


<syntaxhighlight lang="php" enclose="div">
<syntaxhighlight lang="php" enclose="div">
Line 103: Line 95:
</syntaxhighlight>
</syntaxhighlight>


чтобы использовать абсолютные пути к каталогам, чтобы все работало должным образом.
Example:
Пример:


<syntaxhighlight lang="php" enclose="div">
<syntaxhighlight lang="php" enclose="div">
Line 118: Line 109:
</syntaxhighlight>
</syntaxhighlight>


Также не используйте "admin" пользователем по-умолчанию. Отправляйтесь в Вашу MySQL базу данных (или другую, если Вы развернули LimeSurvey на какой либо другой базе) и измените имя пользователя по-умолчанию "admin" на какое угодно (например "admin_xyz"). Теперь подобрать имя пользователя администратора будет гораздо сложнее. Пароль администратора - это другая переменная. Выбирайте его с особой тщательностью.
Also, don't use "admin" as the default user. Go to your MySQL database (or the one in which you installed LimeSurvey on different database) and change default user name "admin" to whatever you prefer (e.g. "admin_xyz"). It will be now much harder to guess administrator's new user name. Remember, this is one of the two variables intruders can use to gain access. The admin password is the other variable. So choose both of them with extreme care.

Revision as of 17:05, 7 August 2017

__ОГЛАВЛЕНИЕ__

Общее

LimeSurvey relies on its own security, which is activated by default. The authors of this software takes no responsibility and makes no claims in relation to the appropriateness or the security level of this software. However, we take security issues very serious and react quickly - if you know of any security problems with LimeSurvey, please let us know either by sending us an e-mail at info@limesurvey.org or by opening a bug report in our bug tracker (please mark it as private).

Права на файлы в Linux

Если вы пользуетесь Linux сервером, то требуется настройка прав файлов для обеспечения безопасной установки LimeSurvey.

Основные сведения о правах на файлы в Linux/*nix

Операционная система Linux/*nix - многопользовательская. Это означает, что кроме Вашей учетной записи другие пользователи могут параллельно с Вами находиться в системе и Вам необходимо позаботиться о правах которые Вы даете на файлы для других пользователей.

Подсказка: Установка правильных прав доступа к файлам особенно важна для конфигурационных файлов, содержащих в себе критичные данные, такие как, например, пароли.

Bear in mind that the 'root' account will always be granted permission to access your files (no matter what file permissions you set) as it is the super-admin user.

The web server (which runs LimeSurvey) is also running under a given identity (user). On Linux, this is usually the 'www', 'www-data' (on Debian/Ubuntu), 'apache' or 'nobody' user. However, some hosting companies use systems (such as suexec) that make possible the running of LimeSurvey scripts with your personal user. Of course, the web server user must have the right to read LimeSurvey files. However, only a small subset of LimeSurvey sub-directories must be writable by the web server user.

Hint: It is very valuable to revoke write permission for the web server user to these LimeSurvey sub-directories that do not require it. Indeed, even if a LimeSurvey vulnerability might be discovered, the main files will still be protected from an illicit modification thanks to the file system permissions.

Установка прав в управляемой системе Linux

If you're managing your web server and operating system configuration (you are the owner of the physical server or are renting a virtual server on which you have root access), you can follow the following the recommendations from below.

You can first set the owner and group of your LimeSurvey files so that it will ease the file permissions setup. A possible strategy is to set the owner of the LimeSurvey files to your personal username, and the group of the LimeSurvey files to the web server group. Usually, this web server group only contains the web server account (and possibly another webmaster account). For instance, if your username is 'myaccount' and the webserver user is 'apache' in the 'apache' group, then, from a shell access, you can use the following command: $ chown -R myaccount:apache limesurvey/. Then set the file and sub-directories permissions.

For the script to work properly, the write access to some directories is needed:

  • The /limesurvey/application/config directory requires Read & Write for saving the application configuration settings.
  • The "/limesurvey/tmp" directory and its sub-directories are used for imports/uploads and should be set to Read & Write for your web server.
  • The upload/directory and all its sub-directories must also have set Read & Write permissions in order to enable pictures and media files upload.
  • All other directories and files can be set to Read Only.
Подсказка: для следования описанным рекомендациям можно выполнить следующие команды:

$ chmod -R o-r-w-x limesurvey/

$ chmod -R -w limesurvey/

$ chmod -R 770 limesurvey/application/config

$ chmod -R 770 limesurvey/tmp

$ chmod -R 770 limesurvey/upload

Setting file permissions on a hosted web server

Giving the difficulty of a standard procedure to secure a web application on a hosted environment, it is rather difficult because hosted environments differ in so many ways.

In the managed server case, the server needs write access to some directories in order for the script to work properly:

  • The "/limesurvey/tmp" directory is used for imports/uploads and should be set to Read & Write for your web server.
  • The upload/directory and all its sub-directories must also have Read & Write for your web server in order to enable pictures and media files upload.
  • The other directories and files should be set to Read Only.
Hint:
  • Depending on your web server configuration, you will have to chmod the rights on the writable folders to 755 or 777 to make it writable for the web server. Try 755 first, if it does not work, 'upgrade' to 777.
  • You can also try to remove other users' read access to config.php by setting this file's permissions to 750 - if it does not work, 'upgrade' to 755.

Права доступа к файлам в Windows

If you are using a Windows server, your should ensure that the admin folder allows the owner of the web server process to write files to this directory, The rest of the files can be set to read-only and execute.

Прочие вопросы безопасности

Ниже были приведены только рекомендации. Сама по себе LimeSurvey и так довольно безопасная система, даже без применения указанных мер. Однако, если Вы обрабатываете исключительно конфиденциальные данные, то безопасности никогда не бывает мало и следующее должно Вам помочь:

SSL usage

We generally recommend the usage of SSL for sensitive survey data. You usually enable SSL by configuring your web server correctly and using a SSQL certificate. If you have enabled SSL, you should enforce SSL all the time via the [Global settings] option of LimeSurvey. Additionally, you could set only to use 'secure' cookies by editing/adding the related option in config.php.

The access to the config.php file

  You must update application/config/config.php only after the first installation is done and it works.


The /application/config/config.php file contains a user name and password for your database server. This poses certain security issues, particularly if you are using a login that has high level administrative access to your database. In the event of some error returning the content of this PHP file to a user's browser, your database password and other details could be compromised (please note, that this is a very unlikely scenario). The best way to minimize risk is to set up a specific login that has specific rights only to your LimeSurvey database.

Another way to secure this information can be to put the certain information from the /application/config/config.php file in a non-web directory, i.e. for Apache users this is the directory above the htdocs (also known as public_html or www) folder. Basically, you will use config.php, but have one line in it - a line that includes the file with ACTUAL configuration information (ex: <?php return include("/home/hostfolder/safedata/configreal.php"); ?>). Remove all actual configuration information from /application/config/config.php and paste it into the other file (configreal.php) that is mentioned in the /application/config/config.php file. This other file should be located in a non-web directory. Then /application/config/config.php will not contain database passwords, etc. - just the name of the file that DOES contain the database info.

This avoids having to change all the other files that include /application/config/config.php, since config.php 're-directs them' towards the configuration file that is located in a non-web directory that includes all the real configuration information. However, you will need to edit configreal.php and change the follow parameters to use absolute directory paths to work properly:

'basePath' => dirname(dirname('''FILE''')),
'runtimePath' => dirname(dirname(dirname('''FILE'''))).DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'runtime',
[...]

'urlManager' => array(
   [...]
   'rules' => require('routes.php'),
   [...]
);

Example:

'basePath' => '/var/www/htdocs/limesurvey',
'runtimePath' => '/var/www/htdocs/limesurvey/tmp/runtime',
[...]

'urlManager' => array(
   [...]
   'rules' => require('/var/www/htdocs/limesurvey/config/routes.php'),
   [...]
);

Also, don't use "admin" as the default user. Go to your MySQL database (or the one in which you installed LimeSurvey on different database) and change default user name "admin" to whatever you prefer (e.g. "admin_xyz"). It will be now much harder to guess administrator's new user name. Remember, this is one of the two variables intruders can use to gain access. The admin password is the other variable. So choose both of them with extreme care.