Suexec error log

This document covers a number of ways to figure out how to fix your Apache installation when things are not working correctly.

This document covers a number of ways to figure out how to fix your Apache installation when things are not working correctly.

Checking the Logs

If there is something wrong with your Apache, but you have no idea how to figure out what’s wrong, your first clues will be in the log files.

There are a few log files around. All of them are located inside /var/log/apache2/. Not all of the following log files will be on your system: this depends on what modules you have enabled.

access_log and ssl_access_log

CODE access_log

67.185.0.236 - - [18/Jun/2005:12:05:50 -0700] "GET / HTTP/1.0" 200 721
10.0.1.80 - - [18/Jun/2005:12:11:07 -0700] "GET /~jaspenelle/__journal1.jpg HTTP/1.1" 200 19079
66.239.233.163 - - [18/Jun/2005:12:15:06 -0700] "GET /~jaspenelle/avy14.gif HTTP/1.0" 200 1661
67.185.60.155 - - [18/Jun/2005:12:18:48 -0700] "GET / HTTP/1.0" 200 721
67.185.0.236 - - [18/Jun/2005:12:25:39 -0700] "GET / HTTP/1.0" 200 721
10.0.1.80 - - [18/Jun/2005:12:28:04 -0700] "GET /~jaspenelle/avy14.gif HTTP/1.1" 200 1661
10.0.1.80 - - [18/Jun/2005:12:28:46 -0700] "GET /~jaspenelle/avy7.png HTTP/1.1" 200 13066

This file is simply a listing of every file requested from your server. Unless you have changed the default configuration, it will be in Common Log Format:

CODE Common Log Format syntax

remotehost rfc931 authuser [date] "request" status bytes
remotehost Remote host name or IP address
rfc931 The remote log name of the user.
authuser The user name as which the user has authenticated himself.
[date] Date and time of the request.
«request» The request line exactly as it came from the client.
status The HTTP status code returned to the client.
bytes The content-length of the document transferred.

error_log and ssl_error_log

CODE error_log

[Mon Feb 07 23:33:18 2005] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec2)
[Mon Feb 07 23:33:18 2005] [notice] Digest: generating secret for digest authentication ...
[Mon Feb 07 23:33:18 2005] [notice] Digest: done
[Mon Feb 07 23:33:18 2005] [notice] Apache/2.0.52 (Gentoo/Linux) PHP/4.3.10 configured -- resuming normal operations
[Sat Jun 18 13:01:54 2005] [error] [client 10.0.1.80] File does not exist: /var/www/localhost/htdocs/favicon.ico
[Sat Jun 18 13:02:14 2005] [error] [client 10.0.1.80] File does not exist: /var/www/localhost/htdocs/favicon.ico
[Sat Jun 18 13:02:18 2005] [error] [client 10.0.1.80] File does not exist: /var/www/localhost/htdocs/favicon.ico
[Sat Jun 18 13:02:21 2005] [error] [client 10.0.1.80] File does not exist: /var/www/localhost/htdocs/favicon.ico
[Sat Jun 18 13:02:24 2005] [error] [client 10.0.1.80] File does not exist: /var/www/localhost/htdocs/favicon.ico

As you can see, this file can contain a lot of stuff, depending on the ErrorLevel directive in your httpd.conf file. It tells you if apache started up correctly, what errors it has run into, … In general it will tell you what went wrong. If something isn’t working right, this should be the first file you check for more information.

suexec_log

CODE suexec_log

[2005-02-11 22:33:19]: uid: (1000/vericgar) gid: (1000/1000) cmd: test.cgi
[2005-03-11 19:20:13]: uid: (1000/vericgar) gid: (1000/1000) cmd: test.cgi
[2005-03-11 19:34:47]: uid: (1000/vericgar) gid: (1000/1000) cmd: test.cgi

This file contains a log entry for every time a script is ran using CGI and suexec. If you can’t get a script to work with suexec, this log is the one to check as it will generally have a line listing why it wouldn’t run a script.

I installed a module, but it’s not working!!!

Just installing a module is not enough — you have to explicitly turn it on. We do this so that it’s easy to turn on and off individual modules, which makes it easy to find which module is causing problems and let’s you test modules and disable them easily.

When you install a module, it should display a message similar to this:

CODE Post-installation message from emerge

* 
 * To enable mod_layout, you need to edit your /etc/conf.d/apache2 file and
 * add '-D LAYOUT' to APACHE2_OPTS.
 * 
 * 
 * Configuration file installed as
 *     /etc/apache2/modules.d/15_mod_layout.conf
 * You may want to edit it before turning the module on in /etc/conf.d/apache2
 *

This is pretty straightforward. It tells you exactly what you need to do to enable this module.

If you missed this message, there is another way to find out what you need to add to APACHE2_OPTS in /etc/conf.d/apache2: simply check the configuration file the module installed. The module’s configuration file should be added to /etc/apache2/modules.d/. Look for it there and find a line that has IfDefine:

CODE An excerpt from 15_mod_layout.conf

<IfDefine LAYOUT>
  <IfModule !mod_layout.c>
    LoadModule layout_module    modules/mod_layout.so
  </IfModule>
</IfDefine>

The IfDefine block is ran when you add -D LAYOUT to /etc/conf.d/apache2. The LAYOUT is just an example.

There are several options you can add to APACHE2_OPTS that are specified in the default configuration and well explained in /etc/conf.d/apache2.

Documentation for all of the built-in modules can be found in the Apache 2.0 documentation.

Apache is returning zero-length pages or segfaulting

This happens mostly after an upgrade because binary compatibility broke in APR (which may happen for a number for reasons). To fix this, you need to rebuild the Apache tool stack:

CODE Rebuilding the Apache tool stack

# (make sure you do these in order, it's very important!)

# (first, we have to remove the currently installed apache)
emerge -aCv '=www-servers/apache-2*'

# (then we rebuild the tool stack)
emerge -av '=dev-libs/apr-0*' '=dev-libs/apr-util-0*'

# (then we reinstall apache)
emerge -av '=www-servers/apache-2*'

# (determine any packages that depend on apache)
equery depends www-servers/apache
[ Searching for packages depending on www-servers/apache... ]
dev-php/phpsysinfo-2.3-r2
dev-php/phpsysinfo-2.1-r2
dev-lang/php-5.2.4_p20070914-r2
net-www/mod_layout-4.0.1a-r1
www-servers/gorg-0.5

# (then rebuild any modules you have installed)
emerge -av '=dev-lang/php-5.2.4_p20070914-r2' '=net-www/mod_layout-4.0.1.a-r1'

Determining a buggy add-on module

If you are still having problems after following the instructions above, the culprit is most likely one of your installed add-on modules.

Start off by disabling all add-on modules and restarting Apache.

CODE Disabling add-on modules

(edit /etc/conf.d/apache2)

(before the change)
APACHE2_OPTS="-D PHP5 -D USERDIR -D SSL"

(after the change)
APACHE2_OPTS=""

CODE Restarting Apache

/etc/init.d/apache2 stop
# (make sure apache is completely stopped)
ps -A 
/etc/init.d/apache2 start

Note
You may have to make minor changes to some places of your configuration if you have added Directives that these modules provide in places that don’t test for the module being loaded. It’s recommended that Directives like these be placed in test containers. See any of the .conf files in /etc/apache2/modules.d examples.

If Apache quits segfaulting and giving blank pages, then you know for sure it was one of the add-on modules. To figure out which add-on modules, we add them back, one at a time, completely restarting apache every time.

When Apache stops working after adding a module back, you know that module is the one that is causing problems. Sometimes, simply rebuilding the module will fix the problem.

