Security with nginx

Intro

Okay, I have quite the complicated issue (at least for me) on my soon to be new production network. I am looking for advice from more experienced users with linux, especially advice on secure ways to setup the netwerk I am about the describe. I am still a newbie with all of this and yet I am now responsible for setting up this new network.

Currently I am running around 150+ websites on a setup with one loadbalancer, three webservers and a dataserver in apache. All fine for now, however I am trying to setup a new network with nginx in the new debian because of the huge increase in performance.

I've read lots and lots of information about nginx and apache, run dozens of tests to compare performance in both situations and came to the conclusion that nginx under high pressure (we run almost only WordPress sites) handles requests a lot faster then apache mainly because of the static files (sometimes more then 100 in one page, which the browser can cash obviously but still).

Current setup

  • Debian 9
  • nginx 1.10.3
  • php-fpm (7.0)
  • ldap 3

I have all the data from websites mounted in a /websites directory on each webserver. The configuration files for nginx and fpm are also located in a configuration directory there. Each website (I'll use example.com) has its own user (authenticated through ldap) and is in the group websites (also in ldap). So each user has his home directory in the /websites folder with permissions 700 owner example.com and group websites. This is done so each website runs in his own isolated "island".

This means that for each website configuration I have an php fpm configuration which uses a different socket for each user. Meaning, it can only execute php files in its own website directory, right?. For PHP this works fine and I rather not change this configuration.

Issue

Here comes the issue, nginx is faster because it serves static files directly in comparison to apache which (how we configured it previously) with the mpm-itk module creates separate processes for each user which then serve static files or PHP.

Nginx does this differently, by using php fpm with different sockets for each user I achieve (at least with php) the same as the mpm-itk module does for apache. However nginx can not do this and tries to serve the static files all as the user nginx is run as (www-data as default). So output is generated by PHP (works fine) but nginx does not have permissions to show the static files.

I've been trying to look for a solution for more then a day now and came to a few different conclusions.

Run as root

My colleague said running nginx as root will tackle the issue, surely it will but that does not seem secure to me. Might as well remove the entire "each website has it own user" policy if I am at it.

Add www-data to the websites group

If I could add a unix user (www-data in this case) to an ldap group (which apparently I can't) I could give the group (websites) read permissions (instead of the current 700) so it can read static files everywhere. Only problem is, websites can read files from each other as well which I am trying to avoid. So this does not seem like a proper solution either.

SELinux

I read some documentation and introductions about SELinux and to me this seems like a to complicated way to fix this issue. I never worked with it and running this on a production network like this does not seem like a good idea since I have no idea what I am doing with this.

Conclusion

So, from where I am now what path would a more experienced user take? Do more research in SELinux? AppArmor? Or is there another simpler way to get the same security apaches mpm_itk offers.

This is the last issue I have and I am not looking for all the configuration files to set this up and the exact commands I need to execute thats all done.

I hope someone with more experience can give me some advice or point me in the right direction. It is much appreciated anyway!

2
задан 6 July 2017 в 15:23
1 ответ

SELinux стоит потраченного времени. ИМХО, на самом деле это не так сложно, как кажется, когда вы просто хотите закрепить права на папки.

Но позвольте мне бросить вызов ... Если это в основном Wordpress, я бы выбрал Litespeed Webserver с плагином Wordpress Cache. Вы получаете невероятно быстрый Wordpress за счет кэширования на уровне веб-сервера:

https://www.litespeedtech.com/products/cache-plugins/wordpress-acceleration

И Litespeed имеет простую в реализации встроенную функцию chroot, которая позаботится о вашей безопасности:

https://www.litespeedtech.com/support/wiki/doku.php/litespeed_wiki:config:chroot

«chroot» - это функция в Unix-подобной системе, которая может изменять корневой каталог процесса. Измененный корневой процесс и его дочерний процесс не могут получить доступ к файлам за пределами нового корневого каталога. Это похоже на помещение процесса в тюрьму с физическими ограничениями доступа к файлам, и причина, по которой этот механизм часто называют «chroot-тюрьмой».

Конечно, chroot также возможен с Nginx:

https: // gir.me.uk/posts/nginx-php-fpm-with-chroot.html

Графический интерфейс администратора Litespeed просто делает его очень простым, возможно, соответствующим вашему уровню опыта, лучше, чем делать все из интерфейса командной строки.

Помимо Chroot, у вас также есть опция SuEXEC:

https://www.litespeedtech.com/support/wiki/doku.php/litespeed_wiki:config:suexec-mode

SuEXEC - это функция, позволяющая Веб-сервер LiteSpeed ​​запускает CGI / FastCGI / LSAPI / PHP / Ruby или любые внешние веб-приложения под UID (идентификатором пользователя), отличным от UID процесса веб-сервера.

Это дополнительно решает ваши основные проблемы, связанные с запуском Nginx как корень.

В настоящее время я использую Nginx и Litespeed для создания сайтов Wordpress. В описанных вами ситуациях с высокой посещаемостью я бы рекомендовал Litespeed со специальным плагином в любой день. Кроме того, вы получаете все другие преимущества быстрого обслуживания файлов, которые отделяют Nginx и Litespeed от Apache.

2
ответ дан 3 December 2019 в 11:28

Теги

Похожие вопросы