Saltar al contenido

Apache

Apache – prefork vs. worker mode, how to check mode and more

  • admin 

Referencia:

https://communities.ca.com/web/ca-identity-and-access-mgmt-distributed-global-user-community/message-board/-/message_boards/view_message/98290538

 

This Tuesday Tip will cover some common questions regarding Apache, specifically prefork vs. worker mode, how to change the default value on RedHat, Solaris and other operating systems as well as verifying what mode apache is currently running in.

A. The default MPM for Unix is the Prefork module.
B. The Worker MPM was introduced in Apache2.

Now Comparing between Worker MPM and Prefork MPM.

Prefork MPM
– prefork MPM uses multiple child processes with one thread each.
– Each process handles one connection at a time and uses more memory.
– Good for non-thread-safe third party modules.

Worker MPM
– worker MPM uses multiple child processes with many threads each.
– Each thread handles one connection at a time.
– Good for high-traffic, smaller memory footprint.

MPM uses a multi-process and multi-threaded structure.
Multi-process –> multi PIDs (use ‘ps -aef’ to find out)
Multi-thread –> more connections per PID. (use ‘lsof’ (on Solaris) to find out. ‘netstat -an’ (You really won’t see everything.)

The worker MPM uses multiple child processes. It’s multi-threaded within each child, and each thread handles a single connection. Worker is fast and highly scalable and the memory footprint is comparatively low. It’s well suited for multiple processors.

Prefork MPM is preferred for better compatibility with older software or for better stability although it uses more memory. It handles requests in a manner similar to Apache 1.3. It is appropriate for sites that need to avoid threading for compatibility with non-thread-safe libraries. It is also the best MPM for isolating each request, so that a problem with a single request will not affect any other. Prefork is well suited for single or double CPU systems, speed is comparable to that of worker, and it’s highly tolerant of faulty modules and crashing children – but the memory usage is high, and more traffic leads to greater memory usage.

Conclusion: For most new websites that are that use thread safe libraries, use multiple processes and high traffic sites, CA SiteMinder recommends MPM worker mode for Apache.

>>>>>>>>>>>

How to tell if I’m running Apache in prefork or worker MPM? (Multi-Processing Module)

Note : You can have one and only one MPM module loaded in apache at any one time.

From the bin directory, you can run ./apachectl -V (Capital V)

./apache2/bin/apachectl -V
Server version: Apache/2.0.50
Server built: Aug 3 2004 16:52:20
Server’s Module Magic Number: 20020903:8
Architecture: 32-bit
Server compiled with….
-D APACHE_MPM_DIR=»server/mpm/prefork» (This is running in prefork mode)

Newer version running in worker mode:

./apachectl -V
Server version: Apache/2.2.21 (Unix)
Server built: Oct 23 2011 17:42:11
Server’s Module Magic Number: 20051115:30
Server loaded: APR 1.4.5, APR-Util 1.3.12
Compiled using: APR 1.4.5, APR-Util 1.3.12
Architecture: 32-bit
Server MPM: Worker <——Worker
threaded: yes (fixed thread count)
forked: yes (variable process count)
Server compiled with….
-D APACHE_MPM_DIR=»server/mpm/worker» <- This same line will still exist.

A second way to check, again from the bin directory:

#./ httpd -l
Compiled in modules:
core.c
prefork.c <—- Prefork
http_core.c
mod_so.c

./httpd -l
Compiled in modules:
core.c
mod_access.c
mod_auth.c
mod_include.c
mod_log_config.c
mod_logio.c
mod_env.c
mod_setenvif.c
worker.c <—–Worker

>>>>>>>>>>>

How do I change the default value on RHEL (Red Hat Enterprise Release)?

Edit the /etc/sysconfig/httpd file.

Change #HTTPD=/usr/sbin/httpd.worker

to

HTTPD=/usr/sbin/httpd.worker

and stop/start the apache service.

>>>>>>>>>>>

Solaris or most unix like operating systems.

When I download the code from apache.org and use certain flags to compile apache, what flag do I use for worker mode?

./configure –with-mpm=worker

For all compile options, please reference www.apache.org

 

Disable apache server signature on your web pages

Source: http://syahik.wordpress.com/tag/server-signature/

In the default configuration of Apache, any error pages will contain the full signature of the server (Apache version) which could be exploited by hackers or Attacker. Each version has some deficiencies that could be exploited, and a hacker who knows your version number may benefit from it by focused attacks.

To disable server signature, you will need to edit your /etc/apache2/apache2.conf file.

root@server# nano /etc/apache2/apache2.conf

Press Ctrl+w to search for “ServerSignature” and press return. If you find it, edit it to:

ServerSignature Off
ServerTokens Prod

If you don’t find it, just scroll to the end of the file and add these two lines.

Then, we need to reload apache configuration to put this new change in effect:

sudo /etc/init.d/apache2 reload

Check the new configuration by entering an invalid address on your server URL (ex:http://www.domain.com/unavailablePage.php). You should not see the server signature now, just the server name.

 

NOTE:

# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to «EMail» to also include a mailto: link to the ServerAdmin.
# Set to one of: On | Off | EMail
#
ServerSignature Off

# Don’t give away too much information about all the subcomponents
# we are running. Comment out this line if you don’t mind remote sites
# finding out what major optional modules you are running
# ServerTokens OS

 

Autenticación en Apache: básica y PAM

  • admin 

FUENTE: http://blog.unlugarenelmundo.es/2010/03/13/autenticacion-en-apache-basica-y-pam/

 

El servidor web Apache puede acompañarse de distintos módulos para proporcionar diferentes modelos de autenticación. Hoy vamos a echarle un vistazo a la configuración básica de dos de los más utilizados y sencillos.

PRIMER METODO

La primera forma que veremos es la más simple. Usamos para ello el módulo de autenticación básica que viene instalada “de serie” con cualquier Apache. La configuración que tenemos que añadir en el fichero de definición del Virtual Host a proteger podría ser algo así:

<Directory "/var/www/miweb/privado">
Order deny,allow
AuthUserFile "/etc/apache2/claves/passwd.txt"
AuthName "Palabra de paso"
AuthType Basic
<Limit GET POST>
Require valid-user
</Limit>
</Directory>

La información a personalizar está marcada en negritas. En Directory escribimos el directorio a proteger, que puede ser el raíz de nuestro Virtual Host o un directorio interior a este. En AuthUserFile ponemos el fichero que guardará la información de usuarios y contraseñas que debería de estar, como en este ejemplo, en un directorio que no sea visitable desde nuestro Apache. Ahora comentaremos la forma de generarlo. Por último, en AutnName personalizamos el mensaje que aparecerá en la ventana del navegador que nos pedirá la contraseña. Existen otras directivas adicionales o modificaciones a estas útiles para personalizar el acceso: AuthGroupFile, Require user, Require group, etc.

El fichero de contraseñas se genera mediante la utilidad htpasswd. Su sintaxis es bien sencilla. Para añadir un nuevo usuario al fichero operamos así:

# htpasswd /etc/apache2/claves/passwd.txt carolina
New password:
Re-type new password:
Adding password for user carolina

Para crear el fichero de contraseñas con la introducción del primer usuario tenemos que añadir la opción -c (create) al comando anterior. Si por error la seguimos usando al incorporar nuevos usuarios borraremos todos los anteriores, así que cuidado con esto. Las contraseñas, como podemos ver a continuación, no se guardan en claro. Lo que se almacena es el resultado de aplicar una función hash.

josemaria:rOUetcAKYaliE
carolina:hmO6V4bM8KLdw
alberto:9RjyKKYK.xyhk

Para denegar el acceso a algún usuario basta con que borremos la línea correspondiente al mismo. No es necesario que le pidamos a Apache que vuelva a leer su configuración (/etc/init.d/apache2 reload) cada vez que hagamos algún cambio en este fichero de contraseñas, pero si lo es después de hacer los cambios en el fichero de definición del Virtual Host.

autenticación en apacheLa principal ventaja de este método es su sencillez. Sus inconvenientes: lo incómodo de delegar la generación de nuevos usuarios en alguien que no sea un administrador de sistemas o de hacer un front-end para que sea el propio usuario quien cambie su contraseña. Y, por supuesto, que dichas contraseñas viajan en claro a través de la red. Si queremos evitar esto último podemos crear una instancia Apache con SSL.

SEGUNDO METODO

El segundo método que vamos a tocar usa PAM, el propio sistema de autenticación de la máquina donde está instalado nuestro servidor de Apache. Si ya tenemos alguna herramienta de gestión de usuarios y contraseñas en la misma este sistema nos ahora el engorro de tener que generar otro tipo de usuario. En caso contrario no ganamos mucho en este sentido y seguimos teniendo el problema de que las contraseñas viajan en claro con el agravante adicional de que ahora se trata de usuarios de la máquina… así que ya sabéis: o configuráis ssl o usáis el truco que comentamos el otro día por aquí para deshabilitar la conexión remota.

Usaremos para ello el módulo mod_auth_pam y lo primero que tenemos que hacer es instalarlo:

# sudo apt-get install libapache2-mod-auth-pam

En el fichero de configuración del Virtual Host tendríamos que incluir algo así:

<Directory "/var/www/privado">
AuthType Basic
AuthName "Palabra de paso"
AuthPAM_Enabled On
AuthBasicAuthoritative Off
AuthUserFile /dev/null
Require user josemaria gemma fernando araceli
</code>

Si en este caso la directiva usada fuese Require valid-user se permitiría el acceso a cualquier usuario con cuenta en la máquina. Ah, y no olvides hacer un reload de apache después de este cambio.

Sólo nos quedan un par de pasos. Primero, añadir el usuario www-data (el que usa apache) al grupo shadow para que pueda verificar las contraseñas:

usermod -a -G shadow www-data

Y dos, hacer un enlace como el que sigue. Ignoro la causa, pero el motivo de que esto sea necesario es debido a que apache (en los binarios de Debian y Ubuntu, al menos) pretende leer del archivo /etc/pam.d/http mientras que el módulo de autenticación ha creado el archvo /etc/pam.d/apache2. El módulo auth_pam hace años que no está soportado e imagino que esto tiene algo que ver, pero no lo se a ciencia cierta. Simplemente lo leí por ahí…

ln -s /etc/pam.d/apache2 /etc/pam.d/httpd

Y con esto está todo listo. No lo he probado nunca pero también he leído que la autenticación se hace contra el directorio activo si Apache está instalado en una máquina windows configurada en un dominio. Existe también un módulo para autenticar contra un ldap (mod_auth_ldap).