If after rebuilding the module and restarting apache, you are still having problems with Apache segfaulting or returning blank pages, you should file a bug listing the specific version and revision of the module and mention that it is segfaulting. Be sure to search for already open bugs first!

Webserver doesn’t interpret PHP or CGI scripts and returns their code instead

Apache sometimes appears to return the PHP or CGI code instead of running those scripts and returning the script output. If this happens even though the module is enabled in /etc/conf.d/apache2 it’s very likely to be a cache issue. Clearing the webbrowser cache fixes this browser side issue.

Sometimes this problem can also be seen only when accessing the webserver using it’s DNS name but not when accessing the webserver using its IP address. This is a strong indication that it’s a cache issue.

This problem can be fixed by clearing the webbrowser cache and any other webproxies like squid or wwwoffle.

configure: error: changes in the environment can compromise the build

If you get this error, then you probably have unneeded spaces in your CFLAGS in /etc/make.conf . The fix is simple, remove the extra spaces:

CODE Example of changes to /etc/make.conf

(before the change)
CFLAGS="-O2 -mcpu=pentium3 -march=pentium3  -pipe"

(after the change - notice the removal of the space)
CFLAGS="-O2 -mcpu=pentium3 -march=pentium3 -pipe"

Address already in use: make_sock: could not bind to address 0.0.0.0:443

This error occurs during start-up and is caused by having multiple Listen directives in your configuration that are incompatible. To solve this problem, you should grep your configuration for Listen and fix each occurrence.

CODE Finding all Listen directives

(Make sure you are in the configuration directory)
# cd /etc/apache2/

(List all listen directives)
# grep Listen httpd.conf vhosts.d/*.conf modules.d/*.conf

What you are looking for conflicts with what Apache is trying to bind to. For example, if there is a Listen 80 in httpd.conf and there is a Listen 10.0.0.15:80 in another file, then Apache will not be able to start. This is because Apache first binds to port 80 on all IP addresses for the machine and then tries to bind to port 80 on IP address 10.0.0.15 and fails because port 80 is already in use.

The recommended configuration is that you have a single Listen 80 (this is in the default httpd.conf ) so that you bind to all addresses by default for the standard HTTP port and then for every SSL VirtualHost you run you create a separate absolute Listen directive (such as Listen 10.0.0.15:443 ).

After upgrade to apache-2.0.54-r13 the default vhosts (SSL and non-SSL) don’t work any more

With the upgrade to apache-2.0.54-r13, two new directives were added to it to fix bug 100624.

The new directives are -D DEFAULT_VHOST to activate the default virtual host and -D SSL_DEFAULT_VHOST to activate the default SSL virtual host. Both need to be added to the APACHE2_OPTS variable in /etc/conf.d/apache2 if you want Apache to behave like before.

Getting Help

If none of the above was of any use to you, or if you have other questions, feel free to stop by our IRC channel, #gentoo-apache (webchat). Or you may also file a bug on Gentoo’s Bugzilla.

Acknowledgements

We would like to thank the following authors and editors for their contributions to this guide:

  • Michael Stewart
  • Elfyn McBratney
  • Bryan Østergaard
  • Benedikt Böhm

 Самыми распространенными ошибками mod_fcgid являются «Premature end of script headers», «can’t lock process table in pid», «can’t apply process slot», «couldn’t bind unix domain socket», «exit(communication error), get unexpected signal 11″…

Причины этих ошибок могут быть разные, от неправильных прав на файлы до неполной загрузки файла на сервер, не правильно написанного скрипта и неправильного режима передачи файла ASCII/Двоичный. Иногда бывает проблема кроется в переводе строк Windows формата, в этом случае может помочь команда col -bx <input_file> output_file (скобки обязательны!) или редактор notepad++ «Конверсия конца строки«.

Но когда mod_fcgid в целом работает нормально, а «Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: …» и «Premature end of script headers: php-fcgi-wrapper, referer: …» продолжают регулярно появляться в error_log, при этом php_errors.log и /var/log/httpd/suexec.log не предоставляет никакой дополнительной информации, то копать нужно глубже — /var/log/messages или /var/log/kernel.log.

Chapter 1. Connection reset by peer: mod_fcgid: error reading data from FastCGI server

[Fri Dec 16 04:30:14.424452 2016] [fcgid:warn] [pid 26593] (104)Connection reset by peer: [client 127.0.0.1:42657] mod_fcgid: error reading data from FastCGI server, referer: http://example.com/install/index.php?restart=true

[Fri Dec 16 04:30:14.424564 2016] [core:error] [pid 26593] [client 127.0.0.1:42657] End of script output before headers: index.php, referer: http://example.com/install/index.php?restart=true

Если увеличение значений в FcgidProcessLifeTime, FcgidIOTimeout, FcgidIdleTimeout, FcgidBusyTimeout, не решает проблему, тогда нужно смотреть, а не используются ли PHP акселераторы типа APC. Например при использовании opcache в PHP 7 установка PrestaShop 1.7 обламывалась с ошибкой «Connection reset by peer: mod_fcgid: error reading data from FastCGI server«, в php.ini была указана директория для дополнительного кеширования байткода «opcache.file_cache=/var/www/.tmp«, но после того, как «;opcache.file_cache=/var/www/.tmp» была закомментирована — проблема исчезла.

Section 1. Причина №1 — неправильные «чмоды»

Основной причиной, как правило, появления этой ошибки может быть нехватка прав/полномочий на выполнение FastCGI скрипта, РНР в нашем случае.

Права на домашний каталог юзера в котором лежат файлы сайта должны быть 0755 и не меньше, а иначе будет «форбайден» (НТТР 403: 13PermissionDenied — Httpd Wiki), на файл же выполняющий обработку (онже FcgidWrapper) CGI скриптов «чмоды» (chmod) как минимум 750.

Если не помогло, смотрим иные варианты…

Section 2. Причина №2 — нахватка системных ресурсов

Например, первые ошибки mod_fcgid мы получили в error_log «Fri Mar 08 13:42:10 2013«:

[Fri Mar 08 13:42:10 2013] [warn] [client 81.83.хх.ххх] (104)Connection reset by

peer: mod_fcgid: error reading data from FastCGI server, referer: ...

[Fri Mar 08 13:42:10 2013] [error] [client 81.83.хх.ххх] Premature end of script

headers: phpfcgiwrapper, referer: ...

Тогда открываем /var/log/messages или /var/log/kernel, находим системные события происходившие в упомянутое выше время вплоть до секунды и смотрим что же там творилось до и после ошибки php-cgi: http://pastebin.com/Gz5ccSNV

Как видим OOM Killer (oom-killer) начал прибивать процессы уже когда памяти совсем не осталось. OOM Killer — это реализация «Out of memory Killer» на уровне ядра Linux.

Виртуальной памяти (swap) в системе может быть немеряно, разумеется в пределах адресации HDD, а вот оперативной (RAM-ы) вполне ограниченное её количество. Бывают ситуации когда «чилды» (форки) процессов системы поедают ее всю (swap + RAM), и тут OOM Killer начинает среди процессов, кроме kernel init и threads, такой, который по его (oom-killer) мнению является самым ущербным (badness) и начинает его убивать.

В примере выше как раз возникла именно такая ситуация, когда «Free swap = 0kB» процессами (их чилдами/форками httpd-олигархов) httpd и php-cgi съедена вся память включая файл подкачки, «Swap is 100% used» и «Memory is 99% used» — обычно в таких ситуациях система уходит в нирвану и прекращает отвечать/реагировать на внешние команды.

Для решения проблемы поедания памяти рекомендуется снизить число чилдов (CHILDREN) апача и PHP, если PHP_FCGI_CHILDREN больше 2. Понизить значение PHP_FCGI_CHILDREN, а в случае использования PHP акселераторов типа APC и т.д. установить PHP_FCGI_CHILDREN = 0 ибо как сказано в секции «Special PHP considerations» официального мана mod_fcgid, чтоPHP акселератор APC не в состоянии расшаривать свой кэш для PHP модуля mod_fcgid если mod_fcgid/PHP использует управление процессами! Про иные акселераторы ничего не сказано, но всё же если используются любые акселераторы, то лучше управление процессами оставить на совести httpd демона.

Второй способ побороть ошибки «Connection reset by peer: mod_fcgid: error reading data from FastCGI server» и «Premature end of script headers: php-fcgi-wrapper» — это не устанавливать слишком высокое значение в PHP_FCGI_MAX_REQUESTS, которое по умолчанию равно = 500. Вместе с этим использовать директиву FcgidMaxRequestsPerProcess, значение которой должно быть <= PHP_FCGI_MAX_REQUESTS — т.е. если PHP_FCGI_MAX_REQUESTS = 1000, то и значение FcgidMaxRequestsPerProcess должно быть = 1000 или меньше, по умолчанию количество запросов отправляемых в php-cgi не контролируется, т.е. FcgidMaxRequestsPerProcess = 0.

В некоторых случаях помогает увеличение РНР лимита в php.ini, в директивах «max_execution_time = 180«, «max_input_time = 120» и «default_socket_timeout = 180«, а также установкой «FcgidIOTimeout 300» и «FcgidBusyTimeout 500» в vi /etc/httpd/conf/httpd.conf или же конфиге виртуального хоста — разумеется под каждые конкретные условия значения подбираются экспериментальным путём.

Следующим шагом будет выбор стратегии выделения памяти (OVERCOMMIT_GUESS (0), OVERCOMMIT_ALWAYS (1), OVERCOMMIT_NEVER (2)) отличной от стратегии по умолчанию. По умолчанию sysctl -w vm.overcommit_memory=0 система пытается оценить объем свободной памяти, а на практике же удовлетворяет все запросы к памяти до момента её полной утечки, после чего вызывает упомянутый выше OOM Killer (oom-killer) уже тогда, когда система ушла в нирвану «Free swap = 0kB», «Swap is 100% used» и «Memory is 99% used».

vm.overcommit_memory=1 почти тоже что и = 0, только теперь уже система не пытается оценивать объем свободной памяти, а делает вид, что её всегда хватает до момента её полной утечки. vm.overcommit_memory=2 запретит выделять больше памяти чем имеется в файле подкачки и больше оперативной памяти в процентном соотношении указанном в параметре vm.overcommit_ratio=?. Также можно вырубить эвристический поиск ущербного процесса для убивания, по умолчанию vm.oom_kill_allocating_task=0 (OOM Killer) сканирует весь список задач и на основе своего эвристического алгоритма выбирает процесс для убивания, что отнимает дополнительные ресурсы системы. Значение выше 0 запрещает сканировать список задач и говорит «OOM Killer-у» уничтожать любой процесс запросивший больше РАМ-ы чем имеется в наличии.

sysctl w vm.overcommit_memory=2

sysctl w vm.overcommit_ratio=90

sysctl w vm.oom_kill_allocating_task=1

Для изменений на постоянной основе добавим в /etc/sysctl.conf. Ещё как вариант можно сделать ещё один файл подкачки, на случай вонючий:)

dd if=/dev/zero of=/root/swap1 bs=1024 count=1024K

1048576+0 records in

1048576+0 records out

1073741824 bytes (1.1 GB) copied, 8.61173 s, 125 MB/s

mkswap /root/swap1

Setting up swapspace version 1, size = 1048572 KiB

no label, UUID=ba18ffdeb25b48449da46fd095c9182f

swapon /root/swap1

vi /etc/fstab

/root/swap1 swap swap defaults 0 0

Chapter 3. mod_fcgid: can’t lock process table in pid

Это сообщение «mod_fcgid: can’t lock process table in pid» (mod_fcgid: не может заблокировать таблицу процессов в pid) может возникать тогда, когда регулярно используется команда «apachectl graceful» — т.е. перезапуск без разрыва текущих соединений, а её выполнение попадает во время интенсивного использования/нагрузки сервера.

Chapter 4. mod_fcgid: can’t apply process slot

«mod_fcgid: can’t apply process slot» — mod_fcgid не может выделить слот для процесса…

Section 1. Причина №1 — проблемы сегментации

В лог файл виртуального хоста получили «[warn] [client 78.159.53.233] mod_fcgid: can’t apply process slot for /var/www/user/php/php-cgi-wrapper, referer: https://www.google.com.ua/«, а в лог файл самого сервера множественные «[crit] (22)Invalid argument: ap_queue_pop failed«.

Ошибкой «Invalid argument: ap_queue_pop failed» в лог файл /var/log/httpd/error_log нагадило мегов на 300 с лишним за какие-то считанные минуты. Этой ошибке предшествовали сообщения «[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread» и «[notice] child pid 2839 exit signal Segmentation fault (11) Error in my_thread_global_end(): 1 threads didn’t exit«.

На ibm.com рекомендовалось увеличить значение «sysctl -w kernel.threads-max=120000» (по умолчанию 3525 в CentOS 6 и 7877 в CentOS 5) и уменьшить «stack size» с 10240 кб до «ulimit -s 256«.

Размер для каждого потока «thread» равен размеру «stack size», а если Apache запущен как Workerи завышены значения MaxClients, MinSpareThreads, MaxSpareThreads и ThreadsPerChild, в условиях нехватки памяти, то получим «[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread Error in my_thread_global_end(): 1 threads didn’t exit»

Можно увеличить kernel.threads-max, но «stack size» лучше оставить как есть, а иначе на некоторых страницах сайта это может вызывать ошибку «exit(communication error), get unexpected signal 11«! Однако принимая во внимание предыдущий абзац, «stack size» можно попробовать урезать в 3-5 раза или же урезать ThreadsPerChild если продолжаем получать «Resource temporarily unavailable: apr_thread_create: unable to create worker thread«.

Установить ограничение для «stack size» на постоянной основе можно в конф. файле /etc/security/limits.conf:

....

*               soft    stack            2048

apache               hard    stack            5120

# End of file

В примере выше мягкий лимит на «stack size» для всех установлен в 2 МБ, а для пользователя apache ограничен жестким лимитом в 5 МБ. После изменения лимитов с помощью «ulimit -s 256» нужно остановить и снова запустить сервер «service httpd stop && service httpd start«, чтобы изменения вступили в силу, изменения в /etc/security/limits.conf вступят в силу после перезагрузки ОС!

Section 2. Причина №2 — проблема конфигурации

…»mod_fcgid: can’t apply process slot» может быть связана не только с ошибками сегментации, но и с другими причинами такими, как например конфигурация самого mod_fcgid. Рядом с ошибкой «mod_fcgid: can’t apply process slot» граничит и «apache https 503» (ака «Service Unavailable»).

Основную погоду делают параметры:

  • FcgidMaxProcesses — максимально допустимое число php-cgi процессов запущенных одновременно;
  • FcgidMaxProcessesPerClass — максимально допустимое число php-cgi процессов для каждого класса.

PerClass-ом в Апаче, имхо … как я понимаю, считается базовый хост и все его виртуальные хосты. Значит, если FcgidMaxProcessesPerClass 2, а виртуальных хостов у нас 15 + 1 базовый хост, то в итоге получаем 32 php-cgi процесса, но если FcgidMaxProcesses (1000 по умолчанию) будет ниже 32, то в итоге в лог можем получить «mod_fcgid: can’t apply process slot», а в браузер «503 Service Unavailable».

В некоторых случаях (зависит от нагрузки) значение FcgidMaxProcessesPerClass должно быть не меньше 3-5.

Chapter 5. exit(communication error), get unexpected signal 11

Эта ошибка результат уменьшения «stack size»:

less /var/log/httpd/error_log

[Sun Nov 03 00:40:30 2013] [error] mod_fcgid: process /var/www/wrs/php/phpcgiw

rapper(2558) exit(communication error), get unexpected signal 11

[Sun Nov 03 00:40:30 2013] [warn] [client xxx.xxx.xxx.xxx] (104)Connection reset by

peer: mod_fcgid: error reading data from FastCGI server, referer: http://example.

com

[Sun Nov 03 00:40:30 2013] [error] [client xxx.xxx.xxx.xxx] Premature end of script

headers: index.php, referer: http://example.com/

less /var/log/messages

Nov  3 00:56:21 samp kernel: phpcgi[2666]: segfault at 7fffe9034f30 ip

00000000004740c3 sp 00007fffe9034ef0 error 6 in phpcgi[400000+341000]

Premature end of script headers / exit(communication error), get unexpected signal 11 в некоторых случаях может возникать из-за PHP акселераторов типа APC, обычно отсутствует если PHP работает «Как модуль APACHE».

Примечательно, что данная ошибка может проявляться только на некоторых страницах, обычно больших по размеру, где, например, может быть много кода раскрашиваемого Geshi плагином. Часто такие страницы создают большую нагрузку на ЦП и превысив всевозможные лимиты вызывают segfault.

Chapter 6. user mismatch (daemon instead of www)

Связанные ошибки:

/home/user/logs/error_log

[Mon Dec 16 12:36:19.011343 2013] [fcgid:warn] [pid 17033:tid 2183892224] [clien

t 178.94.242.15:54550] mod_fcgid: error reading data, FastCGI server closed conn

ection

[Mon Dec 16 12:36:19.016230 2013] [core:error] [pid 17033:tid 2183892224] [clien

t 178.94.242.15:54550] End of script output before headers: writetest.php

logs/error_log

suexec policy violation: see suexec log for more details

logs/suexec_log

[20131216 12:36:19]: user mismatch (daemon instead of www)

Ошибка вызвана несовпадением имени пользователя указанного в директиве AP_HTTPD_USER, имя которого можно узнать выполнив «suexec -V«, с именем пользователя, которое указано в /var/www/conf/httpd.conf.

В данном случае AP_HTTPD_USER для suexec = www, а имя указанное в httpd.conf = daemon. Решение: в конфиге /var/www/conf/httpd.conf, в директивах User и Group указать имя www вместо daemon.

Chapter 7. mod_fcgid: couldn’t bind unix domain socket /var/www/logs/fcgidsock/29944.19

Сопутствующие ошибки:

[Mon Dec 16 12:40:29.310746 2013] [fcgid:warn] [pid 29944:tid 665836768] (13)Per

mission denied: mod_fcgid: spawn process /home/user/php/phpcgiwrapper error

[Mon Dec 16 12:40:30.344063 2013] [fcgid:error] [pid 29944:tid 665836768] (13)Pe

rmission denied: mod_fcgid: couldnt bind unix domain socket /var/www/logs/fcgid

sock/29944.19

Решается сменой прав на каталог «chmod 777 /var/www/logs/fcgidsock/» или же сменой каталога директивой FcgidIPCDir

Если есть ещё какие вопросы по другим ошибкам mod_fcgid, то пишем в комментарии…

Chapter 8. Ссыль по теме:

  • mod_fcgid — Apache HTTP Server
  • Documentation for /proc/sys/vm/*

Побеждаем ошибки mod_fcgid/php-cgi ака suexec HTTP 500 и иже с ними Самыми распространенными ошибками mod_fcgid являются «Premature end of script headers», «can’t lock process table in pid», «can’t apply process slot», «couldn’t bind unix domain socket», «exit(communication error), get unexpected signal 11″…

Причины этих ошибок могут быть разные, от неправильных прав на файлы до неполной загрузки файла на сервер, не правильно написанного скрипта и неправильного режима передачи файла ASCII/Двоичный. Иногда бывает проблема кроется в переводе строк Windows формата, в этом случае может помочь команда col -bx <input_file> output_file (скобки обязательны!) или редактор notepad++ «Конверсия конца строки«.

Но когда mod_fcgid в целом работает нормально, а «Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: …» и «Premature end of script headers: php-fcgi-wrapper, referer: …» продолжают регулярно появляться в error_log, при этом php_errors.log и /var/log/httpd/suexec.log не предоставляет никакой дополнительной информации, то копать нужно глубже — /var/log/messages или /var/log/kernel.log.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

[Fri Dec 16 04:30:14.424452 2016] [fcgid:warn] [pid 26593] (104)Connection reset by peer: [client 127.0.0.1:42657] mod_fcgid: error reading data from FastCGI server, referer: http://example.com/install/index.php?restart=true
[Fri Dec 16 04:30:14.424564 2016] [core:error] [pid 26593] [client 127.0.0.1:42657] End of script output before headers: index.php, referer: http://example.com/install/index.php?restart=true

Если увеличение значений в FcgidProcessLifeTime, FcgidIOTimeout, FcgidIdleTimeout, FcgidBusyTimeout, не решает проблему, тогда нужно смотреть, а не используются ли PHP акселераторы типа APC. Например при использовании opcache в PHP 7 установка PrestaShop 1.7 обламывалась с ошибкой «Connection reset by peer: mod_fcgid: error reading data from FastCGI server«, в php.ini была указана директория для дополнительного кеширования байткода «opcache.file_cache=/var/www/.tmp«, но после того, как «;opcache.file_cache=/var/www/.tmp» была закомментирована — проблема исчезла.

Premature end of script headers: php-fcgi-wrapper

Причина №1 — неправильные «чмоды»

Основной причиной, как правило, появления этой ошибки может быть нехватка прав/полномочий на выполнение FastCGI скрипта, РНР в нашем случае.

Права на домашний каталог юзера в котором лежат файлы сайта должны быть 0755 и не меньше, а иначе будет «форбайден» (НТТР 403: 13PermissionDenied — Httpd Wiki), на файл же выполняющий обработку (онже FcgidWrapper) CGI скриптов «чмоды» (chmod) как минимум 750.

Если не помогло, смотрим иные варианты…

Причина №2 — нахватка системных ресурсов

Например, первые ошибки mod_fcgid мы получили в error_log «Fri Mar 08 13:42:10 2013«:

[Fri Mar 08 13:42:10 2013] [warn] [client 81.83.хх.ххх] (104)Connection reset by 
peer: mod_fcgid: error reading data from FastCGI server, referer: ...
[Fri Mar 08 13:42:10 2013] [error] [client 81.83.хх.ххх] Premature end of script 
headers: php-fcgi-wrapper, referer: ...

Тогда открываем /var/log/messages или /var/log/kernel, находим системные события происходившие в упомянутое выше время вплоть до секунды и смотрим что же там творилось до и после ошибки php-cgi: http://pastebin.com/Gz5ccSNV

Как видим OOM Killer (oom-killer) начал прибивать процессы уже когда памяти совсем не осталось. OOM Killer — это реализация «Out of memory Killer» на уровне ядра Linux.

Виртуальной памяти (swap) в системе может быть немеряно, разумеется в пределах адресации HDD, а вот оперативной (RAM-ы) вполне ограниченное её количество. Бывают ситуации когда «чилды» (форки) процессов системы поедают ее всю (swap + RAM), и тут OOM Killer начинает среди процессов, кроме kernel init и threads, такой, который по его (oom-killer) мнению является самым ущербным (badness) и начинает его убивать.

В примере выше как раз возникла именно такая ситуация, когда «Free swap = 0kB» процессами (их чилдами/форками httpd-олигархов) httpd и php-cgi съедена вся память включая файл подкачки, «Swap is 100% used» и «Memory is 99% used» — обычно в таких ситуациях система уходит в нирвану и прекращает отвечать/реагировать на внешние команды.

Для решения проблемы поедания памяти рекомендуется снизить число чилдов (CHILDREN) апача и PHP, если PHP_FCGI_CHILDREN больше 2. Понизить значение PHP_FCGI_CHILDREN, а в случае использования PHP акселераторов типа APC и т.д. установить PHP_FCGI_CHILDREN = 0 ибо как сказано в секции «Special PHP considerations» официального мана mod_fcgid, чтоPHP акселератор APC не в состоянии расшаривать свой кэш для PHP модуля mod_fcgid если mod_fcgid/PHP использует управление процессами! Про иные акселераторы ничего не сказано, но всё же если используются любые акселераторы, то лучше управление процессами оставить на совести httpd демона.

Второй способ побороть ошибки «Connection reset by peer: mod_fcgid: error reading data from FastCGI server» и «Premature end of script headers: php-fcgi-wrapper» — это не устанавливать слишком высокое значение в PHP_FCGI_MAX_REQUESTS, которое по умолчанию равно = 500. Вместе с этим использовать директиву FcgidMaxRequestsPerProcess, значение которой должно быть <= PHP_FCGI_MAX_REQUESTS — т.е. если PHP_FCGI_MAX_REQUESTS = 1000, то и значение FcgidMaxRequestsPerProcess должно быть = 1000 или меньше, по умолчанию количество запросов отправляемых в php-cgi не контролируется, т.е. FcgidMaxRequestsPerProcess = 0.

В некоторых случаях помогает увеличение РНР лимита в php.ini, в директивах «max_execution_time = 180«, «max_input_time = 120» и «default_socket_timeout = 180«, а также установкой «FcgidIOTimeout 300» и «FcgidBusyTimeout 500» в vi /etc/httpd/conf/httpd.conf или же конфиге виртуального хоста — разумеется под каждые конкретные условия значения подбираются экспериментальным путём.

Следующим шагом будет выбор стратегии выделения памяти (OVERCOMMIT_GUESS (0), OVERCOMMIT_ALWAYS (1), OVERCOMMIT_NEVER (2)) отличной от стратегии по умолчанию. По умолчанию sysctl -w vm.overcommit_memory=0 система пытается оценить объем свободной памяти, а на практике же удовлетворяет все запросы к памяти до момента её полной утечки, после чего вызывает упомянутый выше OOM Killer (oom-killer) уже тогда, когда система ушла в нирвану «Free swap = 0kB», «Swap is 100% used» и «Memory is 99% used».

vm.overcommit_memory=1 почти тоже что и = 0, только теперь уже система не пытается оценивать объем свободной памяти, а делает вид, что её всегда хватает до момента её полной утечки. vm.overcommit_memory=2 запретит выделять больше памяти чем имеется в файле подкачки и больше оперативной памяти в процентном соотношении указанном в параметре vm.overcommit_ratio=?. Также можно вырубить эвристический поиск ущербного процесса для убивания, по умолчанию vm.oom_kill_allocating_task=0 (OOM Killer) сканирует весь список задач и на основе своего эвристического алгоритма выбирает процесс для убивания, что отнимает дополнительные ресурсы системы. Значение выше 0 запрещает сканировать список задач и говорит «OOM Killer-у» уничтожать любой процесс запросивший больше РАМ-ы чем имеется в наличии. Для изменений на постоянной основе добавим в /etc/sysctl.conf:

Только после полного отключения блокировщика скриптов и рекламы на этом месте появится полезная подсказка/ссылка/код/пример конфигурации/etc!

Ещё как вариант можно сделать ещё один файл подкачки, на случай вонючий:)

Только после полного отключения блокировщика скриптов и рекламы на этом месте появится полезная подсказка/ссылка/код/пример конфигурации/etc!

mod_fcgid: can’t lock process table in pid

Это сообщение «mod_fcgid: can’t lock process table in pid» (mod_fcgid: не может заблокировать таблицу процессов в pid) может возникать тогда, когда регулярно используется команда «apachectl graceful» — т.е. перезапуск без разрыва текущих соединений, а её выполнение попадает во время интенсивного использования/нагрузки сервера.

mod_fcgid: can’t apply process slot

«mod_fcgid: can’t apply process slot» — mod_fcgid не может выделить слот для процесса…

Причина №1 — проблемы сегментации

В лог файл виртуального хоста получили «[warn] [client 78.159.53.233] mod_fcgid: can’t apply process slot for /var/www/user/php/php-cgi-wrapper, referer: https://www.google.com.ua/«, а в лог файл самого сервера множественные «[crit] (22)Invalid argument: ap_queue_pop failed«.

Ошибкой «Invalid argument: ap_queue_pop failed» в лог файл /var/log/httpd/error_log нагадило мегов на 300 с лишним за какие-то считанные минуты. Этой ошибке предшествовали сообщения «[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread» и «[notice] child pid 2839 exit signal Segmentation fault (11) Error in my_thread_global_end(): 1 threads didn’t exit«.

На ibm.com рекомендовалось увеличить значение «sysctl -w kernel.threads-max=120000» (по умолчанию 3525 в CentOS 6 и 7877 в CentOS 5) и уменьшить «stack size» с 10240 кб до «ulimit -s 256«.

Размер для каждого потока «thread» равен размеру «stack size», а если Apache запущен как Workerи завышены значения MaxClients, MinSpareThreads, MaxSpareThreads и ThreadsPerChild, в условиях нехватки памяти, то получим «[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread Error in my_thread_global_end(): 1 threads didn’t exit«

Можно увеличить kernel.threads-max, но «stack size» лучше оставить как есть, а иначе на некоторых страницах сайта это может вызывать ошибку «exit(communication error), get unexpected signal 11«! Однако принимая во внимание предыдущий абзац, «stack size» можно попробовать урезать в 3-5 раза или же урезать ThreadsPerChild если продолжаем получать «Resource temporarily unavailable: apr_thread_create: unable to create worker thread«.

Установить ограничение для «stack size» на постоянной основе можно в конф. файле /etc/security/limits.conf:

....
 
*               soft    stack            2048
apache               hard    stack            5120
 
# End of file

В примере выше мягкий лимит на «stack size» для всех установлен в 2 МБ, а для пользователя apache ограничен жестким лимитом в 5 МБ. После изменения лимитов с помощью «ulimit -s 256» нужно остановить и снова запустить сервер «service httpd stop && service httpd start«, чтобы изменения вступили в силу, изменения в /etc/security/limits.conf вступят в силу после перезагрузки ОС!

Причина №2 — проблема конфигурации

…»mod_fcgid: can’t apply process slot» может быть связана не только с ошибками сегментации, но и с другими причинами такими, как например конфигурация самого mod_fcgid. Рядом с ошибкой «mod_fcgid: can’t apply process slot» граничит и «apache https 503» (ака «Service Unavailable»).

Основную погоду делают параметры:

  • FcgidMaxProcesses — максимально допустимое число php-cgi процессов запущенных одновременно;
  • FcgidMaxProcessesPerClass — максимально допустимое число php-cgi процессов для каждого класса.

PerClass-ом в Апаче, имхо … как я понимаю, считается базовый хост и все его виртуальные хосты. Значит, если FcgidMaxProcessesPerClass 2, а виртуальных хостов у нас 15 + 1 базовый хост, то в итоге получаем 32 php-cgi процесса, но если FcgidMaxProcesses (1000 по умолчанию) будет ниже 32, то в итоге в лог можем получить «mod_fcgid: can’t apply process slot», а в браузер «503 Service Unavailable».

В некоторых случаях (зависит от нагрузки) значение FcgidMaxProcessesPerClass должно быть не меньше 3-5.

exit(communication error), get unexpected signal 11

Эта ошибка результат уменьшения «stack size»:

less /var/log/httpd/error_log
 
[Sun Nov 03 00:40:30 2013] [error] mod_fcgid: process /var/www/wrs/php/php-cgi-w
rapper(2558) exit(communication error), get unexpected signal 11
 
[Sun Nov 03 00:40:30 2013] [warn] [client xxx.xxx.xxx.xxx] (104)Connection reset by
 peer: mod_fcgid: error reading data from FastCGI server, referer: http://example.
 com
[Sun Nov 03 00:40:30 2013] [error] [client xxx.xxx.xxx.xxx] Premature end of script
 headers: index.php, referer: http://example.com/
 
 
less /var/log/messages
 
Nov  3 00:56:21 samp kernel: php-cgi[2666]: segfault at 7fffe9034f30 ip
00000000004740c3 sp 00007fffe9034ef0 error 6 in php-cgi[400000+341000]

Premature end of script headers / exit(communication error), get unexpected signal 11 в некоторых случаях может возникать из-за PHP акселераторов типа APC, обычно отсутствует если PHP работает «Как модуль APACHE».

Примечательно, что данная ошибка может проявляться только на некоторых страницах, обычно больших по размеру, где, например, может быть много кода раскрашиваемого Geshi плагином. Часто такие страницы создают большую нагрузку на ЦП и превысив всевозможные лимиты вызывают segfault.

user mismatch (daemon instead of www)

Связанные ошибки:

/home/user/logs/error_log
[Mon Dec 16 12:36:19.011343 2013] [fcgid:warn] [pid 17033:tid 2183892224] [clien
t 178.94.242.15:54550] mod_fcgid: error reading data, FastCGI server closed conn
ection
[Mon Dec 16 12:36:19.016230 2013] [core:error] [pid 17033:tid 2183892224] [clien
t 178.94.242.15:54550] End of script output before headers: writetest.php
 
---
 
logs/error_log
suexec policy violation: see suexec log for more details
 
---
 
logs/suexec_log
[2013-12-16 12:36:19]: user mismatch (daemon instead of www)

Ошибка вызвана несовпадением имени пользователя указанного в директиве AP_HTTPD_USER, имя которого можно узнать выполнив «suexec -V«, с именем пользователя, которое указано в /var/www/conf/httpd.conf.

В данном случае AP_HTTPD_USER для suexec = www, а имя указанное в httpd.conf = daemon. Решение: в конфиге /var/www/conf/httpd.conf, в директивах User и Group указать имя www вместо daemon.

mod_fcgid: couldn’t bind unix domain socket /var/www/logs/fcgidsock/29944.19

Сопутствующие ошибки:

[Mon Dec 16 12:40:29.310746 2013] [fcgid:warn] [pid 29944:tid 665836768] (13)Per
mission denied: mod_fcgid: spawn process /home/user/php/php-cgi-wrapper error
[Mon Dec 16 12:40:30.344063 2013] [fcgid:error] [pid 29944:tid 665836768] (13)Pe
rmission denied: mod_fcgid: couldn't bind unix domain socket /var/www/logs/fcgid
sock/29944.19

Решается сменой прав на каталог «chmod 777 /var/www/logs/fcgidsock/» или же сменой каталога директивой FcgidIPCDir

Если есть ещё какие вопросы по другим ошибкам mod_fcgid, то пишем в комментарии…

Ссыль по теме:

  • mod_fcgid — Apache HTTP Server
  • Documentation for /proc/sys/vm/*

  • #1

Hello all

i have a shared_hosting site and i notice that i got every day in suexec error log messages this message
«uid: («myusername») gid: («myusername») cmd: wredirect.cgi»

i don’t know what is it, i try contact the support and they check everything from there side and i they said that everything is fine from there side, and an optimization for my site will fix it.

i try check everything, i did update my theme and my plugin to the latest version, i install WP-Optimize but nothing work

i don’t have any error message in my public_html folder

my site work fine but sometimes i got 100% resources i don’t know why, i think this is the problem but i don’t know how to debug it i try most thing

does anyone know anything about this error ?

Last edited by a moderator: Oct 29, 2020

CarlosManceraK


  • #2

it is possible that wordpress is trying to use more memory or disk than allocated

cPanelAaronH


  • #3

Hello,

Can you enable WordPress debugging the next time you see this happen and see if you get any additional information that may help your host track this down?

You would add or modify the following lines within your wp-config.php file.

define( ‘WP_DEBUG’, true);
define( ‘WP_DEBUG_LOG’, true );

support.cpanel.net

How-to troubleshoot a white page in WordPress

Introduction This article aims to assist you with troubleshooting a white screen on a WordPress site. Procedure The first recommended step to resolve this issue is to check the site’s PHP error l…


support.cpanel.net

support.cpanel.net

  • #4

Hello,

Can you enable WordPress debugging the next time you see this happen and see if you get any additional information that may help your host track this down?

You would add or modify the following lines within your wp-config.php file.

define( ‘WP_DEBUG’, true);
define( ‘WP_DEBUG_LOG’, true );

support.cpanel.net

How-to troubleshoot a white page in WordPress

Introduction This article aims to assist you with troubleshooting a white screen on a WordPress site. Procedure The first recommended step to resolve this issue is to check the site’s PHP error l…


support.cpanel.net

support.cpanel.net

i just did what you mention and after a few moment the same error happen again in suexec error log, i did check if there’s new error log in public_html or in home directory log folder, but nothing there too,

what should i do now ?

Last edited: Oct 29, 2020

cPRex


  • #5

A previous user had a very similar issue in this thread:

forums.cpanel.net

SOLVED — Could not create cache file | cmd: redirect.cgi

Am getting error in cpanel error logs, my site sometimes got 500 Error. when i see error logs, getting these errors. can somebody please guide? Cpanel::Config::LoadConfig::_do_logger(«warn», «Could not create cache file x{e2}x{80}x{9c}/home/hoardwe/.cpanel/caches/»…) called at…


forums.cpanel.net

forums.cpanel.net

and that ended up being a problem with a plugin. Could you try disabling plugins on the domain to isolate the issue and see if that helps?

  • #6

A previous user had a very similar issue in this thread:

forums.cpanel.net

SOLVED — Could not create cache file | cmd: redirect.cgi

Am getting error in cpanel error logs, my site sometimes got 500 Error. when i see error logs, getting these errors. can somebody please guide? Cpanel::Config::LoadConfig::_do_logger(«warn», «Could not create cache file x{e2}x{80}x{9c}/home/hoardwe/.cpanel/caches/»…) called at…


forums.cpanel.net

forums.cpanel.net

and that ended up being a problem with a plugin. Could you try disabling plugins on the domain to isolate the issue and see if that helps?

thanks for your attention, i saw the the post you mention «Problem solved. it was due to a wordpress plugin which was trying to use more than alloted memory. thanks cpanel staff.»

i will try disable one by one to see if the problem happen, but i wonder is there and way i could debug or trace plugins how much resource they used ??

cPRex


  • #7

Disabling the plugins individually is a great way to isolate the issue and help track down the problem. While not part of any cPanel tools, there are plugins that give you the option to monitor WordPress usage, such as UsageDD. There are also more extensive resource tracking tools such as the guide outlined here:

that explain how to do more in-depth debugging of WordPress and plugins.

The quickest test you could do would be to temporarily rename or move the plugins directory and see if the issue stops, as that would let you know if a plugin is responsible.

suEXEC Support

The suEXEC feature provides users of the Apache HTTP Server the ability to run CGI and SSI programs under user IDs different from the user ID of the calling web server. Normally, when a CGI or SSI program executes, it runs as the same user who is running the web server.

Used properly, this feature can reduce considerably the security risks involved with allowing users to develop and run private CGI or SSI programs. However, if suEXEC is improperly configured, it can cause any number of problems and possibly create new holes in your computer’s security. If you aren’t familiar with managing setuid root programs and the security issues they present, we highly recommend that you not consider using suEXEC.

Before we begin

Before jumping head-first into this document, you should be aware that certain assumptions are made about you and the environment in which you will be using suexec.

First, it is assumed that you are using a UNIX derivative operating system that is capable of setuid and setgid operations. All command examples are given in this regard. Other platforms, if they are capable of supporting suEXEC, may differ in their configuration.

Second, it is assumed you are familiar with some basic concepts of your computer’s security and its administration. This involves an understanding of setuid/setgid operations and the various effects they may have on your system and its level of security.

Third, it is assumed that you are using an unmodified version of suEXEC code. All code for suEXEC has been carefully scrutinized and tested by the developers as well as numerous beta testers. Every precaution has been taken to ensure a simple yet solidly safe base of code. Altering this code can cause unexpected problems and new security risks. It is highly recommended you not alter the suEXEC code unless you are well versed in the particulars of security programming and are willing to share your work with the Apache HTTP Server development team for consideration.

Fourth, and last, it has been the decision of the Apache HTTP Server development team to NOT make suEXEC part of the default installation of Apache httpd. To this end, suEXEC configuration requires of the administrator careful attention to details. After due consideration has been given to the various settings for suEXEC, the administrator may install suEXEC through normal installation methods. The values for these settings need to be carefully determined and specified by the administrator to properly maintain system security during the use of suEXEC functionality. It is through this detailed process that we hope to limit suEXEC installation only to those who are careful and determined enough to use it.

Still with us? Yes? Good. Let’s move on!

suEXEC Security Model

Before we begin configuring and installing suEXEC, we will first discuss the security model you are about to implement. By doing so, you may better understand what exactly is going on inside suEXEC and what precautions are taken to ensure your system’s security.

suEXEC is based on a setuid «wrapper» program that is called by the main Apache HTTP Server. This wrapper is called when an HTTP request is made for a CGI or SSI program that the administrator has designated to run as a userid other than that of the main server. When such a request is made, Apache httpd provides the suEXEC wrapper with the program’s name and the user and group IDs under which the program is to execute.

The wrapper then employs the following process to determine success or failure — if any one of these conditions fail, the program logs the failure and exits with an error, otherwise it will continue:

  1. Is the user executing this wrapper a valid user of this system?

    This is to ensure that the user executing the wrapper is truly a user of the system.

  2. Was the wrapper called with the proper number of arguments?

    The wrapper will only execute if it is given the proper number of arguments. The proper argument format is known to the Apache HTTP Server. If the wrapper is not receiving the proper number of arguments, it is either being hacked, or there is something wrong with the suEXEC portion of your Apache httpd binary.

  3. Is this valid user allowed to run the wrapper?

    Is this user the user allowed to run this wrapper? Only one user (the Apache user) is allowed to execute this program.

  4. Does the target CGI or SSI program have an unsafe hierarchical reference?

    Does the target CGI or SSI program’s path contain a leading ‘/’ or have a ‘..’ backreference? These are not allowed; the target CGI/SSI program must reside within suEXEC’s document root (see --with-suexec-docroot=DIR below).

  5. Is the target user name valid?

    Does the target user exist?

  6. Is the target group name valid?

    Does the target group exist?

  7. Is the target user NOT superuser?

    suEXEC does not allow root to execute CGI/SSI programs.

  8. Is the target userid ABOVE the minimum ID number?

    The minimum user ID number is specified during configuration. This allows you to set the lowest possible userid that will be allowed to execute CGI/SSI programs. This is useful to block out «system» accounts.

  9. Is the target group NOT the superuser group?

    Presently, suEXEC does not allow the root group to execute CGI/SSI programs.

  10. Is the target groupid ABOVE the minimum ID number?

    The minimum group ID number is specified during configuration. This allows you to set the lowest possible groupid that will be allowed to execute CGI/SSI programs. This is useful to block out «system» groups.

  11. Can the wrapper successfully become the target user and group?

    Here is where the program becomes the target user and group via setuid and setgid calls. The group access list is also initialized with all of the groups of which the user is a member.

  12. Can we change directory to the one in which the target CGI/SSI program resides?

    If it doesn’t exist, it can’t very well contain files. If we can’t change directory to it, it might as well not exist.

  13. Is the directory within the httpd webspace?

    If the request is for a regular portion of the server, is the requested directory within suEXEC’s document root? If the request is for a UserDir, is the requested directory within the directory configured as suEXEC’s userdir (see suEXEC’s configuration options)?

  14. Is the directory NOT writable by anyone else?

    We don’t want to open up the directory to others; only the owner user may be able to alter this directories contents.

  15. Does the target CGI/SSI program exist?

    If it doesn’t exists, it can’t very well be executed.

  16. Is the target CGI/SSI program NOT writable by anyone else?

    We don’t want to give anyone other than the owner the ability to change the CGI/SSI program.

  17. Is the target CGI/SSI program NOT setuid or setgid?

    We do not want to execute programs that will then change our UID/GID again.

  18. Is the target user/group the same as the program’s user/group?

    Is the user the owner of the file?

  19. Can we successfully clean the process environment to ensure safe operations?

    suEXEC cleans the process’ environment by establishing a safe execution PATH (defined during configuration), as well as only passing through those variables whose names are listed in the safe environment list (also created during configuration).

  20. Can we successfully become the target CGI/SSI program and execute?

    Here is where suEXEC ends and the target CGI/SSI program begins.

This is the standard operation of the suEXEC wrapper’s security model. It is somewhat stringent and can impose new limitations and guidelines for CGI/SSI design, but it was developed carefully step-by-step with security in mind.

For more information as to how this security model can limit your possibilities in regards to server configuration, as well as what security risks can be avoided with a proper suEXEC setup, see the «Beware the Jabberwock» section of this document.

Configuring & Installing suEXEC

Here’s where we begin the fun.

suEXEC configuration options

--enable-suexec
This option enables the suEXEC feature which is never installed or activated by default. At least one --with-suexec-xxxxx option has to be provided together with the --enable-suexec option to let APACI accept your request for using the suEXEC feature.
--with-suexec-bin=PATH
The path to the suexec binary must be hard-coded in the server for security reasons. Use this option to override the default path. e.g. --with-suexec-bin=/usr/sbin/suexec
--with-suexec-caller=UID
The username under which httpd normally runs. This is the only user allowed to execute the suEXEC wrapper.
--with-suexec-userdir=DIR
Define to be the subdirectory under users’ home directories where suEXEC access should be allowed. All executables under this directory will be executable by suEXEC as the user so they should be «safe» programs. If you are using a «simple» UserDir directive (ie. one without a «*» in it) this should be set to the same value. suEXEC will not work properly in cases where the UserDir directive points to a location that is not the same as the user’s home directory as referenced in the passwd file. Default value is «public_html«.
If you have virtual hosts with a different UserDir for each, you will need to define them to all reside in one parent directory; then name that parent directory here. If this is not defined properly, «~userdir» cgi requests will not work!
--with-suexec-docroot=DIR
Define as the DocumentRoot set for httpd. This will be the only hierarchy (aside from UserDirs) that can be used for suEXEC behavior. The default directory is the --datadir value with the suffix «/htdocs«, e.g. if you configure with «--datadir=/home/apache» the directory «/home/apache/htdocs» is used as document root for the suEXEC wrapper.
--with-suexec-uidmin=UID
Define this as the lowest UID allowed to be a target user for suEXEC. For most systems, 500 or 100 is common. Default value is 100.
--with-suexec-gidmin=GID
Define this as the lowest GID allowed to be a target group for suEXEC. For most systems, 100 is common and therefore used as default value.
--with-suexec-logfile=FILE
This defines the filename to which all suEXEC transactions and errors are logged (useful for auditing and debugging purposes). By default the logfile is named «suexec_log» and located in your standard logfile directory (--logfiledir).
--with-suexec-safepath=PATH
Define a safe PATH environment to pass to CGI executables. Default value is «/usr/local/bin:/usr/bin:/bin«.

Compiling and installing the suEXEC wrapper

If you have enabled the suEXEC feature with the --enable-suexec option the suexec binary (together with httpd itself) is automatically built if you execute the make command.

After all components have been built you can execute the command make install to install them. The binary image suexec is installed in the directory defined by the --sbindir option. The default location is «/usr/local/apache2/bin/suexec».

Please note that you need root privileges for the installation step. In order for the wrapper to set the user ID, it must be installed as owner root and must have the setuserid execution bit set for file modes.

Setting paranoid permissions

Although the suEXEC wrapper will check to ensure that its caller is the correct user as specified with the --with-suexec-caller configure option, there is always the possibility that a system or library call suEXEC uses before this check may be exploitable on your system. To counter this, and because it is best-practise in general, you should use filesystem permissions to ensure that only the group httpd runs as may execute suEXEC.

If for example, your web server is configured to run as:

User www
Group webgroup

and suexec is installed at «/usr/local/apache2/bin/suexec», you should run:

chgrp webgroup /usr/local/apache2/bin/suexec
chmod 4750 /usr/local/apache2/bin/suexec

This will ensure that only the group httpd runs as can even execute the suEXEC wrapper.

Enabling & Disabling suEXEC

Upon startup of httpd, it looks for the file suexec in the directory defined by the --sbindir option (default is «/usr/local/apache/sbin/suexec»). If httpd finds a properly configured suEXEC wrapper, it will print the following message to the error log:

[notice] suEXEC mechanism enabled (wrapper: /path/to/suexec)

If you don’t see this message at server startup, the server is most likely not finding the wrapper program where it expects it, or the executable is not installed setuid root.

If you want to enable the suEXEC mechanism for the first time and an Apache HTTP Server is already running you must kill and restart httpd. Restarting it with a simple HUP or USR1 signal will not be enough.

If you want to disable suEXEC you should kill and restart httpd after you have removed the suexec file.

Using suEXEC

Requests for CGI programs will call the suEXEC wrapper only if they are for a virtual host containing a SuexecUserGroup directive or if they are processed by mod_userdir.

Virtual Hosts:
One way to use the suEXEC wrapper is through the SuexecUserGroup directive in VirtualHost definitions. By setting this directive to values different from the main server user ID, all requests for CGI resources will be executed as the User and Group defined for that <VirtualHost>. If this directive is not specified for a <VirtualHost> then the main server userid is assumed.

User directories:
Requests that are processed by mod_userdir will call the suEXEC wrapper to execute CGI programs under the userid of the requested user directory. The only requirement needed for this feature to work is for CGI execution to be enabled for the user and that the script must meet the scrutiny of the security checks above. See also the --with-suexec-userdir compile time option.

Debugging suEXEC

The suEXEC wrapper will write log information to the file defined with the --with-suexec-logfile option as indicated above. If you feel you have configured and installed the wrapper properly, have a look at this log and the error_log for the server to see where you may have gone astray.

Beware the Jabberwock: Warnings & Examples

NOTE! This section may not be complete. For the latest revision of this section of the documentation, see the Online Documentation version.

There are a few points of interest regarding the wrapper that can cause limitations on server setup. Please review these before submitting any «bugs» regarding suEXEC.

  • suEXEC Points Of Interest
  • Hierarchy limitations

    For security and efficiency reasons, all suEXEC requests must remain within either a top-level document root for virtual host requests, or one top-level personal document root for userdir requests. For example, if you have four VirtualHosts configured, you would need to structure all of your VHosts’ document roots off of one main httpd document hierarchy to take advantage of suEXEC for VirtualHosts. (Example forthcoming.)

  • suEXEC’s PATH environment variable

    This can be a dangerous thing to change. Make certain every path you include in this define is a trusted directory. You don’t want to open people up to having someone from across the world running a trojan horse on them.

  • Altering the suEXEC code

    Again, this can cause Big Trouble if you try this without knowing what you are doing. Stay away from it if at all possible.

The typical warning signal of a suexec problem is a request
for a CGI script that results in a ‘500 Internal Server Error’ page. The
appropriate response behaviour to such an error is to look in the server’s
error log. Unfortunately, because the wrapper is applying its own restrictions
and rules on the script, the server log may be quite unrevealing, containing
only a single line such as the following for the failed request:

[Sun Dec 26 20:02:55 1999] [error] [client n.n.n.n] Premature
end of script headers: script

The real error message will be found in your suexec log
(which is located at /usr/local/web/apache/logs/suexec_log,
according to the assumptions section of this
article). The suexec error message may look like this:

    [1999-12-26 20:02:55]: uid: (user/user) gid: (group/group) cmd: test.cgi
    [1999-12-26 20:02:55]: command not in docroot (/home/user/public_html/test.cgi
  

Here are a couple of other common suexec error messages:

  • directory is writable by others: (path)
  • target uid/gid (uid-1/gid-1) mismatch with directory
    (uid-2/gid-2) or program (uid-3/gid-3)

If it’s still not clear what’s going wrong, review the list of requirements
and make sure they’re all being met.

“Danger, Will Robinson!”

When you suexec-enable your Apache Web server, a lot of
behaviours change:

  • CGI scripts in ScriptAliased directories will be executed
    under the identity of the username specified in the User and
    Group directives
  • CGI scripts in user directories (as specified by the
    USERDIR_SUFFIX definition, set by the
    --suexec-userdir option) will be executed as the owning user if
    and only if

    1. the script was requested using the ~username syntax,
      and
    2. all of the ownership and permission requirements are met

    If the ~username URL format is used but the
    permissions/ownerships aren’t correct, the result will be a ‘500 Internal
    Server Error’ page, not the script being executed by the server user as
    in a non-suexec environment

  • CGI scripts in all user directories accessed through
    ~username URLs will go through the suexec
    process–even those that you didn’t consider or expect.

One effect of these changes is that previously-functioning user scripts may
suddenly begin to fail, giving the visitor the fatal ‘500 Internal Server
Error’ page, and giving you, the Webmaster, an unrevealing
Premature end of script headers” message in the server
error log. This is where it becomes easy to get frustrated by simply forgetting
to check the suexec error log.

Another aspect of the use of suexec is that, if you have
virtual hosts with different User or Group values,
they cannot share ScriptAliased directories–because one of the
requirements is that the script and the directory must be owned by the user and
group suexec is being told to use. So you may have to duplicate a
lot of your cgi-bin/ stuff into per-vhost directories that
are owned and protected appropriately.

Frequently Asked Suexec Questions

Понравилась статья? Поделить с друзьями:
  • Sudo ufw allow openssh error не найдено профилей соответствующих openssh
  • Sudo ufw allow openssh error could not find a profile matching openssh
  • Sudo syntax error
  • Sudo service apache2 restart error
  • Sudo rmmod r8188eu ko rmmod error module r8188eu is not currently loaded